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    /// Install native messaging manifest for browser extension
956    InstallNativeMessaging {
957        /// Browser executable path (e.g., /usr/bin/chromium)
958        #[arg(long)]
959        browser: String,
960
961        /// Extension directory path
962        #[arg(long)]
963        ext_dir: PathBuf,
964
965        /// Sign proxy binary path
966        #[arg(long, default_value = "/usr/bin/sign-proxy")]
967        sign_proxy: PathBuf,
968    },
969    /// Profile management
970    Profile {
971        #[command(subcommand)]
972        action: AdminProfileAction,
973    },
974    /// Policy management
975    Policy {
976        #[command(subcommand)]
977        action: AdminPolicyAction,
978    },
979    /// Credential management
980    Credential {
981        #[command(subcommand)]
982        action: AdminCredentialAction,
983    },
984    /// Delegation management
985    Delegation {
986        #[command(subcommand)]
987        action: AdminDelegationAction,
988    },
989    /// Session management
990    Session {
991        #[command(subcommand)]
992        action: AdminSessionAction,
993    },
994    /// Browser session management
995    Browser {
996        #[command(subcommand)]
997        action: AdminBrowserAction,
998    },
999    /// Audit log management
1000    Audit {
1001        #[command(subcommand)]
1002        action: AdminAuditAction,
1003    },
1004    /// Shut down the running daemon
1005    #[command(hide = true)]
1006    Shutdown {
1007        /// Confirm the shutdown
1008        #[arg(long)]
1009        confirm: bool,
1010    },
1011}
1012
1013/// Admin profile actions
1014#[cfg(feature = "agent")]
1015#[derive(Subcommand, Debug, Clone)]
1016pub enum AdminProfileAction {
1017    /// Check if a profile exists and is valid
1018    Check {
1019        /// Profile identifier
1020        #[arg(value_name = "PROFILE")]
1021        profile: String,
1022    },
1023    /// Show profile details
1024    Show {
1025        /// Profile identifier
1026        #[arg(value_name = "PROFILE")]
1027        profile: String,
1028    },
1029    /// List all configured profiles
1030    List,
1031    /// Enable a profile
1032    Enable {
1033        /// Profile identifier
1034        #[arg(value_name = "PROFILE")]
1035        profile: String,
1036    },
1037    /// Disable a profile
1038    Disable {
1039        /// Profile identifier
1040        #[arg(value_name = "PROFILE")]
1041        profile: String,
1042    },
1043}
1044
1045/// Admin policy actions
1046#[cfg(feature = "agent")]
1047#[derive(Subcommand, Debug, Clone)]
1048pub enum AdminPolicyAction {
1049    /// Check policy validity for a profile
1050    Check {
1051        /// Profile identifier
1052        #[arg(value_name = "PROFILE")]
1053        profile: String,
1054    },
1055    /// Reload policy for a profile
1056    Reload {
1057        /// Profile identifier
1058        #[arg(value_name = "PROFILE")]
1059        profile: String,
1060    },
1061    /// Show current policy for a profile
1062    Show {
1063        /// Profile identifier
1064        #[arg(value_name = "PROFILE")]
1065        profile: String,
1066    },
1067}
1068
1069/// Admin credential actions
1070#[cfg(feature = "agent")]
1071#[derive(Subcommand, Debug, Clone)]
1072pub enum AdminCredentialAction {
1073    /// List credentials
1074    List {
1075        /// Filter by relying party ID
1076        #[arg(short = 'd', long = "domain", value_name = "DOMAIN")]
1077        rp_id: Option<String>,
1078    },
1079    /// Show credential details
1080    Show {
1081        /// Credential reference (hex)
1082        #[arg(value_name = "CREDENTIAL_REF")]
1083        credential_ref: String,
1084    },
1085    /// Revoke a credential
1086    Revoke {
1087        /// Credential reference (hex)
1088        #[arg(value_name = "CREDENTIAL_REF")]
1089        credential_ref: String,
1090        /// Confirm the revocation
1091        #[arg(long)]
1092        confirm: bool,
1093    },
1094    /// Delete a credential
1095    Delete {
1096        /// Credential reference (hex)
1097        #[arg(value_name = "CREDENTIAL_REF")]
1098        credential_ref: String,
1099        /// Confirm the deletion
1100        #[arg(long)]
1101        confirm: bool,
1102    },
1103}
1104
1105/// Admin delegation actions
1106#[cfg(feature = "agent")]
1107#[derive(Subcommand, Debug, Clone)]
1108pub enum AdminDelegationAction {
1109    /// Show delegation details
1110    Show {
1111        /// Grant identifier (hex)
1112        #[arg(value_name = "GRANT_ID")]
1113        grant_id: String,
1114    },
1115    /// List all delegations
1116    List {
1117        /// Filter by profile
1118        #[arg(long, value_name = "PROFILE")]
1119        profile: Option<String>,
1120    },
1121    /// Revoke a delegation
1122    Revoke {
1123        /// Grant identifier (hex)
1124        #[arg(value_name = "GRANT_ID")]
1125        grant_id: String,
1126        /// Confirm the revocation
1127        #[arg(long)]
1128        confirm: bool,
1129    },
1130    /// Create an exact-RP, short-lived, one-shot registration enrollment grant
1131    RequestRegistration {
1132        /// Profile identifier
1133        #[arg(long, value_name = "PROFILE")]
1134        profile: String,
1135        /// Relying party ID
1136        #[arg(long, value_name = "RP_ID")]
1137        rp: String,
1138        /// Enrollment grant TTL in seconds (clamped to profile TTL and 300 seconds)
1139        #[arg(long, value_name = "SECONDS")]
1140        session_ttl: u64,
1141        /// Reason for the registration
1142        #[arg(long, value_name = "REASON")]
1143        reason: Option<String>,
1144    },
1145}
1146
1147/// Admin session actions
1148#[cfg(feature = "agent")]
1149#[derive(Subcommand, Debug, Clone)]
1150pub enum AdminSessionAction {
1151    /// Show session details
1152    Show {
1153        /// Session identifier (hex)
1154        #[arg(value_name = "SESSION_ID")]
1155        session_id: String,
1156    },
1157    /// List all sessions
1158    List {
1159        /// Filter by profile
1160        #[arg(long, value_name = "PROFILE")]
1161        profile: Option<String>,
1162    },
1163    /// Revoke a session
1164    Revoke {
1165        /// Session identifier (hex)
1166        #[arg(value_name = "SESSION_ID")]
1167        session_id: String,
1168        /// Confirm the revocation
1169        #[arg(long)]
1170        confirm: bool,
1171    },
1172}
1173
1174/// Admin browser actions
1175#[cfg(feature = "agent")]
1176#[derive(Subcommand, Debug, Clone)]
1177pub enum AdminBrowserAction {
1178    /// Launch a browser session with the agent extension
1179    Launch {
1180        /// Profile identifier
1181        #[arg(long, value_name = "PROFILE")]
1182        profile: String,
1183        /// Start URL to open in the browser
1184        #[arg(long, value_name = "URL")]
1185        url: Option<String>,
1186    },
1187}
1188
1189/// Admin audit actions
1190#[cfg(feature = "agent")]
1191#[derive(Subcommand, Debug, Clone)]
1192pub enum AdminAuditAction {
1193    /// Show audit subsystem status
1194    Status,
1195    /// Verify audit log integrity
1196    Verify,
1197    /// Export audit log entries
1198    Export {
1199        /// Export format
1200        #[arg(long, value_enum, default_value_t = AdminAuditExportFormat::Json)]
1201        format: AdminAuditExportFormat,
1202    },
1203}
1204
1205/// Audit export format for CLI
1206#[cfg(feature = "agent")]
1207#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1208pub enum AdminAuditExportFormat {
1209    Json,
1210    Csv,
1211}
1212
1213/// Supported coding-agent skill targets
1214#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1215pub enum AgentSkillTarget {
1216    Auto,
1217    Opencode,
1218    Claude,
1219    Pi,
1220}
1221
1222/// Skill installation scope
1223#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1224pub enum AgentSkillScope {
1225    User,
1226    Project,
1227}
1228
1229/// Client actions for FIDO2 authenticator management
1230#[derive(Subcommand, Debug, Clone)]
1231pub enum ClientAction {
1232    /// List all available FIDO2 authenticators/devices
1233    Devices,
1234    /// Get authenticator information (capabilities, AAGUID, versions, etc.)
1235    Info,
1236    /// Reset the authenticator (WARNING: deletes ALL credentials)
1237    Reset {
1238        /// Confirmation flag that must be provided twice for safety
1239        #[arg(long = "yes-i-really-want-to-reset-my-device", action = ArgAction::Count)]
1240        confirm: u8,
1241    },
1242    /// List all credentials on the authenticator
1243    List {
1244        /// Filter by relying party ID (domain)
1245        #[arg(short = 'd', long = "domain", value_name = "DOMAIN")]
1246        rp_id: Option<String>,
1247    },
1248    /// Show detailed information about a specific credential
1249    Show {
1250        /// Credential ID in hexadecimal format
1251        #[arg(value_name = "CREDENTIAL_ID")]
1252        credential_id: String,
1253    },
1254    /// Delete a specific credential by ID
1255    Delete {
1256        /// Credential ID in hexadecimal format
1257        #[arg(value_name = "CREDENTIAL_ID")]
1258        credential_id: String,
1259    },
1260    /// Rename a credential (update user name and/or display name)
1261    Rename {
1262        /// Credential ID in hexadecimal format
1263        #[arg(value_name = "CREDENTIAL_ID")]
1264        credential_id: String,
1265        /// New user name (login identifier)
1266        #[arg(short = 'u', long = "user-name", value_name = "NAME")]
1267        user_name: Option<String>,
1268        /// New display name (friendly name)
1269        #[arg(short = 'n', long = "display-name", value_name = "NAME")]
1270        display_name: Option<String>,
1271    },
1272    /// Export one software-backed credential as an opaque encrypted bundle.
1273    Backup {
1274        /// Credential ID in hexadecimal format
1275        #[arg(value_name = "CREDENTIAL_ID")]
1276        credential_id: String,
1277        /// Authenticator-local credential-backup wrapping-key identifier
1278        #[arg(long, value_name = "RECIPIENT")]
1279        recipient: String,
1280        /// Destination bundle path
1281        #[arg(long, value_name = "PATH")]
1282        output_file: PathBuf,
1283        /// Explicitly acknowledge that a passkey is being exported
1284        #[arg(long = "yes-i-understand-this-exports-a-passkey")]
1285        confirm: bool,
1286    },
1287    /// Restore an encrypted Passless credential bundle.
1288    Restore {
1289        /// Source bundle path
1290        #[arg(value_name = "PATH")]
1291        input_file: PathBuf,
1292        /// Replace a credential with the same ID
1293        #[arg(long)]
1294        replace: bool,
1295        /// Explicitly acknowledge that a passkey is being restored
1296        #[arg(long = "yes-i-understand-this-restores-a-passkey")]
1297        confirm: bool,
1298    },
1299    /// PIN management commands
1300    Pin {
1301        #[command(subcommand)]
1302        action: PinAction,
1303    },
1304}
1305
1306/// PIN management actions
1307#[derive(Subcommand, Debug, Clone)]
1308pub enum PinAction {
1309    /// Set a new PIN (authenticator must not have a PIN set)
1310    Set {
1311        /// The new PIN (minimum 4 characters)
1312        #[arg(value_name = "PIN")]
1313        pin: String,
1314    },
1315    /// Change the existing PIN
1316    Change {
1317        /// The current PIN
1318        #[arg(value_name = "OLD_PIN")]
1319        old_pin: String,
1320        /// The new PIN (minimum 4 characters)
1321        #[arg(value_name = "NEW_PIN")]
1322        new_pin: String,
1323    },
1324    /// Reset built-in user verification retries without deleting credentials
1325    UvReset,
1326}
1327
1328/// Agent principal and session commands
1329#[cfg(feature = "agent")]
1330#[derive(Subcommand, Debug, Clone)]
1331pub enum AgentCommand {
1332    /// Run health diagnostics
1333    Doctor,
1334    /// Show principal capabilities
1335    Capabilities,
1336    /// Show principal instructions
1337    Instructions,
1338    /// Intent management
1339    Intent {
1340        #[command(subcommand)]
1341        action: AgentIntentAction,
1342    },
1343    /// Delegation management
1344    Delegation {
1345        #[command(subcommand)]
1346        action: AgentDelegationAction,
1347    },
1348    /// Credential queries
1349    Credential {
1350        #[command(subcommand)]
1351        action: AgentCredentialAction,
1352    },
1353    /// Show browser bridge status
1354    BrowserStatus,
1355    /// Show endpoint status
1356    EndpointStatus,
1357    /// Send a CDP command to the managed browser session
1358    ///
1359    /// WARNING: This is the full browser-session authority interface.
1360    /// CDP commands can access cookies, DOM, network state, and session data.
1361    /// Output may contain CDP response data — do not mix with credential/admin output.
1362    BrowserControl {
1363        /// CDP request as JSON (e.g. '{"id":1,"method":"Page.navigate","params":{"url":"https://example.com"}}')
1364        #[arg(long, value_name = "JSON", conflicts_with = "request_file")]
1365        request: Option<String>,
1366        /// Path to file containing CDP request JSON (owner/symlink/size checked)
1367        #[arg(long, value_name = "PATH", conflicts_with = "request")]
1368        request_file: Option<std::path::PathBuf>,
1369        /// Timeout in milliseconds (default: 5000, max: 30000)
1370        #[arg(long, value_name = "MS", default_value = "5000")]
1371        timeout_ms: u32,
1372    },
1373    /// Run Playwright MCP with lazy access to the profile's trusted CDP browser
1374    PlaywrightMcp {
1375        /// Profile to bind the Playwright session to
1376        #[arg(long, value_name = "PROFILE")]
1377        profile: String,
1378        /// Start URL to open in the managed browser
1379        #[arg(long, value_name = "URL")]
1380        url: Option<String>,
1381        /// Absolute Playwright MCP executable and arguments
1382        #[arg(last = true, required = true)]
1383        command: Vec<std::path::PathBuf>,
1384    },
1385    /// Launch a detached principal session
1386    Run {
1387        /// Profile to launch
1388        #[arg(long, value_name = "PROFILE")]
1389        profile: String,
1390        /// Absolute command path and arguments
1391        #[arg(last = true, required = true)]
1392        command: Vec<std::path::PathBuf>,
1393    },
1394}
1395
1396/// Agent intent actions
1397#[cfg(feature = "agent")]
1398#[derive(Subcommand, Debug, Clone)]
1399pub enum AgentIntentAction {
1400    /// Create a new intent
1401    Create {
1402        /// Action type
1403        #[arg(value_enum)]
1404        action: AgentIntentActionType,
1405        /// Relying party ID
1406        #[arg(long, value_name = "RP_ID")]
1407        rp: String,
1408        /// Credential reference (hex)
1409        #[arg(long, value_name = "CREDENTIAL_REF")]
1410        credential: Option<String>,
1411        /// Reason for the intent
1412        #[arg(long, value_name = "REASON")]
1413        reason: Option<String>,
1414    },
1415    /// Show intent status
1416    Show {
1417        /// Request identifier (hex)
1418        #[arg(value_name = "REQUEST_ID")]
1419        request_id: String,
1420    },
1421    /// Wait for intent to reach terminal state
1422    Wait {
1423        /// Request identifier (hex)
1424        #[arg(value_name = "REQUEST_ID")]
1425        request_id: String,
1426        /// Timeout in seconds
1427        #[arg(long, value_name = "SECONDS")]
1428        timeout: Option<u64>,
1429        /// Poll interval in milliseconds
1430        #[arg(long, value_name = "MS")]
1431        poll_interval: Option<u64>,
1432    },
1433    /// Cancel a pending intent
1434    Cancel {
1435        /// Request identifier (hex)
1436        #[arg(value_name = "REQUEST_ID")]
1437        request_id: String,
1438    },
1439}
1440
1441/// Intent action type for CLI
1442#[cfg(feature = "agent")]
1443#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1444pub enum AgentIntentActionType {
1445    Register,
1446    Authenticate,
1447}
1448
1449/// Agent delegation actions
1450#[cfg(feature = "agent")]
1451#[derive(Subcommand, Debug, Clone)]
1452pub enum AgentDelegationAction {
1453    /// Request a new delegation
1454    Request {
1455        /// Relying party ID
1456        #[arg(long, value_name = "RP_ID")]
1457        rp: String,
1458        /// Credential reference (hex)
1459        #[arg(long, value_name = "CREDENTIAL_REF")]
1460        credential: String,
1461        /// Session TTL in seconds
1462        #[arg(long, value_name = "SECONDS")]
1463        session_ttl: u64,
1464        /// Reason for the delegation
1465        #[arg(long, value_name = "REASON")]
1466        reason: Option<String>,
1467    },
1468    /// Show delegation status
1469    Show {
1470        /// Request identifier (hex)
1471        #[arg(value_name = "REQUEST_ID")]
1472        request_id: String,
1473    },
1474    /// Wait for delegation to reach terminal state
1475    Wait {
1476        /// Request identifier (hex)
1477        #[arg(value_name = "REQUEST_ID")]
1478        request_id: String,
1479        /// Timeout in seconds
1480        #[arg(long, value_name = "SECONDS")]
1481        timeout: Option<u64>,
1482        /// Poll interval in milliseconds
1483        #[arg(long, value_name = "MS")]
1484        poll_interval: Option<u64>,
1485    },
1486    /// Cancel a pending delegation
1487    Cancel {
1488        /// Request identifier (hex)
1489        #[arg(value_name = "REQUEST_ID")]
1490        request_id: String,
1491    },
1492}
1493
1494/// Agent credential actions
1495#[cfg(feature = "agent")]
1496#[derive(Subcommand, Debug, Clone)]
1497pub enum AgentCredentialAction {
1498    /// List credentials for the profile
1499    List,
1500    /// Show credential details
1501    Show {
1502        /// Credential reference (hex)
1503        #[arg(value_name = "CREDENTIAL_REF")]
1504        credential_ref: String,
1505    },
1506}
1507
1508#[cfg(test)]
1509mod tests {
1510    use super::*;
1511
1512    #[cfg(feature = "agent")]
1513    #[test]
1514    fn test_agent_admin_install_defaults() {
1515        let args = Args::try_parse_from(["passless", "agent-admin", "install"]).unwrap();
1516        assert!(matches!(
1517            args.command,
1518            Some(Commands::AgentAdmin {
1519                action: AgentAdminAction::Install {
1520                    target: AgentSkillTarget::Auto,
1521                    scope: AgentSkillScope::User,
1522                    force: false,
1523                },
1524                ..
1525            })
1526        ));
1527    }
1528
1529    #[cfg(feature = "agent")]
1530    #[test]
1531    fn test_agent_admin_install_explicit_options() {
1532        let args = Args::try_parse_from([
1533            "passless",
1534            "agent-admin",
1535            "install",
1536            "claude",
1537            "--scope",
1538            "project",
1539            "--force",
1540        ])
1541        .unwrap();
1542        assert!(matches!(
1543            args.command,
1544            Some(Commands::AgentAdmin {
1545                action: AgentAdminAction::Install {
1546                    target: AgentSkillTarget::Claude,
1547                    scope: AgentSkillScope::Project,
1548                    force: true,
1549                },
1550                ..
1551            })
1552        ));
1553    }
1554
1555    #[test]
1556    fn test_pin_config_default_max_uv_retries() {
1557        let config = PinConfig {
1558            enforcement: PinEnforcement::Optional,
1559            min_length: 4,
1560            max_retries: 8,
1561            max_uv_retries: 8,
1562            auto_lock_timeout: 0,
1563        };
1564        assert_eq!(config.max_uv_retries, 8);
1565    }
1566
1567    #[test]
1568    fn test_pin_config_validate_success() {
1569        let config = PinConfig {
1570            enforcement: PinEnforcement::Optional,
1571            min_length: 4,
1572            max_retries: 8,
1573            max_uv_retries: 8,
1574            auto_lock_timeout: 0,
1575        };
1576        assert!(config.validate().is_ok());
1577    }
1578
1579    #[test]
1580    fn test_pin_config_validate_zero_max_uv_retries() {
1581        let config = PinConfig {
1582            enforcement: PinEnforcement::Optional,
1583            min_length: 4,
1584            max_retries: 8,
1585            max_uv_retries: 0,
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_uv_retries"));
1591    }
1592
1593    #[test]
1594    fn test_pin_config_validate_zero_max_retries() {
1595        let config = PinConfig {
1596            enforcement: PinEnforcement::Optional,
1597            min_length: 4,
1598            max_retries: 0,
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("max_retries"));
1605    }
1606
1607    #[test]
1608    fn test_pin_config_validate_invalid_min_length() {
1609        let config = PinConfig {
1610            enforcement: PinEnforcement::Optional,
1611            min_length: 3,
1612            max_retries: 8,
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("min_length"));
1619    }
1620
1621    #[test]
1622    fn test_canonicalize_path_existing() {
1623        let dir = std::env::temp_dir();
1624        let canonical = BackendConfig::canonicalize_path(&dir);
1625        assert!(canonical.is_absolute());
1626        assert!(canonical.exists());
1627    }
1628
1629    #[test]
1630    fn test_canonicalize_path_nonexistent() {
1631        let base = std::env::temp_dir();
1632        let nonexistent = base.join("passless_test_nonexistent_dir_12345/sub");
1633        let canonical = BackendConfig::canonicalize_path(&nonexistent);
1634        assert!(canonical.is_absolute());
1635        assert!(canonical.starts_with(BackendConfig::canonicalize_path(&base)));
1636    }
1637
1638    #[test]
1639    fn test_canonicalize_path_symlink() {
1640        let dir = tempfile::tempdir().unwrap();
1641        let real = dir.path().join("real");
1642        std::fs::create_dir(&real).unwrap();
1643        let link = dir.path().join("link");
1644        std::os::unix::fs::symlink(&real, &link).unwrap();
1645
1646        let canonical_real = BackendConfig::canonicalize_path(&real);
1647        let canonical_link = BackendConfig::canonicalize_path(&link);
1648        assert_eq!(canonical_real, canonical_link);
1649    }
1650
1651    #[test]
1652    fn test_local_state_path_relative_and_absolute() {
1653        let dir = tempfile::tempdir_in(".").unwrap();
1654        let abs_path = std::fs::canonicalize(dir.path()).unwrap();
1655        let rel_path = dir.path().to_path_buf();
1656
1657        let backend_abs = BackendConfig::Local {
1658            path: abs_path.display().to_string(),
1659        };
1660        let backend_rel = BackendConfig::Local {
1661            path: rel_path.display().to_string(),
1662        };
1663        assert_eq!(backend_abs.state_path(), backend_rel.state_path());
1664    }
1665
1666    #[test]
1667    fn test_pass_state_path_different_subpaths() {
1668        let store = "/tmp/passless_test_store";
1669        let backend_a = BackendConfig::Pass {
1670            store_path: store.to_string(),
1671            path: "fido2".to_string(),
1672            gpg_backend: "gnupg-bin".to_string(),
1673        };
1674        let backend_b = BackendConfig::Pass {
1675            store_path: store.to_string(),
1676            path: "fido2-other".to_string(),
1677            gpg_backend: "gnupg-bin".to_string(),
1678        };
1679        assert_ne!(backend_a.state_path(), backend_b.state_path());
1680    }
1681
1682    #[test]
1683    fn test_different_local_paths_produce_different_identities() {
1684        let backend_a = BackendConfig::Local {
1685            path: "/tmp/passless_a".to_string(),
1686        };
1687        let backend_b = BackendConfig::Local {
1688            path: "/tmp/passless_b".to_string(),
1689        };
1690        assert_ne!(backend_a.state_path(), backend_b.state_path());
1691    }
1692
1693    #[cfg(feature = "agent")]
1694    #[test]
1695    fn test_agent_admin_profile_list() {
1696        let args = Args::try_parse_from(["passless", "agent-admin", "profile", "list"]).unwrap();
1697        assert!(matches!(
1698            args.command,
1699            Some(Commands::AgentAdmin {
1700                action: AgentAdminAction::Profile {
1701                    action: AdminProfileAction::List,
1702                },
1703                ..
1704            })
1705        ));
1706    }
1707
1708    #[cfg(feature = "agent")]
1709    #[test]
1710    fn test_agent_admin_credential_delete_without_confirm() {
1711        let args = Args::try_parse_from([
1712            "passless",
1713            "agent-admin",
1714            "credential",
1715            "delete",
1716            "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
1717        ])
1718        .unwrap();
1719        assert!(matches!(
1720            args.command,
1721            Some(Commands::AgentAdmin {
1722                action: AgentAdminAction::Credential {
1723                    action: AdminCredentialAction::Delete { confirm: false, .. },
1724                },
1725                ..
1726            })
1727        ));
1728    }
1729
1730    #[cfg(feature = "agent")]
1731    #[test]
1732    fn test_agent_admin_credential_delete_with_confirm() {
1733        let args = Args::try_parse_from([
1734            "passless",
1735            "agent-admin",
1736            "credential",
1737            "delete",
1738            "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
1739            "--confirm",
1740        ])
1741        .unwrap();
1742        assert!(matches!(
1743            args.command,
1744            Some(Commands::AgentAdmin {
1745                action: AgentAdminAction::Credential {
1746                    action: AdminCredentialAction::Delete { confirm: true, .. },
1747                },
1748                ..
1749            })
1750        ));
1751    }
1752
1753    #[cfg(feature = "agent")]
1754    #[test]
1755    fn test_agent_admin_shutdown_hidden() {
1756        let args =
1757            Args::try_parse_from(["passless", "agent-admin", "shutdown", "--confirm"]).unwrap();
1758        assert!(matches!(
1759            args.command,
1760            Some(Commands::AgentAdmin {
1761                action: AgentAdminAction::Shutdown { confirm: true },
1762                ..
1763            })
1764        ));
1765    }
1766
1767    #[cfg(feature = "agent")]
1768    #[test]
1769    fn test_agent_admin_output_default_json() {
1770        let args = Args::try_parse_from(["passless", "agent-admin", "profile", "list"]).unwrap();
1771        match args.command {
1772            Some(Commands::AgentAdmin { output, .. }) => {
1773                assert_eq!(output, OutputFormat::Json);
1774            }
1775            _ => panic!("expected AgentAdmin command"),
1776        }
1777    }
1778
1779    #[cfg(feature = "agent")]
1780    #[test]
1781    fn test_agent_admin_output_plain() {
1782        let args = Args::try_parse_from([
1783            "passless",
1784            "agent-admin",
1785            "--output",
1786            "plain",
1787            "profile",
1788            "list",
1789        ])
1790        .unwrap();
1791        match args.command {
1792            Some(Commands::AgentAdmin { output, .. }) => {
1793                assert_eq!(output, OutputFormat::Plain);
1794            }
1795            _ => panic!("expected AgentAdmin command"),
1796        }
1797    }
1798
1799    #[cfg(feature = "agent")]
1800    #[test]
1801    fn test_agent_doctor_parses() {
1802        let args = Args::try_parse_from(["passless", "agent", "doctor"]).unwrap();
1803        assert!(matches!(
1804            args.command,
1805            Some(Commands::Agent {
1806                action: AgentCommand::Doctor,
1807                ..
1808            })
1809        ));
1810    }
1811
1812    #[cfg(feature = "agent")]
1813    #[test]
1814    fn test_agent_run_with_command() {
1815        let args = Args::try_parse_from([
1816            "passless",
1817            "agent",
1818            "run",
1819            "--profile",
1820            "myprofile",
1821            "--",
1822            "/usr/bin/test",
1823            "arg1",
1824        ])
1825        .unwrap();
1826        match args.command {
1827            Some(Commands::Agent {
1828                action: AgentCommand::Run { profile, command },
1829                ..
1830            }) => {
1831                assert_eq!(profile, "myprofile");
1832                assert_eq!(command.len(), 2);
1833            }
1834            _ => panic!("expected Agent Run command"),
1835        }
1836    }
1837
1838    #[cfg(feature = "agent")]
1839    #[test]
1840    fn test_agent_intent_create_parses() {
1841        let args = Args::try_parse_from([
1842            "passless",
1843            "agent",
1844            "intent",
1845            "create",
1846            "register",
1847            "--rp",
1848            "example.com",
1849        ])
1850        .unwrap();
1851        assert!(matches!(
1852            args.command,
1853            Some(Commands::Agent {
1854                action: AgentCommand::Intent {
1855                    action: AgentIntentAction::Create {
1856                        action: AgentIntentActionType::Register,
1857                        ..
1858                    },
1859                },
1860                ..
1861            })
1862        ));
1863    }
1864
1865    #[cfg(feature = "agent")]
1866    #[test]
1867    fn test_agent_output_default_json() {
1868        let args = Args::try_parse_from(["passless", "agent", "doctor"]).unwrap();
1869        match args.command {
1870            Some(Commands::Agent { output, .. }) => {
1871                assert_eq!(output, OutputFormat::Json);
1872            }
1873            _ => panic!("expected Agent command"),
1874        }
1875    }
1876
1877    #[cfg(feature = "agent")]
1878    #[test]
1879    fn test_shell_completions_contain_agent_commands() {
1880        use clap::CommandFactory;
1881
1882        let cmd = Args::command();
1883        let mut buf = Vec::new();
1884        clap_complete::generate(
1885            clap_complete::Shell::Bash,
1886            &mut cmd.clone(),
1887            "passless",
1888            &mut buf,
1889        );
1890        let completion = String::from_utf8(buf).unwrap();
1891
1892        for expected in [
1893            "agent-admin",
1894            "agent",
1895            "install",
1896            "browser-control",
1897            "intent",
1898            "delegation",
1899            "doctor",
1900            "capabilities",
1901            "instructions",
1902        ] {
1903            assert!(
1904                completion.contains(expected),
1905                "bash completion missing '{}'",
1906                expected
1907            );
1908        }
1909    }
1910
1911    #[cfg(feature = "agent")]
1912    #[test]
1913    fn test_shell_completions_zsh_contain_agent_commands() {
1914        use clap::CommandFactory;
1915
1916        let cmd = Args::command();
1917        let mut buf = Vec::new();
1918        clap_complete::generate(
1919            clap_complete::Shell::Zsh,
1920            &mut cmd.clone(),
1921            "passless",
1922            &mut buf,
1923        );
1924        let completion = String::from_utf8(buf).unwrap();
1925
1926        for expected in ["agent-admin", "agent", "install", "browser-control"] {
1927            assert!(
1928                completion.contains(expected),
1929                "zsh completion missing '{}'",
1930                expected
1931            );
1932        }
1933    }
1934
1935    #[cfg(feature = "agent")]
1936    #[test]
1937    fn test_config_print_includes_agent_fields() {
1938        let mut default_args = Args::parse_from(["passless"]);
1939        let config = AppConfig::from(&mut default_args.config);
1940        let toml_output = config.to_toml_with_comments();
1941
1942        assert!(
1943            toml_output.contains("backend_type"),
1944            "config print missing backend_type"
1945        );
1946        assert!(
1947            toml_output.contains("[security]"),
1948            "config print missing [security] section"
1949        );
1950        assert!(
1951            toml_output.contains("[pin]"),
1952            "config print missing [pin] section"
1953        );
1954        assert!(
1955            toml_output.contains("always_uv"),
1956            "config print missing always_uv"
1957        );
1958        assert!(
1959            toml_output.contains("notification_timeout"),
1960            "config print missing notification_timeout"
1961        );
1962    }
1963
1964    #[test]
1965    fn test_config_print_contains_passless_header() {
1966        let mut default_args = Args::parse_from(["passless"]);
1967        let config = AppConfig::from(&mut default_args.config);
1968        let toml_output = config.to_toml_with_comments();
1969
1970        assert!(toml_output.contains("Passless Configuration File"));
1971        assert!(toml_output.contains("~/.config/passless/config.toml"));
1972    }
1973
1974    #[test]
1975    fn test_config_print_contains_local_backend_section() {
1976        let mut default_args = Args::parse_from(["passless"]);
1977        let config = AppConfig::from(&mut default_args.config);
1978        let toml_output = config.to_toml_with_comments();
1979
1980        assert!(toml_output.contains("[local]"));
1981        assert!(toml_output.contains("path"));
1982    }
1983
1984    #[test]
1985    fn test_config_print_contains_pass_backend_section() {
1986        let mut default_args = Args::parse_from(["passless"]);
1987        let config = AppConfig::from(&mut default_args.config);
1988        let toml_output = config.to_toml_with_comments();
1989
1990        assert!(toml_output.contains("[pass]"));
1991        assert!(toml_output.contains("store_path"));
1992        assert!(toml_output.contains("gpg_backend"));
1993    }
1994
1995    #[test]
1996    fn test_config_print_produces_valid_toml_without_none_literals() {
1997        let mut default_args = Args::parse_from(["passless"]);
1998        let config = AppConfig::from(&mut default_args.config);
1999        let toml_output = config.to_toml_with_comments();
2000
2001        for (line_no, line) in toml_output.lines().enumerate() {
2002            let trimmed = line.trim();
2003            if trimmed.starts_with('#') || trimmed.is_empty() {
2004                continue;
2005            }
2006            assert!(
2007                !trimmed.contains("= None"),
2008                "Line {} contains invalid TOML 'None' literal: {}",
2009                line_no + 1,
2010                line
2011            );
2012        }
2013
2014        let parse_result: Result<toml::Table, _> = toml_output.parse();
2015        assert!(
2016            parse_result.is_ok(),
2017            "Generated TOML is not valid: {:?}",
2018            parse_result.err()
2019        );
2020    }
2021
2022    #[cfg(feature = "agent")]
2023    #[test]
2024    fn test_config_print_comments_out_none_option_fields() {
2025        let mut default_args = Args::parse_from(["passless"]);
2026        let config = AppConfig::from(&mut default_args.config);
2027        let toml_output = config.to_toml_with_comments();
2028
2029        assert!(
2030            toml_output.contains("# audit_path = <not set>"),
2031            "Option::None field 'audit_path' should be commented out, got:\n{}",
2032            toml_output
2033        );
2034    }
2035}