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    /// Load configuration with precedence: CLI > config file > defaults
632    pub fn load(args: &mut Args) -> crate::error::Result<Self> {
633        let default_config_path = dirs::config_dir().map(|p| p.join("passless/config.toml"));
634
635        let config_file_path = args
636            .config_path
637            .as_ref()
638            .or(default_config_path.as_ref())
639            .filter(|p| p.exists());
640
641        if let Some(path) = config_file_path
642            && let Ok(f) = File::open(path)
643        {
644            log::info!("Loading configuration from: {}", path.display());
645            let content = std::io::read_to_string(BufReader::new(f)).unwrap_or_default();
646
647            #[cfg(feature = "agent")]
648            let agent_config = {
649                match toml::from_str::<toml::Table>(&content) {
650                    Ok(table) => match table.get("agents") {
651                        Some(agents_value) => serde::Deserialize::deserialize(agents_value.clone())
652                            .map_err(|e| {
653                                Error::Config(format!(
654                                    "failed to parse [agents] section in {}: {}",
655                                    path.display(),
656                                    e
657                                ))
658                            })?,
659                        None => AgentConfig::default(),
660                    },
661                    Err(e) => {
662                        return Err(Error::Config(format!(
663                            "failed to parse config file {} as TOML: {}",
664                            path.display(),
665                            e
666                        )));
667                    }
668                }
669            };
670
671            match toml::from_str::<<AppConfig as ClapSerde>::Opt>(&content) {
672                Ok(file_config) => {
673                    #[allow(unused_mut)]
674                    let mut config = AppConfig::from(file_config).merge(&mut args.config);
675                    #[cfg(feature = "agent")]
676                    {
677                        config.agents = agent_config;
678                    }
679                    return Ok(config);
680                }
681                Err(e) => {
682                    return Err(Error::Config(format!(
683                        "failed to parse config file {}: {}",
684                        path.display(),
685                        e
686                    )));
687                }
688            }
689        }
690
691        #[allow(unused_mut)]
692        let mut config = AppConfig::from(&mut args.config);
693        #[cfg(feature = "agent")]
694        {
695            config.agents = AgentConfig::default();
696        }
697        Ok(config)
698    }
699
700    /// Get the backend configuration based on the backend_type
701    pub fn backend(&self) -> crate::error::Result<BackendConfig> {
702        match self.backend_type.as_str() {
703            "local" => Ok(BackendConfig::Local {
704                path: self.local.path.clone(),
705            }),
706            "pass" => Ok(BackendConfig::Pass {
707                store_path: self.pass.store_path.clone(),
708                path: self.pass.path.clone(),
709                gpg_backend: self.pass.gpg_backend.clone(),
710            }),
711            #[cfg(feature = "tpm")]
712            "tpm" => Ok(BackendConfig::Tpm {
713                path: self.tpm.path.clone(),
714                tcti: self.tpm.tcti.clone(),
715                portable: self.tpm.portable,
716            }),
717            _ => Err(crate::error::Error::Config(format!(
718                "Invalid backend_type '{}'. Must be one of: local, pass, tpm",
719                self.backend_type
720            ))),
721        }
722    }
723
724    /// Apply security hardening measures
725    pub fn apply_security_hardening(&self) -> Result<(), Box<dyn std::error::Error>> {
726        self.security.apply_hardening()
727    }
728
729    /// Get security configuration
730    pub fn security_config(&self) -> SecurityConfig {
731        self.security.clone()
732    }
733
734    /// Get PIN configuration
735    pub fn pin_config(&self) -> PinConfig {
736        self.pin.clone()
737    }
738
739    /// Validate the configuration
740    pub fn validate(&self) -> crate::error::Result<()> {
741        self.pin.validate()?;
742        #[cfg(feature = "agent")]
743        {
744            let human_path = self.backend().ok().map(|b| b.state_path());
745            self.agents.validate(human_path.as_deref())?;
746        }
747        Ok(())
748    }
749}
750
751/// CLI arguments structure
752#[derive(Parser)]
753#[command(author, version, about)]
754pub struct Args {
755    /// Path to configuration file (TOML format)
756    #[arg(short, long, env = "PASSLESS_CONFIG")]
757    pub config_path: Option<PathBuf>,
758
759    /// Application configuration (can come from CLI or config file)
760    #[command(flatten)]
761    pub config: <AppConfig as ClapSerde>::Opt,
762
763    /// Subcommands
764    #[command(subcommand)]
765    pub command: Option<Commands>,
766}
767
768/// Output format for client commands
769#[derive(Debug, Clone, Copy, PartialEq, Eq)]
770pub enum OutputFormat {
771    /// Human-readable plain text output
772    Plain,
773    /// JSON output for programmatic consumption
774    Json,
775}
776
777impl std::str::FromStr for OutputFormat {
778    type Err = String;
779
780    fn from_str(s: &str) -> Result<Self, Self::Err> {
781        match s.to_lowercase().as_str() {
782            "plain" => Ok(OutputFormat::Plain),
783            "json" => Ok(OutputFormat::Json),
784            _ => Err(format!(
785                "Invalid output format '{}'. Must be 'plain' or 'json'",
786                s
787            )),
788        }
789    }
790}
791
792impl std::fmt::Display for OutputFormat {
793    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
794        match self {
795            OutputFormat::Plain => write!(f, "plain"),
796            OutputFormat::Json => write!(f, "json"),
797        }
798    }
799}
800
801/// Subcommands for passless
802#[derive(Subcommand, Debug, Clone)]
803pub enum Commands {
804    /// Configuration management commands
805    Config {
806        #[command(subcommand)]
807        action: ConfigAction,
808    },
809    /// FIDO2 client commands for managing authenticators
810    ///
811    /// These commands require a running authenticator. For testing:
812    /// 1. Start authenticator: PASSLESS_E2E_AUTO_ACCEPT_UV=1 cargo run -- --backend-type local
813    /// 2. Run client commands in another terminal with the same environment variable
814    Client {
815        /// Select device by index (0-based) or name. Use 'devices' subcommand to list available devices.
816        #[arg(short = 'D', long = "device", value_name = "INDEX|NAME", global = true)]
817        device: Option<String>,
818
819        /// Output format: plain (default) or json
820        #[arg(
821            short = 'o',
822            long = "output",
823            value_name = "FORMAT",
824            default_value = "plain",
825            global = true
826        )]
827        output: OutputFormat,
828
829        #[command(subcommand)]
830        action: ClientAction,
831    },
832    /// Agent administration commands
833    #[cfg(feature = "agent")]
834    AgentAdmin {
835        /// Output format: json (default) or plain
836        #[arg(
837            short = 'o',
838            long = "output",
839            value_name = "FORMAT",
840            default_value = "json",
841            global = true
842        )]
843        output: OutputFormat,
844
845        #[command(subcommand)]
846        action: AgentAdminAction,
847    },
848    /// Agent principal and session commands
849    #[cfg(feature = "agent")]
850    Agent {
851        /// Profile to use for principal commands
852        #[arg(long, value_name = "PROFILE", global = true)]
853        profile: Option<String>,
854
855        /// Output format: json (default) or plain
856        #[arg(
857            short = 'o',
858            long = "output",
859            value_name = "FORMAT",
860            default_value = "json",
861            global = true
862        )]
863        output: OutputFormat,
864
865        #[command(subcommand)]
866        action: crate::AgentCommand,
867    },
868    /// TPM portable parent management
869    #[cfg(feature = "tpm")]
870    Tpm {
871        #[command(subcommand)]
872        action: TpmAction,
873    },
874}
875
876/// TPM portable parent actions
877#[cfg(feature = "tpm")]
878#[derive(Subcommand, Debug, Clone)]
879pub enum TpmAction {
880    /// Provision the portable TPM parent from a recovery seed
881    #[command(group(clap::ArgGroup::new("seed-source").args(["generate", "seed_file", "seed_stdin"])))]
882    Provision {
883        /// Generate a new random 32-byte recovery seed and print it
884        #[arg(long)]
885        generate: bool,
886        /// Read the recovery seed (hex) from this file instead of prompting
887        #[arg(long = "seed-file", value_name = "PATH")]
888        seed_file: Option<PathBuf>,
889        /// Read the recovery seed (hex) from stdin instead of prompting
890        #[arg(long = "seed-stdin")]
891        seed_stdin: bool,
892        /// TPM storage directory
893        #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
894        path: Option<String>,
895        /// TPM TCTI configuration
896        #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
897        tcti: Option<String>,
898    },
899    /// Show provisioning status
900    Status {
901        /// TPM storage directory
902        #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
903        path: Option<String>,
904        /// TPM TCTI configuration
905        #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
906        tcti: Option<String>,
907    },
908    /// Remove the provisioned portable parent
909    Remove {
910        /// Confirm the removal
911        #[arg(long)]
912        confirm: bool,
913        /// TPM storage directory
914        #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
915        path: Option<String>,
916        /// TPM TCTI configuration
917        #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
918        tcti: Option<String>,
919    },
920    /// Migrate legacy sealed credentials to portable TPM format
921    #[command(group(clap::ArgGroup::new("selection").args(["credential_id", "all"]).required(true)))]
922    Migrate {
923        /// Migrate a specific credential by ID (hex)
924        #[arg(long = "credential-id", value_name = "ID")]
925        credential_id: Option<String>,
926        /// Migrate all migratable legacy credentials
927        #[arg(long)]
928        all: bool,
929        /// Show what would be migrated without making changes
930        #[arg(long)]
931        dry_run: bool,
932        /// Directory to store backups of legacy records
933        #[arg(long = "backup-dir", value_name = "PATH")]
934        backup_dir: Option<String>,
935        /// TPM storage directory
936        #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
937        path: Option<String>,
938        /// TPM TCTI configuration
939        #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
940        tcti: Option<String>,
941    },
942}
943
944/// Configuration actions
945#[derive(Subcommand, Debug, Clone)]
946pub enum ConfigAction {
947    /// Print the default configuration in TOML format
948    Print,
949}
950
951/// Agent administration actions
952#[cfg(feature = "agent")]
953#[derive(Subcommand, Debug, Clone)]
954pub enum AgentAdminAction {
955    /// Install the Passless skill for a supported coding agent
956    Install {
957        /// Agent to install for; auto installs to every detected agent
958        #[arg(value_enum, default_value_t = AgentSkillTarget::Auto)]
959        target: AgentSkillTarget,
960
961        /// Install for the current user or the current Git worktree
962        #[arg(long, value_enum, default_value_t = AgentSkillScope::User)]
963        scope: AgentSkillScope,
964
965        /// Replace a different existing file at the skill target
966        #[arg(long)]
967        force: bool,
968    },
969    /// Install native messaging manifest for browser extension
970    InstallNativeMessaging {
971        /// Browser executable path (e.g., /usr/bin/chromium)
972        #[arg(long)]
973        browser: String,
974
975        /// Extension directory path
976        #[arg(long)]
977        ext_dir: PathBuf,
978
979        /// Sign proxy binary path
980        #[arg(long, default_value = "/usr/bin/sign-proxy")]
981        sign_proxy: PathBuf,
982    },
983    /// Profile management
984    Profile {
985        #[command(subcommand)]
986        action: AdminProfileAction,
987    },
988    /// Policy management
989    Policy {
990        #[command(subcommand)]
991        action: AdminPolicyAction,
992    },
993    /// Credential management
994    Credential {
995        #[command(subcommand)]
996        action: AdminCredentialAction,
997    },
998    /// Delegation management
999    Delegation {
1000        #[command(subcommand)]
1001        action: AdminDelegationAction,
1002    },
1003    /// Session management
1004    Session {
1005        #[command(subcommand)]
1006        action: AdminSessionAction,
1007    },
1008    /// Browser session management
1009    Browser {
1010        #[command(subcommand)]
1011        action: AdminBrowserAction,
1012    },
1013    /// Audit log management
1014    Audit {
1015        #[command(subcommand)]
1016        action: AdminAuditAction,
1017    },
1018    /// Shut down the running daemon
1019    #[command(hide = true)]
1020    Shutdown {
1021        /// Confirm the shutdown
1022        #[arg(long)]
1023        confirm: bool,
1024    },
1025}
1026
1027/// Admin profile actions
1028#[cfg(feature = "agent")]
1029#[derive(Subcommand, Debug, Clone)]
1030pub enum AdminProfileAction {
1031    /// Check if a profile exists and is valid
1032    Check {
1033        /// Profile identifier
1034        #[arg(value_name = "PROFILE")]
1035        profile: String,
1036    },
1037    /// Show profile details
1038    Show {
1039        /// Profile identifier
1040        #[arg(value_name = "PROFILE")]
1041        profile: String,
1042    },
1043    /// List all configured profiles
1044    List,
1045    /// Enable a profile
1046    Enable {
1047        /// Profile identifier
1048        #[arg(value_name = "PROFILE")]
1049        profile: String,
1050    },
1051    /// Disable a profile
1052    Disable {
1053        /// Profile identifier
1054        #[arg(value_name = "PROFILE")]
1055        profile: String,
1056    },
1057}
1058
1059/// Admin policy actions
1060#[cfg(feature = "agent")]
1061#[derive(Subcommand, Debug, Clone)]
1062pub enum AdminPolicyAction {
1063    /// Check policy validity for a profile
1064    Check {
1065        /// Profile identifier
1066        #[arg(value_name = "PROFILE")]
1067        profile: String,
1068    },
1069    /// Reload policy for a profile
1070    Reload {
1071        /// Profile identifier
1072        #[arg(value_name = "PROFILE")]
1073        profile: String,
1074    },
1075    /// Show current policy for a profile
1076    Show {
1077        /// Profile identifier
1078        #[arg(value_name = "PROFILE")]
1079        profile: String,
1080    },
1081}
1082
1083/// Admin credential actions
1084#[cfg(feature = "agent")]
1085#[derive(Subcommand, Debug, Clone)]
1086pub enum AdminCredentialAction {
1087    /// List credentials
1088    List {
1089        /// Filter by relying party ID
1090        #[arg(short = 'd', long = "domain", value_name = "DOMAIN")]
1091        rp_id: Option<String>,
1092    },
1093    /// Show credential details
1094    Show {
1095        /// Credential reference (hex)
1096        #[arg(value_name = "CREDENTIAL_REF")]
1097        credential_ref: String,
1098    },
1099    /// Revoke a credential
1100    Revoke {
1101        /// Credential reference (hex)
1102        #[arg(value_name = "CREDENTIAL_REF")]
1103        credential_ref: String,
1104        /// Confirm the revocation
1105        #[arg(long)]
1106        confirm: bool,
1107    },
1108    /// Delete a credential
1109    Delete {
1110        /// Credential reference (hex)
1111        #[arg(value_name = "CREDENTIAL_REF")]
1112        credential_ref: String,
1113        /// Confirm the deletion
1114        #[arg(long)]
1115        confirm: bool,
1116    },
1117}
1118
1119/// Admin delegation actions
1120#[cfg(feature = "agent")]
1121#[derive(Subcommand, Debug, Clone)]
1122pub enum AdminDelegationAction {
1123    /// Show delegation details
1124    Show {
1125        /// Grant identifier (hex)
1126        #[arg(value_name = "GRANT_ID")]
1127        grant_id: String,
1128    },
1129    /// List all delegations
1130    List {
1131        /// Filter by profile
1132        #[arg(long, value_name = "PROFILE")]
1133        profile: Option<String>,
1134    },
1135    /// Revoke a delegation
1136    Revoke {
1137        /// Grant identifier (hex)
1138        #[arg(value_name = "GRANT_ID")]
1139        grant_id: String,
1140        /// Confirm the revocation
1141        #[arg(long)]
1142        confirm: bool,
1143    },
1144    /// Create an exact-RP, short-lived, one-shot registration enrollment grant
1145    RequestRegistration {
1146        /// Profile identifier
1147        #[arg(long, value_name = "PROFILE")]
1148        profile: String,
1149        /// Relying party ID
1150        #[arg(long, value_name = "RP_ID")]
1151        rp: String,
1152        /// Enrollment grant TTL in seconds (clamped to profile TTL and 300 seconds)
1153        #[arg(long, value_name = "SECONDS")]
1154        session_ttl: u64,
1155        /// Reason for the registration
1156        #[arg(long, value_name = "REASON")]
1157        reason: Option<String>,
1158    },
1159}
1160
1161/// Admin session actions
1162#[cfg(feature = "agent")]
1163#[derive(Subcommand, Debug, Clone)]
1164pub enum AdminSessionAction {
1165    /// Show session details
1166    Show {
1167        /// Session identifier (hex)
1168        #[arg(value_name = "SESSION_ID")]
1169        session_id: String,
1170    },
1171    /// List all sessions
1172    List {
1173        /// Filter by profile
1174        #[arg(long, value_name = "PROFILE")]
1175        profile: Option<String>,
1176    },
1177    /// Revoke a session
1178    Revoke {
1179        /// Session identifier (hex)
1180        #[arg(value_name = "SESSION_ID")]
1181        session_id: String,
1182        /// Confirm the revocation
1183        #[arg(long)]
1184        confirm: bool,
1185    },
1186}
1187
1188/// Admin browser actions
1189#[cfg(feature = "agent")]
1190#[derive(Subcommand, Debug, Clone)]
1191pub enum AdminBrowserAction {
1192    /// Launch a browser session with the agent extension
1193    Launch {
1194        /// Profile identifier
1195        #[arg(long, value_name = "PROFILE")]
1196        profile: String,
1197        /// Start URL to open in the browser
1198        #[arg(long, value_name = "URL")]
1199        url: Option<String>,
1200    },
1201}
1202
1203/// Admin audit actions
1204#[cfg(feature = "agent")]
1205#[derive(Subcommand, Debug, Clone)]
1206pub enum AdminAuditAction {
1207    /// Show audit subsystem status
1208    Status,
1209    /// Verify audit log integrity
1210    Verify,
1211    /// Export audit log entries
1212    Export {
1213        /// Export format
1214        #[arg(long, value_enum, default_value_t = AdminAuditExportFormat::Json)]
1215        format: AdminAuditExportFormat,
1216    },
1217}
1218
1219/// Audit export format for CLI
1220#[cfg(feature = "agent")]
1221#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1222pub enum AdminAuditExportFormat {
1223    Json,
1224    Csv,
1225}
1226
1227/// Supported coding-agent skill targets
1228#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1229pub enum AgentSkillTarget {
1230    Auto,
1231    Opencode,
1232    Claude,
1233    Pi,
1234}
1235
1236/// Skill installation scope
1237#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1238pub enum AgentSkillScope {
1239    User,
1240    Project,
1241}
1242
1243/// Client actions for FIDO2 authenticator management
1244#[derive(Subcommand, Debug, Clone)]
1245pub enum ClientAction {
1246    /// List all available FIDO2 authenticators/devices
1247    Devices,
1248    /// Get authenticator information (capabilities, AAGUID, versions, etc.)
1249    Info,
1250    /// Reset the authenticator (WARNING: deletes ALL credentials)
1251    Reset {
1252        /// Confirmation flag that must be provided twice for safety
1253        #[arg(long = "yes-i-really-want-to-reset-my-device", action = ArgAction::Count)]
1254        confirm: u8,
1255    },
1256    /// List all credentials on the authenticator
1257    List {
1258        /// Filter by relying party ID (domain)
1259        #[arg(short = 'd', long = "domain", value_name = "DOMAIN")]
1260        rp_id: Option<String>,
1261    },
1262    /// Show detailed information about a specific credential
1263    Show {
1264        /// Credential ID in hexadecimal format
1265        #[arg(value_name = "CREDENTIAL_ID")]
1266        credential_id: String,
1267    },
1268    /// Delete a specific credential by ID
1269    Delete {
1270        /// Credential ID in hexadecimal format
1271        #[arg(value_name = "CREDENTIAL_ID")]
1272        credential_id: String,
1273    },
1274    /// Rename a credential (update user name and/or display name)
1275    Rename {
1276        /// Credential ID in hexadecimal format
1277        #[arg(value_name = "CREDENTIAL_ID")]
1278        credential_id: String,
1279        /// New user name (login identifier)
1280        #[arg(short = 'u', long = "user-name", value_name = "NAME")]
1281        user_name: Option<String>,
1282        /// New display name (friendly name)
1283        #[arg(short = 'n', long = "display-name", value_name = "NAME")]
1284        display_name: Option<String>,
1285    },
1286    /// Export one software-backed credential as an opaque encrypted bundle.
1287    Backup {
1288        /// Credential ID in hexadecimal format
1289        #[arg(value_name = "CREDENTIAL_ID")]
1290        credential_id: String,
1291        /// Authenticator-local credential-backup wrapping-key identifier
1292        #[arg(long, value_name = "RECIPIENT")]
1293        recipient: String,
1294        /// Destination bundle path
1295        #[arg(long, value_name = "PATH")]
1296        output_file: PathBuf,
1297        /// Explicitly acknowledge that a passkey is being exported
1298        #[arg(long = "yes-i-understand-this-exports-a-passkey")]
1299        confirm: bool,
1300    },
1301    /// Restore an encrypted Passless credential bundle.
1302    Restore {
1303        /// Source bundle path
1304        #[arg(value_name = "PATH")]
1305        input_file: PathBuf,
1306        /// Replace a credential with the same ID
1307        #[arg(long)]
1308        replace: bool,
1309        /// Explicitly acknowledge that a passkey is being restored
1310        #[arg(long = "yes-i-understand-this-restores-a-passkey")]
1311        confirm: bool,
1312    },
1313    /// PIN management commands
1314    Pin {
1315        #[command(subcommand)]
1316        action: PinAction,
1317    },
1318}
1319
1320/// PIN management actions
1321#[derive(Subcommand, Debug, Clone)]
1322pub enum PinAction {
1323    /// Set a new PIN (authenticator must not have a PIN set)
1324    Set {
1325        /// The new PIN (minimum 4 characters)
1326        #[arg(value_name = "PIN")]
1327        pin: String,
1328    },
1329    /// Change the existing PIN
1330    Change {
1331        /// The current PIN
1332        #[arg(value_name = "OLD_PIN")]
1333        old_pin: String,
1334        /// The new PIN (minimum 4 characters)
1335        #[arg(value_name = "NEW_PIN")]
1336        new_pin: String,
1337    },
1338    /// Reset built-in user verification retries without deleting credentials
1339    UvReset,
1340}
1341
1342/// Agent principal and session commands
1343#[cfg(feature = "agent")]
1344#[derive(Subcommand, Debug, Clone)]
1345pub enum AgentCommand {
1346    /// Run health diagnostics
1347    Doctor,
1348    /// Show principal capabilities
1349    Capabilities,
1350    /// Show principal instructions
1351    Instructions,
1352    /// Intent management
1353    Intent {
1354        #[command(subcommand)]
1355        action: AgentIntentAction,
1356    },
1357    /// Delegation management
1358    Delegation {
1359        #[command(subcommand)]
1360        action: AgentDelegationAction,
1361    },
1362    /// Credential queries
1363    Credential {
1364        #[command(subcommand)]
1365        action: AgentCredentialAction,
1366    },
1367    /// Show browser bridge status
1368    BrowserStatus,
1369    /// Show endpoint status
1370    EndpointStatus,
1371    /// Send a CDP command to the managed browser session
1372    ///
1373    /// WARNING: This is the full browser-session authority interface.
1374    /// CDP commands can access cookies, DOM, network state, and session data.
1375    /// Output may contain CDP response data — do not mix with credential/admin output.
1376    BrowserControl {
1377        /// CDP request as JSON (e.g. '{"id":1,"method":"Page.navigate","params":{"url":"https://example.com"}}')
1378        #[arg(long, value_name = "JSON", conflicts_with = "request_file")]
1379        request: Option<String>,
1380        /// Path to file containing CDP request JSON (owner/symlink/size checked)
1381        #[arg(long, value_name = "PATH", conflicts_with = "request")]
1382        request_file: Option<std::path::PathBuf>,
1383        /// Timeout in milliseconds (default: 5000, max: 30000)
1384        #[arg(long, value_name = "MS", default_value = "5000")]
1385        timeout_ms: u32,
1386    },
1387    /// Run Playwright MCP with lazy access to the profile's trusted CDP browser
1388    PlaywrightMcp {
1389        /// Profile to bind the Playwright session to
1390        #[arg(long, value_name = "PROFILE")]
1391        profile: String,
1392        /// Start URL to open in the managed browser
1393        #[arg(long, value_name = "URL")]
1394        url: Option<String>,
1395        /// Absolute Playwright MCP executable and arguments
1396        #[arg(last = true, required = true)]
1397        command: Vec<std::path::PathBuf>,
1398    },
1399    /// Launch a detached principal session
1400    Run {
1401        /// Profile to launch
1402        #[arg(long, value_name = "PROFILE")]
1403        profile: String,
1404        /// Absolute command path and arguments
1405        #[arg(last = true, required = true)]
1406        command: Vec<std::path::PathBuf>,
1407    },
1408}
1409
1410/// Agent intent actions
1411#[cfg(feature = "agent")]
1412#[derive(Subcommand, Debug, Clone)]
1413pub enum AgentIntentAction {
1414    /// Create a new intent
1415    Create {
1416        /// Action type
1417        #[arg(value_enum)]
1418        action: AgentIntentActionType,
1419        /// Relying party ID
1420        #[arg(long, value_name = "RP_ID")]
1421        rp: String,
1422        /// Credential reference (hex)
1423        #[arg(long, value_name = "CREDENTIAL_REF")]
1424        credential: Option<String>,
1425        /// Reason for the intent
1426        #[arg(long, value_name = "REASON")]
1427        reason: Option<String>,
1428    },
1429    /// Show intent status
1430    Show {
1431        /// Request identifier (hex)
1432        #[arg(value_name = "REQUEST_ID")]
1433        request_id: String,
1434    },
1435    /// Wait for intent to reach terminal state
1436    Wait {
1437        /// Request identifier (hex)
1438        #[arg(value_name = "REQUEST_ID")]
1439        request_id: String,
1440        /// Timeout in seconds
1441        #[arg(long, value_name = "SECONDS")]
1442        timeout: Option<u64>,
1443        /// Poll interval in milliseconds
1444        #[arg(long, value_name = "MS")]
1445        poll_interval: Option<u64>,
1446    },
1447    /// Cancel a pending intent
1448    Cancel {
1449        /// Request identifier (hex)
1450        #[arg(value_name = "REQUEST_ID")]
1451        request_id: String,
1452    },
1453}
1454
1455/// Intent action type for CLI
1456#[cfg(feature = "agent")]
1457#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1458pub enum AgentIntentActionType {
1459    Register,
1460    Authenticate,
1461}
1462
1463/// Agent delegation actions
1464#[cfg(feature = "agent")]
1465#[derive(Subcommand, Debug, Clone)]
1466pub enum AgentDelegationAction {
1467    /// Request a new delegation
1468    Request {
1469        /// Relying party ID
1470        #[arg(long, value_name = "RP_ID")]
1471        rp: String,
1472        /// Credential reference (hex)
1473        #[arg(long, value_name = "CREDENTIAL_REF")]
1474        credential: String,
1475        /// Session TTL in seconds
1476        #[arg(long, value_name = "SECONDS")]
1477        session_ttl: u64,
1478        /// Reason for the delegation
1479        #[arg(long, value_name = "REASON")]
1480        reason: Option<String>,
1481    },
1482    /// Show delegation status
1483    Show {
1484        /// Request identifier (hex)
1485        #[arg(value_name = "REQUEST_ID")]
1486        request_id: String,
1487    },
1488    /// Wait for delegation to reach terminal state
1489    Wait {
1490        /// Request identifier (hex)
1491        #[arg(value_name = "REQUEST_ID")]
1492        request_id: String,
1493        /// Timeout in seconds
1494        #[arg(long, value_name = "SECONDS")]
1495        timeout: Option<u64>,
1496        /// Poll interval in milliseconds
1497        #[arg(long, value_name = "MS")]
1498        poll_interval: Option<u64>,
1499    },
1500    /// Cancel a pending delegation
1501    Cancel {
1502        /// Request identifier (hex)
1503        #[arg(value_name = "REQUEST_ID")]
1504        request_id: String,
1505    },
1506}
1507
1508/// Agent credential actions
1509#[cfg(feature = "agent")]
1510#[derive(Subcommand, Debug, Clone)]
1511pub enum AgentCredentialAction {
1512    /// List credentials for the profile
1513    List,
1514    /// Show credential details
1515    Show {
1516        /// Credential reference (hex)
1517        #[arg(value_name = "CREDENTIAL_REF")]
1518        credential_ref: String,
1519    },
1520}
1521
1522#[cfg(test)]
1523mod tests {
1524    use super::*;
1525
1526    #[cfg(feature = "agent")]
1527    #[test]
1528    fn test_agent_admin_install_defaults() {
1529        let args = Args::try_parse_from(["passless", "agent-admin", "install"]).unwrap();
1530        assert!(matches!(
1531            args.command,
1532            Some(Commands::AgentAdmin {
1533                action: AgentAdminAction::Install {
1534                    target: AgentSkillTarget::Auto,
1535                    scope: AgentSkillScope::User,
1536                    force: false,
1537                },
1538                ..
1539            })
1540        ));
1541    }
1542
1543    #[cfg(feature = "agent")]
1544    #[test]
1545    fn test_agent_admin_install_explicit_options() {
1546        let args = Args::try_parse_from([
1547            "passless",
1548            "agent-admin",
1549            "install",
1550            "claude",
1551            "--scope",
1552            "project",
1553            "--force",
1554        ])
1555        .unwrap();
1556        assert!(matches!(
1557            args.command,
1558            Some(Commands::AgentAdmin {
1559                action: AgentAdminAction::Install {
1560                    target: AgentSkillTarget::Claude,
1561                    scope: AgentSkillScope::Project,
1562                    force: true,
1563                },
1564                ..
1565            })
1566        ));
1567    }
1568
1569    #[test]
1570    fn test_pin_config_default_max_uv_retries() {
1571        let config = PinConfig {
1572            enforcement: PinEnforcement::Optional,
1573            min_length: 4,
1574            max_retries: 8,
1575            max_uv_retries: 8,
1576            auto_lock_timeout: 0,
1577        };
1578        assert_eq!(config.max_uv_retries, 8);
1579    }
1580
1581    #[test]
1582    fn test_pin_config_validate_success() {
1583        let config = PinConfig {
1584            enforcement: PinEnforcement::Optional,
1585            min_length: 4,
1586            max_retries: 8,
1587            max_uv_retries: 8,
1588            auto_lock_timeout: 0,
1589        };
1590        assert!(config.validate().is_ok());
1591    }
1592
1593    #[test]
1594    fn test_pin_config_validate_zero_max_uv_retries() {
1595        let config = PinConfig {
1596            enforcement: PinEnforcement::Optional,
1597            min_length: 4,
1598            max_retries: 8,
1599            max_uv_retries: 0,
1600            auto_lock_timeout: 0,
1601        };
1602        let result = config.validate();
1603        assert!(result.is_err());
1604        assert!(result.unwrap_err().to_string().contains("max_uv_retries"));
1605    }
1606
1607    #[test]
1608    fn test_pin_config_validate_zero_max_retries() {
1609        let config = PinConfig {
1610            enforcement: PinEnforcement::Optional,
1611            min_length: 4,
1612            max_retries: 0,
1613            max_uv_retries: 8,
1614            auto_lock_timeout: 0,
1615        };
1616        let result = config.validate();
1617        assert!(result.is_err());
1618        assert!(result.unwrap_err().to_string().contains("max_retries"));
1619    }
1620
1621    #[test]
1622    fn test_pin_config_validate_invalid_min_length() {
1623        let config = PinConfig {
1624            enforcement: PinEnforcement::Optional,
1625            min_length: 3,
1626            max_retries: 8,
1627            max_uv_retries: 8,
1628            auto_lock_timeout: 0,
1629        };
1630        let result = config.validate();
1631        assert!(result.is_err());
1632        assert!(result.unwrap_err().to_string().contains("min_length"));
1633    }
1634
1635    #[test]
1636    fn test_canonicalize_path_existing() {
1637        let dir = std::env::temp_dir();
1638        let canonical = BackendConfig::canonicalize_path(&dir);
1639        assert!(canonical.is_absolute());
1640        assert!(canonical.exists());
1641    }
1642
1643    #[test]
1644    fn test_canonicalize_path_nonexistent() {
1645        let base = std::env::temp_dir();
1646        let nonexistent = base.join("passless_test_nonexistent_dir_12345/sub");
1647        let canonical = BackendConfig::canonicalize_path(&nonexistent);
1648        assert!(canonical.is_absolute());
1649        assert!(canonical.starts_with(BackendConfig::canonicalize_path(&base)));
1650    }
1651
1652    #[test]
1653    fn test_canonicalize_path_symlink() {
1654        let dir = tempfile::tempdir().unwrap();
1655        let real = dir.path().join("real");
1656        std::fs::create_dir(&real).unwrap();
1657        let link = dir.path().join("link");
1658        std::os::unix::fs::symlink(&real, &link).unwrap();
1659
1660        let canonical_real = BackendConfig::canonicalize_path(&real);
1661        let canonical_link = BackendConfig::canonicalize_path(&link);
1662        assert_eq!(canonical_real, canonical_link);
1663    }
1664
1665    #[test]
1666    fn test_local_state_path_relative_and_absolute() {
1667        let dir = tempfile::tempdir_in(".").unwrap();
1668        let abs_path = std::fs::canonicalize(dir.path()).unwrap();
1669        let rel_path = dir.path().to_path_buf();
1670
1671        let backend_abs = BackendConfig::Local {
1672            path: abs_path.display().to_string(),
1673        };
1674        let backend_rel = BackendConfig::Local {
1675            path: rel_path.display().to_string(),
1676        };
1677        assert_eq!(backend_abs.state_path(), backend_rel.state_path());
1678    }
1679
1680    #[test]
1681    fn test_pass_state_path_different_subpaths() {
1682        let store = "/tmp/passless_test_store";
1683        let backend_a = BackendConfig::Pass {
1684            store_path: store.to_string(),
1685            path: "fido2".to_string(),
1686            gpg_backend: "gnupg-bin".to_string(),
1687        };
1688        let backend_b = BackendConfig::Pass {
1689            store_path: store.to_string(),
1690            path: "fido2-other".to_string(),
1691            gpg_backend: "gnupg-bin".to_string(),
1692        };
1693        assert_ne!(backend_a.state_path(), backend_b.state_path());
1694    }
1695
1696    #[test]
1697    fn test_different_local_paths_produce_different_identities() {
1698        let backend_a = BackendConfig::Local {
1699            path: "/tmp/passless_a".to_string(),
1700        };
1701        let backend_b = BackendConfig::Local {
1702            path: "/tmp/passless_b".to_string(),
1703        };
1704        assert_ne!(backend_a.state_path(), backend_b.state_path());
1705    }
1706
1707    #[cfg(feature = "agent")]
1708    #[test]
1709    fn test_agent_admin_profile_list() {
1710        let args = Args::try_parse_from(["passless", "agent-admin", "profile", "list"]).unwrap();
1711        assert!(matches!(
1712            args.command,
1713            Some(Commands::AgentAdmin {
1714                action: AgentAdminAction::Profile {
1715                    action: AdminProfileAction::List,
1716                },
1717                ..
1718            })
1719        ));
1720    }
1721
1722    #[cfg(feature = "agent")]
1723    #[test]
1724    fn test_agent_admin_credential_delete_without_confirm() {
1725        let args = Args::try_parse_from([
1726            "passless",
1727            "agent-admin",
1728            "credential",
1729            "delete",
1730            "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
1731        ])
1732        .unwrap();
1733        assert!(matches!(
1734            args.command,
1735            Some(Commands::AgentAdmin {
1736                action: AgentAdminAction::Credential {
1737                    action: AdminCredentialAction::Delete { confirm: false, .. },
1738                },
1739                ..
1740            })
1741        ));
1742    }
1743
1744    #[cfg(feature = "agent")]
1745    #[test]
1746    fn test_agent_admin_credential_delete_with_confirm() {
1747        let args = Args::try_parse_from([
1748            "passless",
1749            "agent-admin",
1750            "credential",
1751            "delete",
1752            "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
1753            "--confirm",
1754        ])
1755        .unwrap();
1756        assert!(matches!(
1757            args.command,
1758            Some(Commands::AgentAdmin {
1759                action: AgentAdminAction::Credential {
1760                    action: AdminCredentialAction::Delete { confirm: true, .. },
1761                },
1762                ..
1763            })
1764        ));
1765    }
1766
1767    #[cfg(feature = "agent")]
1768    #[test]
1769    fn test_agent_admin_shutdown_hidden() {
1770        let args =
1771            Args::try_parse_from(["passless", "agent-admin", "shutdown", "--confirm"]).unwrap();
1772        assert!(matches!(
1773            args.command,
1774            Some(Commands::AgentAdmin {
1775                action: AgentAdminAction::Shutdown { confirm: true },
1776                ..
1777            })
1778        ));
1779    }
1780
1781    #[cfg(feature = "agent")]
1782    #[test]
1783    fn test_agent_admin_output_default_json() {
1784        let args = Args::try_parse_from(["passless", "agent-admin", "profile", "list"]).unwrap();
1785        match args.command {
1786            Some(Commands::AgentAdmin { output, .. }) => {
1787                assert_eq!(output, OutputFormat::Json);
1788            }
1789            _ => panic!("expected AgentAdmin command"),
1790        }
1791    }
1792
1793    #[cfg(feature = "agent")]
1794    #[test]
1795    fn test_agent_admin_output_plain() {
1796        let args = Args::try_parse_from([
1797            "passless",
1798            "agent-admin",
1799            "--output",
1800            "plain",
1801            "profile",
1802            "list",
1803        ])
1804        .unwrap();
1805        match args.command {
1806            Some(Commands::AgentAdmin { output, .. }) => {
1807                assert_eq!(output, OutputFormat::Plain);
1808            }
1809            _ => panic!("expected AgentAdmin command"),
1810        }
1811    }
1812
1813    #[cfg(feature = "agent")]
1814    #[test]
1815    fn test_agent_doctor_parses() {
1816        let args = Args::try_parse_from(["passless", "agent", "doctor"]).unwrap();
1817        assert!(matches!(
1818            args.command,
1819            Some(Commands::Agent {
1820                action: AgentCommand::Doctor,
1821                ..
1822            })
1823        ));
1824    }
1825
1826    #[cfg(feature = "agent")]
1827    #[test]
1828    fn test_agent_run_with_command() {
1829        let args = Args::try_parse_from([
1830            "passless",
1831            "agent",
1832            "run",
1833            "--profile",
1834            "myprofile",
1835            "--",
1836            "/usr/bin/test",
1837            "arg1",
1838        ])
1839        .unwrap();
1840        match args.command {
1841            Some(Commands::Agent {
1842                action: AgentCommand::Run { profile, command },
1843                ..
1844            }) => {
1845                assert_eq!(profile, "myprofile");
1846                assert_eq!(command.len(), 2);
1847            }
1848            _ => panic!("expected Agent Run command"),
1849        }
1850    }
1851
1852    #[cfg(feature = "agent")]
1853    #[test]
1854    fn test_agent_intent_create_parses() {
1855        let args = Args::try_parse_from([
1856            "passless",
1857            "agent",
1858            "intent",
1859            "create",
1860            "register",
1861            "--rp",
1862            "example.com",
1863        ])
1864        .unwrap();
1865        assert!(matches!(
1866            args.command,
1867            Some(Commands::Agent {
1868                action: AgentCommand::Intent {
1869                    action: AgentIntentAction::Create {
1870                        action: AgentIntentActionType::Register,
1871                        ..
1872                    },
1873                },
1874                ..
1875            })
1876        ));
1877    }
1878
1879    #[cfg(feature = "agent")]
1880    #[test]
1881    fn test_agent_output_default_json() {
1882        let args = Args::try_parse_from(["passless", "agent", "doctor"]).unwrap();
1883        match args.command {
1884            Some(Commands::Agent { output, .. }) => {
1885                assert_eq!(output, OutputFormat::Json);
1886            }
1887            _ => panic!("expected Agent command"),
1888        }
1889    }
1890
1891    #[cfg(feature = "agent")]
1892    #[test]
1893    fn test_shell_completions_contain_agent_commands() {
1894        use clap::CommandFactory;
1895
1896        let cmd = Args::command();
1897        let mut buf = Vec::new();
1898        clap_complete::generate(
1899            clap_complete::Shell::Bash,
1900            &mut cmd.clone(),
1901            "passless",
1902            &mut buf,
1903        );
1904        let completion = String::from_utf8(buf).unwrap();
1905
1906        for expected in [
1907            "agent-admin",
1908            "agent",
1909            "install",
1910            "browser-control",
1911            "intent",
1912            "delegation",
1913            "doctor",
1914            "capabilities",
1915            "instructions",
1916        ] {
1917            assert!(
1918                completion.contains(expected),
1919                "bash completion missing '{}'",
1920                expected
1921            );
1922        }
1923    }
1924
1925    #[cfg(feature = "agent")]
1926    #[test]
1927    fn test_shell_completions_zsh_contain_agent_commands() {
1928        use clap::CommandFactory;
1929
1930        let cmd = Args::command();
1931        let mut buf = Vec::new();
1932        clap_complete::generate(
1933            clap_complete::Shell::Zsh,
1934            &mut cmd.clone(),
1935            "passless",
1936            &mut buf,
1937        );
1938        let completion = String::from_utf8(buf).unwrap();
1939
1940        for expected in ["agent-admin", "agent", "install", "browser-control"] {
1941            assert!(
1942                completion.contains(expected),
1943                "zsh completion missing '{}'",
1944                expected
1945            );
1946        }
1947    }
1948
1949    #[cfg(feature = "agent")]
1950    #[test]
1951    fn test_config_print_includes_agent_fields() {
1952        let mut default_args = Args::parse_from(["passless"]);
1953        let config = AppConfig::from(&mut default_args.config);
1954        let toml_output = config.to_toml_with_comments();
1955
1956        assert!(
1957            toml_output.contains("backend_type"),
1958            "config print missing backend_type"
1959        );
1960        assert!(
1961            toml_output.contains("[security]"),
1962            "config print missing [security] section"
1963        );
1964        assert!(
1965            toml_output.contains("[pin]"),
1966            "config print missing [pin] section"
1967        );
1968        assert!(
1969            toml_output.contains("always_uv"),
1970            "config print missing always_uv"
1971        );
1972        assert!(
1973            toml_output.contains("notification_timeout"),
1974            "config print missing notification_timeout"
1975        );
1976    }
1977
1978    #[test]
1979    fn test_config_print_contains_passless_header() {
1980        let mut default_args = Args::parse_from(["passless"]);
1981        let config = AppConfig::from(&mut default_args.config);
1982        let toml_output = config.to_toml_with_comments();
1983
1984        assert!(toml_output.contains("Passless Configuration File"));
1985        assert!(toml_output.contains("~/.config/passless/config.toml"));
1986    }
1987
1988    #[test]
1989    fn test_config_print_contains_local_backend_section() {
1990        let mut default_args = Args::parse_from(["passless"]);
1991        let config = AppConfig::from(&mut default_args.config);
1992        let toml_output = config.to_toml_with_comments();
1993
1994        assert!(toml_output.contains("[local]"));
1995        assert!(toml_output.contains("path"));
1996    }
1997
1998    #[test]
1999    fn test_config_print_contains_pass_backend_section() {
2000        let mut default_args = Args::parse_from(["passless"]);
2001        let config = AppConfig::from(&mut default_args.config);
2002        let toml_output = config.to_toml_with_comments();
2003
2004        assert!(toml_output.contains("[pass]"));
2005        assert!(toml_output.contains("store_path"));
2006        assert!(toml_output.contains("gpg_backend"));
2007    }
2008
2009    #[test]
2010    fn test_config_print_produces_valid_toml_without_none_literals() {
2011        let mut default_args = Args::parse_from(["passless"]);
2012        let config = AppConfig::from(&mut default_args.config);
2013        let toml_output = config.to_toml_with_comments();
2014
2015        for (line_no, line) in toml_output.lines().enumerate() {
2016            let trimmed = line.trim();
2017            if trimmed.starts_with('#') || trimmed.is_empty() {
2018                continue;
2019            }
2020            assert!(
2021                !trimmed.contains("= None"),
2022                "Line {} contains invalid TOML 'None' literal: {}",
2023                line_no + 1,
2024                line
2025            );
2026        }
2027
2028        let parse_result: Result<toml::Table, _> = toml_output.parse();
2029        assert!(
2030            parse_result.is_ok(),
2031            "Generated TOML is not valid: {:?}",
2032            parse_result.err()
2033        );
2034    }
2035
2036    #[cfg(feature = "agent")]
2037    #[test]
2038    fn test_config_print_comments_out_none_option_fields() {
2039        let mut default_args = Args::parse_from(["passless"]);
2040        let config = AppConfig::from(&mut default_args.config);
2041        let toml_output = config.to_toml_with_comments();
2042
2043        assert!(
2044            toml_output.contains("# audit_path = <not set>"),
2045            "Option::None field 'audit_path' should be commented out, got:\n{}",
2046            toml_output
2047        );
2048    }
2049}