Skip to main content

passless_core/
config.rs

1//! Application configuration using clap-serde-derive
2//!
3//! This module provides a unified configuration approach where settings can come from:
4//! 1. CLI arguments (highest priority)
5//! 2. Configuration file (medium priority)
6//! 3. Default values (lowest priority)
7
8use std::fs::{self, File};
9use std::io::BufReader;
10use std::path::{Path, PathBuf};
11
12use clap::{ArgAction, Parser, Subcommand, ValueEnum};
13use clap_serde_derive::ClapSerde;
14use libc::{PR_SET_DUMPABLE, prctl};
15use libc::{mlock, munlock};
16use log::debug;
17use nix::sys::resource::{Resource, setrlimit};
18use passless_config_doc::ConfigDoc;
19use serde::{Deserialize, Serialize};
20
21#[cfg(feature = "agent")]
22use crate::agent::AgentConfig;
23
24use crate::error::Error;
25
26/// Compute default local storage path
27pub fn local_path() -> String {
28    dirs::data_dir()
29        .expect("Could not determine data directory: $XDG_DATA_HOME or $HOME/.local/share")
30        .join("passless/local")
31        .to_string_lossy()
32        .into_owned()
33}
34
35/// Local backend configuration
36#[derive(ClapSerde, Debug, Clone, Serialize, Deserialize, ConfigDoc)]
37#[group(id = "local-backend-config")]
38pub struct LocalBackendConfig {
39    /// Path to local storage directory
40    #[arg(
41        long = "local-path",
42        env = "PASSLESS_LOCAL_PATH",
43        id = "local-path",
44        value_name = "PATH"
45    )]
46    #[serde(default)]
47    #[default(local_path())]
48    pub path: String,
49}
50
51/// Compute default password-store path
52pub fn pass_store_path() -> String {
53    dirs::home_dir()
54        .expect("Could not determine home directory: $HOME")
55        .join(".password-store")
56        .to_string_lossy()
57        .into_owned()
58}
59/// Pass (password-store) backend configuration
60#[derive(ClapSerde, Debug, Clone, Serialize, Deserialize, ConfigDoc)]
61#[group(id = "pass-backend-config")]
62pub struct PassBackendConfig {
63    /// Path to password store directory
64    #[arg(
65        long = "pass-store-path",
66        env = "PASSLESS_PASS_STORE_PATH",
67        id = "pass-store-path",
68        value_name = "PATH"
69    )]
70    #[serde(default)]
71    #[default(pass_store_path())]
72    pub store_path: String,
73
74    /// Relative path within password store for FIDO2 entries
75    #[arg(
76        long = "pass-path",
77        env = "PASSLESS_PASS_PATH",
78        id = "pass-path",
79        value_name = "PATH"
80    )]
81    #[serde(default)]
82    #[default("fido2".to_string())]
83    pub path: String,
84
85    /// GPG backend: "gpgme" or "gnupg-bin"
86    #[arg(
87        long = "pass-gpg-backend",
88        env = "PASSLESS_PASS_GPG_BACKEND",
89        value_name = "BACKEND"
90    )]
91    #[serde(default)]
92    #[default("gnupg-bin".to_string())]
93    pub gpg_backend: String,
94
95    /// Automatically synchronize password-store Git around Passless operations
96    #[arg(
97        long = "pass-git-sync",
98        env = "PASSLESS_PASS_GIT_SYNC",
99        action = ArgAction::Set,
100        require_equals = true,
101        num_args = 0..=1,
102        default_missing_value = "true"
103    )]
104    #[serde(default)]
105    #[default(true)]
106    pub git_sync: bool,
107
108    /// Automatically push password-store Git commits to the remote (default: true).
109    /// When disabled, Git sync still pulls and commits changes locally.
110    #[arg(
111        long = "pass-git-auto-push",
112        env = "PASSLESS_PASS_GIT_AUTO_PUSH",
113        action = ArgAction::Set,
114        require_equals = true,
115        num_args = 0..=1,
116        default_missing_value = "true"
117    )]
118    #[serde(default)]
119    #[default(true)]
120    pub git_auto_push: bool,
121}
122
123/// Compute default TPM storage path
124pub fn tpm_path() -> String {
125    dirs::data_dir()
126        .expect("Could not determine data directory: $XDG_DATA_HOME or $HOME/.local/share")
127        .join("passless/tpm")
128        .to_string_lossy()
129        .into_owned()
130}
131
132/// TPM backend configuration
133#[cfg(feature = "tpm")]
134#[derive(ClapSerde, Debug, Clone, Serialize, Deserialize, ConfigDoc)]
135#[group(id = "tpm-backend-config")]
136pub struct TpmBackendConfig {
137    /// Path to TPM storage directory
138    #[arg(
139        long = "tpm-path",
140        env = "PASSLESS_TPM_PATH",
141        id = "tpm-path",
142        value_name = "PATH"
143    )]
144    #[serde(default)]
145    #[default(tpm_path())]
146    pub path: String,
147
148    /// TPM TCTI (TPM Command Transmission Interface) configuration
149    #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI", value_name = "TCTI")]
150    #[serde(default)]
151    #[default("device:/dev/tpmrm0".to_string())]
152    pub tcti: String,
153
154    /// Use portable TPM backend with TPM-resident credential keys
155    #[arg(long = "tpm-portable", env = "PASSLESS_TPM_PORTABLE")]
156    #[serde(default)]
157    #[default(false)]
158    pub portable: bool,
159}
160
161/// Security configuration
162#[derive(ClapSerde, Debug, Clone, Serialize, Deserialize, ConfigDoc)]
163#[group(id = "security")]
164pub struct SecurityConfig {
165    /// Check if mlock is available to prevent credentials from being swapped to disk
166    #[arg(long = "check-mlock", env = "PASSLESS_CHECK_MLOCK")]
167    #[serde(default)]
168    #[default(true)]
169    pub check_mlock: bool,
170
171    /// Disable core dumps to prevent credential leakage
172    #[arg(long = "disable-core-dumps", env = "PASSLESS_DISABLE_CORE_DUMPS")]
173    #[serde(default)]
174    #[default(true)]
175    pub disable_core_dumps: bool,
176
177    /// Enable constant signature counter to help RPs detect cloned authenticators
178    #[arg(
179        long = "constant-signature-counter",
180        env = "PASSLESS_CONSTANT_SIGNATURE_COUNTER",
181        action = ArgAction::Set,
182        require_equals = true,
183        num_args = 0..=1,
184        default_missing_value = "true"
185    )]
186    #[serde(default)]
187    pub constant_signature_counter: bool,
188
189    /// Enable Passless encrypted credential backup/restore vendor commands.
190    ///
191    /// Also sets the WebAuthn backup-eligibility (BE) flag assigned to newly
192    /// registered credentials: `false` (default) marks them single-device
193    /// (`BE=0`), `true` marks them backup-eligible (`BE=1`). Existing
194    /// credentials are not migrated; they keep the state they were created with.
195    ///
196    /// Disabled by default because exporting a software credential changes its
197    /// security model. TPM and other non-exportable key providers remain
198    /// unsupported. Strict relying parties (e.g. Kanidm) reject a credential
199    /// whose BE flag changes after registration, so keep this setting stable.
200    /// See docs/CREDENTIAL_BACKUP.md.
201    #[arg(
202        long = "enable-credential-backup",
203        env = "PASSLESS_ENABLE_CREDENTIAL_BACKUP",
204        action = ArgAction::Set,
205        require_equals = true,
206        num_args = 0..=1,
207        default_missing_value = "true"
208    )]
209    #[serde(default)]
210    pub enable_credential_backup: bool,
211
212    /// Always require user verification for all operations
213    /// - When PIN is set + pin.enforcement="required": requires PIN
214    /// - When PIN is set + pin.enforcement="optional": depends on context
215    /// - When PIN is set + pin.enforcement="never": uses notification fallback
216    /// - When PIN not set: uses notification
217    #[arg(
218        long = "always-uv",
219        env = "PASSLESS_ALWAYS_UV",
220        action = ArgAction::Set,
221        require_equals = true,
222        num_args = 0..=1,
223        default_value = "true",
224        default_missing_value = "true"
225    )]
226    #[serde(default)]
227    #[default(true)]
228    pub always_uv: bool,
229
230    /// Show user verification notification during registration
231    #[arg(
232        long = "user-verification-registration",
233        env = "PASSLESS_USER_VERIFICATION_REGISTRATION"
234    )]
235    #[serde(default)]
236    #[default(true)]
237    pub user_verification_registration: bool,
238
239    /// Show user verification notification during authentication
240    #[arg(
241        long = "user-verification-authentication",
242        env = "PASSLESS_USER_VERIFICATION_AUTHENTICATION"
243    )]
244    #[serde(default)]
245    #[default(true)]
246    pub user_verification_authentication: bool,
247
248    /// Notification timeout in seconds (0 = no timeout)
249    #[arg(
250        long = "notification-timeout",
251        env = "PASSLESS_NOTIFICATION_TIMEOUT",
252        value_name = "SECONDS"
253    )]
254    #[serde(default)]
255    #[default(30)]
256    pub notification_timeout: u32,
257}
258
259/// PIN enforcement policy
260#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
261#[serde(rename_all = "lowercase")]
262pub enum PinEnforcement {
263    /// Never require PIN, always use notification fallback (backward compatible)
264    Never,
265    /// Use PIN only when always_uv=true or client requests UV
266    #[default]
267    Optional,
268    /// Always require PIN when set (most secure)
269    Required,
270}
271
272impl std::str::FromStr for PinEnforcement {
273    type Err = String;
274
275    fn from_str(s: &str) -> Result<Self, Self::Err> {
276        match s.to_lowercase().as_str() {
277            "never" => Ok(PinEnforcement::Never),
278            "optional" => Ok(PinEnforcement::Optional),
279            "required" => Ok(PinEnforcement::Required),
280            _ => Err(format!(
281                "Invalid PIN enforcement '{}'. Must be: never, optional, or required",
282                s
283            )),
284        }
285    }
286}
287
288impl std::fmt::Display for PinEnforcement {
289    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
290        match self {
291            PinEnforcement::Never => write!(f, "never"),
292            PinEnforcement::Optional => write!(f, "optional"),
293            PinEnforcement::Required => write!(f, "required"),
294        }
295    }
296}
297
298/// PIN configuration
299#[derive(ClapSerde, Debug, Clone, Serialize, Deserialize, ConfigDoc)]
300#[group(id = "pin")]
301pub struct PinConfig {
302    /// PIN enforcement policy when PIN is set:
303    /// - "never": Always use notification fallback (backward compatible, convenience)
304    /// - "optional": Use PIN only when always_uv=true or client requests UV
305    /// - "required": Always require PIN when set (most secure)
306    #[arg(
307        long = "pin-enforcement",
308        env = "PASSLESS_PIN_ENFORCEMENT",
309        value_name = "POLICY"
310    )]
311    #[serde(default)]
312    #[default(PinEnforcement::Optional)]
313    pub enforcement: PinEnforcement,
314
315    /// Minimum PIN length in characters (CTAP spec: 4-63)
316    #[arg(
317        long = "pin-min-length",
318        env = "PASSLESS_PIN_MIN_LENGTH",
319        value_name = "LENGTH"
320    )]
321    #[serde(default)]
322    #[default(4)]
323    pub min_length: u8,
324
325    /// Maximum PIN retry attempts before lockout (CTAP spec: 8)
326    #[arg(
327        long = "pin-max-retries",
328        env = "PASSLESS_PIN_MAX_RETRIES",
329        value_name = "RETRIES"
330    )]
331    #[serde(default)]
332    #[default(8)]
333    pub max_retries: u8,
334
335    /// Maximum user verification retry attempts before UV is blocked (default: 8)
336    ///
337    /// This controls how many consecutive UV failures are allowed before UV is blocked.
338    /// Use `passless client pin uv-reset` to restore the retry counter after authentication.
339    /// Higher values improve usability but may reduce security against brute-force attacks.
340    #[arg(
341        long = "pin-max-uv-retries",
342        env = "PASSLESS_PIN_MAX_UV_RETRIES",
343        value_name = "RETRIES"
344    )]
345    #[serde(default)]
346    #[default(8)]
347    pub max_uv_retries: u8,
348
349    /// Auto-lock timeout in seconds after max failed attempts (0 = disabled)
350    /// After lockout, authenticator must be reset to use PIN again
351    #[arg(
352        long = "pin-auto-lock-timeout",
353        env = "PASSLESS_PIN_AUTO_LOCK_TIMEOUT",
354        value_name = "SECONDS"
355    )]
356    #[serde(default)]
357    #[default(0)]
358    pub auto_lock_timeout: u32,
359}
360
361impl PinConfig {
362    /// Validate PIN configuration values
363    pub fn validate(&self) -> crate::error::Result<()> {
364        if self.min_length < 4 || self.min_length > 63 {
365            return Err(crate::error::Error::Config(format!(
366                "pin.min_length must be between 4 and 63, got {}",
367                self.min_length
368            )));
369        }
370        if self.max_retries == 0 {
371            return Err(crate::error::Error::Config(
372                "pin.max_retries must be greater than 0".to_string(),
373            ));
374        }
375        if self.max_uv_retries == 0 {
376            return Err(crate::error::Error::Config(
377                "pin.max_uv_retries must be greater than 0".to_string(),
378            ));
379        }
380        Ok(())
381    }
382}
383
384impl SecurityConfig {
385    /// Apply security hardening measures
386    pub fn apply_hardening(&self) -> Result<(), Box<dyn std::error::Error>> {
387        if self.disable_core_dumps {
388            self.disable_core_dumps_impl()?;
389        }
390        if self.check_mlock {
391            self.probe_mlock_capability()?;
392        }
393        Ok(())
394    }
395
396    /// Disable core dumps to prevent credential leakage
397    fn disable_core_dumps_impl(&self) -> Result<(), Box<dyn std::error::Error>> {
398        debug!("Disabling core dumps to prevent credential leakage");
399        setrlimit(Resource::RLIMIT_CORE, 0, 0)?;
400        let r = unsafe { prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) };
401        if r != 0 {
402            log::warn!("prctl(PR_SET_DUMPABLE) failed: {}", r);
403        }
404        Ok(())
405    }
406
407    /// Probe mlock capability by testing with a small allocation
408    fn probe_mlock_capability(&self) -> Result<(), Box<dyn std::error::Error>> {
409        debug!("Check mlock capability");
410
411        let test_size = 4096;
412        let test_buffer = vec![0u8; test_size];
413        let ptr = test_buffer.as_ptr() as *const libc::c_void;
414
415        let lock_result = unsafe { mlock(ptr, test_size) };
416
417        if lock_result == 0 {
418            unsafe { munlock(ptr, test_size) };
419            log::debug!("MLOCK is enabled - sensitive data will not be swapped to disk");
420        } else {
421            log::warn!(
422                "mlock capability probe failed - memory locking may not be available.\n\
423                 Hint: grant CAP_IPC_LOCK to the binary with: 'sudo setcap cap_ipc_lock=+ep $(which passless)'"
424            );
425        }
426        Ok(())
427    }
428}
429
430/// Main application configuration
431/// Note: Cannot derive Clone/Debug because it has #[clap_serde] fields
432#[derive(ClapSerde, Serialize, Deserialize, Debug, ConfigDoc)]
433pub struct AppConfig {
434    /// Storage backend type: pass, tpm (experimental), or local (for testing)
435    #[arg(short = 't', long = "backend-type", env = "PASSLESS_BACKEND_TYPE")]
436    #[serde(default)]
437    #[default("pass".to_string())]
438    pub backend_type: String,
439
440    /// Enable verbose logging
441    // workaround for allowing `-v` syntax instead of `-v=true`
442    #[arg(
443        short,
444        long,
445        env = "PASSLESS_VERBOSE",
446        action = ArgAction::Set,
447        require_equals = true,
448        num_args = 0..=1,
449        default_missing_value = "true"
450    )]
451    #[default(true)]
452    #[serde(default)]
453    pub verbose: bool,
454
455    /// Pass backend configuration
456    #[clap_serde]
457    #[serde(default)]
458    #[command(flatten)]
459    pub pass: PassBackendConfig,
460
461    /// TPM backend configuration
462    #[cfg(feature = "tpm")]
463    #[clap_serde]
464    #[serde(default)]
465    #[command(flatten)]
466    pub tpm: TpmBackendConfig,
467
468    /// Local backend configuration
469    #[clap_serde]
470    #[serde(default)]
471    #[command(flatten)]
472    pub local: LocalBackendConfig,
473
474    /// Security hardening configuration
475    #[clap_serde]
476    #[serde(default)]
477    #[command(flatten)]
478    pub security: SecurityConfig,
479
480    /// PIN configuration
481    #[clap_serde]
482    #[serde(default)]
483    #[command(flatten)]
484    pub pin: PinConfig,
485
486    /// Agent configuration (only available with the `agent` feature)
487    #[cfg(feature = "agent")]
488    #[arg(skip)]
489    pub agents: AgentConfig,
490}
491
492/// Backend-specific configuration
493#[derive(Debug, Clone)]
494pub enum BackendConfig {
495    Local {
496        path: String,
497    },
498    Pass {
499        store_path: String,
500        path: String,
501        gpg_backend: String,
502    },
503    #[cfg(feature = "tpm")]
504    Tpm {
505        path: String,
506        tcti: String,
507        portable: bool,
508    },
509}
510
511impl BackendConfig {
512    /// Canonicalize a path, resolving symlinks for existing parents.
513    ///
514    /// If the full path does not exist, canonicalize the longest existing
515    /// prefix and append the remaining components lexically.
516    pub fn canonicalize_path(path: &Path) -> PathBuf {
517        match fs::canonicalize(path) {
518            Ok(p) => p,
519            Err(_) => {
520                let mut current = path.to_path_buf();
521                let mut suffix = Vec::new();
522                loop {
523                    match fs::canonicalize(&current) {
524                        Ok(base) => {
525                            let mut result = base;
526                            for component in suffix.iter().rev() {
527                                result.push(component);
528                            }
529                            return result;
530                        }
531                        Err(_) => {
532                            if let Some(file_name) = current.file_name() {
533                                suffix.push(file_name.to_os_string());
534                                current = current
535                                    .parent()
536                                    .map(|p| p.to_path_buf())
537                                    .unwrap_or_default();
538                            } else {
539                                return path.to_path_buf();
540                            }
541                        }
542                    }
543                }
544            }
545        }
546    }
547
548    /// Return the canonical state path for this backend.
549    ///
550    /// This is used as the identity for the instance lock: two daemons with the
551    /// same canonical state path will contend for the same lock.
552    pub fn state_path(&self) -> PathBuf {
553        match self {
554            BackendConfig::Local { path } => Self::canonicalize_path(Path::new(path)),
555            BackendConfig::Pass {
556                store_path, path, ..
557            } => Self::canonicalize_path(&Path::new(store_path).join(path)),
558            #[cfg(feature = "tpm")]
559            BackendConfig::Tpm { path, .. } => Self::canonicalize_path(Path::new(path)),
560        }
561    }
562
563    /// Return a human-readable display string for the backend state path.
564    pub fn state_display(&self) -> String {
565        match self {
566            BackendConfig::Local { path } => path.clone(),
567            BackendConfig::Pass {
568                store_path, path, ..
569            } => {
570                format!("{}/{}", store_path, path)
571            }
572            #[cfg(feature = "tpm")]
573            BackendConfig::Tpm { path, .. } => path.clone(),
574        }
575    }
576
577    /// Validate backend configuration for security and correctness.
578    ///
579    /// This checks that paths are well-formed and don't escape their intended roots.
580    pub fn validate(&self) -> crate::error::Result<()> {
581        match self {
582            BackendConfig::Local { path } => {
583                let p = Path::new(path);
584                if !p.is_absolute() && !p.starts_with("~") {
585                    debug!("Local backend path is relative: {}, canonicalizing", path);
586                }
587                Ok(())
588            }
589            BackendConfig::Pass {
590                store_path, path, ..
591            } => {
592                let p = Path::new(path);
593                if p.is_absolute() {
594                    return Err(Error::Config(format!(
595                        "Pass backend 'path' must be relative, got absolute path: {}",
596                        path
597                    )));
598                }
599                if path.contains("..") {
600                    return Err(Error::Config(format!(
601                        "Pass backend 'path' must not contain '..': {}",
602                        path
603                    )));
604                }
605                // Verify the combined path doesn't escape the store
606                let combined = Path::new(store_path).join(path);
607                let canonical_store = Self::canonicalize_path(Path::new(store_path));
608                let canonical_combined = Self::canonicalize_path(&combined);
609                if !canonical_combined.starts_with(&canonical_store) {
610                    return Err(Error::Config(format!(
611                        "Pass backend 'path' escapes store_path: {} not beneath {}",
612                        canonical_combined.display(),
613                        canonical_store.display()
614                    )));
615                }
616                Ok(())
617            }
618            #[cfg(feature = "tpm")]
619            BackendConfig::Tpm { path, .. } => {
620                let p = Path::new(path);
621                if !p.is_absolute() && !p.starts_with("~") {
622                    debug!("TPM backend path is relative: {}, canonicalizing", path);
623                }
624                Ok(())
625            }
626        }
627    }
628}
629
630impl AppConfig {
631    /// The configuration file [`Self::load`] reads: `--config`/`PASSLESS_CONFIG`, else the default
632    /// `~/.config/passless/config.toml`, if it exists.
633    pub fn config_file_path(args: &Args) -> Option<PathBuf> {
634        let default_config_path = dirs::config_dir().map(|p| p.join("passless/config.toml"));
635        args.config_path
636            .clone()
637            .or(default_config_path)
638            .filter(|p| p.exists())
639    }
640
641    /// Load configuration with precedence: CLI > config file > defaults
642    pub fn load(args: &mut Args) -> crate::error::Result<Self> {
643        let config_file_path = Self::config_file_path(args);
644
645        if let Some(path) = config_file_path.as_ref()
646            && let Ok(f) = File::open(path)
647        {
648            log::info!("Loading configuration from: {}", path.display());
649            let content = std::io::read_to_string(BufReader::new(f)).unwrap_or_default();
650
651            #[cfg(feature = "agent")]
652            let agent_config = AgentConfig::from_toml_str(&content, &path.display().to_string())?;
653
654            match toml::from_str::<<AppConfig as ClapSerde>::Opt>(&content) {
655                Ok(file_config) => {
656                    #[allow(unused_mut)]
657                    let mut config = AppConfig::from(file_config).merge(&mut args.config);
658                    #[cfg(feature = "agent")]
659                    {
660                        config.agents = agent_config;
661                    }
662                    return Ok(config);
663                }
664                Err(e) => {
665                    return Err(Error::Config(format!(
666                        "failed to parse config file {}: {}",
667                        path.display(),
668                        e
669                    )));
670                }
671            }
672        }
673
674        #[allow(unused_mut)]
675        let mut config = AppConfig::from(&mut args.config);
676        #[cfg(feature = "agent")]
677        {
678            config.agents = AgentConfig::default();
679        }
680        Ok(config)
681    }
682
683    /// Get the backend configuration based on the backend_type
684    pub fn backend(&self) -> crate::error::Result<BackendConfig> {
685        match self.backend_type.as_str() {
686            "local" => Ok(BackendConfig::Local {
687                path: self.local.path.clone(),
688            }),
689            "pass" => Ok(BackendConfig::Pass {
690                store_path: self.pass.store_path.clone(),
691                path: self.pass.path.clone(),
692                gpg_backend: self.pass.gpg_backend.clone(),
693            }),
694            #[cfg(feature = "tpm")]
695            "tpm" => Ok(BackendConfig::Tpm {
696                path: self.tpm.path.clone(),
697                tcti: self.tpm.tcti.clone(),
698                portable: self.tpm.portable,
699            }),
700            _ => Err(crate::error::Error::Config(format!(
701                "Invalid backend_type '{}'. Must be one of: local, pass, tpm",
702                self.backend_type
703            ))),
704        }
705    }
706
707    /// Apply security hardening measures
708    pub fn apply_security_hardening(&self) -> Result<(), Box<dyn std::error::Error>> {
709        self.security.apply_hardening()
710    }
711
712    /// Get security configuration
713    pub fn security_config(&self) -> SecurityConfig {
714        self.security.clone()
715    }
716
717    /// Get PIN configuration
718    pub fn pin_config(&self) -> PinConfig {
719        self.pin.clone()
720    }
721
722    /// Validate the configuration
723    pub fn validate(&self) -> crate::error::Result<()> {
724        self.pin.validate()?;
725        #[cfg(feature = "agent")]
726        {
727            let human_path = self.backend().ok().map(|b| b.state_path());
728            self.agents.validate(human_path.as_deref())?;
729        }
730        Ok(())
731    }
732}
733
734/// CLI arguments structure
735#[derive(Parser)]
736#[command(author, version, about)]
737pub struct Args {
738    /// Path to configuration file (TOML format)
739    #[arg(short, long, env = "PASSLESS_CONFIG")]
740    pub config_path: Option<PathBuf>,
741
742    /// Application configuration (can come from CLI or config file)
743    #[command(flatten)]
744    pub config: <AppConfig as ClapSerde>::Opt,
745
746    /// Subcommands
747    #[command(subcommand)]
748    pub command: Option<Commands>,
749}
750
751/// Output format for client commands
752#[derive(Debug, Clone, Copy, PartialEq, Eq)]
753pub enum OutputFormat {
754    /// Human-readable plain text output
755    Plain,
756    /// JSON output for programmatic consumption
757    Json,
758}
759
760impl std::str::FromStr for OutputFormat {
761    type Err = String;
762
763    fn from_str(s: &str) -> Result<Self, Self::Err> {
764        match s.to_lowercase().as_str() {
765            "plain" => Ok(OutputFormat::Plain),
766            "json" => Ok(OutputFormat::Json),
767            _ => Err(format!(
768                "Invalid output format '{}'. Must be 'plain' or 'json'",
769                s
770            )),
771        }
772    }
773}
774
775impl std::fmt::Display for OutputFormat {
776    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
777        match self {
778            OutputFormat::Plain => write!(f, "plain"),
779            OutputFormat::Json => write!(f, "json"),
780        }
781    }
782}
783
784/// Subcommands for passless
785#[derive(Subcommand, Debug, Clone)]
786pub enum Commands {
787    /// Configuration management commands
788    Config {
789        #[command(subcommand)]
790        action: ConfigAction,
791    },
792    /// FIDO2 client commands for managing authenticators
793    ///
794    /// These commands require a running authenticator. For testing:
795    /// 1. Start authenticator: PASSLESS_E2E_AUTO_ACCEPT_UV=1 cargo run -- --backend-type local
796    /// 2. Run client commands in another terminal with the same environment variable
797    Client {
798        /// Select device by index (0-based) or name. Use 'devices' subcommand to list available devices.
799        #[arg(short = 'D', long = "device", value_name = "INDEX|NAME", global = true)]
800        device: Option<String>,
801
802        /// Output format: plain (default) or json
803        #[arg(
804            short = 'o',
805            long = "output",
806            value_name = "FORMAT",
807            default_value = "plain",
808            global = true
809        )]
810        output: OutputFormat,
811
812        #[command(subcommand)]
813        action: ClientAction,
814    },
815    /// Agent administration commands
816    #[cfg(feature = "agent")]
817    AgentAdmin {
818        /// Output format: json (default) or plain
819        #[arg(
820            short = 'o',
821            long = "output",
822            value_name = "FORMAT",
823            default_value = "json",
824            global = true
825        )]
826        output: OutputFormat,
827
828        #[command(subcommand)]
829        action: AgentAdminAction,
830    },
831    /// Check this host (does not need a running daemon)
832    #[cfg(feature = "agent")]
833    Doctor {
834        /// Check the agent browser path: a supported browser binary, the interception extension,
835        /// the native messaging host manifest, the notification bus, the state directory and the
836        /// containment of the native WebAuthn path
837        #[arg(long)]
838        agents: bool,
839
840        /// Output format: plain (default) or json
841        #[arg(
842            short = 'o',
843            long = "output",
844            value_name = "FORMAT",
845            default_value = "plain"
846        )]
847        output: OutputFormat,
848    },
849    /// Agent principal and session commands
850    #[cfg(feature = "agent")]
851    Agent {
852        /// Profile to use for principal commands
853        #[arg(long, value_name = "PROFILE", global = true)]
854        profile: Option<String>,
855
856        /// Output format: json (default) or plain
857        #[arg(
858            short = 'o',
859            long = "output",
860            value_name = "FORMAT",
861            default_value = "json",
862            global = true
863        )]
864        output: OutputFormat,
865
866        #[command(subcommand)]
867        action: crate::AgentCommand,
868    },
869    /// TPM portable parent management
870    #[cfg(feature = "tpm")]
871    Tpm {
872        #[command(subcommand)]
873        action: TpmAction,
874    },
875}
876
877/// TPM portable parent actions
878#[cfg(feature = "tpm")]
879#[derive(Subcommand, Debug, Clone)]
880pub enum TpmAction {
881    /// Provision the portable TPM parent from a recovery seed
882    #[command(group(clap::ArgGroup::new("seed-source").args(["generate", "seed_file", "seed_stdin"])))]
883    Provision {
884        /// Generate a new random 32-byte recovery seed and print it
885        #[arg(long)]
886        generate: bool,
887        /// Read the recovery seed (hex) from this file instead of prompting
888        #[arg(long = "seed-file", value_name = "PATH")]
889        seed_file: Option<PathBuf>,
890        /// Read the recovery seed (hex) from stdin instead of prompting
891        #[arg(long = "seed-stdin")]
892        seed_stdin: bool,
893        /// TPM storage directory
894        #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
895        path: Option<String>,
896        /// TPM TCTI configuration
897        #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
898        tcti: Option<String>,
899    },
900    /// Show provisioning status
901    Status {
902        /// TPM storage directory
903        #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
904        path: Option<String>,
905        /// TPM TCTI configuration
906        #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
907        tcti: Option<String>,
908    },
909    /// Remove the provisioned portable parent
910    Remove {
911        /// Confirm the removal
912        #[arg(long)]
913        confirm: bool,
914        /// TPM storage directory
915        #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
916        path: Option<String>,
917        /// TPM TCTI configuration
918        #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
919        tcti: Option<String>,
920    },
921    /// Migrate legacy sealed credentials to portable TPM format
922    #[command(group(clap::ArgGroup::new("selection").args(["credential_id", "all"]).required(true)))]
923    Migrate {
924        /// Migrate a specific credential by ID (hex)
925        #[arg(long = "credential-id", value_name = "ID")]
926        credential_id: Option<String>,
927        /// Migrate all migratable legacy credentials
928        #[arg(long)]
929        all: bool,
930        /// Show what would be migrated without making changes
931        #[arg(long)]
932        dry_run: bool,
933        /// Directory to store backups of legacy records
934        #[arg(long = "backup-dir", value_name = "PATH")]
935        backup_dir: Option<String>,
936        /// TPM storage directory
937        #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
938        path: Option<String>,
939        /// TPM TCTI configuration
940        #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
941        tcti: Option<String>,
942    },
943}
944
945/// Configuration actions
946#[derive(Subcommand, Debug, Clone)]
947pub enum ConfigAction {
948    /// Print the default configuration in TOML format
949    Print,
950}
951
952/// Agent administration actions
953#[cfg(feature = "agent")]
954#[derive(Subcommand, Debug, Clone)]
955pub enum AgentAdminAction {
956    /// Install the Passless skill for a supported coding agent
957    Install {
958        /// Agent to install for; auto installs to every detected agent
959        #[arg(value_enum, default_value_t = AgentSkillTarget::Auto)]
960        target: AgentSkillTarget,
961
962        /// Install for the current user or the current Git worktree
963        #[arg(long, value_enum, default_value_t = AgentSkillScope::User)]
964        scope: AgentSkillScope,
965
966        /// Replace a different existing file at the skill target
967        #[arg(long)]
968        force: bool,
969    },
970    /// Profile management
971    Profile {
972        #[command(subcommand)]
973        action: AdminProfileAction,
974    },
975    /// Policy management
976    Policy {
977        #[command(subcommand)]
978        action: AdminPolicyAction,
979    },
980    /// Credential management
981    Credential {
982        #[command(subcommand)]
983        action: AdminCredentialAction,
984    },
985    /// Persistent granted rules (escalation approvals)
986    Grants {
987        #[command(subcommand)]
988        action: AdminGrantsAction,
989    },
990    /// Browser bearer sessions (session grants)
991    #[command(alias = "delegation")]
992    Sessions {
993        #[command(subcommand)]
994        action: AdminSessionsAction,
995    },
996    /// Principal sessions
997    #[command(alias = "session")]
998    Principals {
999        #[command(subcommand)]
1000        action: AdminPrincipalsAction,
1001    },
1002    /// Browser session management
1003    Browser {
1004        #[command(subcommand)]
1005        action: AdminBrowserAction,
1006    },
1007    /// Audit log management
1008    Audit {
1009        #[command(subcommand)]
1010        action: AdminAuditAction,
1011    },
1012    /// Shut down the running daemon
1013    #[command(hide = true)]
1014    Shutdown {
1015        /// Confirm the shutdown
1016        #[arg(long)]
1017        confirm: bool,
1018    },
1019}
1020
1021/// Admin profile actions
1022#[cfg(feature = "agent")]
1023#[derive(Subcommand, Debug, Clone)]
1024pub enum AdminProfileAction {
1025    /// Check if a profile exists and is valid
1026    Check {
1027        /// Profile identifier
1028        #[arg(value_name = "PROFILE")]
1029        profile: String,
1030    },
1031    /// Show profile details
1032    Show {
1033        /// Profile identifier
1034        #[arg(value_name = "PROFILE")]
1035        profile: String,
1036    },
1037    /// List all configured profiles
1038    List,
1039    /// Enable a profile
1040    Enable {
1041        /// Profile identifier
1042        #[arg(value_name = "PROFILE")]
1043        profile: String,
1044    },
1045    /// Disable a profile
1046    Disable {
1047        /// Profile identifier
1048        #[arg(value_name = "PROFILE")]
1049        profile: String,
1050    },
1051}
1052
1053/// Admin policy actions
1054#[cfg(feature = "agent")]
1055#[derive(Subcommand, Debug, Clone)]
1056pub enum AdminPolicyAction {
1057    /// Check policy validity for a profile
1058    Check {
1059        /// Profile identifier
1060        #[arg(value_name = "PROFILE")]
1061        profile: String,
1062    },
1063    /// Reload policy for a profile
1064    Reload {
1065        /// Profile identifier
1066        #[arg(value_name = "PROFILE")]
1067        profile: String,
1068    },
1069    /// Show current policy for a profile
1070    Show {
1071        /// Profile identifier
1072        #[arg(value_name = "PROFILE")]
1073        profile: String,
1074    },
1075}
1076
1077/// Admin credential actions
1078#[cfg(feature = "agent")]
1079#[derive(Subcommand, Debug, Clone)]
1080pub enum AdminCredentialAction {
1081    /// List credentials
1082    List {
1083        /// Filter by relying party ID
1084        #[arg(short = 'd', long = "domain", value_name = "DOMAIN")]
1085        rp_id: Option<String>,
1086    },
1087    /// Show credential details
1088    Show {
1089        /// Credential reference (hex)
1090        #[arg(value_name = "CREDENTIAL_REF")]
1091        credential_ref: String,
1092    },
1093    /// Revoke a credential
1094    Revoke {
1095        /// Credential reference (hex)
1096        #[arg(value_name = "CREDENTIAL_REF")]
1097        credential_ref: String,
1098        /// Confirm the revocation
1099        #[arg(long)]
1100        confirm: bool,
1101    },
1102    /// Delete a credential
1103    Delete {
1104        /// Credential reference (hex)
1105        #[arg(value_name = "CREDENTIAL_REF")]
1106        credential_ref: String,
1107        /// Confirm the deletion
1108        #[arg(long)]
1109        confirm: bool,
1110    },
1111}
1112
1113/// Admin granted-rule actions (ADR 0014 section 8.4)
1114#[cfg(feature = "agent")]
1115#[derive(Subcommand, Debug, Clone)]
1116pub enum AdminGrantsAction {
1117    /// List granted rules
1118    List {
1119        /// Filter by profile
1120        #[arg(long, value_name = "PROFILE")]
1121        profile: Option<String>,
1122    },
1123    /// Revoke the granted rule of one RP
1124    Revoke {
1125        /// Profile identifier
1126        #[arg(long, value_name = "PROFILE")]
1127        profile: String,
1128        /// Relying party ID
1129        #[arg(long = "rp", value_name = "RP_ID")]
1130        rp_id: String,
1131        /// Action of the granted rule
1132        #[arg(long, value_enum, default_value_t = AdminGrantAction::Authenticate)]
1133        action: AdminGrantAction,
1134        /// Confirm the revocation
1135        #[arg(long)]
1136        confirm: bool,
1137    },
1138    /// Revoke every granted rule of a profile
1139    Clear {
1140        /// Profile identifier
1141        #[arg(long, value_name = "PROFILE")]
1142        profile: String,
1143        /// Confirm the revocation
1144        #[arg(long)]
1145        confirm: bool,
1146    },
1147}
1148
1149/// Action of a granted rule (only `authenticate` is ever granted)
1150#[cfg(feature = "agent")]
1151#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1152pub enum AdminGrantAction {
1153    Authenticate,
1154}
1155
1156/// Admin browser bearer session actions
1157#[cfg(feature = "agent")]
1158#[derive(Subcommand, Debug, Clone)]
1159pub enum AdminSessionsAction {
1160    /// Show session grant details
1161    Show {
1162        /// Grant identifier (hex)
1163        #[arg(value_name = "GRANT_ID")]
1164        grant_id: String,
1165    },
1166    /// List all session grants
1167    List {
1168        /// Filter by profile
1169        #[arg(long, value_name = "PROFILE")]
1170        profile: Option<String>,
1171    },
1172    /// Revoke a session grant
1173    Revoke {
1174        /// Grant identifier (hex)
1175        #[arg(value_name = "GRANT_ID")]
1176        grant_id: String,
1177        /// Confirm the revocation
1178        #[arg(long)]
1179        confirm: bool,
1180    },
1181}
1182
1183/// Admin principal session actions
1184#[cfg(feature = "agent")]
1185#[derive(Subcommand, Debug, Clone)]
1186pub enum AdminPrincipalsAction {
1187    /// Show principal session details
1188    Show {
1189        /// Session identifier (hex)
1190        #[arg(value_name = "SESSION_ID")]
1191        session_id: String,
1192    },
1193    /// List all sessions
1194    List {
1195        /// Filter by profile
1196        #[arg(long, value_name = "PROFILE")]
1197        profile: Option<String>,
1198    },
1199    /// Revoke a session
1200    Revoke {
1201        /// Session identifier (hex)
1202        #[arg(value_name = "SESSION_ID")]
1203        session_id: String,
1204        /// Confirm the revocation
1205        #[arg(long)]
1206        confirm: bool,
1207    },
1208}
1209
1210/// Admin browser actions
1211#[cfg(feature = "agent")]
1212#[derive(Subcommand, Debug, Clone)]
1213pub enum AdminBrowserAction {
1214    /// Launch a browser session with the agent extension
1215    Launch {
1216        /// Profile identifier
1217        #[arg(long, value_name = "PROFILE")]
1218        profile: String,
1219        /// Start URL to open in the browser
1220        #[arg(long, value_name = "URL")]
1221        url: Option<String>,
1222    },
1223}
1224
1225/// Admin audit actions
1226#[cfg(feature = "agent")]
1227#[derive(Subcommand, Debug, Clone)]
1228pub enum AdminAuditAction {
1229    /// Show audit subsystem status
1230    Status,
1231    /// Verify audit log integrity
1232    Verify,
1233    /// Export audit log entries
1234    Export {
1235        /// Export format
1236        #[arg(long, value_enum, default_value_t = AdminAuditExportFormat::Json)]
1237        format: AdminAuditExportFormat,
1238    },
1239}
1240
1241/// Audit export format for CLI
1242#[cfg(feature = "agent")]
1243#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1244pub enum AdminAuditExportFormat {
1245    Json,
1246    Csv,
1247}
1248
1249/// Supported coding-agent skill targets
1250#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1251pub enum AgentSkillTarget {
1252    Auto,
1253    Opencode,
1254    Claude,
1255    Pi,
1256}
1257
1258/// Skill installation scope
1259#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1260pub enum AgentSkillScope {
1261    User,
1262    Project,
1263}
1264
1265/// Client actions for FIDO2 authenticator management
1266#[derive(Subcommand, Debug, Clone)]
1267pub enum ClientAction {
1268    /// List all available FIDO2 authenticators/devices
1269    Devices,
1270    /// Get authenticator information (capabilities, AAGUID, versions, etc.)
1271    Info,
1272    /// Reset the authenticator (WARNING: deletes ALL credentials)
1273    Reset {
1274        /// Confirmation flag that must be provided twice for safety
1275        #[arg(long = "yes-i-really-want-to-reset-my-device", action = ArgAction::Count)]
1276        confirm: u8,
1277    },
1278    /// List all credentials on the authenticator
1279    List {
1280        /// Filter by relying party ID (domain)
1281        #[arg(short = 'd', long = "domain", value_name = "DOMAIN")]
1282        rp_id: Option<String>,
1283    },
1284    /// Show detailed information about a specific credential
1285    Show {
1286        /// Credential ID in hexadecimal format
1287        #[arg(value_name = "CREDENTIAL_ID")]
1288        credential_id: String,
1289    },
1290    /// Delete a specific credential by ID
1291    Delete {
1292        /// Credential ID in hexadecimal format
1293        #[arg(value_name = "CREDENTIAL_ID")]
1294        credential_id: String,
1295    },
1296    /// Rename a credential (update user name and/or display name)
1297    Rename {
1298        /// Credential ID in hexadecimal format
1299        #[arg(value_name = "CREDENTIAL_ID")]
1300        credential_id: String,
1301        /// New user name (login identifier)
1302        #[arg(short = 'u', long = "user-name", value_name = "NAME")]
1303        user_name: Option<String>,
1304        /// New display name (friendly name)
1305        #[arg(short = 'n', long = "display-name", value_name = "NAME")]
1306        display_name: Option<String>,
1307    },
1308    /// Export one software-backed credential as an opaque encrypted bundle.
1309    Backup {
1310        /// Credential ID in hexadecimal format
1311        #[arg(value_name = "CREDENTIAL_ID")]
1312        credential_id: String,
1313        /// Authenticator-local credential-backup wrapping-key identifier
1314        #[arg(long, value_name = "RECIPIENT")]
1315        recipient: String,
1316        /// Destination bundle path
1317        #[arg(long, value_name = "PATH")]
1318        output_file: PathBuf,
1319        /// Explicitly acknowledge that a passkey is being exported
1320        #[arg(long = "yes-i-understand-this-exports-a-passkey")]
1321        confirm: bool,
1322    },
1323    /// Restore an encrypted Passless credential bundle.
1324    Restore {
1325        /// Source bundle path
1326        #[arg(value_name = "PATH")]
1327        input_file: PathBuf,
1328        /// Replace a credential with the same ID
1329        #[arg(long)]
1330        replace: bool,
1331        /// Explicitly acknowledge that a passkey is being restored
1332        #[arg(long = "yes-i-understand-this-restores-a-passkey")]
1333        confirm: bool,
1334    },
1335    /// PIN management commands
1336    Pin {
1337        #[command(subcommand)]
1338        action: PinAction,
1339    },
1340}
1341
1342/// PIN management actions
1343#[derive(Subcommand, Debug, Clone)]
1344pub enum PinAction {
1345    /// Set a new PIN (authenticator must not have a PIN set)
1346    Set {
1347        /// The new PIN (minimum 4 characters)
1348        #[arg(value_name = "PIN")]
1349        pin: String,
1350    },
1351    /// Change the existing PIN
1352    Change {
1353        /// The current PIN
1354        #[arg(value_name = "OLD_PIN")]
1355        old_pin: String,
1356        /// The new PIN (minimum 4 characters)
1357        #[arg(value_name = "NEW_PIN")]
1358        new_pin: String,
1359    },
1360    /// Reset built-in user verification retries without deleting credentials
1361    UvReset,
1362}
1363
1364/// Agent principal and session commands
1365#[cfg(feature = "agent")]
1366#[derive(Subcommand, Debug, Clone)]
1367pub enum AgentCommand {
1368    /// Run health diagnostics
1369    Doctor,
1370    /// Show the profile's effective authority (per-RP rules, credential scope, session limits)
1371    Capabilities,
1372    /// Show principal instructions
1373    Instructions,
1374    /// Credential queries
1375    Credential {
1376        #[command(subcommand)]
1377        action: AgentCredentialAction,
1378    },
1379    /// Show browser bridge status
1380    BrowserStatus,
1381    /// Send a CDP command to the managed browser session
1382    ///
1383    /// WARNING: This is the full browser-session authority interface.
1384    /// CDP commands can access cookies, DOM, network state, and session data.
1385    /// Output may contain CDP response data — do not mix with credential/admin output.
1386    BrowserControl {
1387        /// CDP request as JSON (e.g. '{"id":1,"method":"Page.navigate","params":{"url":"https://example.com"}}')
1388        #[arg(long, value_name = "JSON", conflicts_with = "request_file")]
1389        request: Option<String>,
1390        /// Path to file containing CDP request JSON (owner/symlink/size checked)
1391        #[arg(long, value_name = "PATH", conflicts_with = "request")]
1392        request_file: Option<std::path::PathBuf>,
1393        /// Timeout in milliseconds (default: 5000, max: 30000)
1394        #[arg(long, value_name = "MS", default_value = "5000")]
1395        timeout_ms: u32,
1396    },
1397    /// Ensure the managed browser of this principal and print how to reach it
1398    ///
1399    /// Idempotent: the browser is started on the first call and the same endpoint is printed
1400    /// while it runs (the profile's `browser_scope` decides whether sessions share it). The
1401    /// endpoint is withheld until the interception extension is attached and allowed in
1402    /// incognito, so a printed endpoint is always an intercepted browser. With
1403    /// `browser_cdp_expose = "port"` the CDP endpoint is printed. In pipe mode (the default)
1404    /// there is no endpoint: the browser is ensured and CDP goes through
1405    /// `passless agent browser-control`. It must run inside a principal session of the profile
1406    /// (the browser is closed when that session ends), e.g. an agent started with
1407    /// `passless agent run --profile P -- <command>`.
1408    Browser {
1409        /// Print JSON ({endpoint, ...}) instead of the bare endpoint URL
1410        #[arg(long, conflicts_with = "env")]
1411        json: bool,
1412        /// Print `PASSLESS_CDP_URL=<endpoint>`, for `eval` or a dotenv file
1413        #[arg(long)]
1414        env: bool,
1415        /// Block until the browser is intercepting (attached, incognito allowed) before printing
1416        #[arg(long)]
1417        wait: bool,
1418        /// Start a headed browser instead of the default `--headless=new`
1419        #[arg(long)]
1420        headed: bool,
1421        /// Open this URL once interception is attached
1422        #[arg(long, value_name = "URL")]
1423        url: Option<String>,
1424    },
1425    /// MCP server adapters for the managed browser (stdio launchers)
1426    #[command(args_conflicts_with_subcommands = true)]
1427    Mcp {
1428        /// Print a ready-to-paste MCP server entry for a client instead of running a server
1429        #[arg(long, value_enum, value_name = "CLIENT")]
1430        print_config: Option<McpConfigTarget>,
1431        /// The adapter the printed entry runs
1432        #[arg(long, value_enum, default_value_t = McpAdapterKind::Playwright, requires = "print_config")]
1433        server: McpAdapterKind,
1434        #[command(subcommand)]
1435        adapter: Option<McpAdapter>,
1436    },
1437    /// Run Playwright MCP with lazy access to the profile's trusted CDP browser
1438    ///
1439    /// Deprecated alias of `agent mcp playwright`, kept for one release.
1440    #[command(hide = true)]
1441    PlaywrightMcp {
1442        /// Profile to bind the Playwright session to
1443        #[arg(long, value_name = "PROFILE")]
1444        profile: String,
1445        /// Start URL to open in the managed browser
1446        #[arg(long, value_name = "URL")]
1447        url: Option<String>,
1448        /// Absolute Playwright MCP executable and arguments
1449        #[arg(last = true, required = true)]
1450        command: Vec<std::path::PathBuf>,
1451    },
1452    /// Launch a detached principal session
1453    Run {
1454        /// Profile to launch
1455        #[arg(long, value_name = "PROFILE")]
1456        profile: String,
1457        /// Absolute command path and arguments
1458        #[arg(last = true, required = true)]
1459        command: Vec<std::path::PathBuf>,
1460    },
1461}
1462
1463/// An MCP server the adapters run against the managed browser.
1464#[cfg(feature = "agent")]
1465#[derive(Subcommand, Debug, Clone)]
1466pub enum McpAdapter {
1467    /// Run `npx @playwright/mcp --cdp-endpoint <url>` (the endpoint is resolved on first use)
1468    Playwright {
1469        /// npm package to run (default `@playwright/mcp`; pin a version here)
1470        #[arg(long, value_name = "SPEC")]
1471        package: Option<String>,
1472        /// npx executable (default: `npx` from PATH)
1473        #[arg(long, value_name = "PATH")]
1474        npx: Option<std::path::PathBuf>,
1475        /// Open this URL once interception is attached
1476        #[arg(long, value_name = "URL")]
1477        url: Option<String>,
1478        /// Extra arguments for @playwright/mcp (after `--`)
1479        #[arg(last = true)]
1480        extra: Vec<String>,
1481    },
1482    /// Run `npx chrome-devtools-mcp --browserUrl <url>`
1483    ///
1484    /// The browser starts when the server starts: puppeteer asks `<browserUrl>/json/version`
1485    /// at the root of the URL and cannot send the bootstrap's bearer header, so a lazy,
1486    /// authenticated discovery endpoint is not possible.
1487    ChromeDevtools {
1488        /// npm package to run (default `chrome-devtools-mcp`; pin a version here)
1489        #[arg(long, value_name = "SPEC")]
1490        package: Option<String>,
1491        /// npx executable (default: `npx` from PATH)
1492        #[arg(long, value_name = "PATH")]
1493        npx: Option<std::path::PathBuf>,
1494        /// Open this URL once interception is attached
1495        #[arg(long, value_name = "URL")]
1496        url: Option<String>,
1497        /// Extra arguments for chrome-devtools-mcp (after `--`)
1498        #[arg(last = true)]
1499        extra: Vec<String>,
1500    },
1501}
1502
1503/// Which adapter `agent mcp --print-config` prints an entry for.
1504#[cfg(feature = "agent")]
1505#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1506pub enum McpAdapterKind {
1507    Playwright,
1508    ChromeDevtools,
1509}
1510
1511/// MCP clients `agent mcp --print-config` knows the configuration format of.
1512#[cfg(feature = "agent")]
1513#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1514pub enum McpConfigTarget {
1515    /// `.mcp.json` / `claude mcp add-json`
1516    ClaudeCode,
1517    /// `opencode.json`
1518    Opencode,
1519    /// `.cursor/mcp.json`
1520    Cursor,
1521    /// `.vscode/mcp.json`
1522    Vscode,
1523}
1524
1525/// Agent credential actions
1526#[cfg(feature = "agent")]
1527#[derive(Subcommand, Debug, Clone)]
1528pub enum AgentCredentialAction {
1529    /// List credentials for the profile
1530    List,
1531    /// Show credential details
1532    Show {
1533        /// Credential reference (hex)
1534        #[arg(value_name = "CREDENTIAL_REF")]
1535        credential_ref: String,
1536    },
1537}
1538
1539#[cfg(test)]
1540mod tests {
1541    use super::*;
1542
1543    #[cfg(feature = "agent")]
1544    #[test]
1545    fn test_agent_admin_install_defaults() {
1546        let args = Args::try_parse_from(["passless", "agent-admin", "install"]).unwrap();
1547        assert!(matches!(
1548            args.command,
1549            Some(Commands::AgentAdmin {
1550                action: AgentAdminAction::Install {
1551                    target: AgentSkillTarget::Auto,
1552                    scope: AgentSkillScope::User,
1553                    force: false,
1554                },
1555                ..
1556            })
1557        ));
1558    }
1559
1560    #[cfg(feature = "agent")]
1561    #[test]
1562    fn test_agent_admin_install_explicit_options() {
1563        let args = Args::try_parse_from([
1564            "passless",
1565            "agent-admin",
1566            "install",
1567            "claude",
1568            "--scope",
1569            "project",
1570            "--force",
1571        ])
1572        .unwrap();
1573        assert!(matches!(
1574            args.command,
1575            Some(Commands::AgentAdmin {
1576                action: AgentAdminAction::Install {
1577                    target: AgentSkillTarget::Claude,
1578                    scope: AgentSkillScope::Project,
1579                    force: true,
1580                },
1581                ..
1582            })
1583        ));
1584    }
1585
1586    #[test]
1587    fn test_pin_config_default_max_uv_retries() {
1588        let config = PinConfig {
1589            enforcement: PinEnforcement::Optional,
1590            min_length: 4,
1591            max_retries: 8,
1592            max_uv_retries: 8,
1593            auto_lock_timeout: 0,
1594        };
1595        assert_eq!(config.max_uv_retries, 8);
1596    }
1597
1598    #[test]
1599    fn test_pin_config_validate_success() {
1600        let config = PinConfig {
1601            enforcement: PinEnforcement::Optional,
1602            min_length: 4,
1603            max_retries: 8,
1604            max_uv_retries: 8,
1605            auto_lock_timeout: 0,
1606        };
1607        assert!(config.validate().is_ok());
1608    }
1609
1610    #[test]
1611    fn test_pin_config_validate_zero_max_uv_retries() {
1612        let config = PinConfig {
1613            enforcement: PinEnforcement::Optional,
1614            min_length: 4,
1615            max_retries: 8,
1616            max_uv_retries: 0,
1617            auto_lock_timeout: 0,
1618        };
1619        let result = config.validate();
1620        assert!(result.is_err());
1621        assert!(result.unwrap_err().to_string().contains("max_uv_retries"));
1622    }
1623
1624    #[test]
1625    fn test_pin_config_validate_zero_max_retries() {
1626        let config = PinConfig {
1627            enforcement: PinEnforcement::Optional,
1628            min_length: 4,
1629            max_retries: 0,
1630            max_uv_retries: 8,
1631            auto_lock_timeout: 0,
1632        };
1633        let result = config.validate();
1634        assert!(result.is_err());
1635        assert!(result.unwrap_err().to_string().contains("max_retries"));
1636    }
1637
1638    #[test]
1639    fn test_pin_config_validate_invalid_min_length() {
1640        let config = PinConfig {
1641            enforcement: PinEnforcement::Optional,
1642            min_length: 3,
1643            max_retries: 8,
1644            max_uv_retries: 8,
1645            auto_lock_timeout: 0,
1646        };
1647        let result = config.validate();
1648        assert!(result.is_err());
1649        assert!(result.unwrap_err().to_string().contains("min_length"));
1650    }
1651
1652    #[test]
1653    fn test_canonicalize_path_existing() {
1654        let dir = std::env::temp_dir();
1655        let canonical = BackendConfig::canonicalize_path(&dir);
1656        assert!(canonical.is_absolute());
1657        assert!(canonical.exists());
1658    }
1659
1660    #[test]
1661    fn test_canonicalize_path_nonexistent() {
1662        let base = std::env::temp_dir();
1663        let nonexistent = base.join("passless_test_nonexistent_dir_12345/sub");
1664        let canonical = BackendConfig::canonicalize_path(&nonexistent);
1665        assert!(canonical.is_absolute());
1666        assert!(canonical.starts_with(BackendConfig::canonicalize_path(&base)));
1667    }
1668
1669    #[test]
1670    fn test_canonicalize_path_symlink() {
1671        let dir = tempfile::tempdir().unwrap();
1672        let real = dir.path().join("real");
1673        std::fs::create_dir(&real).unwrap();
1674        let link = dir.path().join("link");
1675        std::os::unix::fs::symlink(&real, &link).unwrap();
1676
1677        let canonical_real = BackendConfig::canonicalize_path(&real);
1678        let canonical_link = BackendConfig::canonicalize_path(&link);
1679        assert_eq!(canonical_real, canonical_link);
1680    }
1681
1682    #[test]
1683    fn test_local_state_path_relative_and_absolute() {
1684        let dir = tempfile::tempdir_in(".").unwrap();
1685        let abs_path = std::fs::canonicalize(dir.path()).unwrap();
1686        let rel_path = dir.path().to_path_buf();
1687
1688        let backend_abs = BackendConfig::Local {
1689            path: abs_path.display().to_string(),
1690        };
1691        let backend_rel = BackendConfig::Local {
1692            path: rel_path.display().to_string(),
1693        };
1694        assert_eq!(backend_abs.state_path(), backend_rel.state_path());
1695    }
1696
1697    #[test]
1698    fn test_pass_state_path_different_subpaths() {
1699        let store = "/tmp/passless_test_store";
1700        let backend_a = BackendConfig::Pass {
1701            store_path: store.to_string(),
1702            path: "fido2".to_string(),
1703            gpg_backend: "gnupg-bin".to_string(),
1704        };
1705        let backend_b = BackendConfig::Pass {
1706            store_path: store.to_string(),
1707            path: "fido2-other".to_string(),
1708            gpg_backend: "gnupg-bin".to_string(),
1709        };
1710        assert_ne!(backend_a.state_path(), backend_b.state_path());
1711    }
1712
1713    #[test]
1714    fn test_different_local_paths_produce_different_identities() {
1715        let backend_a = BackendConfig::Local {
1716            path: "/tmp/passless_a".to_string(),
1717        };
1718        let backend_b = BackendConfig::Local {
1719            path: "/tmp/passless_b".to_string(),
1720        };
1721        assert_ne!(backend_a.state_path(), backend_b.state_path());
1722    }
1723
1724    #[cfg(feature = "agent")]
1725    #[test]
1726    fn test_agent_admin_profile_list() {
1727        let args = Args::try_parse_from(["passless", "agent-admin", "profile", "list"]).unwrap();
1728        assert!(matches!(
1729            args.command,
1730            Some(Commands::AgentAdmin {
1731                action: AgentAdminAction::Profile {
1732                    action: AdminProfileAction::List,
1733                },
1734                ..
1735            })
1736        ));
1737    }
1738
1739    #[cfg(feature = "agent")]
1740    #[test]
1741    fn test_agent_admin_credential_delete_without_confirm() {
1742        let args = Args::try_parse_from([
1743            "passless",
1744            "agent-admin",
1745            "credential",
1746            "delete",
1747            "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
1748        ])
1749        .unwrap();
1750        assert!(matches!(
1751            args.command,
1752            Some(Commands::AgentAdmin {
1753                action: AgentAdminAction::Credential {
1754                    action: AdminCredentialAction::Delete { confirm: false, .. },
1755                },
1756                ..
1757            })
1758        ));
1759    }
1760
1761    #[cfg(feature = "agent")]
1762    #[test]
1763    fn test_agent_admin_credential_delete_with_confirm() {
1764        let args = Args::try_parse_from([
1765            "passless",
1766            "agent-admin",
1767            "credential",
1768            "delete",
1769            "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
1770            "--confirm",
1771        ])
1772        .unwrap();
1773        assert!(matches!(
1774            args.command,
1775            Some(Commands::AgentAdmin {
1776                action: AgentAdminAction::Credential {
1777                    action: AdminCredentialAction::Delete { confirm: true, .. },
1778                },
1779                ..
1780            })
1781        ));
1782    }
1783
1784    #[cfg(feature = "agent")]
1785    #[test]
1786    fn test_agent_admin_shutdown_hidden() {
1787        let args =
1788            Args::try_parse_from(["passless", "agent-admin", "shutdown", "--confirm"]).unwrap();
1789        assert!(matches!(
1790            args.command,
1791            Some(Commands::AgentAdmin {
1792                action: AgentAdminAction::Shutdown { confirm: true },
1793                ..
1794            })
1795        ));
1796    }
1797
1798    #[cfg(feature = "agent")]
1799    #[test]
1800    fn test_agent_admin_output_default_json() {
1801        let args = Args::try_parse_from(["passless", "agent-admin", "profile", "list"]).unwrap();
1802        match args.command {
1803            Some(Commands::AgentAdmin { output, .. }) => {
1804                assert_eq!(output, OutputFormat::Json);
1805            }
1806            _ => panic!("expected AgentAdmin command"),
1807        }
1808    }
1809
1810    #[cfg(feature = "agent")]
1811    #[test]
1812    fn test_agent_admin_output_plain() {
1813        let args = Args::try_parse_from([
1814            "passless",
1815            "agent-admin",
1816            "--output",
1817            "plain",
1818            "profile",
1819            "list",
1820        ])
1821        .unwrap();
1822        match args.command {
1823            Some(Commands::AgentAdmin { output, .. }) => {
1824                assert_eq!(output, OutputFormat::Plain);
1825            }
1826            _ => panic!("expected AgentAdmin command"),
1827        }
1828    }
1829
1830    #[cfg(feature = "agent")]
1831    #[test]
1832    fn test_agent_doctor_parses() {
1833        let args = Args::try_parse_from(["passless", "agent", "doctor"]).unwrap();
1834        assert!(matches!(
1835            args.command,
1836            Some(Commands::Agent {
1837                action: AgentCommand::Doctor,
1838                ..
1839            })
1840        ));
1841    }
1842
1843    #[cfg(feature = "agent")]
1844    #[test]
1845    fn test_agent_browser_parses() {
1846        let args = Args::try_parse_from([
1847            "passless",
1848            "agent",
1849            "--profile",
1850            "p",
1851            "browser",
1852            "--json",
1853            "--wait",
1854            "--headed",
1855        ])
1856        .unwrap();
1857        let Some(Commands::Agent {
1858            profile,
1859            action:
1860                AgentCommand::Browser {
1861                    json,
1862                    env,
1863                    wait,
1864                    headed,
1865                    url,
1866                },
1867            ..
1868        }) = args.command
1869        else {
1870            panic!("not agent browser");
1871        };
1872        assert_eq!(profile.as_deref(), Some("p"));
1873        assert!(json && wait && headed && !env && url.is_none());
1874        // `--profile` after the subcommand works too (it is global), and `--json` excludes `--env`.
1875        let args =
1876            Args::try_parse_from(["passless", "agent", "browser", "--env", "--profile", "p"])
1877                .unwrap();
1878        assert!(matches!(
1879            args.command,
1880            Some(Commands::Agent {
1881                action: AgentCommand::Browser { env: true, .. },
1882                ..
1883            })
1884        ));
1885        assert!(Args::try_parse_from(["passless", "agent", "browser", "--json", "--env"]).is_err());
1886    }
1887
1888    #[cfg(feature = "agent")]
1889    #[test]
1890    fn test_agent_mcp_parses() {
1891        let args = Args::try_parse_from([
1892            "passless",
1893            "agent",
1894            "mcp",
1895            "playwright",
1896            "--profile",
1897            "p",
1898            "--",
1899            "--isolated",
1900        ])
1901        .unwrap();
1902        let Some(Commands::Agent {
1903            action:
1904                AgentCommand::Mcp {
1905                    adapter: Some(McpAdapter::Playwright { extra, .. }),
1906                    print_config: None,
1907                    ..
1908                },
1909            profile,
1910            ..
1911        }) = args.command
1912        else {
1913            panic!("not agent mcp playwright");
1914        };
1915        assert_eq!(profile.as_deref(), Some("p"));
1916        assert_eq!(extra, ["--isolated"]);
1917
1918        let args = Args::try_parse_from(["passless", "agent", "mcp", "chrome-devtools"]).unwrap();
1919        assert!(matches!(
1920            args.command,
1921            Some(Commands::Agent {
1922                action: AgentCommand::Mcp {
1923                    adapter: Some(McpAdapter::ChromeDevtools { .. }),
1924                    ..
1925                },
1926                ..
1927            })
1928        ));
1929
1930        for (name, target) in [
1931            ("claude-code", McpConfigTarget::ClaudeCode),
1932            ("opencode", McpConfigTarget::Opencode),
1933            ("cursor", McpConfigTarget::Cursor),
1934            ("vscode", McpConfigTarget::Vscode),
1935        ] {
1936            let args = Args::try_parse_from([
1937                "passless",
1938                "agent",
1939                "--profile",
1940                "p",
1941                "mcp",
1942                "--print-config",
1943                name,
1944            ])
1945            .unwrap();
1946            assert!(matches!(
1947                args.command,
1948                Some(Commands::Agent {
1949                    action: AgentCommand::Mcp { print_config: Some(t), adapter: None, .. },
1950                    ..
1951                }) if t == target
1952            ));
1953        }
1954        assert!(
1955            Args::try_parse_from(["passless", "agent", "mcp", "--print-config", "emacs"]).is_err()
1956        );
1957        // The old name still parses (hidden alias, one release).
1958        assert!(
1959            Args::try_parse_from([
1960                "passless",
1961                "agent",
1962                "playwright-mcp",
1963                "--profile",
1964                "p",
1965                "--",
1966                "/usr/bin/npx",
1967                "x",
1968            ])
1969            .is_ok()
1970        );
1971    }
1972
1973    #[cfg(feature = "agent")]
1974    #[test]
1975    fn test_doctor_agents_parses() {
1976        let args = Args::try_parse_from(["passless", "doctor", "--agents", "-o", "json"]).unwrap();
1977        assert!(matches!(
1978            args.command,
1979            Some(Commands::Doctor {
1980                agents: true,
1981                output: OutputFormat::Json
1982            })
1983        ));
1984    }
1985
1986    #[cfg(feature = "agent")]
1987    #[test]
1988    fn test_agent_run_with_command() {
1989        let args = Args::try_parse_from([
1990            "passless",
1991            "agent",
1992            "run",
1993            "--profile",
1994            "myprofile",
1995            "--",
1996            "/usr/bin/test",
1997            "arg1",
1998        ])
1999        .unwrap();
2000        match args.command {
2001            Some(Commands::Agent {
2002                action: AgentCommand::Run { profile, command },
2003                ..
2004            }) => {
2005                assert_eq!(profile, "myprofile");
2006                assert_eq!(command.len(), 2);
2007            }
2008            _ => panic!("expected Agent Run command"),
2009        }
2010    }
2011
2012    #[cfg(feature = "agent")]
2013    #[test]
2014    fn test_agent_admin_grants_parse() {
2015        let args = Args::try_parse_from([
2016            "passless",
2017            "agent-admin",
2018            "grants",
2019            "revoke",
2020            "--profile",
2021            "coding",
2022            "--rp",
2023            "example.com",
2024            "--confirm",
2025        ])
2026        .unwrap();
2027        assert!(matches!(
2028            args.command,
2029            Some(Commands::AgentAdmin {
2030                action: AgentAdminAction::Grants {
2031                    action: AdminGrantsAction::Revoke {
2032                        ref profile,
2033                        ref rp_id,
2034                        action: AdminGrantAction::Authenticate,
2035                        confirm: true,
2036                    },
2037                },
2038                ..
2039            }) if profile == "coding" && rp_id == "example.com"
2040        ));
2041        let args = Args::try_parse_from([
2042            "passless",
2043            "agent-admin",
2044            "grants",
2045            "clear",
2046            "--profile",
2047            "p",
2048        ])
2049        .unwrap();
2050        assert!(matches!(
2051            args.command,
2052            Some(Commands::AgentAdmin {
2053                action: AgentAdminAction::Grants {
2054                    action: AdminGrantsAction::Clear { confirm: false, .. },
2055                },
2056                ..
2057            })
2058        ));
2059        assert!(Args::try_parse_from(["passless", "agent-admin", "grants", "list"]).is_ok());
2060    }
2061
2062    #[cfg(feature = "agent")]
2063    #[test]
2064    fn test_agent_admin_renamed_session_commands_keep_hidden_aliases() {
2065        for (spelling, expect_sessions) in [
2066            ("sessions", true),
2067            ("delegation", true),
2068            ("principals", false),
2069            ("session", false),
2070        ] {
2071            let args = Args::try_parse_from(["passless", "agent-admin", spelling, "list"]).unwrap();
2072            let is_sessions = matches!(
2073                args.command,
2074                Some(Commands::AgentAdmin {
2075                    action: AgentAdminAction::Sessions { .. },
2076                    ..
2077                })
2078            );
2079            let is_principals = matches!(
2080                args.command,
2081                Some(Commands::AgentAdmin {
2082                    action: AgentAdminAction::Principals { .. },
2083                    ..
2084                })
2085            );
2086            assert_eq!(is_sessions, expect_sessions, "{spelling}");
2087            assert_eq!(is_principals, !expect_sessions, "{spelling}");
2088        }
2089        assert!(Args::try_parse_from(["passless", "agent", "intent", "show", "x"]).is_err());
2090    }
2091
2092    #[cfg(feature = "agent")]
2093    #[test]
2094    fn test_agent_output_default_json() {
2095        let args = Args::try_parse_from(["passless", "agent", "doctor"]).unwrap();
2096        match args.command {
2097            Some(Commands::Agent { output, .. }) => {
2098                assert_eq!(output, OutputFormat::Json);
2099            }
2100            _ => panic!("expected Agent command"),
2101        }
2102    }
2103
2104    #[cfg(feature = "agent")]
2105    #[test]
2106    fn test_shell_completions_contain_agent_commands() {
2107        use clap::CommandFactory;
2108
2109        let cmd = Args::command();
2110        let mut buf = Vec::new();
2111        clap_complete::generate(
2112            clap_complete::Shell::Bash,
2113            &mut cmd.clone(),
2114            "passless",
2115            &mut buf,
2116        );
2117        let completion = String::from_utf8(buf).unwrap();
2118
2119        for expected in [
2120            "agent-admin",
2121            "agent",
2122            "install",
2123            "browser-control",
2124            "grants",
2125            "sessions",
2126            "principals",
2127            "doctor",
2128            "capabilities",
2129            "instructions",
2130        ] {
2131            assert!(
2132                completion.contains(expected),
2133                "bash completion missing '{}'",
2134                expected
2135            );
2136        }
2137    }
2138
2139    #[cfg(feature = "agent")]
2140    #[test]
2141    fn test_shell_completions_zsh_contain_agent_commands() {
2142        use clap::CommandFactory;
2143
2144        let cmd = Args::command();
2145        let mut buf = Vec::new();
2146        clap_complete::generate(
2147            clap_complete::Shell::Zsh,
2148            &mut cmd.clone(),
2149            "passless",
2150            &mut buf,
2151        );
2152        let completion = String::from_utf8(buf).unwrap();
2153
2154        for expected in ["agent-admin", "agent", "install", "browser-control"] {
2155            assert!(
2156                completion.contains(expected),
2157                "zsh completion missing '{}'",
2158                expected
2159            );
2160        }
2161    }
2162
2163    #[cfg(feature = "agent")]
2164    #[test]
2165    fn test_config_print_includes_agent_fields() {
2166        let mut default_args = Args::parse_from(["passless"]);
2167        let config = AppConfig::from(&mut default_args.config);
2168        let toml_output = config.to_toml_with_comments();
2169
2170        assert!(
2171            toml_output.contains("backend_type"),
2172            "config print missing backend_type"
2173        );
2174        assert!(
2175            toml_output.contains("[security]"),
2176            "config print missing [security] section"
2177        );
2178        assert!(
2179            toml_output.contains("[pin]"),
2180            "config print missing [pin] section"
2181        );
2182        assert!(
2183            toml_output.contains("always_uv"),
2184            "config print missing always_uv"
2185        );
2186        assert!(
2187            toml_output.contains("notification_timeout"),
2188            "config print missing notification_timeout"
2189        );
2190    }
2191
2192    #[test]
2193    fn test_config_print_contains_passless_header() {
2194        let mut default_args = Args::parse_from(["passless"]);
2195        let config = AppConfig::from(&mut default_args.config);
2196        let toml_output = config.to_toml_with_comments();
2197
2198        assert!(toml_output.contains("Passless Configuration File"));
2199        assert!(toml_output.contains("~/.config/passless/config.toml"));
2200    }
2201
2202    #[test]
2203    fn test_config_print_contains_local_backend_section() {
2204        let mut default_args = Args::parse_from(["passless"]);
2205        let config = AppConfig::from(&mut default_args.config);
2206        let toml_output = config.to_toml_with_comments();
2207
2208        assert!(toml_output.contains("[local]"));
2209        assert!(toml_output.contains("path"));
2210    }
2211
2212    #[test]
2213    fn test_config_print_contains_pass_backend_section() {
2214        let mut default_args = Args::parse_from(["passless"]);
2215        let config = AppConfig::from(&mut default_args.config);
2216        let toml_output = config.to_toml_with_comments();
2217
2218        assert!(toml_output.contains("[pass]"));
2219        assert!(toml_output.contains("store_path"));
2220        assert!(toml_output.contains("gpg_backend"));
2221    }
2222
2223    #[test]
2224    fn test_config_print_produces_valid_toml_without_none_literals() {
2225        let mut default_args = Args::parse_from(["passless"]);
2226        let config = AppConfig::from(&mut default_args.config);
2227        let toml_output = config.to_toml_with_comments();
2228
2229        for (line_no, line) in toml_output.lines().enumerate() {
2230            let trimmed = line.trim();
2231            if trimmed.starts_with('#') || trimmed.is_empty() {
2232                continue;
2233            }
2234            assert!(
2235                !trimmed.contains("= None"),
2236                "Line {} contains invalid TOML 'None' literal: {}",
2237                line_no + 1,
2238                line
2239            );
2240        }
2241
2242        let parse_result: Result<toml::Table, _> = toml_output.parse();
2243        assert!(
2244            parse_result.is_ok(),
2245            "Generated TOML is not valid: {:?}",
2246            parse_result.err()
2247        );
2248    }
2249
2250    #[cfg(feature = "agent")]
2251    #[test]
2252    fn test_config_print_comments_out_none_option_fields() {
2253        let mut default_args = Args::parse_from(["passless"]);
2254        let config = AppConfig::from(&mut default_args.config);
2255        let toml_output = config.to_toml_with_comments();
2256
2257        assert!(
2258            toml_output.contains("# audit_path = <not set>"),
2259            "Option::None field 'audit_path' should be commented out, got:\n{}",
2260            toml_output
2261        );
2262    }
2263}