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 check_startup(&self) -> crate::error::Result<()> {
726 self.validate()?;
727 self.backend()?.validate()
728 }
729
730 pub fn validate(&self) -> crate::error::Result<()> {
732 self.pin.validate()?;
733 #[cfg(feature = "agent")]
734 {
735 let human_path = self.backend().ok().map(|b| b.state_path());
736 self.agents.validate(human_path.as_deref())?;
737 }
738 Ok(())
739 }
740}
741
742#[derive(Parser)]
744#[command(author, version, about)]
745pub struct Args {
746 #[arg(short, long, env = "PASSLESS_CONFIG")]
748 pub config_path: Option<PathBuf>,
749
750 #[command(flatten)]
752 pub config: <AppConfig as ClapSerde>::Opt,
753
754 #[command(subcommand)]
756 pub command: Option<Commands>,
757}
758
759#[derive(Debug, Clone, Copy, PartialEq, Eq)]
761pub enum OutputFormat {
762 Plain,
764 Json,
766}
767
768impl std::str::FromStr for OutputFormat {
769 type Err = String;
770
771 fn from_str(s: &str) -> Result<Self, Self::Err> {
772 match s.to_lowercase().as_str() {
773 "plain" => Ok(OutputFormat::Plain),
774 "json" => Ok(OutputFormat::Json),
775 _ => Err(format!(
776 "Invalid output format '{}'. Must be 'plain' or 'json'",
777 s
778 )),
779 }
780 }
781}
782
783impl std::fmt::Display for OutputFormat {
784 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
785 match self {
786 OutputFormat::Plain => write!(f, "plain"),
787 OutputFormat::Json => write!(f, "json"),
788 }
789 }
790}
791
792#[derive(Subcommand, Debug, Clone)]
794pub enum Commands {
795 Config {
797 #[command(subcommand)]
798 action: ConfigAction,
799 },
800 Client {
806 #[arg(short = 'D', long = "device", value_name = "INDEX|NAME", global = true)]
808 device: Option<String>,
809
810 #[arg(
812 short = 'o',
813 long = "output",
814 value_name = "FORMAT",
815 default_value = "plain",
816 global = true
817 )]
818 output: OutputFormat,
819
820 #[command(subcommand)]
821 action: ClientAction,
822 },
823 #[cfg(feature = "agent")]
825 AgentAdmin {
826 #[arg(
828 short = 'o',
829 long = "output",
830 value_name = "FORMAT",
831 default_value = "json",
832 global = true
833 )]
834 output: OutputFormat,
835
836 #[command(subcommand)]
837 action: AgentAdminAction,
838 },
839 #[cfg(feature = "agent")]
841 Doctor {
842 #[arg(long)]
846 agents: bool,
847
848 #[arg(
850 short = 'o',
851 long = "output",
852 value_name = "FORMAT",
853 default_value = "plain"
854 )]
855 output: OutputFormat,
856 },
857 #[cfg(feature = "agent")]
859 Agent {
860 #[arg(long, value_name = "PROFILE", global = true)]
862 profile: Option<String>,
863
864 #[arg(
866 short = 'o',
867 long = "output",
868 value_name = "FORMAT",
869 default_value = "json",
870 global = true
871 )]
872 output: OutputFormat,
873
874 #[command(subcommand)]
875 action: crate::AgentCommand,
876 },
877 #[cfg(feature = "tpm")]
879 Tpm {
880 #[command(subcommand)]
881 action: TpmAction,
882 },
883}
884
885#[cfg(feature = "tpm")]
887#[derive(Subcommand, Debug, Clone)]
888pub enum TpmAction {
889 #[command(group(clap::ArgGroup::new("seed-source").args(["generate", "seed_file", "seed_stdin"])))]
891 Provision {
892 #[arg(long)]
894 generate: bool,
895 #[arg(long = "seed-file", value_name = "PATH")]
897 seed_file: Option<PathBuf>,
898 #[arg(long = "seed-stdin")]
900 seed_stdin: bool,
901 #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
903 path: Option<String>,
904 #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
906 tcti: Option<String>,
907 },
908 Status {
910 #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
912 path: Option<String>,
913 #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
915 tcti: Option<String>,
916 },
917 Remove {
919 #[arg(long)]
921 confirm: bool,
922 #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
924 path: Option<String>,
925 #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
927 tcti: Option<String>,
928 },
929 #[command(group(clap::ArgGroup::new("selection").args(["credential_id", "all"]).required(true)))]
931 Migrate {
932 #[arg(long = "credential-id", value_name = "ID")]
934 credential_id: Option<String>,
935 #[arg(long)]
937 all: bool,
938 #[arg(long)]
940 dry_run: bool,
941 #[arg(long = "backup-dir", value_name = "PATH")]
943 backup_dir: Option<String>,
944 #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
946 path: Option<String>,
947 #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
949 tcti: Option<String>,
950 },
951}
952
953#[derive(Subcommand, Debug, Clone)]
955pub enum ConfigAction {
956 Print,
958 Check {
965 #[arg(short = 'c', long, value_name = "PATH")]
968 config_path: Option<PathBuf>,
969 },
970}
971
972#[cfg(feature = "agent")]
974#[derive(Subcommand, Debug, Clone)]
975pub enum AgentAdminAction {
976 Install {
978 #[arg(value_enum, default_value_t = AgentSkillTarget::Auto)]
980 target: AgentSkillTarget,
981
982 #[arg(long, value_enum, default_value_t = AgentSkillScope::User)]
984 scope: AgentSkillScope,
985
986 #[arg(long)]
988 force: bool,
989 },
990 Profile {
992 #[command(subcommand)]
993 action: AdminProfileAction,
994 },
995 Policy {
997 #[command(subcommand)]
998 action: AdminPolicyAction,
999 },
1000 Credential {
1002 #[command(subcommand)]
1003 action: AdminCredentialAction,
1004 },
1005 Grants {
1007 #[command(subcommand)]
1008 action: AdminGrantsAction,
1009 },
1010 #[command(alias = "delegation")]
1012 Sessions {
1013 #[command(subcommand)]
1014 action: AdminSessionsAction,
1015 },
1016 #[command(alias = "session")]
1018 Principals {
1019 #[command(subcommand)]
1020 action: AdminPrincipalsAction,
1021 },
1022 Browser {
1024 #[command(subcommand)]
1025 action: AdminBrowserAction,
1026 },
1027 Audit {
1029 #[command(subcommand)]
1030 action: AdminAuditAction,
1031 },
1032 #[command(hide = true)]
1034 Shutdown {
1035 #[arg(long)]
1037 confirm: bool,
1038 },
1039}
1040
1041#[cfg(feature = "agent")]
1043#[derive(Subcommand, Debug, Clone)]
1044pub enum AdminProfileAction {
1045 Check {
1047 #[arg(value_name = "PROFILE")]
1049 profile: String,
1050 },
1051 Show {
1053 #[arg(value_name = "PROFILE")]
1055 profile: String,
1056 },
1057 List,
1059 Enable {
1061 #[arg(value_name = "PROFILE")]
1063 profile: String,
1064 },
1065 Disable {
1067 #[arg(value_name = "PROFILE")]
1069 profile: String,
1070 },
1071}
1072
1073#[cfg(feature = "agent")]
1075#[derive(Subcommand, Debug, Clone)]
1076pub enum AdminPolicyAction {
1077 Check {
1079 #[arg(value_name = "PROFILE")]
1081 profile: String,
1082 },
1083 Reload {
1085 #[arg(value_name = "PROFILE")]
1087 profile: String,
1088 },
1089 Show {
1091 #[arg(value_name = "PROFILE")]
1093 profile: String,
1094 },
1095}
1096
1097#[cfg(feature = "agent")]
1099#[derive(Subcommand, Debug, Clone)]
1100pub enum AdminCredentialAction {
1101 List {
1103 #[arg(short = 'd', long = "domain", value_name = "DOMAIN")]
1105 rp_id: Option<String>,
1106 },
1107 Show {
1109 #[arg(value_name = "CREDENTIAL_REF")]
1111 credential_ref: String,
1112 },
1113 Revoke {
1115 #[arg(value_name = "CREDENTIAL_REF")]
1117 credential_ref: String,
1118 #[arg(long)]
1120 confirm: bool,
1121 },
1122 Delete {
1124 #[arg(value_name = "CREDENTIAL_REF")]
1126 credential_ref: String,
1127 #[arg(long)]
1129 confirm: bool,
1130 },
1131}
1132
1133#[cfg(feature = "agent")]
1135#[derive(Subcommand, Debug, Clone)]
1136pub enum AdminGrantsAction {
1137 List {
1139 #[arg(long, value_name = "PROFILE")]
1141 profile: Option<String>,
1142 },
1143 Revoke {
1145 #[arg(long, value_name = "PROFILE")]
1147 profile: String,
1148 #[arg(long = "rp", value_name = "RP_ID")]
1150 rp_id: String,
1151 #[arg(long, value_enum, default_value_t = AdminGrantAction::Authenticate)]
1153 action: AdminGrantAction,
1154 #[arg(long)]
1156 confirm: bool,
1157 },
1158 Clear {
1160 #[arg(long, value_name = "PROFILE")]
1162 profile: String,
1163 #[arg(long)]
1165 confirm: bool,
1166 },
1167}
1168
1169#[cfg(feature = "agent")]
1171#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1172pub enum AdminGrantAction {
1173 Authenticate,
1174}
1175
1176#[cfg(feature = "agent")]
1178#[derive(Subcommand, Debug, Clone)]
1179pub enum AdminSessionsAction {
1180 Show {
1182 #[arg(value_name = "GRANT_ID")]
1184 grant_id: String,
1185 },
1186 List {
1188 #[arg(long, value_name = "PROFILE")]
1190 profile: Option<String>,
1191 },
1192 Revoke {
1194 #[arg(value_name = "GRANT_ID")]
1196 grant_id: String,
1197 #[arg(long)]
1199 confirm: bool,
1200 },
1201}
1202
1203#[cfg(feature = "agent")]
1205#[derive(Subcommand, Debug, Clone)]
1206pub enum AdminPrincipalsAction {
1207 Show {
1209 #[arg(value_name = "SESSION_ID")]
1211 session_id: String,
1212 },
1213 List {
1215 #[arg(long, value_name = "PROFILE")]
1217 profile: Option<String>,
1218 },
1219 Revoke {
1221 #[arg(value_name = "SESSION_ID")]
1223 session_id: String,
1224 #[arg(long)]
1226 confirm: bool,
1227 },
1228}
1229
1230#[cfg(feature = "agent")]
1232#[derive(Subcommand, Debug, Clone)]
1233pub enum AdminBrowserAction {
1234 Launch {
1236 #[arg(long, value_name = "PROFILE")]
1238 profile: String,
1239 #[arg(long, value_name = "URL")]
1241 url: Option<String>,
1242 },
1243}
1244
1245#[cfg(feature = "agent")]
1247#[derive(Subcommand, Debug, Clone)]
1248pub enum AdminAuditAction {
1249 Status,
1251 Verify,
1253 Export {
1255 #[arg(long, value_enum, default_value_t = AdminAuditExportFormat::Json)]
1257 format: AdminAuditExportFormat,
1258 },
1259}
1260
1261#[cfg(feature = "agent")]
1263#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1264pub enum AdminAuditExportFormat {
1265 Json,
1266 Csv,
1267}
1268
1269#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1271pub enum AgentSkillTarget {
1272 Auto,
1273 Opencode,
1274 Claude,
1275 Pi,
1276}
1277
1278#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1280pub enum AgentSkillScope {
1281 User,
1282 Project,
1283}
1284
1285#[derive(Subcommand, Debug, Clone)]
1287pub enum ClientAction {
1288 Devices,
1290 Info,
1292 Reset {
1294 #[arg(long = "yes-i-really-want-to-reset-my-device", action = ArgAction::Count)]
1296 confirm: u8,
1297 },
1298 List {
1300 #[arg(short = 'd', long = "domain", value_name = "DOMAIN")]
1302 rp_id: Option<String>,
1303 },
1304 Show {
1306 #[arg(value_name = "CREDENTIAL_ID")]
1308 credential_id: String,
1309 },
1310 Delete {
1312 #[arg(value_name = "CREDENTIAL_ID")]
1314 credential_id: String,
1315 },
1316 Rename {
1318 #[arg(value_name = "CREDENTIAL_ID")]
1320 credential_id: String,
1321 #[arg(short = 'u', long = "user-name", value_name = "NAME")]
1323 user_name: Option<String>,
1324 #[arg(short = 'n', long = "display-name", value_name = "NAME")]
1326 display_name: Option<String>,
1327 },
1328 Backup {
1330 #[arg(value_name = "CREDENTIAL_ID")]
1332 credential_id: String,
1333 #[arg(long, value_name = "RECIPIENT")]
1335 recipient: String,
1336 #[arg(long, value_name = "PATH")]
1338 output_file: PathBuf,
1339 #[arg(long = "yes-i-understand-this-exports-a-passkey")]
1341 confirm: bool,
1342 },
1343 Restore {
1345 #[arg(value_name = "PATH")]
1347 input_file: PathBuf,
1348 #[arg(long)]
1350 replace: bool,
1351 #[arg(long = "yes-i-understand-this-restores-a-passkey")]
1353 confirm: bool,
1354 },
1355 Pin {
1357 #[command(subcommand)]
1358 action: PinAction,
1359 },
1360}
1361
1362#[derive(Subcommand, Debug, Clone)]
1364pub enum PinAction {
1365 Set {
1367 #[arg(value_name = "PIN")]
1369 pin: String,
1370 },
1371 Change {
1373 #[arg(value_name = "OLD_PIN")]
1375 old_pin: String,
1376 #[arg(value_name = "NEW_PIN")]
1378 new_pin: String,
1379 },
1380 UvReset,
1382}
1383
1384#[cfg(feature = "agent")]
1386#[derive(Subcommand, Debug, Clone)]
1387pub enum AgentCommand {
1388 Doctor,
1390 Capabilities,
1392 Instructions,
1394 Credential {
1396 #[command(subcommand)]
1397 action: AgentCredentialAction,
1398 },
1399 BrowserStatus,
1401 BrowserControl {
1407 #[arg(long, value_name = "JSON", conflicts_with = "request_file")]
1409 request: Option<String>,
1410 #[arg(long, value_name = "PATH", conflicts_with = "request")]
1412 request_file: Option<std::path::PathBuf>,
1413 #[arg(long, value_name = "MS", default_value = "5000")]
1415 timeout_ms: u32,
1416 },
1417 Browser {
1429 #[arg(long, conflicts_with = "env")]
1431 json: bool,
1432 #[arg(long)]
1434 env: bool,
1435 #[arg(long)]
1437 wait: bool,
1438 #[arg(long)]
1440 headed: bool,
1441 #[arg(long, value_name = "URL")]
1443 url: Option<String>,
1444 },
1445 #[command(args_conflicts_with_subcommands = true)]
1447 Mcp {
1448 #[arg(long, value_enum, value_name = "CLIENT")]
1450 print_config: Option<McpConfigTarget>,
1451 #[arg(long, value_enum, default_value_t = McpAdapterKind::Playwright, requires = "print_config")]
1453 server: McpAdapterKind,
1454 #[command(subcommand)]
1455 adapter: Option<McpAdapter>,
1456 },
1457 #[command(hide = true)]
1461 PlaywrightMcp {
1462 #[arg(long, value_name = "PROFILE")]
1464 profile: String,
1465 #[arg(long, value_name = "URL")]
1467 url: Option<String>,
1468 #[arg(last = true, required = true)]
1470 command: Vec<std::path::PathBuf>,
1471 },
1472 #[command(hide = true)]
1478 McpSessionBroker {
1479 #[arg(long, value_name = "PROFILE")]
1481 profile: String,
1482 #[arg(long, value_name = "URL")]
1484 url: Option<String>,
1485 },
1486 Run {
1488 #[arg(long, value_name = "PROFILE")]
1490 profile: String,
1491 #[arg(last = true, required = true)]
1493 command: Vec<std::path::PathBuf>,
1494 },
1495}
1496
1497#[cfg(feature = "agent")]
1499#[derive(Subcommand, Debug, Clone)]
1500pub enum McpAdapter {
1501 Playwright {
1503 #[arg(long, value_name = "SPEC")]
1505 package: Option<String>,
1506 #[arg(long, value_name = "PATH")]
1508 npx: Option<std::path::PathBuf>,
1509 #[arg(long, value_name = "URL")]
1511 url: Option<String>,
1512 #[arg(long, value_enum, value_name = "CLIENT")]
1514 print_config: Option<McpConfigTarget>,
1515 #[arg(last = true)]
1517 extra: Vec<String>,
1518 },
1519 ChromeDevtools {
1525 #[arg(long, value_name = "SPEC")]
1527 package: Option<String>,
1528 #[arg(long, value_name = "PATH")]
1530 npx: Option<std::path::PathBuf>,
1531 #[arg(long, value_name = "URL")]
1533 url: Option<String>,
1534 #[arg(long, value_enum, value_name = "CLIENT")]
1536 print_config: Option<McpConfigTarget>,
1537 #[arg(last = true)]
1539 extra: Vec<String>,
1540 },
1541 Install {
1555 #[arg(long, value_enum, value_name = "CLIENT")]
1557 client: McpInstallClient,
1558 #[arg(long, conflicts_with = "project")]
1560 user: bool,
1561 #[arg(long, value_name = "DIR", conflicts_with = "user")]
1563 project: Option<std::path::PathBuf>,
1564 #[arg(long)]
1567 yes: bool,
1568 #[arg(long)]
1570 skill: bool,
1571 #[arg(long, value_name = "ABS")]
1574 passless_path: Option<std::path::PathBuf>,
1575 },
1576}
1577
1578#[cfg(feature = "agent")]
1580#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1581pub enum McpAdapterKind {
1582 Playwright,
1583 ChromeDevtools,
1584}
1585
1586#[cfg(feature = "agent")]
1588#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1589pub enum McpInstallClient {
1590 Opencode,
1592 ClaudeCode,
1594}
1595
1596#[cfg(feature = "agent")]
1598#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1599pub enum McpConfigTarget {
1600 ClaudeCode,
1602 Opencode,
1604 Cursor,
1606 Vscode,
1608}
1609
1610#[cfg(feature = "agent")]
1612#[derive(Subcommand, Debug, Clone)]
1613pub enum AgentCredentialAction {
1614 List,
1616 Show {
1618 #[arg(value_name = "CREDENTIAL_REF")]
1620 credential_ref: String,
1621 },
1622}
1623
1624#[cfg(test)]
1625mod tests {
1626 use super::*;
1627
1628 #[cfg(feature = "agent")]
1629 #[test]
1630 fn test_agent_admin_install_defaults() {
1631 let args = Args::try_parse_from(["passless", "agent-admin", "install"]).unwrap();
1632 assert!(matches!(
1633 args.command,
1634 Some(Commands::AgentAdmin {
1635 action: AgentAdminAction::Install {
1636 target: AgentSkillTarget::Auto,
1637 scope: AgentSkillScope::User,
1638 force: false,
1639 },
1640 ..
1641 })
1642 ));
1643 }
1644
1645 #[cfg(feature = "agent")]
1646 #[test]
1647 fn test_agent_admin_install_explicit_options() {
1648 let args = Args::try_parse_from([
1649 "passless",
1650 "agent-admin",
1651 "install",
1652 "claude",
1653 "--scope",
1654 "project",
1655 "--force",
1656 ])
1657 .unwrap();
1658 assert!(matches!(
1659 args.command,
1660 Some(Commands::AgentAdmin {
1661 action: AgentAdminAction::Install {
1662 target: AgentSkillTarget::Claude,
1663 scope: AgentSkillScope::Project,
1664 force: true,
1665 },
1666 ..
1667 })
1668 ));
1669 }
1670
1671 #[test]
1672 fn test_pin_config_default_max_uv_retries() {
1673 let config = PinConfig {
1674 enforcement: PinEnforcement::Optional,
1675 min_length: 4,
1676 max_retries: 8,
1677 max_uv_retries: 8,
1678 auto_lock_timeout: 0,
1679 };
1680 assert_eq!(config.max_uv_retries, 8);
1681 }
1682
1683 #[test]
1684 fn test_pin_config_validate_success() {
1685 let config = PinConfig {
1686 enforcement: PinEnforcement::Optional,
1687 min_length: 4,
1688 max_retries: 8,
1689 max_uv_retries: 8,
1690 auto_lock_timeout: 0,
1691 };
1692 assert!(config.validate().is_ok());
1693 }
1694
1695 #[test]
1696 fn test_pin_config_validate_zero_max_uv_retries() {
1697 let config = PinConfig {
1698 enforcement: PinEnforcement::Optional,
1699 min_length: 4,
1700 max_retries: 8,
1701 max_uv_retries: 0,
1702 auto_lock_timeout: 0,
1703 };
1704 let result = config.validate();
1705 assert!(result.is_err());
1706 assert!(result.unwrap_err().to_string().contains("max_uv_retries"));
1707 }
1708
1709 #[test]
1710 fn test_pin_config_validate_zero_max_retries() {
1711 let config = PinConfig {
1712 enforcement: PinEnforcement::Optional,
1713 min_length: 4,
1714 max_retries: 0,
1715 max_uv_retries: 8,
1716 auto_lock_timeout: 0,
1717 };
1718 let result = config.validate();
1719 assert!(result.is_err());
1720 assert!(result.unwrap_err().to_string().contains("max_retries"));
1721 }
1722
1723 #[test]
1724 fn test_pin_config_validate_invalid_min_length() {
1725 let config = PinConfig {
1726 enforcement: PinEnforcement::Optional,
1727 min_length: 3,
1728 max_retries: 8,
1729 max_uv_retries: 8,
1730 auto_lock_timeout: 0,
1731 };
1732 let result = config.validate();
1733 assert!(result.is_err());
1734 assert!(result.unwrap_err().to_string().contains("min_length"));
1735 }
1736
1737 #[test]
1738 fn test_canonicalize_path_existing() {
1739 let dir = std::env::temp_dir();
1740 let canonical = BackendConfig::canonicalize_path(&dir);
1741 assert!(canonical.is_absolute());
1742 assert!(canonical.exists());
1743 }
1744
1745 #[test]
1746 fn test_canonicalize_path_nonexistent() {
1747 let base = std::env::temp_dir();
1748 let nonexistent = base.join("passless_test_nonexistent_dir_12345/sub");
1749 let canonical = BackendConfig::canonicalize_path(&nonexistent);
1750 assert!(canonical.is_absolute());
1751 assert!(canonical.starts_with(BackendConfig::canonicalize_path(&base)));
1752 }
1753
1754 #[test]
1755 fn test_canonicalize_path_symlink() {
1756 let dir = tempfile::tempdir().unwrap();
1757 let real = dir.path().join("real");
1758 std::fs::create_dir(&real).unwrap();
1759 let link = dir.path().join("link");
1760 std::os::unix::fs::symlink(&real, &link).unwrap();
1761
1762 let canonical_real = BackendConfig::canonicalize_path(&real);
1763 let canonical_link = BackendConfig::canonicalize_path(&link);
1764 assert_eq!(canonical_real, canonical_link);
1765 }
1766
1767 #[test]
1768 fn test_local_state_path_relative_and_absolute() {
1769 let dir = tempfile::tempdir_in(".").unwrap();
1770 let abs_path = std::fs::canonicalize(dir.path()).unwrap();
1771 let rel_path = dir.path().to_path_buf();
1772
1773 let backend_abs = BackendConfig::Local {
1774 path: abs_path.display().to_string(),
1775 };
1776 let backend_rel = BackendConfig::Local {
1777 path: rel_path.display().to_string(),
1778 };
1779 assert_eq!(backend_abs.state_path(), backend_rel.state_path());
1780 }
1781
1782 #[test]
1783 fn test_pass_state_path_different_subpaths() {
1784 let store = "/tmp/passless_test_store";
1785 let backend_a = BackendConfig::Pass {
1786 store_path: store.to_string(),
1787 path: "fido2".to_string(),
1788 gpg_backend: "gnupg-bin".to_string(),
1789 };
1790 let backend_b = BackendConfig::Pass {
1791 store_path: store.to_string(),
1792 path: "fido2-other".to_string(),
1793 gpg_backend: "gnupg-bin".to_string(),
1794 };
1795 assert_ne!(backend_a.state_path(), backend_b.state_path());
1796 }
1797
1798 #[test]
1799 fn test_different_local_paths_produce_different_identities() {
1800 let backend_a = BackendConfig::Local {
1801 path: "/tmp/passless_a".to_string(),
1802 };
1803 let backend_b = BackendConfig::Local {
1804 path: "/tmp/passless_b".to_string(),
1805 };
1806 assert_ne!(backend_a.state_path(), backend_b.state_path());
1807 }
1808
1809 #[cfg(feature = "agent")]
1810 #[test]
1811 fn test_agent_admin_profile_list() {
1812 let args = Args::try_parse_from(["passless", "agent-admin", "profile", "list"]).unwrap();
1813 assert!(matches!(
1814 args.command,
1815 Some(Commands::AgentAdmin {
1816 action: AgentAdminAction::Profile {
1817 action: AdminProfileAction::List,
1818 },
1819 ..
1820 })
1821 ));
1822 }
1823
1824 #[cfg(feature = "agent")]
1825 #[test]
1826 fn test_agent_admin_credential_delete_without_confirm() {
1827 let args = Args::try_parse_from([
1828 "passless",
1829 "agent-admin",
1830 "credential",
1831 "delete",
1832 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
1833 ])
1834 .unwrap();
1835 assert!(matches!(
1836 args.command,
1837 Some(Commands::AgentAdmin {
1838 action: AgentAdminAction::Credential {
1839 action: AdminCredentialAction::Delete { confirm: false, .. },
1840 },
1841 ..
1842 })
1843 ));
1844 }
1845
1846 #[cfg(feature = "agent")]
1847 #[test]
1848 fn test_agent_admin_credential_delete_with_confirm() {
1849 let args = Args::try_parse_from([
1850 "passless",
1851 "agent-admin",
1852 "credential",
1853 "delete",
1854 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
1855 "--confirm",
1856 ])
1857 .unwrap();
1858 assert!(matches!(
1859 args.command,
1860 Some(Commands::AgentAdmin {
1861 action: AgentAdminAction::Credential {
1862 action: AdminCredentialAction::Delete { confirm: true, .. },
1863 },
1864 ..
1865 })
1866 ));
1867 }
1868
1869 #[cfg(feature = "agent")]
1870 #[test]
1871 fn test_agent_admin_shutdown_hidden() {
1872 let args =
1873 Args::try_parse_from(["passless", "agent-admin", "shutdown", "--confirm"]).unwrap();
1874 assert!(matches!(
1875 args.command,
1876 Some(Commands::AgentAdmin {
1877 action: AgentAdminAction::Shutdown { confirm: true },
1878 ..
1879 })
1880 ));
1881 }
1882
1883 #[cfg(feature = "agent")]
1884 #[test]
1885 fn test_agent_admin_output_default_json() {
1886 let args = Args::try_parse_from(["passless", "agent-admin", "profile", "list"]).unwrap();
1887 match args.command {
1888 Some(Commands::AgentAdmin { output, .. }) => {
1889 assert_eq!(output, OutputFormat::Json);
1890 }
1891 _ => panic!("expected AgentAdmin command"),
1892 }
1893 }
1894
1895 #[cfg(feature = "agent")]
1896 #[test]
1897 fn test_agent_admin_output_plain() {
1898 let args = Args::try_parse_from([
1899 "passless",
1900 "agent-admin",
1901 "--output",
1902 "plain",
1903 "profile",
1904 "list",
1905 ])
1906 .unwrap();
1907 match args.command {
1908 Some(Commands::AgentAdmin { output, .. }) => {
1909 assert_eq!(output, OutputFormat::Plain);
1910 }
1911 _ => panic!("expected AgentAdmin command"),
1912 }
1913 }
1914
1915 #[cfg(feature = "agent")]
1916 #[test]
1917 fn test_agent_doctor_parses() {
1918 let args = Args::try_parse_from(["passless", "agent", "doctor"]).unwrap();
1919 assert!(matches!(
1920 args.command,
1921 Some(Commands::Agent {
1922 action: AgentCommand::Doctor,
1923 ..
1924 })
1925 ));
1926 }
1927
1928 #[cfg(feature = "agent")]
1929 #[test]
1930 fn test_agent_browser_parses() {
1931 let args = Args::try_parse_from([
1932 "passless",
1933 "agent",
1934 "--profile",
1935 "p",
1936 "browser",
1937 "--json",
1938 "--wait",
1939 "--headed",
1940 ])
1941 .unwrap();
1942 let Some(Commands::Agent {
1943 profile,
1944 action:
1945 AgentCommand::Browser {
1946 json,
1947 env,
1948 wait,
1949 headed,
1950 url,
1951 },
1952 ..
1953 }) = args.command
1954 else {
1955 panic!("not agent browser");
1956 };
1957 assert_eq!(profile.as_deref(), Some("p"));
1958 assert!(json && wait && headed && !env && url.is_none());
1959 let args =
1961 Args::try_parse_from(["passless", "agent", "browser", "--env", "--profile", "p"])
1962 .unwrap();
1963 assert!(matches!(
1964 args.command,
1965 Some(Commands::Agent {
1966 action: AgentCommand::Browser { env: true, .. },
1967 ..
1968 })
1969 ));
1970 assert!(Args::try_parse_from(["passless", "agent", "browser", "--json", "--env"]).is_err());
1971 }
1972
1973 #[cfg(feature = "agent")]
1974 #[test]
1975 fn test_agent_mcp_parses() {
1976 let args = Args::try_parse_from([
1977 "passless",
1978 "agent",
1979 "mcp",
1980 "playwright",
1981 "--profile",
1982 "p",
1983 "--",
1984 "--isolated",
1985 ])
1986 .unwrap();
1987 let Some(Commands::Agent {
1988 action:
1989 AgentCommand::Mcp {
1990 adapter: Some(McpAdapter::Playwright { extra, .. }),
1991 print_config: None,
1992 ..
1993 },
1994 profile,
1995 ..
1996 }) = args.command
1997 else {
1998 panic!("not agent mcp playwright");
1999 };
2000 assert_eq!(profile.as_deref(), Some("p"));
2001 assert_eq!(extra, ["--isolated"]);
2002
2003 let args = Args::try_parse_from(["passless", "agent", "mcp", "chrome-devtools"]).unwrap();
2004 assert!(matches!(
2005 args.command,
2006 Some(Commands::Agent {
2007 action: AgentCommand::Mcp {
2008 adapter: Some(McpAdapter::ChromeDevtools { .. }),
2009 ..
2010 },
2011 ..
2012 })
2013 ));
2014
2015 for (name, target) in [
2016 ("claude-code", McpConfigTarget::ClaudeCode),
2017 ("opencode", McpConfigTarget::Opencode),
2018 ("cursor", McpConfigTarget::Cursor),
2019 ("vscode", McpConfigTarget::Vscode),
2020 ] {
2021 let args = Args::try_parse_from([
2022 "passless",
2023 "agent",
2024 "--profile",
2025 "p",
2026 "mcp",
2027 "--print-config",
2028 name,
2029 ])
2030 .unwrap();
2031 assert!(matches!(
2032 args.command,
2033 Some(Commands::Agent {
2034 action: AgentCommand::Mcp { print_config: Some(t), adapter: None, .. },
2035 ..
2036 }) if t == target
2037 ));
2038 }
2039 assert!(
2040 Args::try_parse_from(["passless", "agent", "mcp", "--print-config", "emacs"]).is_err()
2041 );
2042 let args = Args::try_parse_from([
2044 "passless",
2045 "agent",
2046 "mcp",
2047 "playwright",
2048 "--profile",
2049 "coding",
2050 "--print-config",
2051 "claude-code",
2052 ])
2053 .unwrap();
2054 assert!(matches!(
2055 args.command,
2056 Some(Commands::Agent {
2057 profile: Some(ref profile),
2058 action: AgentCommand::Mcp {
2059 print_config: None,
2060 adapter: Some(McpAdapter::Playwright {
2061 print_config: Some(McpConfigTarget::ClaudeCode),
2062 ..
2063 }),
2064 ..
2065 },
2066 ..
2067 }) if profile == "coding"
2068 ));
2069 assert!(
2070 Args::try_parse_from([
2071 "passless",
2072 "agent",
2073 "mcp",
2074 "chrome-devtools",
2075 "--print-config",
2076 "opencode",
2077 ])
2078 .is_ok()
2079 );
2080 assert!(
2082 Args::try_parse_from([
2083 "passless",
2084 "agent",
2085 "playwright-mcp",
2086 "--profile",
2087 "p",
2088 "--",
2089 "/usr/bin/npx",
2090 "x",
2091 ])
2092 .is_ok()
2093 );
2094 }
2095
2096 #[cfg(feature = "agent")]
2097 #[test]
2098 fn test_agent_mcp_install_parses() {
2099 let parse = |extra: &[&str]| {
2100 let mut argv = vec!["passless", "agent", "mcp", "install"];
2101 argv.extend_from_slice(extra);
2102 Args::try_parse_from(argv)
2103 };
2104 assert!(parse(&[]).is_err());
2106 assert!(parse(&["--client", "emacs"]).is_err());
2107 let args = parse(&["--client", "opencode"]).unwrap();
2108 assert!(matches!(
2109 args.command,
2110 Some(Commands::Agent {
2111 profile: None,
2112 action: AgentCommand::Mcp {
2113 adapter: Some(McpAdapter::Install {
2114 client: McpInstallClient::Opencode,
2115 user: false,
2116 project: None,
2117 yes: false,
2118 skill: false,
2119 passless_path: None,
2120 }),
2121 ..
2122 },
2123 ..
2124 })
2125 ));
2126 let args = parse(&[
2127 "--client",
2128 "claude-code",
2129 "--project",
2130 "/work/p",
2131 "--profile",
2132 "agent",
2133 "--yes",
2134 "--skill",
2135 ])
2136 .unwrap();
2137 match args.command {
2138 Some(Commands::Agent {
2139 profile,
2140 action:
2141 AgentCommand::Mcp {
2142 adapter:
2143 Some(McpAdapter::Install {
2144 client,
2145 project,
2146 yes,
2147 skill,
2148 ..
2149 }),
2150 ..
2151 },
2152 ..
2153 }) => {
2154 assert_eq!(profile.as_deref(), Some("agent"));
2155 assert_eq!(client, McpInstallClient::ClaudeCode);
2156 assert_eq!(project, Some(std::path::PathBuf::from("/work/p")));
2157 assert!(yes && skill);
2158 }
2159 other => panic!("unexpected: {other:?}"),
2160 }
2161 assert!(parse(&["--client", "opencode", "--user", "--project", "/p"]).is_err());
2163 assert!(parse(&["--client", "opencode", "--user"]).is_ok());
2164 let args = parse(&[
2165 "--client",
2166 "opencode",
2167 "--passless-path",
2168 "/usr/bin/passless",
2169 ])
2170 .unwrap();
2171 assert!(matches!(
2172 args.command,
2173 Some(Commands::Agent {
2174 action: AgentCommand::Mcp {
2175 adapter: Some(McpAdapter::Install { passless_path: Some(ref p), .. }),
2176 ..
2177 },
2178 ..
2179 }) if p == std::path::Path::new("/usr/bin/passless")
2180 ));
2181 }
2182
2183 #[cfg(feature = "agent")]
2184 #[test]
2185 fn test_doctor_agents_parses() {
2186 let args = Args::try_parse_from(["passless", "doctor", "--agents", "-o", "json"]).unwrap();
2187 assert!(matches!(
2188 args.command,
2189 Some(Commands::Doctor {
2190 agents: true,
2191 output: OutputFormat::Json
2192 })
2193 ));
2194 }
2195
2196 #[cfg(feature = "agent")]
2197 #[test]
2198 fn test_agent_run_with_command() {
2199 let args = Args::try_parse_from([
2200 "passless",
2201 "agent",
2202 "run",
2203 "--profile",
2204 "myprofile",
2205 "--",
2206 "/usr/bin/test",
2207 "arg1",
2208 ])
2209 .unwrap();
2210 match args.command {
2211 Some(Commands::Agent {
2212 action: AgentCommand::Run { profile, command },
2213 ..
2214 }) => {
2215 assert_eq!(profile, "myprofile");
2216 assert_eq!(command.len(), 2);
2217 }
2218 _ => panic!("expected Agent Run command"),
2219 }
2220 }
2221
2222 #[cfg(feature = "agent")]
2223 #[test]
2224 fn test_agent_admin_grants_parse() {
2225 let args = Args::try_parse_from([
2226 "passless",
2227 "agent-admin",
2228 "grants",
2229 "revoke",
2230 "--profile",
2231 "coding",
2232 "--rp",
2233 "example.com",
2234 "--confirm",
2235 ])
2236 .unwrap();
2237 assert!(matches!(
2238 args.command,
2239 Some(Commands::AgentAdmin {
2240 action: AgentAdminAction::Grants {
2241 action: AdminGrantsAction::Revoke {
2242 ref profile,
2243 ref rp_id,
2244 action: AdminGrantAction::Authenticate,
2245 confirm: true,
2246 },
2247 },
2248 ..
2249 }) if profile == "coding" && rp_id == "example.com"
2250 ));
2251 let args = Args::try_parse_from([
2252 "passless",
2253 "agent-admin",
2254 "grants",
2255 "clear",
2256 "--profile",
2257 "p",
2258 ])
2259 .unwrap();
2260 assert!(matches!(
2261 args.command,
2262 Some(Commands::AgentAdmin {
2263 action: AgentAdminAction::Grants {
2264 action: AdminGrantsAction::Clear { confirm: false, .. },
2265 },
2266 ..
2267 })
2268 ));
2269 assert!(Args::try_parse_from(["passless", "agent-admin", "grants", "list"]).is_ok());
2270 }
2271
2272 #[cfg(feature = "agent")]
2273 #[test]
2274 fn test_agent_admin_renamed_session_commands_keep_hidden_aliases() {
2275 for (spelling, expect_sessions) in [
2276 ("sessions", true),
2277 ("delegation", true),
2278 ("principals", false),
2279 ("session", false),
2280 ] {
2281 let args = Args::try_parse_from(["passless", "agent-admin", spelling, "list"]).unwrap();
2282 let is_sessions = matches!(
2283 args.command,
2284 Some(Commands::AgentAdmin {
2285 action: AgentAdminAction::Sessions { .. },
2286 ..
2287 })
2288 );
2289 let is_principals = matches!(
2290 args.command,
2291 Some(Commands::AgentAdmin {
2292 action: AgentAdminAction::Principals { .. },
2293 ..
2294 })
2295 );
2296 assert_eq!(is_sessions, expect_sessions, "{spelling}");
2297 assert_eq!(is_principals, !expect_sessions, "{spelling}");
2298 }
2299 assert!(Args::try_parse_from(["passless", "agent", "intent", "show", "x"]).is_err());
2300 }
2301
2302 #[cfg(feature = "agent")]
2303 #[test]
2304 fn test_agent_output_default_json() {
2305 let args = Args::try_parse_from(["passless", "agent", "doctor"]).unwrap();
2306 match args.command {
2307 Some(Commands::Agent { output, .. }) => {
2308 assert_eq!(output, OutputFormat::Json);
2309 }
2310 _ => panic!("expected Agent command"),
2311 }
2312 }
2313
2314 #[cfg(feature = "agent")]
2315 #[test]
2316 fn test_shell_completions_contain_agent_commands() {
2317 use clap::CommandFactory;
2318
2319 let cmd = Args::command();
2320 let mut buf = Vec::new();
2321 clap_complete::generate(
2322 clap_complete::Shell::Bash,
2323 &mut cmd.clone(),
2324 "passless",
2325 &mut buf,
2326 );
2327 let completion = String::from_utf8(buf).unwrap();
2328
2329 for expected in [
2330 "agent-admin",
2331 "agent",
2332 "install",
2333 "browser-control",
2334 "grants",
2335 "sessions",
2336 "principals",
2337 "doctor",
2338 "capabilities",
2339 "instructions",
2340 ] {
2341 assert!(
2342 completion.contains(expected),
2343 "bash completion missing '{}'",
2344 expected
2345 );
2346 }
2347 }
2348
2349 #[cfg(feature = "agent")]
2350 #[test]
2351 fn test_shell_completions_zsh_contain_agent_commands() {
2352 use clap::CommandFactory;
2353
2354 let cmd = Args::command();
2355 let mut buf = Vec::new();
2356 clap_complete::generate(
2357 clap_complete::Shell::Zsh,
2358 &mut cmd.clone(),
2359 "passless",
2360 &mut buf,
2361 );
2362 let completion = String::from_utf8(buf).unwrap();
2363
2364 for expected in ["agent-admin", "agent", "install", "browser-control"] {
2365 assert!(
2366 completion.contains(expected),
2367 "zsh completion missing '{}'",
2368 expected
2369 );
2370 }
2371 }
2372
2373 #[cfg(feature = "agent")]
2374 #[test]
2375 fn test_config_print_includes_agent_fields() {
2376 let mut default_args = Args::parse_from(["passless"]);
2377 let config = AppConfig::from(&mut default_args.config);
2378 let toml_output = config.to_toml_with_comments();
2379
2380 assert!(
2381 toml_output.contains("backend_type"),
2382 "config print missing backend_type"
2383 );
2384 assert!(
2385 toml_output.contains("[security]"),
2386 "config print missing [security] section"
2387 );
2388 assert!(
2389 toml_output.contains("[pin]"),
2390 "config print missing [pin] section"
2391 );
2392 assert!(
2393 toml_output.contains("always_uv"),
2394 "config print missing always_uv"
2395 );
2396 assert!(
2397 toml_output.contains("notification_timeout"),
2398 "config print missing notification_timeout"
2399 );
2400 }
2401
2402 #[test]
2403 fn test_config_print_contains_passless_header() {
2404 let mut default_args = Args::parse_from(["passless"]);
2405 let config = AppConfig::from(&mut default_args.config);
2406 let toml_output = config.to_toml_with_comments();
2407
2408 assert!(toml_output.contains("Passless Configuration File"));
2409 assert!(toml_output.contains("~/.config/passless/config.toml"));
2410 }
2411
2412 #[test]
2413 fn test_config_print_contains_local_backend_section() {
2414 let mut default_args = Args::parse_from(["passless"]);
2415 let config = AppConfig::from(&mut default_args.config);
2416 let toml_output = config.to_toml_with_comments();
2417
2418 assert!(toml_output.contains("[local]"));
2419 assert!(toml_output.contains("path"));
2420 }
2421
2422 #[test]
2423 fn test_config_print_contains_pass_backend_section() {
2424 let mut default_args = Args::parse_from(["passless"]);
2425 let config = AppConfig::from(&mut default_args.config);
2426 let toml_output = config.to_toml_with_comments();
2427
2428 assert!(toml_output.contains("[pass]"));
2429 assert!(toml_output.contains("store_path"));
2430 assert!(toml_output.contains("gpg_backend"));
2431 }
2432
2433 #[test]
2434 fn test_config_print_produces_valid_toml_without_none_literals() {
2435 let mut default_args = Args::parse_from(["passless"]);
2436 let config = AppConfig::from(&mut default_args.config);
2437 let toml_output = config.to_toml_with_comments();
2438
2439 for (line_no, line) in toml_output.lines().enumerate() {
2440 let trimmed = line.trim();
2441 if trimmed.starts_with('#') || trimmed.is_empty() {
2442 continue;
2443 }
2444 assert!(
2445 !trimmed.contains("= None"),
2446 "Line {} contains invalid TOML 'None' literal: {}",
2447 line_no + 1,
2448 line
2449 );
2450 }
2451
2452 let parse_result: Result<toml::Table, _> = toml_output.parse();
2453 assert!(
2454 parse_result.is_ok(),
2455 "Generated TOML is not valid: {:?}",
2456 parse_result.err()
2457 );
2458 }
2459
2460 #[cfg(feature = "agent")]
2461 #[test]
2462 fn test_config_print_comments_out_none_option_fields() {
2463 let mut default_args = Args::parse_from(["passless"]);
2464 let config = AppConfig::from(&mut default_args.config);
2465 let toml_output = config.to_toml_with_comments();
2466
2467 assert!(
2468 toml_output.contains("# audit_path = <not set>"),
2469 "Option::None field 'audit_path' should be commented out, got:\n{}",
2470 toml_output
2471 );
2472 }
2473}