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