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 #[command(hide = true)]
1458 McpSessionBroker {
1459 #[arg(long, value_name = "PROFILE")]
1461 profile: String,
1462 #[arg(long, value_name = "URL")]
1464 url: Option<String>,
1465 },
1466 Run {
1468 #[arg(long, value_name = "PROFILE")]
1470 profile: String,
1471 #[arg(last = true, required = true)]
1473 command: Vec<std::path::PathBuf>,
1474 },
1475}
1476
1477#[cfg(feature = "agent")]
1479#[derive(Subcommand, Debug, Clone)]
1480pub enum McpAdapter {
1481 Playwright {
1483 #[arg(long, value_name = "SPEC")]
1485 package: Option<String>,
1486 #[arg(long, value_name = "PATH")]
1488 npx: Option<std::path::PathBuf>,
1489 #[arg(long, value_name = "URL")]
1491 url: Option<String>,
1492 #[arg(last = true)]
1494 extra: Vec<String>,
1495 },
1496 ChromeDevtools {
1502 #[arg(long, value_name = "SPEC")]
1504 package: Option<String>,
1505 #[arg(long, value_name = "PATH")]
1507 npx: Option<std::path::PathBuf>,
1508 #[arg(long, value_name = "URL")]
1510 url: Option<String>,
1511 #[arg(last = true)]
1513 extra: Vec<String>,
1514 },
1515 Install {
1525 #[arg(long, value_enum, value_name = "CLIENT")]
1527 client: McpInstallClient,
1528 #[arg(long, conflicts_with = "project")]
1530 user: bool,
1531 #[arg(long, value_name = "DIR", conflicts_with = "user")]
1533 project: Option<std::path::PathBuf>,
1534 #[arg(long)]
1537 yes: bool,
1538 #[arg(long)]
1540 skill: bool,
1541 #[arg(long, value_name = "ABS")]
1544 passless_path: Option<std::path::PathBuf>,
1545 },
1546}
1547
1548#[cfg(feature = "agent")]
1550#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1551pub enum McpAdapterKind {
1552 Playwright,
1553 ChromeDevtools,
1554}
1555
1556#[cfg(feature = "agent")]
1558#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1559pub enum McpInstallClient {
1560 Opencode,
1562 ClaudeCode,
1564}
1565
1566#[cfg(feature = "agent")]
1568#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1569pub enum McpConfigTarget {
1570 ClaudeCode,
1572 Opencode,
1574 Cursor,
1576 Vscode,
1578}
1579
1580#[cfg(feature = "agent")]
1582#[derive(Subcommand, Debug, Clone)]
1583pub enum AgentCredentialAction {
1584 List,
1586 Show {
1588 #[arg(value_name = "CREDENTIAL_REF")]
1590 credential_ref: String,
1591 },
1592}
1593
1594#[cfg(test)]
1595mod tests {
1596 use super::*;
1597
1598 #[cfg(feature = "agent")]
1599 #[test]
1600 fn test_agent_admin_install_defaults() {
1601 let args = Args::try_parse_from(["passless", "agent-admin", "install"]).unwrap();
1602 assert!(matches!(
1603 args.command,
1604 Some(Commands::AgentAdmin {
1605 action: AgentAdminAction::Install {
1606 target: AgentSkillTarget::Auto,
1607 scope: AgentSkillScope::User,
1608 force: false,
1609 },
1610 ..
1611 })
1612 ));
1613 }
1614
1615 #[cfg(feature = "agent")]
1616 #[test]
1617 fn test_agent_admin_install_explicit_options() {
1618 let args = Args::try_parse_from([
1619 "passless",
1620 "agent-admin",
1621 "install",
1622 "claude",
1623 "--scope",
1624 "project",
1625 "--force",
1626 ])
1627 .unwrap();
1628 assert!(matches!(
1629 args.command,
1630 Some(Commands::AgentAdmin {
1631 action: AgentAdminAction::Install {
1632 target: AgentSkillTarget::Claude,
1633 scope: AgentSkillScope::Project,
1634 force: true,
1635 },
1636 ..
1637 })
1638 ));
1639 }
1640
1641 #[test]
1642 fn test_pin_config_default_max_uv_retries() {
1643 let config = PinConfig {
1644 enforcement: PinEnforcement::Optional,
1645 min_length: 4,
1646 max_retries: 8,
1647 max_uv_retries: 8,
1648 auto_lock_timeout: 0,
1649 };
1650 assert_eq!(config.max_uv_retries, 8);
1651 }
1652
1653 #[test]
1654 fn test_pin_config_validate_success() {
1655 let config = PinConfig {
1656 enforcement: PinEnforcement::Optional,
1657 min_length: 4,
1658 max_retries: 8,
1659 max_uv_retries: 8,
1660 auto_lock_timeout: 0,
1661 };
1662 assert!(config.validate().is_ok());
1663 }
1664
1665 #[test]
1666 fn test_pin_config_validate_zero_max_uv_retries() {
1667 let config = PinConfig {
1668 enforcement: PinEnforcement::Optional,
1669 min_length: 4,
1670 max_retries: 8,
1671 max_uv_retries: 0,
1672 auto_lock_timeout: 0,
1673 };
1674 let result = config.validate();
1675 assert!(result.is_err());
1676 assert!(result.unwrap_err().to_string().contains("max_uv_retries"));
1677 }
1678
1679 #[test]
1680 fn test_pin_config_validate_zero_max_retries() {
1681 let config = PinConfig {
1682 enforcement: PinEnforcement::Optional,
1683 min_length: 4,
1684 max_retries: 0,
1685 max_uv_retries: 8,
1686 auto_lock_timeout: 0,
1687 };
1688 let result = config.validate();
1689 assert!(result.is_err());
1690 assert!(result.unwrap_err().to_string().contains("max_retries"));
1691 }
1692
1693 #[test]
1694 fn test_pin_config_validate_invalid_min_length() {
1695 let config = PinConfig {
1696 enforcement: PinEnforcement::Optional,
1697 min_length: 3,
1698 max_retries: 8,
1699 max_uv_retries: 8,
1700 auto_lock_timeout: 0,
1701 };
1702 let result = config.validate();
1703 assert!(result.is_err());
1704 assert!(result.unwrap_err().to_string().contains("min_length"));
1705 }
1706
1707 #[test]
1708 fn test_canonicalize_path_existing() {
1709 let dir = std::env::temp_dir();
1710 let canonical = BackendConfig::canonicalize_path(&dir);
1711 assert!(canonical.is_absolute());
1712 assert!(canonical.exists());
1713 }
1714
1715 #[test]
1716 fn test_canonicalize_path_nonexistent() {
1717 let base = std::env::temp_dir();
1718 let nonexistent = base.join("passless_test_nonexistent_dir_12345/sub");
1719 let canonical = BackendConfig::canonicalize_path(&nonexistent);
1720 assert!(canonical.is_absolute());
1721 assert!(canonical.starts_with(BackendConfig::canonicalize_path(&base)));
1722 }
1723
1724 #[test]
1725 fn test_canonicalize_path_symlink() {
1726 let dir = tempfile::tempdir().unwrap();
1727 let real = dir.path().join("real");
1728 std::fs::create_dir(&real).unwrap();
1729 let link = dir.path().join("link");
1730 std::os::unix::fs::symlink(&real, &link).unwrap();
1731
1732 let canonical_real = BackendConfig::canonicalize_path(&real);
1733 let canonical_link = BackendConfig::canonicalize_path(&link);
1734 assert_eq!(canonical_real, canonical_link);
1735 }
1736
1737 #[test]
1738 fn test_local_state_path_relative_and_absolute() {
1739 let dir = tempfile::tempdir_in(".").unwrap();
1740 let abs_path = std::fs::canonicalize(dir.path()).unwrap();
1741 let rel_path = dir.path().to_path_buf();
1742
1743 let backend_abs = BackendConfig::Local {
1744 path: abs_path.display().to_string(),
1745 };
1746 let backend_rel = BackendConfig::Local {
1747 path: rel_path.display().to_string(),
1748 };
1749 assert_eq!(backend_abs.state_path(), backend_rel.state_path());
1750 }
1751
1752 #[test]
1753 fn test_pass_state_path_different_subpaths() {
1754 let store = "/tmp/passless_test_store";
1755 let backend_a = BackendConfig::Pass {
1756 store_path: store.to_string(),
1757 path: "fido2".to_string(),
1758 gpg_backend: "gnupg-bin".to_string(),
1759 };
1760 let backend_b = BackendConfig::Pass {
1761 store_path: store.to_string(),
1762 path: "fido2-other".to_string(),
1763 gpg_backend: "gnupg-bin".to_string(),
1764 };
1765 assert_ne!(backend_a.state_path(), backend_b.state_path());
1766 }
1767
1768 #[test]
1769 fn test_different_local_paths_produce_different_identities() {
1770 let backend_a = BackendConfig::Local {
1771 path: "/tmp/passless_a".to_string(),
1772 };
1773 let backend_b = BackendConfig::Local {
1774 path: "/tmp/passless_b".to_string(),
1775 };
1776 assert_ne!(backend_a.state_path(), backend_b.state_path());
1777 }
1778
1779 #[cfg(feature = "agent")]
1780 #[test]
1781 fn test_agent_admin_profile_list() {
1782 let args = Args::try_parse_from(["passless", "agent-admin", "profile", "list"]).unwrap();
1783 assert!(matches!(
1784 args.command,
1785 Some(Commands::AgentAdmin {
1786 action: AgentAdminAction::Profile {
1787 action: AdminProfileAction::List,
1788 },
1789 ..
1790 })
1791 ));
1792 }
1793
1794 #[cfg(feature = "agent")]
1795 #[test]
1796 fn test_agent_admin_credential_delete_without_confirm() {
1797 let args = Args::try_parse_from([
1798 "passless",
1799 "agent-admin",
1800 "credential",
1801 "delete",
1802 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
1803 ])
1804 .unwrap();
1805 assert!(matches!(
1806 args.command,
1807 Some(Commands::AgentAdmin {
1808 action: AgentAdminAction::Credential {
1809 action: AdminCredentialAction::Delete { confirm: false, .. },
1810 },
1811 ..
1812 })
1813 ));
1814 }
1815
1816 #[cfg(feature = "agent")]
1817 #[test]
1818 fn test_agent_admin_credential_delete_with_confirm() {
1819 let args = Args::try_parse_from([
1820 "passless",
1821 "agent-admin",
1822 "credential",
1823 "delete",
1824 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
1825 "--confirm",
1826 ])
1827 .unwrap();
1828 assert!(matches!(
1829 args.command,
1830 Some(Commands::AgentAdmin {
1831 action: AgentAdminAction::Credential {
1832 action: AdminCredentialAction::Delete { confirm: true, .. },
1833 },
1834 ..
1835 })
1836 ));
1837 }
1838
1839 #[cfg(feature = "agent")]
1840 #[test]
1841 fn test_agent_admin_shutdown_hidden() {
1842 let args =
1843 Args::try_parse_from(["passless", "agent-admin", "shutdown", "--confirm"]).unwrap();
1844 assert!(matches!(
1845 args.command,
1846 Some(Commands::AgentAdmin {
1847 action: AgentAdminAction::Shutdown { confirm: true },
1848 ..
1849 })
1850 ));
1851 }
1852
1853 #[cfg(feature = "agent")]
1854 #[test]
1855 fn test_agent_admin_output_default_json() {
1856 let args = Args::try_parse_from(["passless", "agent-admin", "profile", "list"]).unwrap();
1857 match args.command {
1858 Some(Commands::AgentAdmin { output, .. }) => {
1859 assert_eq!(output, OutputFormat::Json);
1860 }
1861 _ => panic!("expected AgentAdmin command"),
1862 }
1863 }
1864
1865 #[cfg(feature = "agent")]
1866 #[test]
1867 fn test_agent_admin_output_plain() {
1868 let args = Args::try_parse_from([
1869 "passless",
1870 "agent-admin",
1871 "--output",
1872 "plain",
1873 "profile",
1874 "list",
1875 ])
1876 .unwrap();
1877 match args.command {
1878 Some(Commands::AgentAdmin { output, .. }) => {
1879 assert_eq!(output, OutputFormat::Plain);
1880 }
1881 _ => panic!("expected AgentAdmin command"),
1882 }
1883 }
1884
1885 #[cfg(feature = "agent")]
1886 #[test]
1887 fn test_agent_doctor_parses() {
1888 let args = Args::try_parse_from(["passless", "agent", "doctor"]).unwrap();
1889 assert!(matches!(
1890 args.command,
1891 Some(Commands::Agent {
1892 action: AgentCommand::Doctor,
1893 ..
1894 })
1895 ));
1896 }
1897
1898 #[cfg(feature = "agent")]
1899 #[test]
1900 fn test_agent_browser_parses() {
1901 let args = Args::try_parse_from([
1902 "passless",
1903 "agent",
1904 "--profile",
1905 "p",
1906 "browser",
1907 "--json",
1908 "--wait",
1909 "--headed",
1910 ])
1911 .unwrap();
1912 let Some(Commands::Agent {
1913 profile,
1914 action:
1915 AgentCommand::Browser {
1916 json,
1917 env,
1918 wait,
1919 headed,
1920 url,
1921 },
1922 ..
1923 }) = args.command
1924 else {
1925 panic!("not agent browser");
1926 };
1927 assert_eq!(profile.as_deref(), Some("p"));
1928 assert!(json && wait && headed && !env && url.is_none());
1929 let args =
1931 Args::try_parse_from(["passless", "agent", "browser", "--env", "--profile", "p"])
1932 .unwrap();
1933 assert!(matches!(
1934 args.command,
1935 Some(Commands::Agent {
1936 action: AgentCommand::Browser { env: true, .. },
1937 ..
1938 })
1939 ));
1940 assert!(Args::try_parse_from(["passless", "agent", "browser", "--json", "--env"]).is_err());
1941 }
1942
1943 #[cfg(feature = "agent")]
1944 #[test]
1945 fn test_agent_mcp_parses() {
1946 let args = Args::try_parse_from([
1947 "passless",
1948 "agent",
1949 "mcp",
1950 "playwright",
1951 "--profile",
1952 "p",
1953 "--",
1954 "--isolated",
1955 ])
1956 .unwrap();
1957 let Some(Commands::Agent {
1958 action:
1959 AgentCommand::Mcp {
1960 adapter: Some(McpAdapter::Playwright { extra, .. }),
1961 print_config: None,
1962 ..
1963 },
1964 profile,
1965 ..
1966 }) = args.command
1967 else {
1968 panic!("not agent mcp playwright");
1969 };
1970 assert_eq!(profile.as_deref(), Some("p"));
1971 assert_eq!(extra, ["--isolated"]);
1972
1973 let args = Args::try_parse_from(["passless", "agent", "mcp", "chrome-devtools"]).unwrap();
1974 assert!(matches!(
1975 args.command,
1976 Some(Commands::Agent {
1977 action: AgentCommand::Mcp {
1978 adapter: Some(McpAdapter::ChromeDevtools { .. }),
1979 ..
1980 },
1981 ..
1982 })
1983 ));
1984
1985 for (name, target) in [
1986 ("claude-code", McpConfigTarget::ClaudeCode),
1987 ("opencode", McpConfigTarget::Opencode),
1988 ("cursor", McpConfigTarget::Cursor),
1989 ("vscode", McpConfigTarget::Vscode),
1990 ] {
1991 let args = Args::try_parse_from([
1992 "passless",
1993 "agent",
1994 "--profile",
1995 "p",
1996 "mcp",
1997 "--print-config",
1998 name,
1999 ])
2000 .unwrap();
2001 assert!(matches!(
2002 args.command,
2003 Some(Commands::Agent {
2004 action: AgentCommand::Mcp { print_config: Some(t), adapter: None, .. },
2005 ..
2006 }) if t == target
2007 ));
2008 }
2009 assert!(
2010 Args::try_parse_from(["passless", "agent", "mcp", "--print-config", "emacs"]).is_err()
2011 );
2012 assert!(
2014 Args::try_parse_from([
2015 "passless",
2016 "agent",
2017 "playwright-mcp",
2018 "--profile",
2019 "p",
2020 "--",
2021 "/usr/bin/npx",
2022 "x",
2023 ])
2024 .is_ok()
2025 );
2026 }
2027
2028 #[cfg(feature = "agent")]
2029 #[test]
2030 fn test_agent_mcp_install_parses() {
2031 let parse = |extra: &[&str]| {
2032 let mut argv = vec!["passless", "agent", "mcp", "install"];
2033 argv.extend_from_slice(extra);
2034 Args::try_parse_from(argv)
2035 };
2036 assert!(parse(&[]).is_err());
2038 assert!(parse(&["--client", "emacs"]).is_err());
2039 let args = parse(&["--client", "opencode"]).unwrap();
2040 assert!(matches!(
2041 args.command,
2042 Some(Commands::Agent {
2043 profile: None,
2044 action: AgentCommand::Mcp {
2045 adapter: Some(McpAdapter::Install {
2046 client: McpInstallClient::Opencode,
2047 user: false,
2048 project: None,
2049 yes: false,
2050 skill: false,
2051 passless_path: None,
2052 }),
2053 ..
2054 },
2055 ..
2056 })
2057 ));
2058 let args = parse(&[
2059 "--client",
2060 "claude-code",
2061 "--project",
2062 "/work/p",
2063 "--profile",
2064 "agent",
2065 "--yes",
2066 "--skill",
2067 ])
2068 .unwrap();
2069 match args.command {
2070 Some(Commands::Agent {
2071 profile,
2072 action:
2073 AgentCommand::Mcp {
2074 adapter:
2075 Some(McpAdapter::Install {
2076 client,
2077 project,
2078 yes,
2079 skill,
2080 ..
2081 }),
2082 ..
2083 },
2084 ..
2085 }) => {
2086 assert_eq!(profile.as_deref(), Some("agent"));
2087 assert_eq!(client, McpInstallClient::ClaudeCode);
2088 assert_eq!(project, Some(std::path::PathBuf::from("/work/p")));
2089 assert!(yes && skill);
2090 }
2091 other => panic!("unexpected: {other:?}"),
2092 }
2093 assert!(parse(&["--client", "opencode", "--user", "--project", "/p"]).is_err());
2095 assert!(parse(&["--client", "opencode", "--user"]).is_ok());
2096 let args = parse(&[
2097 "--client",
2098 "opencode",
2099 "--passless-path",
2100 "/usr/bin/passless",
2101 ])
2102 .unwrap();
2103 assert!(matches!(
2104 args.command,
2105 Some(Commands::Agent {
2106 action: AgentCommand::Mcp {
2107 adapter: Some(McpAdapter::Install { passless_path: Some(ref p), .. }),
2108 ..
2109 },
2110 ..
2111 }) if p == std::path::Path::new("/usr/bin/passless")
2112 ));
2113 }
2114
2115 #[cfg(feature = "agent")]
2116 #[test]
2117 fn test_doctor_agents_parses() {
2118 let args = Args::try_parse_from(["passless", "doctor", "--agents", "-o", "json"]).unwrap();
2119 assert!(matches!(
2120 args.command,
2121 Some(Commands::Doctor {
2122 agents: true,
2123 output: OutputFormat::Json
2124 })
2125 ));
2126 }
2127
2128 #[cfg(feature = "agent")]
2129 #[test]
2130 fn test_agent_run_with_command() {
2131 let args = Args::try_parse_from([
2132 "passless",
2133 "agent",
2134 "run",
2135 "--profile",
2136 "myprofile",
2137 "--",
2138 "/usr/bin/test",
2139 "arg1",
2140 ])
2141 .unwrap();
2142 match args.command {
2143 Some(Commands::Agent {
2144 action: AgentCommand::Run { profile, command },
2145 ..
2146 }) => {
2147 assert_eq!(profile, "myprofile");
2148 assert_eq!(command.len(), 2);
2149 }
2150 _ => panic!("expected Agent Run command"),
2151 }
2152 }
2153
2154 #[cfg(feature = "agent")]
2155 #[test]
2156 fn test_agent_admin_grants_parse() {
2157 let args = Args::try_parse_from([
2158 "passless",
2159 "agent-admin",
2160 "grants",
2161 "revoke",
2162 "--profile",
2163 "coding",
2164 "--rp",
2165 "example.com",
2166 "--confirm",
2167 ])
2168 .unwrap();
2169 assert!(matches!(
2170 args.command,
2171 Some(Commands::AgentAdmin {
2172 action: AgentAdminAction::Grants {
2173 action: AdminGrantsAction::Revoke {
2174 ref profile,
2175 ref rp_id,
2176 action: AdminGrantAction::Authenticate,
2177 confirm: true,
2178 },
2179 },
2180 ..
2181 }) if profile == "coding" && rp_id == "example.com"
2182 ));
2183 let args = Args::try_parse_from([
2184 "passless",
2185 "agent-admin",
2186 "grants",
2187 "clear",
2188 "--profile",
2189 "p",
2190 ])
2191 .unwrap();
2192 assert!(matches!(
2193 args.command,
2194 Some(Commands::AgentAdmin {
2195 action: AgentAdminAction::Grants {
2196 action: AdminGrantsAction::Clear { confirm: false, .. },
2197 },
2198 ..
2199 })
2200 ));
2201 assert!(Args::try_parse_from(["passless", "agent-admin", "grants", "list"]).is_ok());
2202 }
2203
2204 #[cfg(feature = "agent")]
2205 #[test]
2206 fn test_agent_admin_renamed_session_commands_keep_hidden_aliases() {
2207 for (spelling, expect_sessions) in [
2208 ("sessions", true),
2209 ("delegation", true),
2210 ("principals", false),
2211 ("session", false),
2212 ] {
2213 let args = Args::try_parse_from(["passless", "agent-admin", spelling, "list"]).unwrap();
2214 let is_sessions = matches!(
2215 args.command,
2216 Some(Commands::AgentAdmin {
2217 action: AgentAdminAction::Sessions { .. },
2218 ..
2219 })
2220 );
2221 let is_principals = matches!(
2222 args.command,
2223 Some(Commands::AgentAdmin {
2224 action: AgentAdminAction::Principals { .. },
2225 ..
2226 })
2227 );
2228 assert_eq!(is_sessions, expect_sessions, "{spelling}");
2229 assert_eq!(is_principals, !expect_sessions, "{spelling}");
2230 }
2231 assert!(Args::try_parse_from(["passless", "agent", "intent", "show", "x"]).is_err());
2232 }
2233
2234 #[cfg(feature = "agent")]
2235 #[test]
2236 fn test_agent_output_default_json() {
2237 let args = Args::try_parse_from(["passless", "agent", "doctor"]).unwrap();
2238 match args.command {
2239 Some(Commands::Agent { output, .. }) => {
2240 assert_eq!(output, OutputFormat::Json);
2241 }
2242 _ => panic!("expected Agent command"),
2243 }
2244 }
2245
2246 #[cfg(feature = "agent")]
2247 #[test]
2248 fn test_shell_completions_contain_agent_commands() {
2249 use clap::CommandFactory;
2250
2251 let cmd = Args::command();
2252 let mut buf = Vec::new();
2253 clap_complete::generate(
2254 clap_complete::Shell::Bash,
2255 &mut cmd.clone(),
2256 "passless",
2257 &mut buf,
2258 );
2259 let completion = String::from_utf8(buf).unwrap();
2260
2261 for expected in [
2262 "agent-admin",
2263 "agent",
2264 "install",
2265 "browser-control",
2266 "grants",
2267 "sessions",
2268 "principals",
2269 "doctor",
2270 "capabilities",
2271 "instructions",
2272 ] {
2273 assert!(
2274 completion.contains(expected),
2275 "bash completion missing '{}'",
2276 expected
2277 );
2278 }
2279 }
2280
2281 #[cfg(feature = "agent")]
2282 #[test]
2283 fn test_shell_completions_zsh_contain_agent_commands() {
2284 use clap::CommandFactory;
2285
2286 let cmd = Args::command();
2287 let mut buf = Vec::new();
2288 clap_complete::generate(
2289 clap_complete::Shell::Zsh,
2290 &mut cmd.clone(),
2291 "passless",
2292 &mut buf,
2293 );
2294 let completion = String::from_utf8(buf).unwrap();
2295
2296 for expected in ["agent-admin", "agent", "install", "browser-control"] {
2297 assert!(
2298 completion.contains(expected),
2299 "zsh completion missing '{}'",
2300 expected
2301 );
2302 }
2303 }
2304
2305 #[cfg(feature = "agent")]
2306 #[test]
2307 fn test_config_print_includes_agent_fields() {
2308 let mut default_args = Args::parse_from(["passless"]);
2309 let config = AppConfig::from(&mut default_args.config);
2310 let toml_output = config.to_toml_with_comments();
2311
2312 assert!(
2313 toml_output.contains("backend_type"),
2314 "config print missing backend_type"
2315 );
2316 assert!(
2317 toml_output.contains("[security]"),
2318 "config print missing [security] section"
2319 );
2320 assert!(
2321 toml_output.contains("[pin]"),
2322 "config print missing [pin] section"
2323 );
2324 assert!(
2325 toml_output.contains("always_uv"),
2326 "config print missing always_uv"
2327 );
2328 assert!(
2329 toml_output.contains("notification_timeout"),
2330 "config print missing notification_timeout"
2331 );
2332 }
2333
2334 #[test]
2335 fn test_config_print_contains_passless_header() {
2336 let mut default_args = Args::parse_from(["passless"]);
2337 let config = AppConfig::from(&mut default_args.config);
2338 let toml_output = config.to_toml_with_comments();
2339
2340 assert!(toml_output.contains("Passless Configuration File"));
2341 assert!(toml_output.contains("~/.config/passless/config.toml"));
2342 }
2343
2344 #[test]
2345 fn test_config_print_contains_local_backend_section() {
2346 let mut default_args = Args::parse_from(["passless"]);
2347 let config = AppConfig::from(&mut default_args.config);
2348 let toml_output = config.to_toml_with_comments();
2349
2350 assert!(toml_output.contains("[local]"));
2351 assert!(toml_output.contains("path"));
2352 }
2353
2354 #[test]
2355 fn test_config_print_contains_pass_backend_section() {
2356 let mut default_args = Args::parse_from(["passless"]);
2357 let config = AppConfig::from(&mut default_args.config);
2358 let toml_output = config.to_toml_with_comments();
2359
2360 assert!(toml_output.contains("[pass]"));
2361 assert!(toml_output.contains("store_path"));
2362 assert!(toml_output.contains("gpg_backend"));
2363 }
2364
2365 #[test]
2366 fn test_config_print_produces_valid_toml_without_none_literals() {
2367 let mut default_args = Args::parse_from(["passless"]);
2368 let config = AppConfig::from(&mut default_args.config);
2369 let toml_output = config.to_toml_with_comments();
2370
2371 for (line_no, line) in toml_output.lines().enumerate() {
2372 let trimmed = line.trim();
2373 if trimmed.starts_with('#') || trimmed.is_empty() {
2374 continue;
2375 }
2376 assert!(
2377 !trimmed.contains("= None"),
2378 "Line {} contains invalid TOML 'None' literal: {}",
2379 line_no + 1,
2380 line
2381 );
2382 }
2383
2384 let parse_result: Result<toml::Table, _> = toml_output.parse();
2385 assert!(
2386 parse_result.is_ok(),
2387 "Generated TOML is not valid: {:?}",
2388 parse_result.err()
2389 );
2390 }
2391
2392 #[cfg(feature = "agent")]
2393 #[test]
2394 fn test_config_print_comments_out_none_option_fields() {
2395 let mut default_args = Args::parse_from(["passless"]);
2396 let config = AppConfig::from(&mut default_args.config);
2397 let toml_output = config.to_toml_with_comments();
2398
2399 assert!(
2400 toml_output.contains("# audit_path = <not set>"),
2401 "Option::None field 'audit_path' should be commented out, got:\n{}",
2402 toml_output
2403 );
2404 }
2405}