1use 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
26pub 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#[derive(ClapSerde, Debug, Clone, Serialize, Deserialize, ConfigDoc)]
37#[group(id = "local-backend-config")]
38pub struct LocalBackendConfig {
39 #[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
51pub 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#[derive(ClapSerde, Debug, Clone, Serialize, Deserialize, ConfigDoc)]
61#[group(id = "pass-backend-config")]
62pub struct PassBackendConfig {
63 #[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 #[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 #[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 #[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 #[arg(
111 long = "pass-git-auto-push",
112 env = "PASSLESS_PASS_GIT_AUTO_PUSH",
113 action = ArgAction::Set,
114 require_equals = true,
115 num_args = 0..=1,
116 default_missing_value = "true"
117 )]
118 #[serde(default)]
119 #[default(true)]
120 pub git_auto_push: bool,
121}
122
123pub fn tpm_path() -> String {
125 dirs::data_dir()
126 .expect("Could not determine data directory: $XDG_DATA_HOME or $HOME/.local/share")
127 .join("passless/tpm")
128 .to_string_lossy()
129 .into_owned()
130}
131
132#[cfg(feature = "tpm")]
134#[derive(ClapSerde, Debug, Clone, Serialize, Deserialize, ConfigDoc)]
135#[group(id = "tpm-backend-config")]
136pub struct TpmBackendConfig {
137 #[arg(
139 long = "tpm-path",
140 env = "PASSLESS_TPM_PATH",
141 id = "tpm-path",
142 value_name = "PATH"
143 )]
144 #[serde(default)]
145 #[default(tpm_path())]
146 pub path: String,
147
148 #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI", value_name = "TCTI")]
150 #[serde(default)]
151 #[default("device:/dev/tpmrm0".to_string())]
152 pub tcti: String,
153
154 #[arg(long = "tpm-portable", env = "PASSLESS_TPM_PORTABLE")]
156 #[serde(default)]
157 #[default(false)]
158 pub portable: bool,
159}
160
161#[derive(ClapSerde, Debug, Clone, Serialize, Deserialize, ConfigDoc)]
163#[group(id = "security")]
164pub struct SecurityConfig {
165 #[arg(long = "check-mlock", env = "PASSLESS_CHECK_MLOCK")]
167 #[serde(default)]
168 #[default(true)]
169 pub check_mlock: bool,
170
171 #[arg(long = "disable-core-dumps", env = "PASSLESS_DISABLE_CORE_DUMPS")]
173 #[serde(default)]
174 #[default(true)]
175 pub disable_core_dumps: bool,
176
177 #[arg(
179 long = "constant-signature-counter",
180 env = "PASSLESS_CONSTANT_SIGNATURE_COUNTER",
181 action = ArgAction::Set,
182 require_equals = true,
183 num_args = 0..=1,
184 default_missing_value = "true"
185 )]
186 #[serde(default)]
187 pub constant_signature_counter: bool,
188
189 #[arg(
202 long = "enable-credential-backup",
203 env = "PASSLESS_ENABLE_CREDENTIAL_BACKUP",
204 action = ArgAction::Set,
205 require_equals = true,
206 num_args = 0..=1,
207 default_missing_value = "true"
208 )]
209 #[serde(default)]
210 pub enable_credential_backup: bool,
211
212 #[arg(
218 long = "always-uv",
219 env = "PASSLESS_ALWAYS_UV",
220 action = ArgAction::Set,
221 require_equals = true,
222 num_args = 0..=1,
223 default_value = "true",
224 default_missing_value = "true"
225 )]
226 #[serde(default)]
227 #[default(true)]
228 pub always_uv: bool,
229
230 #[arg(
232 long = "user-verification-registration",
233 env = "PASSLESS_USER_VERIFICATION_REGISTRATION"
234 )]
235 #[serde(default)]
236 #[default(true)]
237 pub user_verification_registration: bool,
238
239 #[arg(
241 long = "user-verification-authentication",
242 env = "PASSLESS_USER_VERIFICATION_AUTHENTICATION"
243 )]
244 #[serde(default)]
245 #[default(true)]
246 pub user_verification_authentication: bool,
247
248 #[arg(
250 long = "notification-timeout",
251 env = "PASSLESS_NOTIFICATION_TIMEOUT",
252 value_name = "SECONDS"
253 )]
254 #[serde(default)]
255 #[default(30)]
256 pub notification_timeout: u32,
257}
258
259#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
261#[serde(rename_all = "lowercase")]
262pub enum PinEnforcement {
263 Never,
265 #[default]
267 Optional,
268 Required,
270}
271
272impl std::str::FromStr for PinEnforcement {
273 type Err = String;
274
275 fn from_str(s: &str) -> Result<Self, Self::Err> {
276 match s.to_lowercase().as_str() {
277 "never" => Ok(PinEnforcement::Never),
278 "optional" => Ok(PinEnforcement::Optional),
279 "required" => Ok(PinEnforcement::Required),
280 _ => Err(format!(
281 "Invalid PIN enforcement '{}'. Must be: never, optional, or required",
282 s
283 )),
284 }
285 }
286}
287
288impl std::fmt::Display for PinEnforcement {
289 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
290 match self {
291 PinEnforcement::Never => write!(f, "never"),
292 PinEnforcement::Optional => write!(f, "optional"),
293 PinEnforcement::Required => write!(f, "required"),
294 }
295 }
296}
297
298#[derive(ClapSerde, Debug, Clone, Serialize, Deserialize, ConfigDoc)]
300#[group(id = "pin")]
301pub struct PinConfig {
302 #[arg(
307 long = "pin-enforcement",
308 env = "PASSLESS_PIN_ENFORCEMENT",
309 value_name = "POLICY"
310 )]
311 #[serde(default)]
312 #[default(PinEnforcement::Optional)]
313 pub enforcement: PinEnforcement,
314
315 #[arg(
317 long = "pin-min-length",
318 env = "PASSLESS_PIN_MIN_LENGTH",
319 value_name = "LENGTH"
320 )]
321 #[serde(default)]
322 #[default(4)]
323 pub min_length: u8,
324
325 #[arg(
327 long = "pin-max-retries",
328 env = "PASSLESS_PIN_MAX_RETRIES",
329 value_name = "RETRIES"
330 )]
331 #[serde(default)]
332 #[default(8)]
333 pub max_retries: u8,
334
335 #[arg(
341 long = "pin-max-uv-retries",
342 env = "PASSLESS_PIN_MAX_UV_RETRIES",
343 value_name = "RETRIES"
344 )]
345 #[serde(default)]
346 #[default(8)]
347 pub max_uv_retries: u8,
348
349 #[arg(
352 long = "pin-auto-lock-timeout",
353 env = "PASSLESS_PIN_AUTO_LOCK_TIMEOUT",
354 value_name = "SECONDS"
355 )]
356 #[serde(default)]
357 #[default(0)]
358 pub auto_lock_timeout: u32,
359}
360
361impl PinConfig {
362 pub fn validate(&self) -> crate::error::Result<()> {
364 if self.min_length < 4 || self.min_length > 63 {
365 return Err(crate::error::Error::Config(format!(
366 "pin.min_length must be between 4 and 63, got {}",
367 self.min_length
368 )));
369 }
370 if self.max_retries == 0 {
371 return Err(crate::error::Error::Config(
372 "pin.max_retries must be greater than 0".to_string(),
373 ));
374 }
375 if self.max_uv_retries == 0 {
376 return Err(crate::error::Error::Config(
377 "pin.max_uv_retries must be greater than 0".to_string(),
378 ));
379 }
380 Ok(())
381 }
382}
383
384impl SecurityConfig {
385 pub fn apply_hardening(&self) -> Result<(), Box<dyn std::error::Error>> {
387 if self.disable_core_dumps {
388 self.disable_core_dumps_impl()?;
389 }
390 if self.check_mlock {
391 self.probe_mlock_capability()?;
392 }
393 Ok(())
394 }
395
396 fn disable_core_dumps_impl(&self) -> Result<(), Box<dyn std::error::Error>> {
398 debug!("Disabling core dumps to prevent credential leakage");
399 setrlimit(Resource::RLIMIT_CORE, 0, 0)?;
400 let r = unsafe { prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) };
401 if r != 0 {
402 log::warn!("prctl(PR_SET_DUMPABLE) failed: {}", r);
403 }
404 Ok(())
405 }
406
407 fn probe_mlock_capability(&self) -> Result<(), Box<dyn std::error::Error>> {
409 debug!("Check mlock capability");
410
411 let test_size = 4096;
412 let test_buffer = vec![0u8; test_size];
413 let ptr = test_buffer.as_ptr() as *const libc::c_void;
414
415 let lock_result = unsafe { mlock(ptr, test_size) };
416
417 if lock_result == 0 {
418 unsafe { munlock(ptr, test_size) };
419 log::debug!("MLOCK is enabled - sensitive data will not be swapped to disk");
420 } else {
421 log::warn!(
422 "mlock capability probe failed - memory locking may not be available.\n\
423 Hint: grant CAP_IPC_LOCK to the binary with: 'sudo setcap cap_ipc_lock=+ep $(which passless)'"
424 );
425 }
426 Ok(())
427 }
428}
429
430#[derive(ClapSerde, Serialize, Deserialize, Debug, ConfigDoc)]
433pub struct AppConfig {
434 #[arg(short = 't', long = "backend-type", env = "PASSLESS_BACKEND_TYPE")]
436 #[serde(default)]
437 #[default("pass".to_string())]
438 pub backend_type: String,
439
440 #[arg(
443 short,
444 long,
445 env = "PASSLESS_VERBOSE",
446 action = ArgAction::Set,
447 require_equals = true,
448 num_args = 0..=1,
449 default_missing_value = "true"
450 )]
451 #[default(true)]
452 #[serde(default)]
453 pub verbose: bool,
454
455 #[clap_serde]
457 #[command(flatten)]
458 pub pass: PassBackendConfig,
459
460 #[cfg(feature = "tpm")]
462 #[clap_serde]
463 #[command(flatten)]
464 pub tpm: TpmBackendConfig,
465
466 #[clap_serde]
468 #[command(flatten)]
469 pub local: LocalBackendConfig,
470
471 #[clap_serde]
473 #[command(flatten)]
474 pub security: SecurityConfig,
475
476 #[clap_serde]
478 #[command(flatten)]
479 pub pin: PinConfig,
480
481 #[cfg(feature = "agent")]
483 #[arg(skip)]
484 pub agents: AgentConfig,
485}
486
487#[derive(Debug, Clone)]
489pub enum BackendConfig {
490 Local {
491 path: String,
492 },
493 Pass {
494 store_path: String,
495 path: String,
496 gpg_backend: String,
497 },
498 #[cfg(feature = "tpm")]
499 Tpm {
500 path: String,
501 tcti: String,
502 portable: bool,
503 },
504}
505
506impl BackendConfig {
507 pub fn canonicalize_path(path: &Path) -> PathBuf {
512 match fs::canonicalize(path) {
513 Ok(p) => p,
514 Err(_) => {
515 let mut current = path.to_path_buf();
516 let mut suffix = Vec::new();
517 loop {
518 match fs::canonicalize(¤t) {
519 Ok(base) => {
520 let mut result = base;
521 for component in suffix.iter().rev() {
522 result.push(component);
523 }
524 return result;
525 }
526 Err(_) => {
527 if let Some(file_name) = current.file_name() {
528 suffix.push(file_name.to_os_string());
529 current = current
530 .parent()
531 .map(|p| p.to_path_buf())
532 .unwrap_or_default();
533 } else {
534 return path.to_path_buf();
535 }
536 }
537 }
538 }
539 }
540 }
541 }
542
543 pub fn state_path(&self) -> PathBuf {
548 match self {
549 BackendConfig::Local { path } => Self::canonicalize_path(Path::new(path)),
550 BackendConfig::Pass {
551 store_path, path, ..
552 } => Self::canonicalize_path(&Path::new(store_path).join(path)),
553 #[cfg(feature = "tpm")]
554 BackendConfig::Tpm { path, .. } => Self::canonicalize_path(Path::new(path)),
555 }
556 }
557
558 pub fn state_display(&self) -> String {
560 match self {
561 BackendConfig::Local { path } => path.clone(),
562 BackendConfig::Pass {
563 store_path, path, ..
564 } => {
565 format!("{}/{}", store_path, path)
566 }
567 #[cfg(feature = "tpm")]
568 BackendConfig::Tpm { path, .. } => path.clone(),
569 }
570 }
571
572 pub fn validate(&self) -> crate::error::Result<()> {
576 match self {
577 BackendConfig::Local { path } => {
578 let p = Path::new(path);
579 if !p.is_absolute() && !p.starts_with("~") {
580 debug!("Local backend path is relative: {}, canonicalizing", path);
581 }
582 Ok(())
583 }
584 BackendConfig::Pass {
585 store_path, path, ..
586 } => {
587 let p = Path::new(path);
588 if p.is_absolute() {
589 return Err(Error::Config(format!(
590 "Pass backend 'path' must be relative, got absolute path: {}",
591 path
592 )));
593 }
594 if path.contains("..") {
595 return Err(Error::Config(format!(
596 "Pass backend 'path' must not contain '..': {}",
597 path
598 )));
599 }
600 let combined = Path::new(store_path).join(path);
602 let canonical_store = Self::canonicalize_path(Path::new(store_path));
603 let canonical_combined = Self::canonicalize_path(&combined);
604 if !canonical_combined.starts_with(&canonical_store) {
605 return Err(Error::Config(format!(
606 "Pass backend 'path' escapes store_path: {} not beneath {}",
607 canonical_combined.display(),
608 canonical_store.display()
609 )));
610 }
611 Ok(())
612 }
613 #[cfg(feature = "tpm")]
614 BackendConfig::Tpm { path, .. } => {
615 let p = Path::new(path);
616 if !p.is_absolute() && !p.starts_with("~") {
617 debug!("TPM backend path is relative: {}, canonicalizing", path);
618 }
619 Ok(())
620 }
621 }
622 }
623}
624
625impl AppConfig {
626 pub fn config_file_path(args: &Args) -> Option<PathBuf> {
629 let default_config_path = dirs::config_dir().map(|p| p.join("passless/config.toml"));
630 args.config_path
631 .clone()
632 .or(default_config_path)
633 .filter(|p| p.exists())
634 }
635
636 pub fn load(args: &mut Args) -> crate::error::Result<Self> {
638 let config_file_path = Self::config_file_path(args);
639
640 if let Some(path) = config_file_path.as_ref()
641 && let Ok(f) = File::open(path)
642 {
643 log::info!("Loading configuration from: {}", path.display());
644 let content = std::io::read_to_string(BufReader::new(f)).unwrap_or_default();
645
646 #[cfg(feature = "agent")]
647 let agent_config = AgentConfig::from_toml_str(&content, &path.display().to_string())?;
648
649 match toml::from_str::<<AppConfig as ClapSerde>::Opt>(&content) {
650 Ok(file_config) => {
651 #[allow(unused_mut)]
652 let mut config = AppConfig::from(file_config).merge(&mut args.config);
653 #[cfg(feature = "agent")]
654 {
655 config.agents = agent_config;
656 }
657 return Ok(config);
658 }
659 Err(e) => {
660 return Err(Error::Config(format!(
661 "failed to parse config file {}: {}",
662 path.display(),
663 e
664 )));
665 }
666 }
667 }
668
669 #[allow(unused_mut)]
670 let mut config = AppConfig::from(&mut args.config);
671 #[cfg(feature = "agent")]
672 {
673 config.agents = AgentConfig::default();
674 }
675 Ok(config)
676 }
677
678 pub fn backend(&self) -> crate::error::Result<BackendConfig> {
680 match self.backend_type.as_str() {
681 "local" => Ok(BackendConfig::Local {
682 path: self.local.path.clone(),
683 }),
684 "pass" => Ok(BackendConfig::Pass {
685 store_path: self.pass.store_path.clone(),
686 path: self.pass.path.clone(),
687 gpg_backend: self.pass.gpg_backend.clone(),
688 }),
689 #[cfg(feature = "tpm")]
690 "tpm" => Ok(BackendConfig::Tpm {
691 path: self.tpm.path.clone(),
692 tcti: self.tpm.tcti.clone(),
693 portable: self.tpm.portable,
694 }),
695 _ => Err(crate::error::Error::Config(format!(
696 "Invalid backend_type '{}'. Must be one of: local, pass, tpm",
697 self.backend_type
698 ))),
699 }
700 }
701
702 pub fn apply_security_hardening(&self) -> Result<(), Box<dyn std::error::Error>> {
704 self.security.apply_hardening()
705 }
706
707 pub fn security_config(&self) -> SecurityConfig {
709 self.security.clone()
710 }
711
712 pub fn pin_config(&self) -> PinConfig {
714 self.pin.clone()
715 }
716
717 pub fn check_startup(&self) -> crate::error::Result<()> {
721 self.validate()?;
722 self.backend()?.validate()
723 }
724
725 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#[derive(Parser)]
739#[command(author, version, about)]
740pub struct Args {
741 #[arg(short, long, env = "PASSLESS_CONFIG")]
743 pub config_path: Option<PathBuf>,
744
745 #[command(flatten)]
747 pub config: <AppConfig as ClapSerde>::Opt,
748
749 #[command(subcommand)]
751 pub command: Option<Commands>,
752}
753
754#[derive(Debug, Clone, Copy, PartialEq, Eq)]
756pub enum OutputFormat {
757 Plain,
759 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#[derive(Subcommand, Debug, Clone)]
789pub enum Commands {
790 Config {
792 #[command(subcommand)]
793 action: ConfigAction,
794 },
795 Client {
801 #[arg(short = 'D', long = "device", value_name = "INDEX|NAME", global = true)]
803 device: Option<String>,
804
805 #[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 #[cfg(feature = "agent")]
820 AgentAdmin {
821 #[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 #[cfg(feature = "agent")]
836 Doctor {
837 #[arg(long)]
841 agents: bool,
842
843 #[arg(
845 short = 'o',
846 long = "output",
847 value_name = "FORMAT",
848 default_value = "plain"
849 )]
850 output: OutputFormat,
851 },
852 #[cfg(feature = "agent")]
854 Agent {
855 #[arg(long, value_name = "PROFILE", global = true)]
857 profile: Option<String>,
858
859 #[arg(
861 short = 'o',
862 long = "output",
863 value_name = "FORMAT",
864 default_value = "json",
865 global = true
866 )]
867 output: OutputFormat,
868
869 #[command(subcommand)]
870 action: crate::AgentCommand,
871 },
872 #[cfg(feature = "tpm")]
874 Tpm {
875 #[command(subcommand)]
876 action: TpmAction,
877 },
878}
879
880#[cfg(feature = "tpm")]
882#[derive(Subcommand, Debug, Clone)]
883pub enum TpmAction {
884 #[command(group(clap::ArgGroup::new("seed-source").args(["generate", "seed_file", "seed_stdin"])))]
886 Provision {
887 #[arg(long)]
889 generate: bool,
890 #[arg(long = "seed-file", value_name = "PATH")]
892 seed_file: Option<PathBuf>,
893 #[arg(long = "seed-stdin")]
895 seed_stdin: bool,
896 #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
898 path: Option<String>,
899 #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
901 tcti: Option<String>,
902 },
903 Status {
905 #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
907 path: Option<String>,
908 #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
910 tcti: Option<String>,
911 },
912 Remove {
914 #[arg(long)]
916 confirm: bool,
917 #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
919 path: Option<String>,
920 #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
922 tcti: Option<String>,
923 },
924 #[command(group(clap::ArgGroup::new("selection").args(["credential_id", "all"]).required(true)))]
926 Migrate {
927 #[arg(long = "credential-id", value_name = "ID")]
929 credential_id: Option<String>,
930 #[arg(long)]
932 all: bool,
933 #[arg(long)]
935 dry_run: bool,
936 #[arg(long = "backup-dir", value_name = "PATH")]
938 backup_dir: Option<String>,
939 #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
941 path: Option<String>,
942 #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
944 tcti: Option<String>,
945 },
946}
947
948#[derive(Subcommand, Debug, Clone)]
950pub enum ConfigAction {
951 Print,
953 Check {
960 #[arg(short = 'c', long, value_name = "PATH")]
963 config_path: Option<PathBuf>,
964 },
965}
966
967#[cfg(feature = "agent")]
969#[derive(Subcommand, Debug, Clone)]
970pub enum AgentAdminAction {
971 Install {
973 #[arg(value_enum, default_value_t = AgentSkillTarget::Auto)]
975 target: AgentSkillTarget,
976
977 #[arg(long, value_enum, default_value_t = AgentSkillScope::User)]
979 scope: AgentSkillScope,
980
981 #[arg(long)]
983 force: bool,
984 },
985 Profile {
987 #[command(subcommand)]
988 action: AdminProfileAction,
989 },
990 Policy {
992 #[command(subcommand)]
993 action: AdminPolicyAction,
994 },
995 Credential {
997 #[command(subcommand)]
998 action: AdminCredentialAction,
999 },
1000 Grants {
1002 #[command(subcommand)]
1003 action: AdminGrantsAction,
1004 },
1005 #[command(alias = "delegation")]
1007 Sessions {
1008 #[command(subcommand)]
1009 action: AdminSessionsAction,
1010 },
1011 #[command(alias = "session")]
1013 Principals {
1014 #[command(subcommand)]
1015 action: AdminPrincipalsAction,
1016 },
1017 Browser {
1019 #[command(subcommand)]
1020 action: AdminBrowserAction,
1021 },
1022 Audit {
1024 #[command(subcommand)]
1025 action: AdminAuditAction,
1026 },
1027 #[command(hide = true)]
1029 Shutdown {
1030 #[arg(long)]
1032 confirm: bool,
1033 },
1034}
1035
1036#[cfg(feature = "agent")]
1038#[derive(Subcommand, Debug, Clone)]
1039pub enum AdminProfileAction {
1040 Check {
1042 #[arg(value_name = "PROFILE")]
1044 profile: String,
1045 },
1046 Show {
1048 #[arg(value_name = "PROFILE")]
1050 profile: String,
1051 },
1052 List,
1054 Enable {
1056 #[arg(value_name = "PROFILE")]
1058 profile: String,
1059 },
1060 Disable {
1062 #[arg(value_name = "PROFILE")]
1064 profile: String,
1065 },
1066}
1067
1068#[cfg(feature = "agent")]
1070#[derive(Subcommand, Debug, Clone)]
1071pub enum AdminPolicyAction {
1072 Check {
1074 #[arg(value_name = "PROFILE")]
1076 profile: String,
1077 },
1078 Reload {
1080 #[arg(value_name = "PROFILE")]
1082 profile: String,
1083 },
1084 Show {
1086 #[arg(value_name = "PROFILE")]
1088 profile: String,
1089 },
1090}
1091
1092#[cfg(feature = "agent")]
1094#[derive(Subcommand, Debug, Clone)]
1095pub enum AdminCredentialAction {
1096 List {
1098 #[arg(short = 'd', long = "domain", value_name = "DOMAIN")]
1100 rp_id: Option<String>,
1101 },
1102 Show {
1104 #[arg(value_name = "CREDENTIAL_REF")]
1106 credential_ref: String,
1107 },
1108 Revoke {
1110 #[arg(value_name = "CREDENTIAL_REF")]
1112 credential_ref: String,
1113 #[arg(long)]
1115 confirm: bool,
1116 },
1117 Delete {
1119 #[arg(value_name = "CREDENTIAL_REF")]
1121 credential_ref: String,
1122 #[arg(long)]
1124 confirm: bool,
1125 },
1126}
1127
1128#[cfg(feature = "agent")]
1130#[derive(Subcommand, Debug, Clone)]
1131pub enum AdminGrantsAction {
1132 List {
1134 #[arg(long, value_name = "PROFILE")]
1136 profile: Option<String>,
1137 },
1138 Revoke {
1140 #[arg(long, value_name = "PROFILE")]
1142 profile: String,
1143 #[arg(long = "rp", value_name = "RP_ID")]
1145 rp_id: String,
1146 #[arg(long, value_enum, default_value_t = AdminGrantAction::Authenticate)]
1148 action: AdminGrantAction,
1149 #[arg(long)]
1151 confirm: bool,
1152 },
1153 Clear {
1155 #[arg(long, value_name = "PROFILE")]
1157 profile: String,
1158 #[arg(long)]
1160 confirm: bool,
1161 },
1162}
1163
1164#[cfg(feature = "agent")]
1166#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1167pub enum AdminGrantAction {
1168 Authenticate,
1169}
1170
1171#[cfg(feature = "agent")]
1173#[derive(Subcommand, Debug, Clone)]
1174pub enum AdminSessionsAction {
1175 Show {
1177 #[arg(value_name = "GRANT_ID")]
1179 grant_id: String,
1180 },
1181 List {
1183 #[arg(long, value_name = "PROFILE")]
1185 profile: Option<String>,
1186 },
1187 Revoke {
1189 #[arg(value_name = "GRANT_ID")]
1191 grant_id: String,
1192 #[arg(long)]
1194 confirm: bool,
1195 },
1196}
1197
1198#[cfg(feature = "agent")]
1200#[derive(Subcommand, Debug, Clone)]
1201pub enum AdminPrincipalsAction {
1202 Show {
1204 #[arg(value_name = "SESSION_ID")]
1206 session_id: String,
1207 },
1208 List {
1210 #[arg(long, value_name = "PROFILE")]
1212 profile: Option<String>,
1213 },
1214 Revoke {
1216 #[arg(value_name = "SESSION_ID")]
1218 session_id: String,
1219 #[arg(long)]
1221 confirm: bool,
1222 },
1223}
1224
1225#[cfg(feature = "agent")]
1227#[derive(Subcommand, Debug, Clone)]
1228pub enum AdminBrowserAction {
1229 Launch {
1231 #[arg(long, value_name = "PROFILE")]
1233 profile: String,
1234 #[arg(long, value_name = "URL")]
1236 url: Option<String>,
1237 },
1238}
1239
1240#[cfg(feature = "agent")]
1242#[derive(Subcommand, Debug, Clone)]
1243pub enum AdminAuditAction {
1244 Status,
1246 Verify,
1248 Export {
1250 #[arg(long, value_enum, default_value_t = AdminAuditExportFormat::Json)]
1252 format: AdminAuditExportFormat,
1253 },
1254}
1255
1256#[cfg(feature = "agent")]
1258#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1259pub enum AdminAuditExportFormat {
1260 Json,
1261 Csv,
1262}
1263
1264#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1266pub enum AgentSkillTarget {
1267 Auto,
1268 Opencode,
1269 Claude,
1270 Pi,
1271}
1272
1273#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1275pub enum AgentSkillScope {
1276 User,
1277 Project,
1278}
1279
1280#[derive(Subcommand, Debug, Clone)]
1282pub enum ClientAction {
1283 Devices,
1285 Info,
1287 Reset {
1289 #[arg(long = "yes-i-really-want-to-reset-my-device", action = ArgAction::Count)]
1291 confirm: u8,
1292 },
1293 List {
1295 #[arg(short = 'd', long = "domain", value_name = "DOMAIN")]
1297 rp_id: Option<String>,
1298 },
1299 Show {
1301 #[arg(value_name = "CREDENTIAL_ID")]
1303 credential_id: String,
1304 },
1305 Delete {
1307 #[arg(value_name = "CREDENTIAL_ID")]
1309 credential_id: String,
1310 },
1311 Rename {
1313 #[arg(value_name = "CREDENTIAL_ID")]
1315 credential_id: String,
1316 #[arg(short = 'u', long = "user-name", value_name = "NAME")]
1318 user_name: Option<String>,
1319 #[arg(short = 'n', long = "display-name", value_name = "NAME")]
1321 display_name: Option<String>,
1322 },
1323 SetCredProtect {
1336 #[arg(
1338 long = "id",
1339 value_name = "CREDENTIAL_ID",
1340 conflicts_with = "rp_id",
1341 required_unless_present = "rp_id"
1342 )]
1343 credential_id: Option<String>,
1344 #[arg(long = "rp", value_name = "RP_ID")]
1346 rp_id: Option<String>,
1347 #[arg(long, value_name = "LEVEL", value_parser = clap::value_parser!(u8).range(1..=3))]
1349 level: u8,
1350 #[arg(long)]
1352 yes: bool,
1353 },
1354 Backup {
1356 #[arg(value_name = "CREDENTIAL_ID")]
1358 credential_id: String,
1359 #[arg(long, value_name = "RECIPIENT")]
1361 recipient: String,
1362 #[arg(long, value_name = "PATH")]
1364 output_file: PathBuf,
1365 #[arg(long = "yes-i-understand-this-exports-a-passkey")]
1367 confirm: bool,
1368 },
1369 Restore {
1371 #[arg(value_name = "PATH")]
1373 input_file: PathBuf,
1374 #[arg(long)]
1376 replace: bool,
1377 #[arg(long = "yes-i-understand-this-restores-a-passkey")]
1379 confirm: bool,
1380 },
1381 Pin {
1383 #[command(subcommand)]
1384 action: PinAction,
1385 },
1386}
1387
1388#[derive(Subcommand, Debug, Clone)]
1390pub enum PinAction {
1391 Set {
1393 #[arg(value_name = "PIN")]
1395 pin: String,
1396 },
1397 Change {
1399 #[arg(value_name = "OLD_PIN")]
1401 old_pin: String,
1402 #[arg(value_name = "NEW_PIN")]
1404 new_pin: String,
1405 },
1406 UvReset,
1408}
1409
1410#[cfg(feature = "agent")]
1412#[derive(Subcommand, Debug, Clone)]
1413pub enum AgentCommand {
1414 Doctor,
1416 Capabilities,
1418 Instructions,
1420 Credential {
1422 #[command(subcommand)]
1423 action: AgentCredentialAction,
1424 },
1425 BrowserStatus,
1427 BrowserControl {
1433 #[arg(long, value_name = "JSON", conflicts_with = "request_file")]
1435 request: Option<String>,
1436 #[arg(long, value_name = "PATH", conflicts_with = "request")]
1438 request_file: Option<std::path::PathBuf>,
1439 #[arg(long, value_name = "MS", default_value = "5000")]
1441 timeout_ms: u32,
1442 },
1443 Browser {
1455 #[arg(long, conflicts_with = "env")]
1457 json: bool,
1458 #[arg(long)]
1460 env: bool,
1461 #[arg(long)]
1463 wait: bool,
1464 #[arg(long)]
1466 headed: bool,
1467 #[arg(long, value_name = "URL")]
1469 url: Option<String>,
1470 },
1471 #[command(args_conflicts_with_subcommands = true)]
1473 Mcp {
1474 #[arg(long, value_enum, value_name = "CLIENT")]
1476 print_config: Option<McpConfigTarget>,
1477 #[arg(long, value_enum, default_value_t = McpAdapterKind::Playwright, requires = "print_config")]
1479 server: McpAdapterKind,
1480 #[command(subcommand)]
1481 adapter: Option<McpAdapter>,
1482 },
1483 #[command(hide = true)]
1487 PlaywrightMcp {
1488 #[arg(long, value_name = "PROFILE")]
1490 profile: String,
1491 #[arg(long, value_name = "URL")]
1493 url: Option<String>,
1494 #[arg(last = true, required = true)]
1496 command: Vec<std::path::PathBuf>,
1497 },
1498 #[command(hide = true)]
1504 McpSessionBroker {
1505 #[arg(long, value_name = "PROFILE")]
1507 profile: String,
1508 #[arg(long, value_name = "URL")]
1510 url: Option<String>,
1511 },
1512 Run {
1514 #[arg(long, value_name = "PROFILE")]
1516 profile: String,
1517 #[arg(last = true, required = true)]
1519 command: Vec<std::path::PathBuf>,
1520 },
1521}
1522
1523#[cfg(feature = "agent")]
1525#[derive(Subcommand, Debug, Clone)]
1526pub enum McpAdapter {
1527 Playwright {
1529 #[arg(long, value_name = "SPEC")]
1531 package: Option<String>,
1532 #[arg(long, value_name = "PATH")]
1534 npx: Option<std::path::PathBuf>,
1535 #[arg(long, value_name = "URL")]
1537 url: Option<String>,
1538 #[arg(long, value_enum, value_name = "CLIENT")]
1540 print_config: Option<McpConfigTarget>,
1541 #[arg(last = true)]
1543 extra: Vec<String>,
1544 },
1545 ChromeDevtools {
1551 #[arg(long, value_name = "SPEC")]
1553 package: Option<String>,
1554 #[arg(long, value_name = "PATH")]
1556 npx: Option<std::path::PathBuf>,
1557 #[arg(long, value_name = "URL")]
1559 url: Option<String>,
1560 #[arg(long, value_enum, value_name = "CLIENT")]
1562 print_config: Option<McpConfigTarget>,
1563 #[arg(last = true)]
1565 extra: Vec<String>,
1566 },
1567 Install {
1581 #[arg(long, value_enum, value_name = "CLIENT")]
1583 client: McpInstallClient,
1584 #[arg(long, conflicts_with = "project")]
1586 user: bool,
1587 #[arg(long, value_name = "DIR", conflicts_with = "user")]
1589 project: Option<std::path::PathBuf>,
1590 #[arg(long)]
1593 yes: bool,
1594 #[arg(long)]
1596 skill: bool,
1597 #[arg(long, value_name = "ABS")]
1600 passless_path: Option<std::path::PathBuf>,
1601 },
1602}
1603
1604#[cfg(feature = "agent")]
1606#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1607pub enum McpAdapterKind {
1608 Playwright,
1609 ChromeDevtools,
1610}
1611
1612#[cfg(feature = "agent")]
1614#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1615pub enum McpInstallClient {
1616 Opencode,
1618 ClaudeCode,
1620}
1621
1622#[cfg(feature = "agent")]
1624#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1625pub enum McpConfigTarget {
1626 ClaudeCode,
1628 Opencode,
1630 Cursor,
1632 Vscode,
1634}
1635
1636#[cfg(feature = "agent")]
1638#[derive(Subcommand, Debug, Clone)]
1639pub enum AgentCredentialAction {
1640 List,
1642 Show {
1644 #[arg(value_name = "CREDENTIAL_REF")]
1646 credential_ref: String,
1647 },
1648}
1649
1650#[cfg(test)]
1651mod tests {
1652 use super::*;
1653
1654 #[cfg(feature = "agent")]
1655 #[test]
1656 fn test_agent_admin_install_defaults() {
1657 let args = Args::try_parse_from(["passless", "agent-admin", "install"]).unwrap();
1658 assert!(matches!(
1659 args.command,
1660 Some(Commands::AgentAdmin {
1661 action: AgentAdminAction::Install {
1662 target: AgentSkillTarget::Auto,
1663 scope: AgentSkillScope::User,
1664 force: false,
1665 },
1666 ..
1667 })
1668 ));
1669 }
1670
1671 #[cfg(feature = "agent")]
1672 #[test]
1673 fn test_agent_admin_install_explicit_options() {
1674 let args = Args::try_parse_from([
1675 "passless",
1676 "agent-admin",
1677 "install",
1678 "claude",
1679 "--scope",
1680 "project",
1681 "--force",
1682 ])
1683 .unwrap();
1684 assert!(matches!(
1685 args.command,
1686 Some(Commands::AgentAdmin {
1687 action: AgentAdminAction::Install {
1688 target: AgentSkillTarget::Claude,
1689 scope: AgentSkillScope::Project,
1690 force: true,
1691 },
1692 ..
1693 })
1694 ));
1695 }
1696
1697 #[test]
1698 fn test_pin_config_default_max_uv_retries() {
1699 let config = PinConfig {
1700 enforcement: PinEnforcement::Optional,
1701 min_length: 4,
1702 max_retries: 8,
1703 max_uv_retries: 8,
1704 auto_lock_timeout: 0,
1705 };
1706 assert_eq!(config.max_uv_retries, 8);
1707 }
1708
1709 #[test]
1710 fn test_pin_config_validate_success() {
1711 let config = PinConfig {
1712 enforcement: PinEnforcement::Optional,
1713 min_length: 4,
1714 max_retries: 8,
1715 max_uv_retries: 8,
1716 auto_lock_timeout: 0,
1717 };
1718 assert!(config.validate().is_ok());
1719 }
1720
1721 #[test]
1722 fn test_pin_config_validate_zero_max_uv_retries() {
1723 let config = PinConfig {
1724 enforcement: PinEnforcement::Optional,
1725 min_length: 4,
1726 max_retries: 8,
1727 max_uv_retries: 0,
1728 auto_lock_timeout: 0,
1729 };
1730 let result = config.validate();
1731 assert!(result.is_err());
1732 assert!(result.unwrap_err().to_string().contains("max_uv_retries"));
1733 }
1734
1735 #[test]
1736 fn test_pin_config_validate_zero_max_retries() {
1737 let config = PinConfig {
1738 enforcement: PinEnforcement::Optional,
1739 min_length: 4,
1740 max_retries: 0,
1741 max_uv_retries: 8,
1742 auto_lock_timeout: 0,
1743 };
1744 let result = config.validate();
1745 assert!(result.is_err());
1746 assert!(result.unwrap_err().to_string().contains("max_retries"));
1747 }
1748
1749 #[test]
1750 fn test_pin_config_validate_invalid_min_length() {
1751 let config = PinConfig {
1752 enforcement: PinEnforcement::Optional,
1753 min_length: 3,
1754 max_retries: 8,
1755 max_uv_retries: 8,
1756 auto_lock_timeout: 0,
1757 };
1758 let result = config.validate();
1759 assert!(result.is_err());
1760 assert!(result.unwrap_err().to_string().contains("min_length"));
1761 }
1762
1763 #[test]
1764 fn test_canonicalize_path_existing() {
1765 let dir = std::env::temp_dir();
1766 let canonical = BackendConfig::canonicalize_path(&dir);
1767 assert!(canonical.is_absolute());
1768 assert!(canonical.exists());
1769 }
1770
1771 #[test]
1772 fn test_canonicalize_path_nonexistent() {
1773 let base = std::env::temp_dir();
1774 let nonexistent = base.join("passless_test_nonexistent_dir_12345/sub");
1775 let canonical = BackendConfig::canonicalize_path(&nonexistent);
1776 assert!(canonical.is_absolute());
1777 assert!(canonical.starts_with(BackendConfig::canonicalize_path(&base)));
1778 }
1779
1780 #[test]
1781 fn test_canonicalize_path_symlink() {
1782 let dir = tempfile::tempdir().unwrap();
1783 let real = dir.path().join("real");
1784 std::fs::create_dir(&real).unwrap();
1785 let link = dir.path().join("link");
1786 std::os::unix::fs::symlink(&real, &link).unwrap();
1787
1788 let canonical_real = BackendConfig::canonicalize_path(&real);
1789 let canonical_link = BackendConfig::canonicalize_path(&link);
1790 assert_eq!(canonical_real, canonical_link);
1791 }
1792
1793 #[test]
1794 fn test_local_state_path_relative_and_absolute() {
1795 let dir = tempfile::tempdir_in(".").unwrap();
1796 let abs_path = std::fs::canonicalize(dir.path()).unwrap();
1797 let rel_path = dir.path().to_path_buf();
1798
1799 let backend_abs = BackendConfig::Local {
1800 path: abs_path.display().to_string(),
1801 };
1802 let backend_rel = BackendConfig::Local {
1803 path: rel_path.display().to_string(),
1804 };
1805 assert_eq!(backend_abs.state_path(), backend_rel.state_path());
1806 }
1807
1808 #[test]
1809 fn test_pass_state_path_different_subpaths() {
1810 let store = "/tmp/passless_test_store";
1811 let backend_a = BackendConfig::Pass {
1812 store_path: store.to_string(),
1813 path: "fido2".to_string(),
1814 gpg_backend: "gnupg-bin".to_string(),
1815 };
1816 let backend_b = BackendConfig::Pass {
1817 store_path: store.to_string(),
1818 path: "fido2-other".to_string(),
1819 gpg_backend: "gnupg-bin".to_string(),
1820 };
1821 assert_ne!(backend_a.state_path(), backend_b.state_path());
1822 }
1823
1824 #[test]
1825 fn test_different_local_paths_produce_different_identities() {
1826 let backend_a = BackendConfig::Local {
1827 path: "/tmp/passless_a".to_string(),
1828 };
1829 let backend_b = BackendConfig::Local {
1830 path: "/tmp/passless_b".to_string(),
1831 };
1832 assert_ne!(backend_a.state_path(), backend_b.state_path());
1833 }
1834
1835 #[cfg(feature = "agent")]
1836 #[test]
1837 fn test_agent_admin_profile_list() {
1838 let args = Args::try_parse_from(["passless", "agent-admin", "profile", "list"]).unwrap();
1839 assert!(matches!(
1840 args.command,
1841 Some(Commands::AgentAdmin {
1842 action: AgentAdminAction::Profile {
1843 action: AdminProfileAction::List,
1844 },
1845 ..
1846 })
1847 ));
1848 }
1849
1850 #[cfg(feature = "agent")]
1851 #[test]
1852 fn test_agent_admin_credential_delete_without_confirm() {
1853 let args = Args::try_parse_from([
1854 "passless",
1855 "agent-admin",
1856 "credential",
1857 "delete",
1858 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
1859 ])
1860 .unwrap();
1861 assert!(matches!(
1862 args.command,
1863 Some(Commands::AgentAdmin {
1864 action: AgentAdminAction::Credential {
1865 action: AdminCredentialAction::Delete { confirm: false, .. },
1866 },
1867 ..
1868 })
1869 ));
1870 }
1871
1872 #[cfg(feature = "agent")]
1873 #[test]
1874 fn test_agent_admin_credential_delete_with_confirm() {
1875 let args = Args::try_parse_from([
1876 "passless",
1877 "agent-admin",
1878 "credential",
1879 "delete",
1880 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
1881 "--confirm",
1882 ])
1883 .unwrap();
1884 assert!(matches!(
1885 args.command,
1886 Some(Commands::AgentAdmin {
1887 action: AgentAdminAction::Credential {
1888 action: AdminCredentialAction::Delete { confirm: true, .. },
1889 },
1890 ..
1891 })
1892 ));
1893 }
1894
1895 #[cfg(feature = "agent")]
1896 #[test]
1897 fn test_agent_admin_shutdown_hidden() {
1898 let args =
1899 Args::try_parse_from(["passless", "agent-admin", "shutdown", "--confirm"]).unwrap();
1900 assert!(matches!(
1901 args.command,
1902 Some(Commands::AgentAdmin {
1903 action: AgentAdminAction::Shutdown { confirm: true },
1904 ..
1905 })
1906 ));
1907 }
1908
1909 #[cfg(feature = "agent")]
1910 #[test]
1911 fn test_agent_admin_output_default_json() {
1912 let args = Args::try_parse_from(["passless", "agent-admin", "profile", "list"]).unwrap();
1913 match args.command {
1914 Some(Commands::AgentAdmin { output, .. }) => {
1915 assert_eq!(output, OutputFormat::Json);
1916 }
1917 _ => panic!("expected AgentAdmin command"),
1918 }
1919 }
1920
1921 #[cfg(feature = "agent")]
1922 #[test]
1923 fn test_agent_admin_output_plain() {
1924 let args = Args::try_parse_from([
1925 "passless",
1926 "agent-admin",
1927 "--output",
1928 "plain",
1929 "profile",
1930 "list",
1931 ])
1932 .unwrap();
1933 match args.command {
1934 Some(Commands::AgentAdmin { output, .. }) => {
1935 assert_eq!(output, OutputFormat::Plain);
1936 }
1937 _ => panic!("expected AgentAdmin command"),
1938 }
1939 }
1940
1941 #[cfg(feature = "agent")]
1942 #[test]
1943 fn test_agent_doctor_parses() {
1944 let args = Args::try_parse_from(["passless", "agent", "doctor"]).unwrap();
1945 assert!(matches!(
1946 args.command,
1947 Some(Commands::Agent {
1948 action: AgentCommand::Doctor,
1949 ..
1950 })
1951 ));
1952 }
1953
1954 #[cfg(feature = "agent")]
1955 #[test]
1956 fn test_agent_browser_parses() {
1957 let args = Args::try_parse_from([
1958 "passless",
1959 "agent",
1960 "--profile",
1961 "p",
1962 "browser",
1963 "--json",
1964 "--wait",
1965 "--headed",
1966 ])
1967 .unwrap();
1968 let Some(Commands::Agent {
1969 profile,
1970 action:
1971 AgentCommand::Browser {
1972 json,
1973 env,
1974 wait,
1975 headed,
1976 url,
1977 },
1978 ..
1979 }) = args.command
1980 else {
1981 panic!("not agent browser");
1982 };
1983 assert_eq!(profile.as_deref(), Some("p"));
1984 assert!(json && wait && headed && !env && url.is_none());
1985 let args =
1987 Args::try_parse_from(["passless", "agent", "browser", "--env", "--profile", "p"])
1988 .unwrap();
1989 assert!(matches!(
1990 args.command,
1991 Some(Commands::Agent {
1992 action: AgentCommand::Browser { env: true, .. },
1993 ..
1994 })
1995 ));
1996 assert!(Args::try_parse_from(["passless", "agent", "browser", "--json", "--env"]).is_err());
1997 }
1998
1999 #[cfg(feature = "agent")]
2000 #[test]
2001 fn test_agent_mcp_parses() {
2002 let args = Args::try_parse_from([
2003 "passless",
2004 "agent",
2005 "mcp",
2006 "playwright",
2007 "--profile",
2008 "p",
2009 "--",
2010 "--isolated",
2011 ])
2012 .unwrap();
2013 let Some(Commands::Agent {
2014 action:
2015 AgentCommand::Mcp {
2016 adapter: Some(McpAdapter::Playwright { extra, .. }),
2017 print_config: None,
2018 ..
2019 },
2020 profile,
2021 ..
2022 }) = args.command
2023 else {
2024 panic!("not agent mcp playwright");
2025 };
2026 assert_eq!(profile.as_deref(), Some("p"));
2027 assert_eq!(extra, ["--isolated"]);
2028
2029 let args = Args::try_parse_from(["passless", "agent", "mcp", "chrome-devtools"]).unwrap();
2030 assert!(matches!(
2031 args.command,
2032 Some(Commands::Agent {
2033 action: AgentCommand::Mcp {
2034 adapter: Some(McpAdapter::ChromeDevtools { .. }),
2035 ..
2036 },
2037 ..
2038 })
2039 ));
2040
2041 for (name, target) in [
2042 ("claude-code", McpConfigTarget::ClaudeCode),
2043 ("opencode", McpConfigTarget::Opencode),
2044 ("cursor", McpConfigTarget::Cursor),
2045 ("vscode", McpConfigTarget::Vscode),
2046 ] {
2047 let args = Args::try_parse_from([
2048 "passless",
2049 "agent",
2050 "--profile",
2051 "p",
2052 "mcp",
2053 "--print-config",
2054 name,
2055 ])
2056 .unwrap();
2057 assert!(matches!(
2058 args.command,
2059 Some(Commands::Agent {
2060 action: AgentCommand::Mcp { print_config: Some(t), adapter: None, .. },
2061 ..
2062 }) if t == target
2063 ));
2064 }
2065 assert!(
2066 Args::try_parse_from(["passless", "agent", "mcp", "--print-config", "emacs"]).is_err()
2067 );
2068 let args = Args::try_parse_from([
2070 "passless",
2071 "agent",
2072 "mcp",
2073 "playwright",
2074 "--profile",
2075 "coding",
2076 "--print-config",
2077 "claude-code",
2078 ])
2079 .unwrap();
2080 assert!(matches!(
2081 args.command,
2082 Some(Commands::Agent {
2083 profile: Some(ref profile),
2084 action: AgentCommand::Mcp {
2085 print_config: None,
2086 adapter: Some(McpAdapter::Playwright {
2087 print_config: Some(McpConfigTarget::ClaudeCode),
2088 ..
2089 }),
2090 ..
2091 },
2092 ..
2093 }) if profile == "coding"
2094 ));
2095 assert!(
2096 Args::try_parse_from([
2097 "passless",
2098 "agent",
2099 "mcp",
2100 "chrome-devtools",
2101 "--print-config",
2102 "opencode",
2103 ])
2104 .is_ok()
2105 );
2106 assert!(
2108 Args::try_parse_from([
2109 "passless",
2110 "agent",
2111 "playwright-mcp",
2112 "--profile",
2113 "p",
2114 "--",
2115 "/usr/bin/npx",
2116 "x",
2117 ])
2118 .is_ok()
2119 );
2120 }
2121
2122 #[cfg(feature = "agent")]
2123 #[test]
2124 fn test_agent_mcp_install_parses() {
2125 let parse = |extra: &[&str]| {
2126 let mut argv = vec!["passless", "agent", "mcp", "install"];
2127 argv.extend_from_slice(extra);
2128 Args::try_parse_from(argv)
2129 };
2130 assert!(parse(&[]).is_err());
2132 assert!(parse(&["--client", "emacs"]).is_err());
2133 let args = parse(&["--client", "opencode"]).unwrap();
2134 assert!(matches!(
2135 args.command,
2136 Some(Commands::Agent {
2137 profile: None,
2138 action: AgentCommand::Mcp {
2139 adapter: Some(McpAdapter::Install {
2140 client: McpInstallClient::Opencode,
2141 user: false,
2142 project: None,
2143 yes: false,
2144 skill: false,
2145 passless_path: None,
2146 }),
2147 ..
2148 },
2149 ..
2150 })
2151 ));
2152 let args = parse(&[
2153 "--client",
2154 "claude-code",
2155 "--project",
2156 "/work/p",
2157 "--profile",
2158 "agent",
2159 "--yes",
2160 "--skill",
2161 ])
2162 .unwrap();
2163 match args.command {
2164 Some(Commands::Agent {
2165 profile,
2166 action:
2167 AgentCommand::Mcp {
2168 adapter:
2169 Some(McpAdapter::Install {
2170 client,
2171 project,
2172 yes,
2173 skill,
2174 ..
2175 }),
2176 ..
2177 },
2178 ..
2179 }) => {
2180 assert_eq!(profile.as_deref(), Some("agent"));
2181 assert_eq!(client, McpInstallClient::ClaudeCode);
2182 assert_eq!(project, Some(std::path::PathBuf::from("/work/p")));
2183 assert!(yes && skill);
2184 }
2185 other => panic!("unexpected: {other:?}"),
2186 }
2187 assert!(parse(&["--client", "opencode", "--user", "--project", "/p"]).is_err());
2189 assert!(parse(&["--client", "opencode", "--user"]).is_ok());
2190 let args = parse(&[
2191 "--client",
2192 "opencode",
2193 "--passless-path",
2194 "/usr/bin/passless",
2195 ])
2196 .unwrap();
2197 assert!(matches!(
2198 args.command,
2199 Some(Commands::Agent {
2200 action: AgentCommand::Mcp {
2201 adapter: Some(McpAdapter::Install { passless_path: Some(ref p), .. }),
2202 ..
2203 },
2204 ..
2205 }) if p == std::path::Path::new("/usr/bin/passless")
2206 ));
2207 }
2208
2209 #[cfg(feature = "agent")]
2210 #[test]
2211 fn test_doctor_agents_parses() {
2212 let args = Args::try_parse_from(["passless", "doctor", "--agents", "-o", "json"]).unwrap();
2213 assert!(matches!(
2214 args.command,
2215 Some(Commands::Doctor {
2216 agents: true,
2217 output: OutputFormat::Json
2218 })
2219 ));
2220 }
2221
2222 #[cfg(feature = "agent")]
2223 #[test]
2224 fn test_agent_run_with_command() {
2225 let args = Args::try_parse_from([
2226 "passless",
2227 "agent",
2228 "run",
2229 "--profile",
2230 "myprofile",
2231 "--",
2232 "/usr/bin/test",
2233 "arg1",
2234 ])
2235 .unwrap();
2236 match args.command {
2237 Some(Commands::Agent {
2238 action: AgentCommand::Run { profile, command },
2239 ..
2240 }) => {
2241 assert_eq!(profile, "myprofile");
2242 assert_eq!(command.len(), 2);
2243 }
2244 _ => panic!("expected Agent Run command"),
2245 }
2246 }
2247
2248 #[cfg(feature = "agent")]
2249 #[test]
2250 fn test_agent_admin_grants_parse() {
2251 let args = Args::try_parse_from([
2252 "passless",
2253 "agent-admin",
2254 "grants",
2255 "revoke",
2256 "--profile",
2257 "coding",
2258 "--rp",
2259 "example.com",
2260 "--confirm",
2261 ])
2262 .unwrap();
2263 assert!(matches!(
2264 args.command,
2265 Some(Commands::AgentAdmin {
2266 action: AgentAdminAction::Grants {
2267 action: AdminGrantsAction::Revoke {
2268 ref profile,
2269 ref rp_id,
2270 action: AdminGrantAction::Authenticate,
2271 confirm: true,
2272 },
2273 },
2274 ..
2275 }) if profile == "coding" && rp_id == "example.com"
2276 ));
2277 let args = Args::try_parse_from([
2278 "passless",
2279 "agent-admin",
2280 "grants",
2281 "clear",
2282 "--profile",
2283 "p",
2284 ])
2285 .unwrap();
2286 assert!(matches!(
2287 args.command,
2288 Some(Commands::AgentAdmin {
2289 action: AgentAdminAction::Grants {
2290 action: AdminGrantsAction::Clear { confirm: false, .. },
2291 },
2292 ..
2293 })
2294 ));
2295 assert!(Args::try_parse_from(["passless", "agent-admin", "grants", "list"]).is_ok());
2296 }
2297
2298 #[cfg(feature = "agent")]
2299 #[test]
2300 fn test_agent_admin_renamed_session_commands_keep_hidden_aliases() {
2301 for (spelling, expect_sessions) in [
2302 ("sessions", true),
2303 ("delegation", true),
2304 ("principals", false),
2305 ("session", false),
2306 ] {
2307 let args = Args::try_parse_from(["passless", "agent-admin", spelling, "list"]).unwrap();
2308 let is_sessions = matches!(
2309 args.command,
2310 Some(Commands::AgentAdmin {
2311 action: AgentAdminAction::Sessions { .. },
2312 ..
2313 })
2314 );
2315 let is_principals = matches!(
2316 args.command,
2317 Some(Commands::AgentAdmin {
2318 action: AgentAdminAction::Principals { .. },
2319 ..
2320 })
2321 );
2322 assert_eq!(is_sessions, expect_sessions, "{spelling}");
2323 assert_eq!(is_principals, !expect_sessions, "{spelling}");
2324 }
2325 assert!(Args::try_parse_from(["passless", "agent", "intent", "show", "x"]).is_err());
2326 }
2327
2328 #[cfg(feature = "agent")]
2329 #[test]
2330 fn test_agent_output_default_json() {
2331 let args = Args::try_parse_from(["passless", "agent", "doctor"]).unwrap();
2332 match args.command {
2333 Some(Commands::Agent { output, .. }) => {
2334 assert_eq!(output, OutputFormat::Json);
2335 }
2336 _ => panic!("expected Agent command"),
2337 }
2338 }
2339
2340 #[cfg(feature = "agent")]
2341 #[test]
2342 fn test_shell_completions_contain_agent_commands() {
2343 use clap::CommandFactory;
2344
2345 let cmd = Args::command();
2346 let mut buf = Vec::new();
2347 clap_complete::generate(
2348 clap_complete::Shell::Bash,
2349 &mut cmd.clone(),
2350 "passless",
2351 &mut buf,
2352 );
2353 let completion = String::from_utf8(buf).unwrap();
2354
2355 for expected in [
2356 "agent-admin",
2357 "agent",
2358 "install",
2359 "browser-control",
2360 "grants",
2361 "sessions",
2362 "principals",
2363 "doctor",
2364 "capabilities",
2365 "instructions",
2366 ] {
2367 assert!(
2368 completion.contains(expected),
2369 "bash completion missing '{}'",
2370 expected
2371 );
2372 }
2373 }
2374
2375 #[cfg(feature = "agent")]
2376 #[test]
2377 fn test_shell_completions_zsh_contain_agent_commands() {
2378 use clap::CommandFactory;
2379
2380 let cmd = Args::command();
2381 let mut buf = Vec::new();
2382 clap_complete::generate(
2383 clap_complete::Shell::Zsh,
2384 &mut cmd.clone(),
2385 "passless",
2386 &mut buf,
2387 );
2388 let completion = String::from_utf8(buf).unwrap();
2389
2390 for expected in ["agent-admin", "agent", "install", "browser-control"] {
2391 assert!(
2392 completion.contains(expected),
2393 "zsh completion missing '{}'",
2394 expected
2395 );
2396 }
2397 }
2398
2399 #[cfg(feature = "agent")]
2400 #[test]
2401 fn test_config_print_includes_agent_fields() {
2402 let mut default_args = Args::parse_from(["passless"]);
2403 let config = AppConfig::from(&mut default_args.config);
2404 let toml_output = config.to_toml_with_comments();
2405
2406 assert!(
2407 toml_output.contains("backend_type"),
2408 "config print missing backend_type"
2409 );
2410 assert!(
2411 toml_output.contains("[security]"),
2412 "config print missing [security] section"
2413 );
2414 assert!(
2415 toml_output.contains("[pin]"),
2416 "config print missing [pin] section"
2417 );
2418 assert!(
2419 toml_output.contains("always_uv"),
2420 "config print missing always_uv"
2421 );
2422 assert!(
2423 toml_output.contains("notification_timeout"),
2424 "config print missing notification_timeout"
2425 );
2426 }
2427
2428 #[test]
2429 fn test_config_print_contains_passless_header() {
2430 let mut default_args = Args::parse_from(["passless"]);
2431 let config = AppConfig::from(&mut default_args.config);
2432 let toml_output = config.to_toml_with_comments();
2433
2434 assert!(toml_output.contains("Passless Configuration File"));
2435 assert!(toml_output.contains("~/.config/passless/config.toml"));
2436 }
2437
2438 #[test]
2439 fn test_config_print_contains_local_backend_section() {
2440 let mut default_args = Args::parse_from(["passless"]);
2441 let config = AppConfig::from(&mut default_args.config);
2442 let toml_output = config.to_toml_with_comments();
2443
2444 assert!(toml_output.contains("[local]"));
2445 assert!(toml_output.contains("path"));
2446 }
2447
2448 #[test]
2449 fn test_config_print_contains_pass_backend_section() {
2450 let mut default_args = Args::parse_from(["passless"]);
2451 let config = AppConfig::from(&mut default_args.config);
2452 let toml_output = config.to_toml_with_comments();
2453
2454 assert!(toml_output.contains("[pass]"));
2455 assert!(toml_output.contains("store_path"));
2456 assert!(toml_output.contains("gpg_backend"));
2457 }
2458
2459 #[test]
2460 fn test_config_print_produces_valid_toml_without_none_literals() {
2461 let mut default_args = Args::parse_from(["passless"]);
2462 let config = AppConfig::from(&mut default_args.config);
2463 let toml_output = config.to_toml_with_comments();
2464
2465 for (line_no, line) in toml_output.lines().enumerate() {
2466 let trimmed = line.trim();
2467 if trimmed.starts_with('#') || trimmed.is_empty() {
2468 continue;
2469 }
2470 assert!(
2471 !trimmed.contains("= None"),
2472 "Line {} contains invalid TOML 'None' literal: {}",
2473 line_no + 1,
2474 line
2475 );
2476 }
2477
2478 let parse_result: Result<toml::Table, _> = toml_output.parse();
2479 assert!(
2480 parse_result.is_ok(),
2481 "Generated TOML is not valid: {:?}",
2482 parse_result.err()
2483 );
2484 }
2485
2486 #[cfg(feature = "agent")]
2487 #[test]
2488 fn test_config_print_comments_out_none_option_fields() {
2489 let mut default_args = Args::parse_from(["passless"]);
2490 let config = AppConfig::from(&mut default_args.config);
2491 let toml_output = config.to_toml_with_comments();
2492
2493 assert!(
2494 toml_output.contains("# audit_path = <not set>"),
2495 "Option::None field 'audit_path' should be commented out, got:\n{}",
2496 toml_output
2497 );
2498 }
2499}