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 #[arg(long, requires = "print_config")]
1482 with_access_tool: bool,
1483 #[command(subcommand)]
1484 adapter: Option<McpAdapter>,
1485 },
1486 #[command(hide = true)]
1490 PlaywrightMcp {
1491 #[arg(long, value_name = "PROFILE")]
1493 profile: String,
1494 #[arg(long, value_name = "URL")]
1496 url: Option<String>,
1497 #[arg(last = true, required = true)]
1499 command: Vec<std::path::PathBuf>,
1500 },
1501 #[command(hide = true)]
1507 McpSessionBroker {
1508 #[arg(long, value_name = "PROFILE")]
1510 profile: String,
1511 #[arg(long, value_name = "URL")]
1513 url: Option<String>,
1514 },
1515 RequestAccess {
1532 #[arg(value_name = "RP_ID")]
1534 rp_id: String,
1535 #[arg(long)]
1537 register: bool,
1538 #[arg(long, value_name = "TEXT")]
1541 note: Option<String>,
1542 #[arg(long, value_name = "SECS", default_value_t = 30, value_parser = clap::value_parser!(u32).range(0..=120))]
1544 wait: u32,
1545 #[arg(long)]
1547 json: bool,
1548 #[arg(long, hide = true)]
1550 fresh_session: bool,
1551 },
1552 Run {
1554 #[arg(long, value_name = "PROFILE")]
1556 profile: String,
1557 #[arg(last = true, required = true)]
1559 command: Vec<std::path::PathBuf>,
1560 },
1561}
1562
1563#[cfg(feature = "agent")]
1565#[derive(Subcommand, Debug, Clone)]
1566pub enum McpAdapter {
1567 Playwright {
1569 #[arg(long, value_name = "SPEC")]
1571 package: Option<String>,
1572 #[arg(long, value_name = "PATH")]
1574 npx: Option<std::path::PathBuf>,
1575 #[arg(long, value_name = "URL")]
1577 url: Option<String>,
1578 #[arg(long)]
1586 with_access_tool: bool,
1587 #[arg(long, value_enum, value_name = "CLIENT")]
1589 print_config: Option<McpConfigTarget>,
1590 #[arg(last = true)]
1592 extra: Vec<String>,
1593 },
1594 ChromeDevtools {
1600 #[arg(long, value_name = "SPEC")]
1602 package: Option<String>,
1603 #[arg(long, value_name = "PATH")]
1605 npx: Option<std::path::PathBuf>,
1606 #[arg(long, value_name = "URL")]
1608 url: Option<String>,
1609 #[arg(long, value_enum, value_name = "CLIENT")]
1611 print_config: Option<McpConfigTarget>,
1612 #[arg(last = true)]
1614 extra: Vec<String>,
1615 },
1616 Install {
1630 #[arg(long, value_enum, value_name = "CLIENT")]
1632 client: McpInstallClient,
1633 #[arg(long, conflicts_with = "project")]
1635 user: bool,
1636 #[arg(long, value_name = "DIR", conflicts_with = "user")]
1638 project: Option<std::path::PathBuf>,
1639 #[arg(long)]
1642 yes: bool,
1643 #[arg(long)]
1645 skill: bool,
1646 #[arg(long, value_name = "ABS")]
1649 passless_path: Option<std::path::PathBuf>,
1650 #[arg(long)]
1653 with_access_tool: bool,
1654 },
1655}
1656
1657#[cfg(feature = "agent")]
1659#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1660pub enum McpAdapterKind {
1661 Playwright,
1662 ChromeDevtools,
1663}
1664
1665#[cfg(feature = "agent")]
1667#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1668pub enum McpInstallClient {
1669 Opencode,
1671 ClaudeCode,
1673}
1674
1675#[cfg(feature = "agent")]
1677#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1678pub enum McpConfigTarget {
1679 ClaudeCode,
1681 Opencode,
1683 Cursor,
1685 Vscode,
1687}
1688
1689#[cfg(feature = "agent")]
1691#[derive(Subcommand, Debug, Clone)]
1692pub enum AgentCredentialAction {
1693 List,
1695 Show {
1697 #[arg(value_name = "CREDENTIAL_REF")]
1699 credential_ref: String,
1700 },
1701}
1702
1703#[cfg(test)]
1704mod tests {
1705 use super::*;
1706
1707 #[cfg(feature = "agent")]
1708 #[test]
1709 fn test_agent_admin_install_defaults() {
1710 let args = Args::try_parse_from(["passless", "agent-admin", "install"]).unwrap();
1711 assert!(matches!(
1712 args.command,
1713 Some(Commands::AgentAdmin {
1714 action: AgentAdminAction::Install {
1715 target: AgentSkillTarget::Auto,
1716 scope: AgentSkillScope::User,
1717 force: false,
1718 },
1719 ..
1720 })
1721 ));
1722 }
1723
1724 #[cfg(feature = "agent")]
1725 #[test]
1726 fn test_agent_admin_install_explicit_options() {
1727 let args = Args::try_parse_from([
1728 "passless",
1729 "agent-admin",
1730 "install",
1731 "claude",
1732 "--scope",
1733 "project",
1734 "--force",
1735 ])
1736 .unwrap();
1737 assert!(matches!(
1738 args.command,
1739 Some(Commands::AgentAdmin {
1740 action: AgentAdminAction::Install {
1741 target: AgentSkillTarget::Claude,
1742 scope: AgentSkillScope::Project,
1743 force: true,
1744 },
1745 ..
1746 })
1747 ));
1748 }
1749
1750 #[test]
1751 fn test_pin_config_default_max_uv_retries() {
1752 let config = PinConfig {
1753 enforcement: PinEnforcement::Optional,
1754 min_length: 4,
1755 max_retries: 8,
1756 max_uv_retries: 8,
1757 auto_lock_timeout: 0,
1758 };
1759 assert_eq!(config.max_uv_retries, 8);
1760 }
1761
1762 #[test]
1763 fn test_pin_config_validate_success() {
1764 let config = PinConfig {
1765 enforcement: PinEnforcement::Optional,
1766 min_length: 4,
1767 max_retries: 8,
1768 max_uv_retries: 8,
1769 auto_lock_timeout: 0,
1770 };
1771 assert!(config.validate().is_ok());
1772 }
1773
1774 #[test]
1775 fn test_pin_config_validate_zero_max_uv_retries() {
1776 let config = PinConfig {
1777 enforcement: PinEnforcement::Optional,
1778 min_length: 4,
1779 max_retries: 8,
1780 max_uv_retries: 0,
1781 auto_lock_timeout: 0,
1782 };
1783 let result = config.validate();
1784 assert!(result.is_err());
1785 assert!(result.unwrap_err().to_string().contains("max_uv_retries"));
1786 }
1787
1788 #[test]
1789 fn test_pin_config_validate_zero_max_retries() {
1790 let config = PinConfig {
1791 enforcement: PinEnforcement::Optional,
1792 min_length: 4,
1793 max_retries: 0,
1794 max_uv_retries: 8,
1795 auto_lock_timeout: 0,
1796 };
1797 let result = config.validate();
1798 assert!(result.is_err());
1799 assert!(result.unwrap_err().to_string().contains("max_retries"));
1800 }
1801
1802 #[test]
1803 fn test_pin_config_validate_invalid_min_length() {
1804 let config = PinConfig {
1805 enforcement: PinEnforcement::Optional,
1806 min_length: 3,
1807 max_retries: 8,
1808 max_uv_retries: 8,
1809 auto_lock_timeout: 0,
1810 };
1811 let result = config.validate();
1812 assert!(result.is_err());
1813 assert!(result.unwrap_err().to_string().contains("min_length"));
1814 }
1815
1816 #[test]
1817 fn test_canonicalize_path_existing() {
1818 let dir = std::env::temp_dir();
1819 let canonical = BackendConfig::canonicalize_path(&dir);
1820 assert!(canonical.is_absolute());
1821 assert!(canonical.exists());
1822 }
1823
1824 #[test]
1825 fn test_canonicalize_path_nonexistent() {
1826 let base = std::env::temp_dir();
1827 let nonexistent = base.join("passless_test_nonexistent_dir_12345/sub");
1828 let canonical = BackendConfig::canonicalize_path(&nonexistent);
1829 assert!(canonical.is_absolute());
1830 assert!(canonical.starts_with(BackendConfig::canonicalize_path(&base)));
1831 }
1832
1833 #[test]
1834 fn test_canonicalize_path_symlink() {
1835 let dir = tempfile::tempdir().unwrap();
1836 let real = dir.path().join("real");
1837 std::fs::create_dir(&real).unwrap();
1838 let link = dir.path().join("link");
1839 std::os::unix::fs::symlink(&real, &link).unwrap();
1840
1841 let canonical_real = BackendConfig::canonicalize_path(&real);
1842 let canonical_link = BackendConfig::canonicalize_path(&link);
1843 assert_eq!(canonical_real, canonical_link);
1844 }
1845
1846 #[test]
1847 fn test_local_state_path_relative_and_absolute() {
1848 let dir = tempfile::tempdir_in(".").unwrap();
1849 let abs_path = std::fs::canonicalize(dir.path()).unwrap();
1850 let rel_path = dir.path().to_path_buf();
1851
1852 let backend_abs = BackendConfig::Local {
1853 path: abs_path.display().to_string(),
1854 };
1855 let backend_rel = BackendConfig::Local {
1856 path: rel_path.display().to_string(),
1857 };
1858 assert_eq!(backend_abs.state_path(), backend_rel.state_path());
1859 }
1860
1861 #[test]
1862 fn test_pass_state_path_different_subpaths() {
1863 let store = "/tmp/passless_test_store";
1864 let backend_a = BackendConfig::Pass {
1865 store_path: store.to_string(),
1866 path: "fido2".to_string(),
1867 gpg_backend: "gnupg-bin".to_string(),
1868 };
1869 let backend_b = BackendConfig::Pass {
1870 store_path: store.to_string(),
1871 path: "fido2-other".to_string(),
1872 gpg_backend: "gnupg-bin".to_string(),
1873 };
1874 assert_ne!(backend_a.state_path(), backend_b.state_path());
1875 }
1876
1877 #[test]
1878 fn test_different_local_paths_produce_different_identities() {
1879 let backend_a = BackendConfig::Local {
1880 path: "/tmp/passless_a".to_string(),
1881 };
1882 let backend_b = BackendConfig::Local {
1883 path: "/tmp/passless_b".to_string(),
1884 };
1885 assert_ne!(backend_a.state_path(), backend_b.state_path());
1886 }
1887
1888 #[cfg(feature = "agent")]
1889 #[test]
1890 fn test_agent_admin_profile_list() {
1891 let args = Args::try_parse_from(["passless", "agent-admin", "profile", "list"]).unwrap();
1892 assert!(matches!(
1893 args.command,
1894 Some(Commands::AgentAdmin {
1895 action: AgentAdminAction::Profile {
1896 action: AdminProfileAction::List,
1897 },
1898 ..
1899 })
1900 ));
1901 }
1902
1903 #[cfg(feature = "agent")]
1904 #[test]
1905 fn test_agent_admin_credential_delete_without_confirm() {
1906 let args = Args::try_parse_from([
1907 "passless",
1908 "agent-admin",
1909 "credential",
1910 "delete",
1911 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
1912 ])
1913 .unwrap();
1914 assert!(matches!(
1915 args.command,
1916 Some(Commands::AgentAdmin {
1917 action: AgentAdminAction::Credential {
1918 action: AdminCredentialAction::Delete { confirm: false, .. },
1919 },
1920 ..
1921 })
1922 ));
1923 }
1924
1925 #[cfg(feature = "agent")]
1926 #[test]
1927 fn test_agent_admin_credential_delete_with_confirm() {
1928 let args = Args::try_parse_from([
1929 "passless",
1930 "agent-admin",
1931 "credential",
1932 "delete",
1933 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
1934 "--confirm",
1935 ])
1936 .unwrap();
1937 assert!(matches!(
1938 args.command,
1939 Some(Commands::AgentAdmin {
1940 action: AgentAdminAction::Credential {
1941 action: AdminCredentialAction::Delete { confirm: true, .. },
1942 },
1943 ..
1944 })
1945 ));
1946 }
1947
1948 #[cfg(feature = "agent")]
1949 #[test]
1950 fn test_agent_admin_shutdown_hidden() {
1951 let args =
1952 Args::try_parse_from(["passless", "agent-admin", "shutdown", "--confirm"]).unwrap();
1953 assert!(matches!(
1954 args.command,
1955 Some(Commands::AgentAdmin {
1956 action: AgentAdminAction::Shutdown { confirm: true },
1957 ..
1958 })
1959 ));
1960 }
1961
1962 #[cfg(feature = "agent")]
1963 #[test]
1964 fn test_agent_admin_output_default_json() {
1965 let args = Args::try_parse_from(["passless", "agent-admin", "profile", "list"]).unwrap();
1966 match args.command {
1967 Some(Commands::AgentAdmin { output, .. }) => {
1968 assert_eq!(output, OutputFormat::Json);
1969 }
1970 _ => panic!("expected AgentAdmin command"),
1971 }
1972 }
1973
1974 #[cfg(feature = "agent")]
1975 #[test]
1976 fn test_agent_admin_output_plain() {
1977 let args = Args::try_parse_from([
1978 "passless",
1979 "agent-admin",
1980 "--output",
1981 "plain",
1982 "profile",
1983 "list",
1984 ])
1985 .unwrap();
1986 match args.command {
1987 Some(Commands::AgentAdmin { output, .. }) => {
1988 assert_eq!(output, OutputFormat::Plain);
1989 }
1990 _ => panic!("expected AgentAdmin command"),
1991 }
1992 }
1993
1994 #[cfg(feature = "agent")]
1995 #[test]
1996 fn test_agent_doctor_parses() {
1997 let args = Args::try_parse_from(["passless", "agent", "doctor"]).unwrap();
1998 assert!(matches!(
1999 args.command,
2000 Some(Commands::Agent {
2001 action: AgentCommand::Doctor,
2002 ..
2003 })
2004 ));
2005 }
2006
2007 #[cfg(feature = "agent")]
2008 #[test]
2009 fn test_agent_request_access_parses() {
2010 let args = Args::try_parse_from([
2011 "passless",
2012 "agent",
2013 "--profile",
2014 "p",
2015 "request-access",
2016 "example.org",
2017 "--register",
2018 "--note",
2019 "why",
2020 "--wait",
2021 "120",
2022 "--json",
2023 ])
2024 .unwrap();
2025 let Some(Commands::Agent {
2026 profile,
2027 action:
2028 AgentCommand::RequestAccess {
2029 rp_id,
2030 register,
2031 note,
2032 wait,
2033 json,
2034 fresh_session,
2035 },
2036 ..
2037 }) = args.command
2038 else {
2039 panic!("not agent request-access");
2040 };
2041 assert_eq!(profile.as_deref(), Some("p"));
2042 assert_eq!(rp_id, "example.org");
2043 assert!(register && json && !fresh_session);
2044 assert_eq!(note.as_deref(), Some("why"));
2045 assert_eq!(wait, 120);
2046
2047 let args =
2049 Args::try_parse_from(["passless", "agent", "request-access", "example.org"]).unwrap();
2050 assert!(matches!(
2051 args.command,
2052 Some(Commands::Agent {
2053 action: AgentCommand::RequestAccess {
2054 register: false,
2055 note: None,
2056 wait: 30,
2057 json: false,
2058 ..
2059 },
2060 ..
2061 })
2062 ));
2063 assert!(
2065 Args::try_parse_from([
2066 "passless",
2067 "agent",
2068 "request-access",
2069 "a.b",
2070 "--wait",
2071 "121"
2072 ])
2073 .is_err()
2074 );
2075 assert!(Args::try_parse_from(["passless", "agent", "request-access"]).is_err());
2076 }
2077
2078 #[cfg(feature = "agent")]
2079 #[test]
2080 fn test_agent_mcp_playwright_with_access_tool_parses() {
2081 let on = Args::try_parse_from([
2082 "passless",
2083 "agent",
2084 "mcp",
2085 "playwright",
2086 "--profile",
2087 "p",
2088 "--with-access-tool",
2089 ])
2090 .unwrap();
2091 assert!(matches!(
2092 on.command,
2093 Some(Commands::Agent {
2094 action: AgentCommand::Mcp {
2095 adapter: Some(McpAdapter::Playwright {
2096 with_access_tool: true,
2097 ..
2098 }),
2099 ..
2100 },
2101 ..
2102 })
2103 ));
2104 let off =
2106 Args::try_parse_from(["passless", "agent", "mcp", "playwright", "--profile", "p"])
2107 .unwrap();
2108 assert!(matches!(
2109 off.command,
2110 Some(Commands::Agent {
2111 action: AgentCommand::Mcp {
2112 adapter: Some(McpAdapter::Playwright {
2113 with_access_tool: false,
2114 ..
2115 }),
2116 ..
2117 },
2118 ..
2119 })
2120 ));
2121 assert!(
2122 Args::try_parse_from([
2123 "passless",
2124 "agent",
2125 "mcp",
2126 "chrome-devtools",
2127 "--with-access-tool"
2128 ])
2129 .is_err()
2130 );
2131 let print = Args::try_parse_from([
2133 "passless",
2134 "agent",
2135 "mcp",
2136 "--print-config",
2137 "claude-code",
2138 "--with-access-tool",
2139 ])
2140 .unwrap();
2141 assert!(matches!(
2142 print.command,
2143 Some(Commands::Agent {
2144 action: AgentCommand::Mcp {
2145 with_access_tool: true,
2146 ..
2147 },
2148 ..
2149 })
2150 ));
2151 assert!(Args::try_parse_from(["passless", "agent", "mcp", "--with-access-tool"]).is_err());
2152 }
2153
2154 #[cfg(feature = "agent")]
2155 #[test]
2156 fn test_agent_browser_parses() {
2157 let args = Args::try_parse_from([
2158 "passless",
2159 "agent",
2160 "--profile",
2161 "p",
2162 "browser",
2163 "--json",
2164 "--wait",
2165 "--headed",
2166 ])
2167 .unwrap();
2168 let Some(Commands::Agent {
2169 profile,
2170 action:
2171 AgentCommand::Browser {
2172 json,
2173 env,
2174 wait,
2175 headed,
2176 url,
2177 },
2178 ..
2179 }) = args.command
2180 else {
2181 panic!("not agent browser");
2182 };
2183 assert_eq!(profile.as_deref(), Some("p"));
2184 assert!(json && wait && headed && !env && url.is_none());
2185 let args =
2187 Args::try_parse_from(["passless", "agent", "browser", "--env", "--profile", "p"])
2188 .unwrap();
2189 assert!(matches!(
2190 args.command,
2191 Some(Commands::Agent {
2192 action: AgentCommand::Browser { env: true, .. },
2193 ..
2194 })
2195 ));
2196 assert!(Args::try_parse_from(["passless", "agent", "browser", "--json", "--env"]).is_err());
2197 }
2198
2199 #[cfg(feature = "agent")]
2200 #[test]
2201 fn test_agent_mcp_parses() {
2202 let args = Args::try_parse_from([
2203 "passless",
2204 "agent",
2205 "mcp",
2206 "playwright",
2207 "--profile",
2208 "p",
2209 "--",
2210 "--isolated",
2211 ])
2212 .unwrap();
2213 let Some(Commands::Agent {
2214 action:
2215 AgentCommand::Mcp {
2216 adapter: Some(McpAdapter::Playwright { extra, .. }),
2217 print_config: None,
2218 ..
2219 },
2220 profile,
2221 ..
2222 }) = args.command
2223 else {
2224 panic!("not agent mcp playwright");
2225 };
2226 assert_eq!(profile.as_deref(), Some("p"));
2227 assert_eq!(extra, ["--isolated"]);
2228
2229 let args = Args::try_parse_from(["passless", "agent", "mcp", "chrome-devtools"]).unwrap();
2230 assert!(matches!(
2231 args.command,
2232 Some(Commands::Agent {
2233 action: AgentCommand::Mcp {
2234 adapter: Some(McpAdapter::ChromeDevtools { .. }),
2235 ..
2236 },
2237 ..
2238 })
2239 ));
2240
2241 for (name, target) in [
2242 ("claude-code", McpConfigTarget::ClaudeCode),
2243 ("opencode", McpConfigTarget::Opencode),
2244 ("cursor", McpConfigTarget::Cursor),
2245 ("vscode", McpConfigTarget::Vscode),
2246 ] {
2247 let args = Args::try_parse_from([
2248 "passless",
2249 "agent",
2250 "--profile",
2251 "p",
2252 "mcp",
2253 "--print-config",
2254 name,
2255 ])
2256 .unwrap();
2257 assert!(matches!(
2258 args.command,
2259 Some(Commands::Agent {
2260 action: AgentCommand::Mcp { print_config: Some(t), adapter: None, .. },
2261 ..
2262 }) if t == target
2263 ));
2264 }
2265 assert!(
2266 Args::try_parse_from(["passless", "agent", "mcp", "--print-config", "emacs"]).is_err()
2267 );
2268 let args = Args::try_parse_from([
2270 "passless",
2271 "agent",
2272 "mcp",
2273 "playwright",
2274 "--profile",
2275 "coding",
2276 "--print-config",
2277 "claude-code",
2278 ])
2279 .unwrap();
2280 assert!(matches!(
2281 args.command,
2282 Some(Commands::Agent {
2283 profile: Some(ref profile),
2284 action: AgentCommand::Mcp {
2285 print_config: None,
2286 adapter: Some(McpAdapter::Playwright {
2287 print_config: Some(McpConfigTarget::ClaudeCode),
2288 ..
2289 }),
2290 ..
2291 },
2292 ..
2293 }) if profile == "coding"
2294 ));
2295 assert!(
2296 Args::try_parse_from([
2297 "passless",
2298 "agent",
2299 "mcp",
2300 "chrome-devtools",
2301 "--print-config",
2302 "opencode",
2303 ])
2304 .is_ok()
2305 );
2306 assert!(
2308 Args::try_parse_from([
2309 "passless",
2310 "agent",
2311 "playwright-mcp",
2312 "--profile",
2313 "p",
2314 "--",
2315 "/usr/bin/npx",
2316 "x",
2317 ])
2318 .is_ok()
2319 );
2320 }
2321
2322 #[cfg(feature = "agent")]
2323 #[test]
2324 fn test_agent_mcp_install_parses() {
2325 let parse = |extra: &[&str]| {
2326 let mut argv = vec!["passless", "agent", "mcp", "install"];
2327 argv.extend_from_slice(extra);
2328 Args::try_parse_from(argv)
2329 };
2330 assert!(parse(&[]).is_err());
2332 assert!(parse(&["--client", "emacs"]).is_err());
2333 let args = parse(&["--client", "opencode"]).unwrap();
2334 assert!(matches!(
2335 args.command,
2336 Some(Commands::Agent {
2337 profile: None,
2338 action: AgentCommand::Mcp {
2339 adapter: Some(McpAdapter::Install {
2340 client: McpInstallClient::Opencode,
2341 user: false,
2342 project: None,
2343 yes: false,
2344 skill: false,
2345 passless_path: None,
2346 with_access_tool: false,
2347 }),
2348 ..
2349 },
2350 ..
2351 })
2352 ));
2353 let args = parse(&[
2354 "--client",
2355 "claude-code",
2356 "--project",
2357 "/work/p",
2358 "--profile",
2359 "agent",
2360 "--yes",
2361 "--skill",
2362 ])
2363 .unwrap();
2364 match args.command {
2365 Some(Commands::Agent {
2366 profile,
2367 action:
2368 AgentCommand::Mcp {
2369 adapter:
2370 Some(McpAdapter::Install {
2371 client,
2372 project,
2373 yes,
2374 skill,
2375 ..
2376 }),
2377 ..
2378 },
2379 ..
2380 }) => {
2381 assert_eq!(profile.as_deref(), Some("agent"));
2382 assert_eq!(client, McpInstallClient::ClaudeCode);
2383 assert_eq!(project, Some(std::path::PathBuf::from("/work/p")));
2384 assert!(yes && skill);
2385 }
2386 other => panic!("unexpected: {other:?}"),
2387 }
2388 assert!(parse(&["--client", "opencode", "--user", "--project", "/p"]).is_err());
2390 assert!(parse(&["--client", "opencode", "--user"]).is_ok());
2391 let args = parse(&[
2392 "--client",
2393 "opencode",
2394 "--passless-path",
2395 "/usr/bin/passless",
2396 ])
2397 .unwrap();
2398 assert!(matches!(
2399 args.command,
2400 Some(Commands::Agent {
2401 action: AgentCommand::Mcp {
2402 adapter: Some(McpAdapter::Install { passless_path: Some(ref p), .. }),
2403 ..
2404 },
2405 ..
2406 }) if p == std::path::Path::new("/usr/bin/passless")
2407 ));
2408 }
2409
2410 #[cfg(feature = "agent")]
2411 #[test]
2412 fn test_doctor_agents_parses() {
2413 let args = Args::try_parse_from(["passless", "doctor", "--agents", "-o", "json"]).unwrap();
2414 assert!(matches!(
2415 args.command,
2416 Some(Commands::Doctor {
2417 agents: true,
2418 output: OutputFormat::Json
2419 })
2420 ));
2421 }
2422
2423 #[cfg(feature = "agent")]
2424 #[test]
2425 fn test_agent_run_with_command() {
2426 let args = Args::try_parse_from([
2427 "passless",
2428 "agent",
2429 "run",
2430 "--profile",
2431 "myprofile",
2432 "--",
2433 "/usr/bin/test",
2434 "arg1",
2435 ])
2436 .unwrap();
2437 match args.command {
2438 Some(Commands::Agent {
2439 action: AgentCommand::Run { profile, command },
2440 ..
2441 }) => {
2442 assert_eq!(profile, "myprofile");
2443 assert_eq!(command.len(), 2);
2444 }
2445 _ => panic!("expected Agent Run command"),
2446 }
2447 }
2448
2449 #[cfg(feature = "agent")]
2450 #[test]
2451 fn test_agent_admin_grants_parse() {
2452 let args = Args::try_parse_from([
2453 "passless",
2454 "agent-admin",
2455 "grants",
2456 "revoke",
2457 "--profile",
2458 "coding",
2459 "--rp",
2460 "example.com",
2461 "--confirm",
2462 ])
2463 .unwrap();
2464 assert!(matches!(
2465 args.command,
2466 Some(Commands::AgentAdmin {
2467 action: AgentAdminAction::Grants {
2468 action: AdminGrantsAction::Revoke {
2469 ref profile,
2470 ref rp_id,
2471 action: AdminGrantAction::Authenticate,
2472 confirm: true,
2473 },
2474 },
2475 ..
2476 }) if profile == "coding" && rp_id == "example.com"
2477 ));
2478 let args = Args::try_parse_from([
2479 "passless",
2480 "agent-admin",
2481 "grants",
2482 "clear",
2483 "--profile",
2484 "p",
2485 ])
2486 .unwrap();
2487 assert!(matches!(
2488 args.command,
2489 Some(Commands::AgentAdmin {
2490 action: AgentAdminAction::Grants {
2491 action: AdminGrantsAction::Clear { confirm: false, .. },
2492 },
2493 ..
2494 })
2495 ));
2496 assert!(Args::try_parse_from(["passless", "agent-admin", "grants", "list"]).is_ok());
2497 }
2498
2499 #[cfg(feature = "agent")]
2500 #[test]
2501 fn test_agent_admin_renamed_session_commands_keep_hidden_aliases() {
2502 for (spelling, expect_sessions) in [
2503 ("sessions", true),
2504 ("delegation", true),
2505 ("principals", false),
2506 ("session", false),
2507 ] {
2508 let args = Args::try_parse_from(["passless", "agent-admin", spelling, "list"]).unwrap();
2509 let is_sessions = matches!(
2510 args.command,
2511 Some(Commands::AgentAdmin {
2512 action: AgentAdminAction::Sessions { .. },
2513 ..
2514 })
2515 );
2516 let is_principals = matches!(
2517 args.command,
2518 Some(Commands::AgentAdmin {
2519 action: AgentAdminAction::Principals { .. },
2520 ..
2521 })
2522 );
2523 assert_eq!(is_sessions, expect_sessions, "{spelling}");
2524 assert_eq!(is_principals, !expect_sessions, "{spelling}");
2525 }
2526 assert!(Args::try_parse_from(["passless", "agent", "intent", "show", "x"]).is_err());
2527 }
2528
2529 #[cfg(feature = "agent")]
2530 #[test]
2531 fn test_agent_output_default_json() {
2532 let args = Args::try_parse_from(["passless", "agent", "doctor"]).unwrap();
2533 match args.command {
2534 Some(Commands::Agent { output, .. }) => {
2535 assert_eq!(output, OutputFormat::Json);
2536 }
2537 _ => panic!("expected Agent command"),
2538 }
2539 }
2540
2541 #[cfg(feature = "agent")]
2542 #[test]
2543 fn test_shell_completions_contain_agent_commands() {
2544 use clap::CommandFactory;
2545
2546 let cmd = Args::command();
2547 let mut buf = Vec::new();
2548 clap_complete::generate(
2549 clap_complete::Shell::Bash,
2550 &mut cmd.clone(),
2551 "passless",
2552 &mut buf,
2553 );
2554 let completion = String::from_utf8(buf).unwrap();
2555
2556 for expected in [
2557 "agent-admin",
2558 "agent",
2559 "install",
2560 "browser-control",
2561 "grants",
2562 "sessions",
2563 "principals",
2564 "doctor",
2565 "capabilities",
2566 "instructions",
2567 ] {
2568 assert!(
2569 completion.contains(expected),
2570 "bash completion missing '{}'",
2571 expected
2572 );
2573 }
2574 }
2575
2576 #[cfg(feature = "agent")]
2577 #[test]
2578 fn test_shell_completions_zsh_contain_agent_commands() {
2579 use clap::CommandFactory;
2580
2581 let cmd = Args::command();
2582 let mut buf = Vec::new();
2583 clap_complete::generate(
2584 clap_complete::Shell::Zsh,
2585 &mut cmd.clone(),
2586 "passless",
2587 &mut buf,
2588 );
2589 let completion = String::from_utf8(buf).unwrap();
2590
2591 for expected in ["agent-admin", "agent", "install", "browser-control"] {
2592 assert!(
2593 completion.contains(expected),
2594 "zsh completion missing '{}'",
2595 expected
2596 );
2597 }
2598 }
2599
2600 #[cfg(feature = "agent")]
2601 #[test]
2602 fn test_config_print_includes_agent_fields() {
2603 let mut default_args = Args::parse_from(["passless"]);
2604 let config = AppConfig::from(&mut default_args.config);
2605 let toml_output = config.to_toml_with_comments();
2606
2607 assert!(
2608 toml_output.contains("backend_type"),
2609 "config print missing backend_type"
2610 );
2611 assert!(
2612 toml_output.contains("[security]"),
2613 "config print missing [security] section"
2614 );
2615 assert!(
2616 toml_output.contains("[pin]"),
2617 "config print missing [pin] section"
2618 );
2619 assert!(
2620 toml_output.contains("always_uv"),
2621 "config print missing always_uv"
2622 );
2623 assert!(
2624 toml_output.contains("notification_timeout"),
2625 "config print missing notification_timeout"
2626 );
2627 }
2628
2629 #[test]
2630 fn test_config_print_contains_passless_header() {
2631 let mut default_args = Args::parse_from(["passless"]);
2632 let config = AppConfig::from(&mut default_args.config);
2633 let toml_output = config.to_toml_with_comments();
2634
2635 assert!(toml_output.contains("Passless Configuration File"));
2636 assert!(toml_output.contains("~/.config/passless/config.toml"));
2637 }
2638
2639 #[test]
2640 fn test_config_print_contains_local_backend_section() {
2641 let mut default_args = Args::parse_from(["passless"]);
2642 let config = AppConfig::from(&mut default_args.config);
2643 let toml_output = config.to_toml_with_comments();
2644
2645 assert!(toml_output.contains("[local]"));
2646 assert!(toml_output.contains("path"));
2647 }
2648
2649 #[test]
2650 fn test_config_print_contains_pass_backend_section() {
2651 let mut default_args = Args::parse_from(["passless"]);
2652 let config = AppConfig::from(&mut default_args.config);
2653 let toml_output = config.to_toml_with_comments();
2654
2655 assert!(toml_output.contains("[pass]"));
2656 assert!(toml_output.contains("store_path"));
2657 assert!(toml_output.contains("gpg_backend"));
2658 }
2659
2660 #[test]
2661 fn test_config_print_produces_valid_toml_without_none_literals() {
2662 let mut default_args = Args::parse_from(["passless"]);
2663 let config = AppConfig::from(&mut default_args.config);
2664 let toml_output = config.to_toml_with_comments();
2665
2666 for (line_no, line) in toml_output.lines().enumerate() {
2667 let trimmed = line.trim();
2668 if trimmed.starts_with('#') || trimmed.is_empty() {
2669 continue;
2670 }
2671 assert!(
2672 !trimmed.contains("= None"),
2673 "Line {} contains invalid TOML 'None' literal: {}",
2674 line_no + 1,
2675 line
2676 );
2677 }
2678
2679 let parse_result: Result<toml::Table, _> = toml_output.parse();
2680 assert!(
2681 parse_result.is_ok(),
2682 "Generated TOML is not valid: {:?}",
2683 parse_result.err()
2684 );
2685 }
2686
2687 #[cfg(feature = "agent")]
2688 #[test]
2689 fn test_config_print_comments_out_none_option_fields() {
2690 let mut default_args = Args::parse_from(["passless"]);
2691 let config = AppConfig::from(&mut default_args.config);
2692 let toml_output = config.to_toml_with_comments();
2693
2694 assert!(
2695 toml_output.contains("# audit_path = <not set>"),
2696 "Option::None field 'audit_path' should be commented out, got:\n{}",
2697 toml_output
2698 );
2699 }
2700}