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 #[serde(default)]
458 #[command(flatten)]
459 pub pass: PassBackendConfig,
460
461 #[cfg(feature = "tpm")]
463 #[clap_serde]
464 #[serde(default)]
465 #[command(flatten)]
466 pub tpm: TpmBackendConfig,
467
468 #[clap_serde]
470 #[serde(default)]
471 #[command(flatten)]
472 pub local: LocalBackendConfig,
473
474 #[clap_serde]
476 #[serde(default)]
477 #[command(flatten)]
478 pub security: SecurityConfig,
479
480 #[clap_serde]
482 #[serde(default)]
483 #[command(flatten)]
484 pub pin: PinConfig,
485
486 #[cfg(feature = "agent")]
488 #[arg(skip)]
489 pub agents: AgentConfig,
490}
491
492#[derive(Debug, Clone)]
494pub enum BackendConfig {
495 Local {
496 path: String,
497 },
498 Pass {
499 store_path: String,
500 path: String,
501 gpg_backend: String,
502 },
503 #[cfg(feature = "tpm")]
504 Tpm {
505 path: String,
506 tcti: String,
507 portable: bool,
508 },
509}
510
511impl BackendConfig {
512 pub fn canonicalize_path(path: &Path) -> PathBuf {
517 match fs::canonicalize(path) {
518 Ok(p) => p,
519 Err(_) => {
520 let mut current = path.to_path_buf();
521 let mut suffix = Vec::new();
522 loop {
523 match fs::canonicalize(¤t) {
524 Ok(base) => {
525 let mut result = base;
526 for component in suffix.iter().rev() {
527 result.push(component);
528 }
529 return result;
530 }
531 Err(_) => {
532 if let Some(file_name) = current.file_name() {
533 suffix.push(file_name.to_os_string());
534 current = current
535 .parent()
536 .map(|p| p.to_path_buf())
537 .unwrap_or_default();
538 } else {
539 return path.to_path_buf();
540 }
541 }
542 }
543 }
544 }
545 }
546 }
547
548 pub fn state_path(&self) -> PathBuf {
553 match self {
554 BackendConfig::Local { path } => Self::canonicalize_path(Path::new(path)),
555 BackendConfig::Pass {
556 store_path, path, ..
557 } => Self::canonicalize_path(&Path::new(store_path).join(path)),
558 #[cfg(feature = "tpm")]
559 BackendConfig::Tpm { path, .. } => Self::canonicalize_path(Path::new(path)),
560 }
561 }
562
563 pub fn state_display(&self) -> String {
565 match self {
566 BackendConfig::Local { path } => path.clone(),
567 BackendConfig::Pass {
568 store_path, path, ..
569 } => {
570 format!("{}/{}", store_path, path)
571 }
572 #[cfg(feature = "tpm")]
573 BackendConfig::Tpm { path, .. } => path.clone(),
574 }
575 }
576
577 pub fn validate(&self) -> crate::error::Result<()> {
581 match self {
582 BackendConfig::Local { path } => {
583 let p = Path::new(path);
584 if !p.is_absolute() && !p.starts_with("~") {
585 debug!("Local backend path is relative: {}, canonicalizing", path);
586 }
587 Ok(())
588 }
589 BackendConfig::Pass {
590 store_path, path, ..
591 } => {
592 let p = Path::new(path);
593 if p.is_absolute() {
594 return Err(Error::Config(format!(
595 "Pass backend 'path' must be relative, got absolute path: {}",
596 path
597 )));
598 }
599 if path.contains("..") {
600 return Err(Error::Config(format!(
601 "Pass backend 'path' must not contain '..': {}",
602 path
603 )));
604 }
605 let combined = Path::new(store_path).join(path);
607 let canonical_store = Self::canonicalize_path(Path::new(store_path));
608 let canonical_combined = Self::canonicalize_path(&combined);
609 if !canonical_combined.starts_with(&canonical_store) {
610 return Err(Error::Config(format!(
611 "Pass backend 'path' escapes store_path: {} not beneath {}",
612 canonical_combined.display(),
613 canonical_store.display()
614 )));
615 }
616 Ok(())
617 }
618 #[cfg(feature = "tpm")]
619 BackendConfig::Tpm { path, .. } => {
620 let p = Path::new(path);
621 if !p.is_absolute() && !p.starts_with("~") {
622 debug!("TPM backend path is relative: {}, canonicalizing", path);
623 }
624 Ok(())
625 }
626 }
627 }
628}
629
630impl AppConfig {
631 pub fn config_file_path(args: &Args) -> Option<PathBuf> {
634 let default_config_path = dirs::config_dir().map(|p| p.join("passless/config.toml"));
635 args.config_path
636 .clone()
637 .or(default_config_path)
638 .filter(|p| p.exists())
639 }
640
641 pub fn load(args: &mut Args) -> crate::error::Result<Self> {
643 let config_file_path = Self::config_file_path(args);
644
645 if let Some(path) = config_file_path.as_ref()
646 && let Ok(f) = File::open(path)
647 {
648 log::info!("Loading configuration from: {}", path.display());
649 let content = std::io::read_to_string(BufReader::new(f)).unwrap_or_default();
650
651 #[cfg(feature = "agent")]
652 let agent_config = AgentConfig::from_toml_str(&content, &path.display().to_string())?;
653
654 match toml::from_str::<<AppConfig as ClapSerde>::Opt>(&content) {
655 Ok(file_config) => {
656 #[allow(unused_mut)]
657 let mut config = AppConfig::from(file_config).merge(&mut args.config);
658 #[cfg(feature = "agent")]
659 {
660 config.agents = agent_config;
661 }
662 return Ok(config);
663 }
664 Err(e) => {
665 return Err(Error::Config(format!(
666 "failed to parse config file {}: {}",
667 path.display(),
668 e
669 )));
670 }
671 }
672 }
673
674 #[allow(unused_mut)]
675 let mut config = AppConfig::from(&mut args.config);
676 #[cfg(feature = "agent")]
677 {
678 config.agents = AgentConfig::default();
679 }
680 Ok(config)
681 }
682
683 pub fn backend(&self) -> crate::error::Result<BackendConfig> {
685 match self.backend_type.as_str() {
686 "local" => Ok(BackendConfig::Local {
687 path: self.local.path.clone(),
688 }),
689 "pass" => Ok(BackendConfig::Pass {
690 store_path: self.pass.store_path.clone(),
691 path: self.pass.path.clone(),
692 gpg_backend: self.pass.gpg_backend.clone(),
693 }),
694 #[cfg(feature = "tpm")]
695 "tpm" => Ok(BackendConfig::Tpm {
696 path: self.tpm.path.clone(),
697 tcti: self.tpm.tcti.clone(),
698 portable: self.tpm.portable,
699 }),
700 _ => Err(crate::error::Error::Config(format!(
701 "Invalid backend_type '{}'. Must be one of: local, pass, tpm",
702 self.backend_type
703 ))),
704 }
705 }
706
707 pub fn apply_security_hardening(&self) -> Result<(), Box<dyn std::error::Error>> {
709 self.security.apply_hardening()
710 }
711
712 pub fn security_config(&self) -> SecurityConfig {
714 self.security.clone()
715 }
716
717 pub fn pin_config(&self) -> PinConfig {
719 self.pin.clone()
720 }
721
722 pub fn validate(&self) -> crate::error::Result<()> {
724 self.pin.validate()?;
725 #[cfg(feature = "agent")]
726 {
727 let human_path = self.backend().ok().map(|b| b.state_path());
728 self.agents.validate(human_path.as_deref())?;
729 }
730 Ok(())
731 }
732}
733
734#[derive(Parser)]
736#[command(author, version, about)]
737pub struct Args {
738 #[arg(short, long, env = "PASSLESS_CONFIG")]
740 pub config_path: Option<PathBuf>,
741
742 #[command(flatten)]
744 pub config: <AppConfig as ClapSerde>::Opt,
745
746 #[command(subcommand)]
748 pub command: Option<Commands>,
749}
750
751#[derive(Debug, Clone, Copy, PartialEq, Eq)]
753pub enum OutputFormat {
754 Plain,
756 Json,
758}
759
760impl std::str::FromStr for OutputFormat {
761 type Err = String;
762
763 fn from_str(s: &str) -> Result<Self, Self::Err> {
764 match s.to_lowercase().as_str() {
765 "plain" => Ok(OutputFormat::Plain),
766 "json" => Ok(OutputFormat::Json),
767 _ => Err(format!(
768 "Invalid output format '{}'. Must be 'plain' or 'json'",
769 s
770 )),
771 }
772 }
773}
774
775impl std::fmt::Display for OutputFormat {
776 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
777 match self {
778 OutputFormat::Plain => write!(f, "plain"),
779 OutputFormat::Json => write!(f, "json"),
780 }
781 }
782}
783
784#[derive(Subcommand, Debug, Clone)]
786pub enum Commands {
787 Config {
789 #[command(subcommand)]
790 action: ConfigAction,
791 },
792 Client {
798 #[arg(short = 'D', long = "device", value_name = "INDEX|NAME", global = true)]
800 device: Option<String>,
801
802 #[arg(
804 short = 'o',
805 long = "output",
806 value_name = "FORMAT",
807 default_value = "plain",
808 global = true
809 )]
810 output: OutputFormat,
811
812 #[command(subcommand)]
813 action: ClientAction,
814 },
815 #[cfg(feature = "agent")]
817 AgentAdmin {
818 #[arg(
820 short = 'o',
821 long = "output",
822 value_name = "FORMAT",
823 default_value = "json",
824 global = true
825 )]
826 output: OutputFormat,
827
828 #[command(subcommand)]
829 action: AgentAdminAction,
830 },
831 #[cfg(feature = "agent")]
833 Doctor {
834 #[arg(long)]
838 agents: bool,
839
840 #[arg(
842 short = 'o',
843 long = "output",
844 value_name = "FORMAT",
845 default_value = "plain"
846 )]
847 output: OutputFormat,
848 },
849 #[cfg(feature = "agent")]
851 Agent {
852 #[arg(long, value_name = "PROFILE", global = true)]
854 profile: Option<String>,
855
856 #[arg(
858 short = 'o',
859 long = "output",
860 value_name = "FORMAT",
861 default_value = "json",
862 global = true
863 )]
864 output: OutputFormat,
865
866 #[command(subcommand)]
867 action: crate::AgentCommand,
868 },
869 #[cfg(feature = "tpm")]
871 Tpm {
872 #[command(subcommand)]
873 action: TpmAction,
874 },
875}
876
877#[cfg(feature = "tpm")]
879#[derive(Subcommand, Debug, Clone)]
880pub enum TpmAction {
881 #[command(group(clap::ArgGroup::new("seed-source").args(["generate", "seed_file", "seed_stdin"])))]
883 Provision {
884 #[arg(long)]
886 generate: bool,
887 #[arg(long = "seed-file", value_name = "PATH")]
889 seed_file: Option<PathBuf>,
890 #[arg(long = "seed-stdin")]
892 seed_stdin: bool,
893 #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
895 path: Option<String>,
896 #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
898 tcti: Option<String>,
899 },
900 Status {
902 #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
904 path: Option<String>,
905 #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
907 tcti: Option<String>,
908 },
909 Remove {
911 #[arg(long)]
913 confirm: bool,
914 #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
916 path: Option<String>,
917 #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
919 tcti: Option<String>,
920 },
921 #[command(group(clap::ArgGroup::new("selection").args(["credential_id", "all"]).required(true)))]
923 Migrate {
924 #[arg(long = "credential-id", value_name = "ID")]
926 credential_id: Option<String>,
927 #[arg(long)]
929 all: bool,
930 #[arg(long)]
932 dry_run: bool,
933 #[arg(long = "backup-dir", value_name = "PATH")]
935 backup_dir: Option<String>,
936 #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
938 path: Option<String>,
939 #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
941 tcti: Option<String>,
942 },
943}
944
945#[derive(Subcommand, Debug, Clone)]
947pub enum ConfigAction {
948 Print,
950}
951
952#[cfg(feature = "agent")]
954#[derive(Subcommand, Debug, Clone)]
955pub enum AgentAdminAction {
956 Install {
958 #[arg(value_enum, default_value_t = AgentSkillTarget::Auto)]
960 target: AgentSkillTarget,
961
962 #[arg(long, value_enum, default_value_t = AgentSkillScope::User)]
964 scope: AgentSkillScope,
965
966 #[arg(long)]
968 force: bool,
969 },
970 Profile {
972 #[command(subcommand)]
973 action: AdminProfileAction,
974 },
975 Policy {
977 #[command(subcommand)]
978 action: AdminPolicyAction,
979 },
980 Credential {
982 #[command(subcommand)]
983 action: AdminCredentialAction,
984 },
985 Grants {
987 #[command(subcommand)]
988 action: AdminGrantsAction,
989 },
990 #[command(alias = "delegation")]
992 Sessions {
993 #[command(subcommand)]
994 action: AdminSessionsAction,
995 },
996 #[command(alias = "session")]
998 Principals {
999 #[command(subcommand)]
1000 action: AdminPrincipalsAction,
1001 },
1002 Browser {
1004 #[command(subcommand)]
1005 action: AdminBrowserAction,
1006 },
1007 Audit {
1009 #[command(subcommand)]
1010 action: AdminAuditAction,
1011 },
1012 #[command(hide = true)]
1014 Shutdown {
1015 #[arg(long)]
1017 confirm: bool,
1018 },
1019}
1020
1021#[cfg(feature = "agent")]
1023#[derive(Subcommand, Debug, Clone)]
1024pub enum AdminProfileAction {
1025 Check {
1027 #[arg(value_name = "PROFILE")]
1029 profile: String,
1030 },
1031 Show {
1033 #[arg(value_name = "PROFILE")]
1035 profile: String,
1036 },
1037 List,
1039 Enable {
1041 #[arg(value_name = "PROFILE")]
1043 profile: String,
1044 },
1045 Disable {
1047 #[arg(value_name = "PROFILE")]
1049 profile: String,
1050 },
1051}
1052
1053#[cfg(feature = "agent")]
1055#[derive(Subcommand, Debug, Clone)]
1056pub enum AdminPolicyAction {
1057 Check {
1059 #[arg(value_name = "PROFILE")]
1061 profile: String,
1062 },
1063 Reload {
1065 #[arg(value_name = "PROFILE")]
1067 profile: String,
1068 },
1069 Show {
1071 #[arg(value_name = "PROFILE")]
1073 profile: String,
1074 },
1075}
1076
1077#[cfg(feature = "agent")]
1079#[derive(Subcommand, Debug, Clone)]
1080pub enum AdminCredentialAction {
1081 List {
1083 #[arg(short = 'd', long = "domain", value_name = "DOMAIN")]
1085 rp_id: Option<String>,
1086 },
1087 Show {
1089 #[arg(value_name = "CREDENTIAL_REF")]
1091 credential_ref: String,
1092 },
1093 Revoke {
1095 #[arg(value_name = "CREDENTIAL_REF")]
1097 credential_ref: String,
1098 #[arg(long)]
1100 confirm: bool,
1101 },
1102 Delete {
1104 #[arg(value_name = "CREDENTIAL_REF")]
1106 credential_ref: String,
1107 #[arg(long)]
1109 confirm: bool,
1110 },
1111}
1112
1113#[cfg(feature = "agent")]
1115#[derive(Subcommand, Debug, Clone)]
1116pub enum AdminGrantsAction {
1117 List {
1119 #[arg(long, value_name = "PROFILE")]
1121 profile: Option<String>,
1122 },
1123 Revoke {
1125 #[arg(long, value_name = "PROFILE")]
1127 profile: String,
1128 #[arg(long = "rp", value_name = "RP_ID")]
1130 rp_id: String,
1131 #[arg(long, value_enum, default_value_t = AdminGrantAction::Authenticate)]
1133 action: AdminGrantAction,
1134 #[arg(long)]
1136 confirm: bool,
1137 },
1138 Clear {
1140 #[arg(long, value_name = "PROFILE")]
1142 profile: String,
1143 #[arg(long)]
1145 confirm: bool,
1146 },
1147}
1148
1149#[cfg(feature = "agent")]
1151#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1152pub enum AdminGrantAction {
1153 Authenticate,
1154}
1155
1156#[cfg(feature = "agent")]
1158#[derive(Subcommand, Debug, Clone)]
1159pub enum AdminSessionsAction {
1160 Show {
1162 #[arg(value_name = "GRANT_ID")]
1164 grant_id: String,
1165 },
1166 List {
1168 #[arg(long, value_name = "PROFILE")]
1170 profile: Option<String>,
1171 },
1172 Revoke {
1174 #[arg(value_name = "GRANT_ID")]
1176 grant_id: String,
1177 #[arg(long)]
1179 confirm: bool,
1180 },
1181}
1182
1183#[cfg(feature = "agent")]
1185#[derive(Subcommand, Debug, Clone)]
1186pub enum AdminPrincipalsAction {
1187 Show {
1189 #[arg(value_name = "SESSION_ID")]
1191 session_id: String,
1192 },
1193 List {
1195 #[arg(long, value_name = "PROFILE")]
1197 profile: Option<String>,
1198 },
1199 Revoke {
1201 #[arg(value_name = "SESSION_ID")]
1203 session_id: String,
1204 #[arg(long)]
1206 confirm: bool,
1207 },
1208}
1209
1210#[cfg(feature = "agent")]
1212#[derive(Subcommand, Debug, Clone)]
1213pub enum AdminBrowserAction {
1214 Launch {
1216 #[arg(long, value_name = "PROFILE")]
1218 profile: String,
1219 #[arg(long, value_name = "URL")]
1221 url: Option<String>,
1222 },
1223}
1224
1225#[cfg(feature = "agent")]
1227#[derive(Subcommand, Debug, Clone)]
1228pub enum AdminAuditAction {
1229 Status,
1231 Verify,
1233 Export {
1235 #[arg(long, value_enum, default_value_t = AdminAuditExportFormat::Json)]
1237 format: AdminAuditExportFormat,
1238 },
1239}
1240
1241#[cfg(feature = "agent")]
1243#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1244pub enum AdminAuditExportFormat {
1245 Json,
1246 Csv,
1247}
1248
1249#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1251pub enum AgentSkillTarget {
1252 Auto,
1253 Opencode,
1254 Claude,
1255 Pi,
1256}
1257
1258#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1260pub enum AgentSkillScope {
1261 User,
1262 Project,
1263}
1264
1265#[derive(Subcommand, Debug, Clone)]
1267pub enum ClientAction {
1268 Devices,
1270 Info,
1272 Reset {
1274 #[arg(long = "yes-i-really-want-to-reset-my-device", action = ArgAction::Count)]
1276 confirm: u8,
1277 },
1278 List {
1280 #[arg(short = 'd', long = "domain", value_name = "DOMAIN")]
1282 rp_id: Option<String>,
1283 },
1284 Show {
1286 #[arg(value_name = "CREDENTIAL_ID")]
1288 credential_id: String,
1289 },
1290 Delete {
1292 #[arg(value_name = "CREDENTIAL_ID")]
1294 credential_id: String,
1295 },
1296 Rename {
1298 #[arg(value_name = "CREDENTIAL_ID")]
1300 credential_id: String,
1301 #[arg(short = 'u', long = "user-name", value_name = "NAME")]
1303 user_name: Option<String>,
1304 #[arg(short = 'n', long = "display-name", value_name = "NAME")]
1306 display_name: Option<String>,
1307 },
1308 Backup {
1310 #[arg(value_name = "CREDENTIAL_ID")]
1312 credential_id: String,
1313 #[arg(long, value_name = "RECIPIENT")]
1315 recipient: String,
1316 #[arg(long, value_name = "PATH")]
1318 output_file: PathBuf,
1319 #[arg(long = "yes-i-understand-this-exports-a-passkey")]
1321 confirm: bool,
1322 },
1323 Restore {
1325 #[arg(value_name = "PATH")]
1327 input_file: PathBuf,
1328 #[arg(long)]
1330 replace: bool,
1331 #[arg(long = "yes-i-understand-this-restores-a-passkey")]
1333 confirm: bool,
1334 },
1335 Pin {
1337 #[command(subcommand)]
1338 action: PinAction,
1339 },
1340}
1341
1342#[derive(Subcommand, Debug, Clone)]
1344pub enum PinAction {
1345 Set {
1347 #[arg(value_name = "PIN")]
1349 pin: String,
1350 },
1351 Change {
1353 #[arg(value_name = "OLD_PIN")]
1355 old_pin: String,
1356 #[arg(value_name = "NEW_PIN")]
1358 new_pin: String,
1359 },
1360 UvReset,
1362}
1363
1364#[cfg(feature = "agent")]
1366#[derive(Subcommand, Debug, Clone)]
1367pub enum AgentCommand {
1368 Doctor,
1370 Capabilities,
1372 Instructions,
1374 Credential {
1376 #[command(subcommand)]
1377 action: AgentCredentialAction,
1378 },
1379 BrowserStatus,
1381 BrowserControl {
1387 #[arg(long, value_name = "JSON", conflicts_with = "request_file")]
1389 request: Option<String>,
1390 #[arg(long, value_name = "PATH", conflicts_with = "request")]
1392 request_file: Option<std::path::PathBuf>,
1393 #[arg(long, value_name = "MS", default_value = "5000")]
1395 timeout_ms: u32,
1396 },
1397 Browser {
1409 #[arg(long, conflicts_with = "env")]
1411 json: bool,
1412 #[arg(long)]
1414 env: bool,
1415 #[arg(long)]
1417 wait: bool,
1418 #[arg(long)]
1420 headed: bool,
1421 #[arg(long, value_name = "URL")]
1423 url: Option<String>,
1424 },
1425 #[command(args_conflicts_with_subcommands = true)]
1427 Mcp {
1428 #[arg(long, value_enum, value_name = "CLIENT")]
1430 print_config: Option<McpConfigTarget>,
1431 #[arg(long, value_enum, default_value_t = McpAdapterKind::Playwright, requires = "print_config")]
1433 server: McpAdapterKind,
1434 #[command(subcommand)]
1435 adapter: Option<McpAdapter>,
1436 },
1437 #[command(hide = true)]
1441 PlaywrightMcp {
1442 #[arg(long, value_name = "PROFILE")]
1444 profile: String,
1445 #[arg(long, value_name = "URL")]
1447 url: Option<String>,
1448 #[arg(last = true, required = true)]
1450 command: Vec<std::path::PathBuf>,
1451 },
1452 Run {
1454 #[arg(long, value_name = "PROFILE")]
1456 profile: String,
1457 #[arg(last = true, required = true)]
1459 command: Vec<std::path::PathBuf>,
1460 },
1461}
1462
1463#[cfg(feature = "agent")]
1465#[derive(Subcommand, Debug, Clone)]
1466pub enum McpAdapter {
1467 Playwright {
1469 #[arg(long, value_name = "SPEC")]
1471 package: Option<String>,
1472 #[arg(long, value_name = "PATH")]
1474 npx: Option<std::path::PathBuf>,
1475 #[arg(long, value_name = "URL")]
1477 url: Option<String>,
1478 #[arg(last = true)]
1480 extra: Vec<String>,
1481 },
1482 ChromeDevtools {
1488 #[arg(long, value_name = "SPEC")]
1490 package: Option<String>,
1491 #[arg(long, value_name = "PATH")]
1493 npx: Option<std::path::PathBuf>,
1494 #[arg(long, value_name = "URL")]
1496 url: Option<String>,
1497 #[arg(last = true)]
1499 extra: Vec<String>,
1500 },
1501}
1502
1503#[cfg(feature = "agent")]
1505#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1506pub enum McpAdapterKind {
1507 Playwright,
1508 ChromeDevtools,
1509}
1510
1511#[cfg(feature = "agent")]
1513#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1514pub enum McpConfigTarget {
1515 ClaudeCode,
1517 Opencode,
1519 Cursor,
1521 Vscode,
1523}
1524
1525#[cfg(feature = "agent")]
1527#[derive(Subcommand, Debug, Clone)]
1528pub enum AgentCredentialAction {
1529 List,
1531 Show {
1533 #[arg(value_name = "CREDENTIAL_REF")]
1535 credential_ref: String,
1536 },
1537}
1538
1539#[cfg(test)]
1540mod tests {
1541 use super::*;
1542
1543 #[cfg(feature = "agent")]
1544 #[test]
1545 fn test_agent_admin_install_defaults() {
1546 let args = Args::try_parse_from(["passless", "agent-admin", "install"]).unwrap();
1547 assert!(matches!(
1548 args.command,
1549 Some(Commands::AgentAdmin {
1550 action: AgentAdminAction::Install {
1551 target: AgentSkillTarget::Auto,
1552 scope: AgentSkillScope::User,
1553 force: false,
1554 },
1555 ..
1556 })
1557 ));
1558 }
1559
1560 #[cfg(feature = "agent")]
1561 #[test]
1562 fn test_agent_admin_install_explicit_options() {
1563 let args = Args::try_parse_from([
1564 "passless",
1565 "agent-admin",
1566 "install",
1567 "claude",
1568 "--scope",
1569 "project",
1570 "--force",
1571 ])
1572 .unwrap();
1573 assert!(matches!(
1574 args.command,
1575 Some(Commands::AgentAdmin {
1576 action: AgentAdminAction::Install {
1577 target: AgentSkillTarget::Claude,
1578 scope: AgentSkillScope::Project,
1579 force: true,
1580 },
1581 ..
1582 })
1583 ));
1584 }
1585
1586 #[test]
1587 fn test_pin_config_default_max_uv_retries() {
1588 let config = PinConfig {
1589 enforcement: PinEnforcement::Optional,
1590 min_length: 4,
1591 max_retries: 8,
1592 max_uv_retries: 8,
1593 auto_lock_timeout: 0,
1594 };
1595 assert_eq!(config.max_uv_retries, 8);
1596 }
1597
1598 #[test]
1599 fn test_pin_config_validate_success() {
1600 let config = PinConfig {
1601 enforcement: PinEnforcement::Optional,
1602 min_length: 4,
1603 max_retries: 8,
1604 max_uv_retries: 8,
1605 auto_lock_timeout: 0,
1606 };
1607 assert!(config.validate().is_ok());
1608 }
1609
1610 #[test]
1611 fn test_pin_config_validate_zero_max_uv_retries() {
1612 let config = PinConfig {
1613 enforcement: PinEnforcement::Optional,
1614 min_length: 4,
1615 max_retries: 8,
1616 max_uv_retries: 0,
1617 auto_lock_timeout: 0,
1618 };
1619 let result = config.validate();
1620 assert!(result.is_err());
1621 assert!(result.unwrap_err().to_string().contains("max_uv_retries"));
1622 }
1623
1624 #[test]
1625 fn test_pin_config_validate_zero_max_retries() {
1626 let config = PinConfig {
1627 enforcement: PinEnforcement::Optional,
1628 min_length: 4,
1629 max_retries: 0,
1630 max_uv_retries: 8,
1631 auto_lock_timeout: 0,
1632 };
1633 let result = config.validate();
1634 assert!(result.is_err());
1635 assert!(result.unwrap_err().to_string().contains("max_retries"));
1636 }
1637
1638 #[test]
1639 fn test_pin_config_validate_invalid_min_length() {
1640 let config = PinConfig {
1641 enforcement: PinEnforcement::Optional,
1642 min_length: 3,
1643 max_retries: 8,
1644 max_uv_retries: 8,
1645 auto_lock_timeout: 0,
1646 };
1647 let result = config.validate();
1648 assert!(result.is_err());
1649 assert!(result.unwrap_err().to_string().contains("min_length"));
1650 }
1651
1652 #[test]
1653 fn test_canonicalize_path_existing() {
1654 let dir = std::env::temp_dir();
1655 let canonical = BackendConfig::canonicalize_path(&dir);
1656 assert!(canonical.is_absolute());
1657 assert!(canonical.exists());
1658 }
1659
1660 #[test]
1661 fn test_canonicalize_path_nonexistent() {
1662 let base = std::env::temp_dir();
1663 let nonexistent = base.join("passless_test_nonexistent_dir_12345/sub");
1664 let canonical = BackendConfig::canonicalize_path(&nonexistent);
1665 assert!(canonical.is_absolute());
1666 assert!(canonical.starts_with(BackendConfig::canonicalize_path(&base)));
1667 }
1668
1669 #[test]
1670 fn test_canonicalize_path_symlink() {
1671 let dir = tempfile::tempdir().unwrap();
1672 let real = dir.path().join("real");
1673 std::fs::create_dir(&real).unwrap();
1674 let link = dir.path().join("link");
1675 std::os::unix::fs::symlink(&real, &link).unwrap();
1676
1677 let canonical_real = BackendConfig::canonicalize_path(&real);
1678 let canonical_link = BackendConfig::canonicalize_path(&link);
1679 assert_eq!(canonical_real, canonical_link);
1680 }
1681
1682 #[test]
1683 fn test_local_state_path_relative_and_absolute() {
1684 let dir = tempfile::tempdir_in(".").unwrap();
1685 let abs_path = std::fs::canonicalize(dir.path()).unwrap();
1686 let rel_path = dir.path().to_path_buf();
1687
1688 let backend_abs = BackendConfig::Local {
1689 path: abs_path.display().to_string(),
1690 };
1691 let backend_rel = BackendConfig::Local {
1692 path: rel_path.display().to_string(),
1693 };
1694 assert_eq!(backend_abs.state_path(), backend_rel.state_path());
1695 }
1696
1697 #[test]
1698 fn test_pass_state_path_different_subpaths() {
1699 let store = "/tmp/passless_test_store";
1700 let backend_a = BackendConfig::Pass {
1701 store_path: store.to_string(),
1702 path: "fido2".to_string(),
1703 gpg_backend: "gnupg-bin".to_string(),
1704 };
1705 let backend_b = BackendConfig::Pass {
1706 store_path: store.to_string(),
1707 path: "fido2-other".to_string(),
1708 gpg_backend: "gnupg-bin".to_string(),
1709 };
1710 assert_ne!(backend_a.state_path(), backend_b.state_path());
1711 }
1712
1713 #[test]
1714 fn test_different_local_paths_produce_different_identities() {
1715 let backend_a = BackendConfig::Local {
1716 path: "/tmp/passless_a".to_string(),
1717 };
1718 let backend_b = BackendConfig::Local {
1719 path: "/tmp/passless_b".to_string(),
1720 };
1721 assert_ne!(backend_a.state_path(), backend_b.state_path());
1722 }
1723
1724 #[cfg(feature = "agent")]
1725 #[test]
1726 fn test_agent_admin_profile_list() {
1727 let args = Args::try_parse_from(["passless", "agent-admin", "profile", "list"]).unwrap();
1728 assert!(matches!(
1729 args.command,
1730 Some(Commands::AgentAdmin {
1731 action: AgentAdminAction::Profile {
1732 action: AdminProfileAction::List,
1733 },
1734 ..
1735 })
1736 ));
1737 }
1738
1739 #[cfg(feature = "agent")]
1740 #[test]
1741 fn test_agent_admin_credential_delete_without_confirm() {
1742 let args = Args::try_parse_from([
1743 "passless",
1744 "agent-admin",
1745 "credential",
1746 "delete",
1747 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
1748 ])
1749 .unwrap();
1750 assert!(matches!(
1751 args.command,
1752 Some(Commands::AgentAdmin {
1753 action: AgentAdminAction::Credential {
1754 action: AdminCredentialAction::Delete { confirm: false, .. },
1755 },
1756 ..
1757 })
1758 ));
1759 }
1760
1761 #[cfg(feature = "agent")]
1762 #[test]
1763 fn test_agent_admin_credential_delete_with_confirm() {
1764 let args = Args::try_parse_from([
1765 "passless",
1766 "agent-admin",
1767 "credential",
1768 "delete",
1769 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
1770 "--confirm",
1771 ])
1772 .unwrap();
1773 assert!(matches!(
1774 args.command,
1775 Some(Commands::AgentAdmin {
1776 action: AgentAdminAction::Credential {
1777 action: AdminCredentialAction::Delete { confirm: true, .. },
1778 },
1779 ..
1780 })
1781 ));
1782 }
1783
1784 #[cfg(feature = "agent")]
1785 #[test]
1786 fn test_agent_admin_shutdown_hidden() {
1787 let args =
1788 Args::try_parse_from(["passless", "agent-admin", "shutdown", "--confirm"]).unwrap();
1789 assert!(matches!(
1790 args.command,
1791 Some(Commands::AgentAdmin {
1792 action: AgentAdminAction::Shutdown { confirm: true },
1793 ..
1794 })
1795 ));
1796 }
1797
1798 #[cfg(feature = "agent")]
1799 #[test]
1800 fn test_agent_admin_output_default_json() {
1801 let args = Args::try_parse_from(["passless", "agent-admin", "profile", "list"]).unwrap();
1802 match args.command {
1803 Some(Commands::AgentAdmin { output, .. }) => {
1804 assert_eq!(output, OutputFormat::Json);
1805 }
1806 _ => panic!("expected AgentAdmin command"),
1807 }
1808 }
1809
1810 #[cfg(feature = "agent")]
1811 #[test]
1812 fn test_agent_admin_output_plain() {
1813 let args = Args::try_parse_from([
1814 "passless",
1815 "agent-admin",
1816 "--output",
1817 "plain",
1818 "profile",
1819 "list",
1820 ])
1821 .unwrap();
1822 match args.command {
1823 Some(Commands::AgentAdmin { output, .. }) => {
1824 assert_eq!(output, OutputFormat::Plain);
1825 }
1826 _ => panic!("expected AgentAdmin command"),
1827 }
1828 }
1829
1830 #[cfg(feature = "agent")]
1831 #[test]
1832 fn test_agent_doctor_parses() {
1833 let args = Args::try_parse_from(["passless", "agent", "doctor"]).unwrap();
1834 assert!(matches!(
1835 args.command,
1836 Some(Commands::Agent {
1837 action: AgentCommand::Doctor,
1838 ..
1839 })
1840 ));
1841 }
1842
1843 #[cfg(feature = "agent")]
1844 #[test]
1845 fn test_agent_browser_parses() {
1846 let args = Args::try_parse_from([
1847 "passless",
1848 "agent",
1849 "--profile",
1850 "p",
1851 "browser",
1852 "--json",
1853 "--wait",
1854 "--headed",
1855 ])
1856 .unwrap();
1857 let Some(Commands::Agent {
1858 profile,
1859 action:
1860 AgentCommand::Browser {
1861 json,
1862 env,
1863 wait,
1864 headed,
1865 url,
1866 },
1867 ..
1868 }) = args.command
1869 else {
1870 panic!("not agent browser");
1871 };
1872 assert_eq!(profile.as_deref(), Some("p"));
1873 assert!(json && wait && headed && !env && url.is_none());
1874 let args =
1876 Args::try_parse_from(["passless", "agent", "browser", "--env", "--profile", "p"])
1877 .unwrap();
1878 assert!(matches!(
1879 args.command,
1880 Some(Commands::Agent {
1881 action: AgentCommand::Browser { env: true, .. },
1882 ..
1883 })
1884 ));
1885 assert!(Args::try_parse_from(["passless", "agent", "browser", "--json", "--env"]).is_err());
1886 }
1887
1888 #[cfg(feature = "agent")]
1889 #[test]
1890 fn test_agent_mcp_parses() {
1891 let args = Args::try_parse_from([
1892 "passless",
1893 "agent",
1894 "mcp",
1895 "playwright",
1896 "--profile",
1897 "p",
1898 "--",
1899 "--isolated",
1900 ])
1901 .unwrap();
1902 let Some(Commands::Agent {
1903 action:
1904 AgentCommand::Mcp {
1905 adapter: Some(McpAdapter::Playwright { extra, .. }),
1906 print_config: None,
1907 ..
1908 },
1909 profile,
1910 ..
1911 }) = args.command
1912 else {
1913 panic!("not agent mcp playwright");
1914 };
1915 assert_eq!(profile.as_deref(), Some("p"));
1916 assert_eq!(extra, ["--isolated"]);
1917
1918 let args = Args::try_parse_from(["passless", "agent", "mcp", "chrome-devtools"]).unwrap();
1919 assert!(matches!(
1920 args.command,
1921 Some(Commands::Agent {
1922 action: AgentCommand::Mcp {
1923 adapter: Some(McpAdapter::ChromeDevtools { .. }),
1924 ..
1925 },
1926 ..
1927 })
1928 ));
1929
1930 for (name, target) in [
1931 ("claude-code", McpConfigTarget::ClaudeCode),
1932 ("opencode", McpConfigTarget::Opencode),
1933 ("cursor", McpConfigTarget::Cursor),
1934 ("vscode", McpConfigTarget::Vscode),
1935 ] {
1936 let args = Args::try_parse_from([
1937 "passless",
1938 "agent",
1939 "--profile",
1940 "p",
1941 "mcp",
1942 "--print-config",
1943 name,
1944 ])
1945 .unwrap();
1946 assert!(matches!(
1947 args.command,
1948 Some(Commands::Agent {
1949 action: AgentCommand::Mcp { print_config: Some(t), adapter: None, .. },
1950 ..
1951 }) if t == target
1952 ));
1953 }
1954 assert!(
1955 Args::try_parse_from(["passless", "agent", "mcp", "--print-config", "emacs"]).is_err()
1956 );
1957 assert!(
1959 Args::try_parse_from([
1960 "passless",
1961 "agent",
1962 "playwright-mcp",
1963 "--profile",
1964 "p",
1965 "--",
1966 "/usr/bin/npx",
1967 "x",
1968 ])
1969 .is_ok()
1970 );
1971 }
1972
1973 #[cfg(feature = "agent")]
1974 #[test]
1975 fn test_doctor_agents_parses() {
1976 let args = Args::try_parse_from(["passless", "doctor", "--agents", "-o", "json"]).unwrap();
1977 assert!(matches!(
1978 args.command,
1979 Some(Commands::Doctor {
1980 agents: true,
1981 output: OutputFormat::Json
1982 })
1983 ));
1984 }
1985
1986 #[cfg(feature = "agent")]
1987 #[test]
1988 fn test_agent_run_with_command() {
1989 let args = Args::try_parse_from([
1990 "passless",
1991 "agent",
1992 "run",
1993 "--profile",
1994 "myprofile",
1995 "--",
1996 "/usr/bin/test",
1997 "arg1",
1998 ])
1999 .unwrap();
2000 match args.command {
2001 Some(Commands::Agent {
2002 action: AgentCommand::Run { profile, command },
2003 ..
2004 }) => {
2005 assert_eq!(profile, "myprofile");
2006 assert_eq!(command.len(), 2);
2007 }
2008 _ => panic!("expected Agent Run command"),
2009 }
2010 }
2011
2012 #[cfg(feature = "agent")]
2013 #[test]
2014 fn test_agent_admin_grants_parse() {
2015 let args = Args::try_parse_from([
2016 "passless",
2017 "agent-admin",
2018 "grants",
2019 "revoke",
2020 "--profile",
2021 "coding",
2022 "--rp",
2023 "example.com",
2024 "--confirm",
2025 ])
2026 .unwrap();
2027 assert!(matches!(
2028 args.command,
2029 Some(Commands::AgentAdmin {
2030 action: AgentAdminAction::Grants {
2031 action: AdminGrantsAction::Revoke {
2032 ref profile,
2033 ref rp_id,
2034 action: AdminGrantAction::Authenticate,
2035 confirm: true,
2036 },
2037 },
2038 ..
2039 }) if profile == "coding" && rp_id == "example.com"
2040 ));
2041 let args = Args::try_parse_from([
2042 "passless",
2043 "agent-admin",
2044 "grants",
2045 "clear",
2046 "--profile",
2047 "p",
2048 ])
2049 .unwrap();
2050 assert!(matches!(
2051 args.command,
2052 Some(Commands::AgentAdmin {
2053 action: AgentAdminAction::Grants {
2054 action: AdminGrantsAction::Clear { confirm: false, .. },
2055 },
2056 ..
2057 })
2058 ));
2059 assert!(Args::try_parse_from(["passless", "agent-admin", "grants", "list"]).is_ok());
2060 }
2061
2062 #[cfg(feature = "agent")]
2063 #[test]
2064 fn test_agent_admin_renamed_session_commands_keep_hidden_aliases() {
2065 for (spelling, expect_sessions) in [
2066 ("sessions", true),
2067 ("delegation", true),
2068 ("principals", false),
2069 ("session", false),
2070 ] {
2071 let args = Args::try_parse_from(["passless", "agent-admin", spelling, "list"]).unwrap();
2072 let is_sessions = matches!(
2073 args.command,
2074 Some(Commands::AgentAdmin {
2075 action: AgentAdminAction::Sessions { .. },
2076 ..
2077 })
2078 );
2079 let is_principals = matches!(
2080 args.command,
2081 Some(Commands::AgentAdmin {
2082 action: AgentAdminAction::Principals { .. },
2083 ..
2084 })
2085 );
2086 assert_eq!(is_sessions, expect_sessions, "{spelling}");
2087 assert_eq!(is_principals, !expect_sessions, "{spelling}");
2088 }
2089 assert!(Args::try_parse_from(["passless", "agent", "intent", "show", "x"]).is_err());
2090 }
2091
2092 #[cfg(feature = "agent")]
2093 #[test]
2094 fn test_agent_output_default_json() {
2095 let args = Args::try_parse_from(["passless", "agent", "doctor"]).unwrap();
2096 match args.command {
2097 Some(Commands::Agent { output, .. }) => {
2098 assert_eq!(output, OutputFormat::Json);
2099 }
2100 _ => panic!("expected Agent command"),
2101 }
2102 }
2103
2104 #[cfg(feature = "agent")]
2105 #[test]
2106 fn test_shell_completions_contain_agent_commands() {
2107 use clap::CommandFactory;
2108
2109 let cmd = Args::command();
2110 let mut buf = Vec::new();
2111 clap_complete::generate(
2112 clap_complete::Shell::Bash,
2113 &mut cmd.clone(),
2114 "passless",
2115 &mut buf,
2116 );
2117 let completion = String::from_utf8(buf).unwrap();
2118
2119 for expected in [
2120 "agent-admin",
2121 "agent",
2122 "install",
2123 "browser-control",
2124 "grants",
2125 "sessions",
2126 "principals",
2127 "doctor",
2128 "capabilities",
2129 "instructions",
2130 ] {
2131 assert!(
2132 completion.contains(expected),
2133 "bash completion missing '{}'",
2134 expected
2135 );
2136 }
2137 }
2138
2139 #[cfg(feature = "agent")]
2140 #[test]
2141 fn test_shell_completions_zsh_contain_agent_commands() {
2142 use clap::CommandFactory;
2143
2144 let cmd = Args::command();
2145 let mut buf = Vec::new();
2146 clap_complete::generate(
2147 clap_complete::Shell::Zsh,
2148 &mut cmd.clone(),
2149 "passless",
2150 &mut buf,
2151 );
2152 let completion = String::from_utf8(buf).unwrap();
2153
2154 for expected in ["agent-admin", "agent", "install", "browser-control"] {
2155 assert!(
2156 completion.contains(expected),
2157 "zsh completion missing '{}'",
2158 expected
2159 );
2160 }
2161 }
2162
2163 #[cfg(feature = "agent")]
2164 #[test]
2165 fn test_config_print_includes_agent_fields() {
2166 let mut default_args = Args::parse_from(["passless"]);
2167 let config = AppConfig::from(&mut default_args.config);
2168 let toml_output = config.to_toml_with_comments();
2169
2170 assert!(
2171 toml_output.contains("backend_type"),
2172 "config print missing backend_type"
2173 );
2174 assert!(
2175 toml_output.contains("[security]"),
2176 "config print missing [security] section"
2177 );
2178 assert!(
2179 toml_output.contains("[pin]"),
2180 "config print missing [pin] section"
2181 );
2182 assert!(
2183 toml_output.contains("always_uv"),
2184 "config print missing always_uv"
2185 );
2186 assert!(
2187 toml_output.contains("notification_timeout"),
2188 "config print missing notification_timeout"
2189 );
2190 }
2191
2192 #[test]
2193 fn test_config_print_contains_passless_header() {
2194 let mut default_args = Args::parse_from(["passless"]);
2195 let config = AppConfig::from(&mut default_args.config);
2196 let toml_output = config.to_toml_with_comments();
2197
2198 assert!(toml_output.contains("Passless Configuration File"));
2199 assert!(toml_output.contains("~/.config/passless/config.toml"));
2200 }
2201
2202 #[test]
2203 fn test_config_print_contains_local_backend_section() {
2204 let mut default_args = Args::parse_from(["passless"]);
2205 let config = AppConfig::from(&mut default_args.config);
2206 let toml_output = config.to_toml_with_comments();
2207
2208 assert!(toml_output.contains("[local]"));
2209 assert!(toml_output.contains("path"));
2210 }
2211
2212 #[test]
2213 fn test_config_print_contains_pass_backend_section() {
2214 let mut default_args = Args::parse_from(["passless"]);
2215 let config = AppConfig::from(&mut default_args.config);
2216 let toml_output = config.to_toml_with_comments();
2217
2218 assert!(toml_output.contains("[pass]"));
2219 assert!(toml_output.contains("store_path"));
2220 assert!(toml_output.contains("gpg_backend"));
2221 }
2222
2223 #[test]
2224 fn test_config_print_produces_valid_toml_without_none_literals() {
2225 let mut default_args = Args::parse_from(["passless"]);
2226 let config = AppConfig::from(&mut default_args.config);
2227 let toml_output = config.to_toml_with_comments();
2228
2229 for (line_no, line) in toml_output.lines().enumerate() {
2230 let trimmed = line.trim();
2231 if trimmed.starts_with('#') || trimmed.is_empty() {
2232 continue;
2233 }
2234 assert!(
2235 !trimmed.contains("= None"),
2236 "Line {} contains invalid TOML 'None' literal: {}",
2237 line_no + 1,
2238 line
2239 );
2240 }
2241
2242 let parse_result: Result<toml::Table, _> = toml_output.parse();
2243 assert!(
2244 parse_result.is_ok(),
2245 "Generated TOML is not valid: {:?}",
2246 parse_result.err()
2247 );
2248 }
2249
2250 #[cfg(feature = "agent")]
2251 #[test]
2252 fn test_config_print_comments_out_none_option_fields() {
2253 let mut default_args = Args::parse_from(["passless"]);
2254 let config = AppConfig::from(&mut default_args.config);
2255 let toml_output = config.to_toml_with_comments();
2256
2257 assert!(
2258 toml_output.contains("# audit_path = <not set>"),
2259 "Option::None field 'audit_path' should be commented out, got:\n{}",
2260 toml_output
2261 );
2262 }
2263}