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
109pub fn tpm_path() -> String {
111 dirs::data_dir()
112 .expect("Could not determine data directory: $XDG_DATA_HOME or $HOME/.local/share")
113 .join("passless/tpm")
114 .to_string_lossy()
115 .into_owned()
116}
117
118#[cfg(feature = "tpm")]
120#[derive(ClapSerde, Debug, Clone, Serialize, Deserialize, ConfigDoc)]
121#[group(id = "tpm-backend-config")]
122pub struct TpmBackendConfig {
123 #[arg(
125 long = "tpm-path",
126 env = "PASSLESS_TPM_PATH",
127 id = "tpm-path",
128 value_name = "PATH"
129 )]
130 #[serde(default)]
131 #[default(tpm_path())]
132 pub path: String,
133
134 #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI", value_name = "TCTI")]
136 #[serde(default)]
137 #[default("device:/dev/tpmrm0".to_string())]
138 pub tcti: String,
139
140 #[arg(long = "tpm-portable", env = "PASSLESS_TPM_PORTABLE")]
142 #[serde(default)]
143 #[default(false)]
144 pub portable: bool,
145}
146
147#[derive(ClapSerde, Debug, Clone, Serialize, Deserialize, ConfigDoc)]
149#[group(id = "security")]
150pub struct SecurityConfig {
151 #[arg(long = "check-mlock", env = "PASSLESS_CHECK_MLOCK")]
153 #[serde(default)]
154 #[default(true)]
155 pub check_mlock: bool,
156
157 #[arg(long = "disable-core-dumps", env = "PASSLESS_DISABLE_CORE_DUMPS")]
159 #[serde(default)]
160 #[default(true)]
161 pub disable_core_dumps: bool,
162
163 #[arg(
165 long = "constant-signature-counter",
166 env = "PASSLESS_CONSTANT_SIGNATURE_COUNTER",
167 action = ArgAction::Set,
168 require_equals = true,
169 num_args = 0..=1,
170 default_missing_value = "true"
171 )]
172 #[serde(default)]
173 pub constant_signature_counter: bool,
174
175 #[arg(
188 long = "enable-credential-backup",
189 env = "PASSLESS_ENABLE_CREDENTIAL_BACKUP",
190 action = ArgAction::Set,
191 require_equals = true,
192 num_args = 0..=1,
193 default_missing_value = "true"
194 )]
195 #[serde(default)]
196 pub enable_credential_backup: bool,
197
198 #[arg(
204 long = "always-uv",
205 env = "PASSLESS_ALWAYS_UV",
206 action = ArgAction::Set,
207 require_equals = true,
208 num_args = 0..=1,
209 default_value = "true",
210 default_missing_value = "true"
211 )]
212 #[serde(default)]
213 #[default(true)]
214 pub always_uv: bool,
215
216 #[arg(
218 long = "user-verification-registration",
219 env = "PASSLESS_USER_VERIFICATION_REGISTRATION"
220 )]
221 #[serde(default)]
222 #[default(true)]
223 pub user_verification_registration: bool,
224
225 #[arg(
227 long = "user-verification-authentication",
228 env = "PASSLESS_USER_VERIFICATION_AUTHENTICATION"
229 )]
230 #[serde(default)]
231 #[default(true)]
232 pub user_verification_authentication: bool,
233
234 #[arg(
236 long = "notification-timeout",
237 env = "PASSLESS_NOTIFICATION_TIMEOUT",
238 value_name = "SECONDS"
239 )]
240 #[serde(default)]
241 #[default(30)]
242 pub notification_timeout: u32,
243}
244
245#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
247#[serde(rename_all = "lowercase")]
248pub enum PinEnforcement {
249 Never,
251 #[default]
253 Optional,
254 Required,
256}
257
258impl std::str::FromStr for PinEnforcement {
259 type Err = String;
260
261 fn from_str(s: &str) -> Result<Self, Self::Err> {
262 match s.to_lowercase().as_str() {
263 "never" => Ok(PinEnforcement::Never),
264 "optional" => Ok(PinEnforcement::Optional),
265 "required" => Ok(PinEnforcement::Required),
266 _ => Err(format!(
267 "Invalid PIN enforcement '{}'. Must be: never, optional, or required",
268 s
269 )),
270 }
271 }
272}
273
274impl std::fmt::Display for PinEnforcement {
275 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
276 match self {
277 PinEnforcement::Never => write!(f, "never"),
278 PinEnforcement::Optional => write!(f, "optional"),
279 PinEnforcement::Required => write!(f, "required"),
280 }
281 }
282}
283
284#[derive(ClapSerde, Debug, Clone, Serialize, Deserialize, ConfigDoc)]
286#[group(id = "pin")]
287pub struct PinConfig {
288 #[arg(
293 long = "pin-enforcement",
294 env = "PASSLESS_PIN_ENFORCEMENT",
295 value_name = "POLICY"
296 )]
297 #[serde(default)]
298 #[default(PinEnforcement::Optional)]
299 pub enforcement: PinEnforcement,
300
301 #[arg(
303 long = "pin-min-length",
304 env = "PASSLESS_PIN_MIN_LENGTH",
305 value_name = "LENGTH"
306 )]
307 #[serde(default)]
308 #[default(4)]
309 pub min_length: u8,
310
311 #[arg(
313 long = "pin-max-retries",
314 env = "PASSLESS_PIN_MAX_RETRIES",
315 value_name = "RETRIES"
316 )]
317 #[serde(default)]
318 #[default(8)]
319 pub max_retries: u8,
320
321 #[arg(
327 long = "pin-max-uv-retries",
328 env = "PASSLESS_PIN_MAX_UV_RETRIES",
329 value_name = "RETRIES"
330 )]
331 #[serde(default)]
332 #[default(8)]
333 pub max_uv_retries: u8,
334
335 #[arg(
338 long = "pin-auto-lock-timeout",
339 env = "PASSLESS_PIN_AUTO_LOCK_TIMEOUT",
340 value_name = "SECONDS"
341 )]
342 #[serde(default)]
343 #[default(0)]
344 pub auto_lock_timeout: u32,
345}
346
347impl PinConfig {
348 pub fn validate(&self) -> crate::error::Result<()> {
350 if self.min_length < 4 || self.min_length > 63 {
351 return Err(crate::error::Error::Config(format!(
352 "pin.min_length must be between 4 and 63, got {}",
353 self.min_length
354 )));
355 }
356 if self.max_retries == 0 {
357 return Err(crate::error::Error::Config(
358 "pin.max_retries must be greater than 0".to_string(),
359 ));
360 }
361 if self.max_uv_retries == 0 {
362 return Err(crate::error::Error::Config(
363 "pin.max_uv_retries must be greater than 0".to_string(),
364 ));
365 }
366 Ok(())
367 }
368}
369
370impl SecurityConfig {
371 pub fn apply_hardening(&self) -> Result<(), Box<dyn std::error::Error>> {
373 if self.disable_core_dumps {
374 self.disable_core_dumps_impl()?;
375 }
376 if self.check_mlock {
377 self.probe_mlock_capability()?;
378 }
379 Ok(())
380 }
381
382 fn disable_core_dumps_impl(&self) -> Result<(), Box<dyn std::error::Error>> {
384 debug!("Disabling core dumps to prevent credential leakage");
385 setrlimit(Resource::RLIMIT_CORE, 0, 0)?;
386 let r = unsafe { prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) };
387 if r != 0 {
388 log::warn!("prctl(PR_SET_DUMPABLE) failed: {}", r);
389 }
390 Ok(())
391 }
392
393 fn probe_mlock_capability(&self) -> Result<(), Box<dyn std::error::Error>> {
395 debug!("Check mlock capability");
396
397 let test_size = 4096;
398 let test_buffer = vec![0u8; test_size];
399 let ptr = test_buffer.as_ptr() as *const libc::c_void;
400
401 let lock_result = unsafe { mlock(ptr, test_size) };
402
403 if lock_result == 0 {
404 unsafe { munlock(ptr, test_size) };
405 log::debug!("MLOCK is enabled - sensitive data will not be swapped to disk");
406 } else {
407 log::warn!(
408 "mlock capability probe failed - memory locking may not be available.\n\
409 Hint: grant CAP_IPC_LOCK to the binary with: 'sudo setcap cap_ipc_lock=+ep $(which passless)'"
410 );
411 }
412 Ok(())
413 }
414}
415
416#[derive(ClapSerde, Serialize, Deserialize, Debug, ConfigDoc)]
419pub struct AppConfig {
420 #[arg(short = 't', long = "backend-type", env = "PASSLESS_BACKEND_TYPE")]
422 #[serde(default)]
423 #[default("pass".to_string())]
424 pub backend_type: String,
425
426 #[arg(
429 short,
430 long,
431 env = "PASSLESS_VERBOSE",
432 action = ArgAction::Set,
433 require_equals = true,
434 num_args = 0..=1,
435 default_missing_value = "true"
436 )]
437 #[default(true)]
438 #[serde(default)]
439 pub verbose: bool,
440
441 #[clap_serde]
443 #[serde(default)]
444 #[command(flatten)]
445 pub pass: PassBackendConfig,
446
447 #[cfg(feature = "tpm")]
449 #[clap_serde]
450 #[serde(default)]
451 #[command(flatten)]
452 pub tpm: TpmBackendConfig,
453
454 #[clap_serde]
456 #[serde(default)]
457 #[command(flatten)]
458 pub local: LocalBackendConfig,
459
460 #[clap_serde]
462 #[serde(default)]
463 #[command(flatten)]
464 pub security: SecurityConfig,
465
466 #[clap_serde]
468 #[serde(default)]
469 #[command(flatten)]
470 pub pin: PinConfig,
471
472 #[cfg(feature = "agent")]
474 #[arg(skip)]
475 pub agents: AgentConfig,
476}
477
478#[derive(Debug, Clone)]
480pub enum BackendConfig {
481 Local {
482 path: String,
483 },
484 Pass {
485 store_path: String,
486 path: String,
487 gpg_backend: String,
488 },
489 #[cfg(feature = "tpm")]
490 Tpm {
491 path: String,
492 tcti: String,
493 portable: bool,
494 },
495}
496
497impl BackendConfig {
498 pub fn canonicalize_path(path: &Path) -> PathBuf {
503 match fs::canonicalize(path) {
504 Ok(p) => p,
505 Err(_) => {
506 let mut current = path.to_path_buf();
507 let mut suffix = Vec::new();
508 loop {
509 match fs::canonicalize(¤t) {
510 Ok(base) => {
511 let mut result = base;
512 for component in suffix.iter().rev() {
513 result.push(component);
514 }
515 return result;
516 }
517 Err(_) => {
518 if let Some(file_name) = current.file_name() {
519 suffix.push(file_name.to_os_string());
520 current = current
521 .parent()
522 .map(|p| p.to_path_buf())
523 .unwrap_or_default();
524 } else {
525 return path.to_path_buf();
526 }
527 }
528 }
529 }
530 }
531 }
532 }
533
534 pub fn state_path(&self) -> PathBuf {
539 match self {
540 BackendConfig::Local { path } => Self::canonicalize_path(Path::new(path)),
541 BackendConfig::Pass {
542 store_path, path, ..
543 } => Self::canonicalize_path(&Path::new(store_path).join(path)),
544 #[cfg(feature = "tpm")]
545 BackendConfig::Tpm { path, .. } => Self::canonicalize_path(Path::new(path)),
546 }
547 }
548
549 pub fn state_display(&self) -> String {
551 match self {
552 BackendConfig::Local { path } => path.clone(),
553 BackendConfig::Pass {
554 store_path, path, ..
555 } => {
556 format!("{}/{}", store_path, path)
557 }
558 #[cfg(feature = "tpm")]
559 BackendConfig::Tpm { path, .. } => path.clone(),
560 }
561 }
562
563 pub fn validate(&self) -> crate::error::Result<()> {
567 match self {
568 BackendConfig::Local { path } => {
569 let p = Path::new(path);
570 if !p.is_absolute() && !p.starts_with("~") {
571 debug!("Local backend path is relative: {}, canonicalizing", path);
572 }
573 Ok(())
574 }
575 BackendConfig::Pass {
576 store_path, path, ..
577 } => {
578 let p = Path::new(path);
579 if p.is_absolute() {
580 return Err(Error::Config(format!(
581 "Pass backend 'path' must be relative, got absolute path: {}",
582 path
583 )));
584 }
585 if path.contains("..") {
586 return Err(Error::Config(format!(
587 "Pass backend 'path' must not contain '..': {}",
588 path
589 )));
590 }
591 let combined = Path::new(store_path).join(path);
593 let canonical_store = Self::canonicalize_path(Path::new(store_path));
594 let canonical_combined = Self::canonicalize_path(&combined);
595 if !canonical_combined.starts_with(&canonical_store) {
596 return Err(Error::Config(format!(
597 "Pass backend 'path' escapes store_path: {} not beneath {}",
598 canonical_combined.display(),
599 canonical_store.display()
600 )));
601 }
602 Ok(())
603 }
604 #[cfg(feature = "tpm")]
605 BackendConfig::Tpm { path, .. } => {
606 let p = Path::new(path);
607 if !p.is_absolute() && !p.starts_with("~") {
608 debug!("TPM backend path is relative: {}, canonicalizing", path);
609 }
610 Ok(())
611 }
612 }
613 }
614}
615
616impl AppConfig {
617 pub fn load(args: &mut Args) -> crate::error::Result<Self> {
619 let default_config_path = dirs::config_dir().map(|p| p.join("passless/config.toml"));
620
621 let config_file_path = args
622 .config_path
623 .as_ref()
624 .or(default_config_path.as_ref())
625 .filter(|p| p.exists());
626
627 if let Some(path) = config_file_path
628 && let Ok(f) = File::open(path)
629 {
630 log::info!("Loading configuration from: {}", path.display());
631 let content = std::io::read_to_string(BufReader::new(f)).unwrap_or_default();
632
633 #[cfg(feature = "agent")]
634 let agent_config = {
635 match toml::from_str::<toml::Table>(&content) {
636 Ok(table) => match table.get("agents") {
637 Some(agents_value) => serde::Deserialize::deserialize(agents_value.clone())
638 .map_err(|e| {
639 Error::Config(format!(
640 "failed to parse [agents] section in {}: {}",
641 path.display(),
642 e
643 ))
644 })?,
645 None => AgentConfig::default(),
646 },
647 Err(e) => {
648 return Err(Error::Config(format!(
649 "failed to parse config file {} as TOML: {}",
650 path.display(),
651 e
652 )));
653 }
654 }
655 };
656
657 match toml::from_str::<<AppConfig as ClapSerde>::Opt>(&content) {
658 Ok(file_config) => {
659 #[allow(unused_mut)]
660 let mut config = AppConfig::from(file_config).merge(&mut args.config);
661 #[cfg(feature = "agent")]
662 {
663 config.agents = agent_config;
664 }
665 return Ok(config);
666 }
667 Err(e) => {
668 return Err(Error::Config(format!(
669 "failed to parse config file {}: {}",
670 path.display(),
671 e
672 )));
673 }
674 }
675 }
676
677 #[allow(unused_mut)]
678 let mut config = AppConfig::from(&mut args.config);
679 #[cfg(feature = "agent")]
680 {
681 config.agents = AgentConfig::default();
682 }
683 Ok(config)
684 }
685
686 pub fn backend(&self) -> crate::error::Result<BackendConfig> {
688 match self.backend_type.as_str() {
689 "local" => Ok(BackendConfig::Local {
690 path: self.local.path.clone(),
691 }),
692 "pass" => Ok(BackendConfig::Pass {
693 store_path: self.pass.store_path.clone(),
694 path: self.pass.path.clone(),
695 gpg_backend: self.pass.gpg_backend.clone(),
696 }),
697 #[cfg(feature = "tpm")]
698 "tpm" => Ok(BackendConfig::Tpm {
699 path: self.tpm.path.clone(),
700 tcti: self.tpm.tcti.clone(),
701 portable: self.tpm.portable,
702 }),
703 _ => Err(crate::error::Error::Config(format!(
704 "Invalid backend_type '{}'. Must be one of: local, pass, tpm",
705 self.backend_type
706 ))),
707 }
708 }
709
710 pub fn apply_security_hardening(&self) -> Result<(), Box<dyn std::error::Error>> {
712 self.security.apply_hardening()
713 }
714
715 pub fn security_config(&self) -> SecurityConfig {
717 self.security.clone()
718 }
719
720 pub fn pin_config(&self) -> PinConfig {
722 self.pin.clone()
723 }
724
725 pub fn validate(&self) -> crate::error::Result<()> {
727 self.pin.validate()?;
728 #[cfg(feature = "agent")]
729 {
730 let human_path = self.backend().ok().map(|b| b.state_path());
731 self.agents.validate(human_path.as_deref())?;
732 }
733 Ok(())
734 }
735}
736
737#[derive(Parser)]
739#[command(author, version, about)]
740pub struct Args {
741 #[arg(short, long, env = "PASSLESS_CONFIG")]
743 pub config_path: Option<PathBuf>,
744
745 #[command(flatten)]
747 pub config: <AppConfig as ClapSerde>::Opt,
748
749 #[command(subcommand)]
751 pub command: Option<Commands>,
752}
753
754#[derive(Debug, Clone, Copy, PartialEq, Eq)]
756pub enum OutputFormat {
757 Plain,
759 Json,
761}
762
763impl std::str::FromStr for OutputFormat {
764 type Err = String;
765
766 fn from_str(s: &str) -> Result<Self, Self::Err> {
767 match s.to_lowercase().as_str() {
768 "plain" => Ok(OutputFormat::Plain),
769 "json" => Ok(OutputFormat::Json),
770 _ => Err(format!(
771 "Invalid output format '{}'. Must be 'plain' or 'json'",
772 s
773 )),
774 }
775 }
776}
777
778impl std::fmt::Display for OutputFormat {
779 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
780 match self {
781 OutputFormat::Plain => write!(f, "plain"),
782 OutputFormat::Json => write!(f, "json"),
783 }
784 }
785}
786
787#[derive(Subcommand, Debug, Clone)]
789pub enum Commands {
790 Config {
792 #[command(subcommand)]
793 action: ConfigAction,
794 },
795 Client {
801 #[arg(short = 'D', long = "device", value_name = "INDEX|NAME", global = true)]
803 device: Option<String>,
804
805 #[arg(
807 short = 'o',
808 long = "output",
809 value_name = "FORMAT",
810 default_value = "plain",
811 global = true
812 )]
813 output: OutputFormat,
814
815 #[command(subcommand)]
816 action: ClientAction,
817 },
818 #[cfg(feature = "agent")]
820 AgentAdmin {
821 #[arg(
823 short = 'o',
824 long = "output",
825 value_name = "FORMAT",
826 default_value = "json",
827 global = true
828 )]
829 output: OutputFormat,
830
831 #[command(subcommand)]
832 action: AgentAdminAction,
833 },
834 #[cfg(feature = "agent")]
836 Agent {
837 #[arg(long, value_name = "PROFILE", global = true)]
839 profile: Option<String>,
840
841 #[arg(
843 short = 'o',
844 long = "output",
845 value_name = "FORMAT",
846 default_value = "json",
847 global = true
848 )]
849 output: OutputFormat,
850
851 #[command(subcommand)]
852 action: crate::AgentCommand,
853 },
854 #[cfg(feature = "tpm")]
856 Tpm {
857 #[command(subcommand)]
858 action: TpmAction,
859 },
860}
861
862#[cfg(feature = "tpm")]
864#[derive(Subcommand, Debug, Clone)]
865pub enum TpmAction {
866 #[command(group(clap::ArgGroup::new("seed-source").args(["generate", "seed_file", "seed_stdin"])))]
868 Provision {
869 #[arg(long)]
871 generate: bool,
872 #[arg(long = "seed-file", value_name = "PATH")]
874 seed_file: Option<PathBuf>,
875 #[arg(long = "seed-stdin")]
877 seed_stdin: bool,
878 #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
880 path: Option<String>,
881 #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
883 tcti: Option<String>,
884 },
885 Status {
887 #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
889 path: Option<String>,
890 #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
892 tcti: Option<String>,
893 },
894 Remove {
896 #[arg(long)]
898 confirm: bool,
899 #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
901 path: Option<String>,
902 #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
904 tcti: Option<String>,
905 },
906 #[command(group(clap::ArgGroup::new("selection").args(["credential_id", "all"]).required(true)))]
908 Migrate {
909 #[arg(long = "credential-id", value_name = "ID")]
911 credential_id: Option<String>,
912 #[arg(long)]
914 all: bool,
915 #[arg(long)]
917 dry_run: bool,
918 #[arg(long = "backup-dir", value_name = "PATH")]
920 backup_dir: Option<String>,
921 #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
923 path: Option<String>,
924 #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
926 tcti: Option<String>,
927 },
928}
929
930#[derive(Subcommand, Debug, Clone)]
932pub enum ConfigAction {
933 Print,
935}
936
937#[cfg(feature = "agent")]
939#[derive(Subcommand, Debug, Clone)]
940pub enum AgentAdminAction {
941 Install {
943 #[arg(value_enum, default_value_t = AgentSkillTarget::Auto)]
945 target: AgentSkillTarget,
946
947 #[arg(long, value_enum, default_value_t = AgentSkillScope::User)]
949 scope: AgentSkillScope,
950
951 #[arg(long)]
953 force: bool,
954 },
955 Profile {
957 #[command(subcommand)]
958 action: AdminProfileAction,
959 },
960 Policy {
962 #[command(subcommand)]
963 action: AdminPolicyAction,
964 },
965 Credential {
967 #[command(subcommand)]
968 action: AdminCredentialAction,
969 },
970 Delegation {
972 #[command(subcommand)]
973 action: AdminDelegationAction,
974 },
975 Session {
977 #[command(subcommand)]
978 action: AdminSessionAction,
979 },
980 Browser {
982 #[command(subcommand)]
983 action: AdminBrowserAction,
984 },
985 Audit {
987 #[command(subcommand)]
988 action: AdminAuditAction,
989 },
990 #[command(hide = true)]
992 Shutdown {
993 #[arg(long)]
995 confirm: bool,
996 },
997}
998
999#[cfg(feature = "agent")]
1001#[derive(Subcommand, Debug, Clone)]
1002pub enum AdminProfileAction {
1003 Check {
1005 #[arg(value_name = "PROFILE")]
1007 profile: String,
1008 },
1009 Show {
1011 #[arg(value_name = "PROFILE")]
1013 profile: String,
1014 },
1015 List,
1017 Enable {
1019 #[arg(value_name = "PROFILE")]
1021 profile: String,
1022 },
1023 Disable {
1025 #[arg(value_name = "PROFILE")]
1027 profile: String,
1028 },
1029}
1030
1031#[cfg(feature = "agent")]
1033#[derive(Subcommand, Debug, Clone)]
1034pub enum AdminPolicyAction {
1035 Check {
1037 #[arg(value_name = "PROFILE")]
1039 profile: String,
1040 },
1041 Reload {
1043 #[arg(value_name = "PROFILE")]
1045 profile: String,
1046 },
1047 Show {
1049 #[arg(value_name = "PROFILE")]
1051 profile: String,
1052 },
1053}
1054
1055#[cfg(feature = "agent")]
1057#[derive(Subcommand, Debug, Clone)]
1058pub enum AdminCredentialAction {
1059 List {
1061 #[arg(short = 'd', long = "domain", value_name = "DOMAIN")]
1063 rp_id: Option<String>,
1064 },
1065 Show {
1067 #[arg(value_name = "CREDENTIAL_REF")]
1069 credential_ref: String,
1070 },
1071 Revoke {
1073 #[arg(value_name = "CREDENTIAL_REF")]
1075 credential_ref: String,
1076 #[arg(long)]
1078 confirm: bool,
1079 },
1080 Delete {
1082 #[arg(value_name = "CREDENTIAL_REF")]
1084 credential_ref: String,
1085 #[arg(long)]
1087 confirm: bool,
1088 },
1089}
1090
1091#[cfg(feature = "agent")]
1093#[derive(Subcommand, Debug, Clone)]
1094pub enum AdminDelegationAction {
1095 Show {
1097 #[arg(value_name = "GRANT_ID")]
1099 grant_id: String,
1100 },
1101 List {
1103 #[arg(long, value_name = "PROFILE")]
1105 profile: Option<String>,
1106 },
1107 Revoke {
1109 #[arg(value_name = "GRANT_ID")]
1111 grant_id: String,
1112 #[arg(long)]
1114 confirm: bool,
1115 },
1116 RequestRegistration {
1118 #[arg(long, value_name = "PROFILE")]
1120 profile: String,
1121 #[arg(long, value_name = "RP_ID")]
1123 rp: String,
1124 #[arg(long, value_name = "SECONDS")]
1126 session_ttl: u64,
1127 #[arg(long, value_name = "REASON")]
1129 reason: Option<String>,
1130 },
1131}
1132
1133#[cfg(feature = "agent")]
1135#[derive(Subcommand, Debug, Clone)]
1136pub enum AdminSessionAction {
1137 Show {
1139 #[arg(value_name = "SESSION_ID")]
1141 session_id: String,
1142 },
1143 List {
1145 #[arg(long, value_name = "PROFILE")]
1147 profile: Option<String>,
1148 },
1149 Revoke {
1151 #[arg(value_name = "SESSION_ID")]
1153 session_id: String,
1154 #[arg(long)]
1156 confirm: bool,
1157 },
1158}
1159
1160#[cfg(feature = "agent")]
1162#[derive(Subcommand, Debug, Clone)]
1163pub enum AdminBrowserAction {
1164 Launch {
1166 #[arg(long, value_name = "PROFILE")]
1168 profile: String,
1169 #[arg(long, value_name = "URL")]
1171 url: Option<String>,
1172 },
1173}
1174
1175#[cfg(feature = "agent")]
1177#[derive(Subcommand, Debug, Clone)]
1178pub enum AdminAuditAction {
1179 Status,
1181 Verify,
1183 Export {
1185 #[arg(long, value_enum, default_value_t = AdminAuditExportFormat::Json)]
1187 format: AdminAuditExportFormat,
1188 },
1189}
1190
1191#[cfg(feature = "agent")]
1193#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1194pub enum AdminAuditExportFormat {
1195 Json,
1196 Csv,
1197}
1198
1199#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1201pub enum AgentSkillTarget {
1202 Auto,
1203 Opencode,
1204 Claude,
1205 Pi,
1206}
1207
1208#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1210pub enum AgentSkillScope {
1211 User,
1212 Project,
1213}
1214
1215#[derive(Subcommand, Debug, Clone)]
1217pub enum ClientAction {
1218 Devices,
1220 Info,
1222 Reset {
1224 #[arg(long = "yes-i-really-want-to-reset-my-device", action = ArgAction::Count)]
1226 confirm: u8,
1227 },
1228 List {
1230 #[arg(short = 'd', long = "domain", value_name = "DOMAIN")]
1232 rp_id: Option<String>,
1233 },
1234 Show {
1236 #[arg(value_name = "CREDENTIAL_ID")]
1238 credential_id: String,
1239 },
1240 Delete {
1242 #[arg(value_name = "CREDENTIAL_ID")]
1244 credential_id: String,
1245 },
1246 Rename {
1248 #[arg(value_name = "CREDENTIAL_ID")]
1250 credential_id: String,
1251 #[arg(short = 'u', long = "user-name", value_name = "NAME")]
1253 user_name: Option<String>,
1254 #[arg(short = 'n', long = "display-name", value_name = "NAME")]
1256 display_name: Option<String>,
1257 },
1258 Backup {
1260 #[arg(value_name = "CREDENTIAL_ID")]
1262 credential_id: String,
1263 #[arg(long, value_name = "RECIPIENT")]
1265 recipient: String,
1266 #[arg(long, value_name = "PATH")]
1268 output_file: PathBuf,
1269 #[arg(long = "yes-i-understand-this-exports-a-passkey")]
1271 confirm: bool,
1272 },
1273 Restore {
1275 #[arg(value_name = "PATH")]
1277 input_file: PathBuf,
1278 #[arg(long)]
1280 replace: bool,
1281 #[arg(long = "yes-i-understand-this-restores-a-passkey")]
1283 confirm: bool,
1284 },
1285 Pin {
1287 #[command(subcommand)]
1288 action: PinAction,
1289 },
1290}
1291
1292#[derive(Subcommand, Debug, Clone)]
1294pub enum PinAction {
1295 Set {
1297 #[arg(value_name = "PIN")]
1299 pin: String,
1300 },
1301 Change {
1303 #[arg(value_name = "OLD_PIN")]
1305 old_pin: String,
1306 #[arg(value_name = "NEW_PIN")]
1308 new_pin: String,
1309 },
1310 UvReset,
1312}
1313
1314#[cfg(feature = "agent")]
1316#[derive(Subcommand, Debug, Clone)]
1317pub enum AgentCommand {
1318 Doctor,
1320 Capabilities,
1322 Instructions,
1324 Intent {
1326 #[command(subcommand)]
1327 action: AgentIntentAction,
1328 },
1329 Delegation {
1331 #[command(subcommand)]
1332 action: AgentDelegationAction,
1333 },
1334 Credential {
1336 #[command(subcommand)]
1337 action: AgentCredentialAction,
1338 },
1339 BrowserStatus,
1341 EndpointStatus,
1343 BrowserControl {
1349 #[arg(long, value_name = "JSON", conflicts_with = "request_file")]
1351 request: Option<String>,
1352 #[arg(long, value_name = "PATH", conflicts_with = "request")]
1354 request_file: Option<std::path::PathBuf>,
1355 #[arg(long, value_name = "MS", default_value = "5000")]
1357 timeout_ms: u32,
1358 },
1359 PlaywrightMcp {
1361 #[arg(long, value_name = "PROFILE")]
1363 profile: String,
1364 #[arg(long, value_name = "URL")]
1366 url: Option<String>,
1367 #[arg(last = true, required = true)]
1369 command: Vec<std::path::PathBuf>,
1370 },
1371 Run {
1373 #[arg(long, value_name = "PROFILE")]
1375 profile: String,
1376 #[arg(last = true, required = true)]
1378 command: Vec<std::path::PathBuf>,
1379 },
1380}
1381
1382#[cfg(feature = "agent")]
1384#[derive(Subcommand, Debug, Clone)]
1385pub enum AgentIntentAction {
1386 Create {
1388 #[arg(value_enum)]
1390 action: AgentIntentActionType,
1391 #[arg(long, value_name = "RP_ID")]
1393 rp: String,
1394 #[arg(long, value_name = "CREDENTIAL_REF")]
1396 credential: Option<String>,
1397 #[arg(long, value_name = "REASON")]
1399 reason: Option<String>,
1400 },
1401 Show {
1403 #[arg(value_name = "REQUEST_ID")]
1405 request_id: String,
1406 },
1407 Wait {
1409 #[arg(value_name = "REQUEST_ID")]
1411 request_id: String,
1412 #[arg(long, value_name = "SECONDS")]
1414 timeout: Option<u64>,
1415 #[arg(long, value_name = "MS")]
1417 poll_interval: Option<u64>,
1418 },
1419 Cancel {
1421 #[arg(value_name = "REQUEST_ID")]
1423 request_id: String,
1424 },
1425}
1426
1427#[cfg(feature = "agent")]
1429#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1430pub enum AgentIntentActionType {
1431 Register,
1432 Authenticate,
1433}
1434
1435#[cfg(feature = "agent")]
1437#[derive(Subcommand, Debug, Clone)]
1438pub enum AgentDelegationAction {
1439 Request {
1441 #[arg(long, value_name = "RP_ID")]
1443 rp: String,
1444 #[arg(long, value_name = "CREDENTIAL_REF")]
1446 credential: String,
1447 #[arg(long, value_name = "SECONDS")]
1449 session_ttl: u64,
1450 #[arg(long, value_name = "REASON")]
1452 reason: Option<String>,
1453 },
1454 Show {
1456 #[arg(value_name = "REQUEST_ID")]
1458 request_id: String,
1459 },
1460 Wait {
1462 #[arg(value_name = "REQUEST_ID")]
1464 request_id: String,
1465 #[arg(long, value_name = "SECONDS")]
1467 timeout: Option<u64>,
1468 #[arg(long, value_name = "MS")]
1470 poll_interval: Option<u64>,
1471 },
1472 Cancel {
1474 #[arg(value_name = "REQUEST_ID")]
1476 request_id: String,
1477 },
1478}
1479
1480#[cfg(feature = "agent")]
1482#[derive(Subcommand, Debug, Clone)]
1483pub enum AgentCredentialAction {
1484 List,
1486 Show {
1488 #[arg(value_name = "CREDENTIAL_REF")]
1490 credential_ref: String,
1491 },
1492}
1493
1494#[cfg(test)]
1495mod tests {
1496 use super::*;
1497
1498 #[cfg(feature = "agent")]
1499 #[test]
1500 fn test_agent_admin_install_defaults() {
1501 let args = Args::try_parse_from(["passless", "agent-admin", "install"]).unwrap();
1502 assert!(matches!(
1503 args.command,
1504 Some(Commands::AgentAdmin {
1505 action: AgentAdminAction::Install {
1506 target: AgentSkillTarget::Auto,
1507 scope: AgentSkillScope::User,
1508 force: false,
1509 },
1510 ..
1511 })
1512 ));
1513 }
1514
1515 #[cfg(feature = "agent")]
1516 #[test]
1517 fn test_agent_admin_install_explicit_options() {
1518 let args = Args::try_parse_from([
1519 "passless",
1520 "agent-admin",
1521 "install",
1522 "claude",
1523 "--scope",
1524 "project",
1525 "--force",
1526 ])
1527 .unwrap();
1528 assert!(matches!(
1529 args.command,
1530 Some(Commands::AgentAdmin {
1531 action: AgentAdminAction::Install {
1532 target: AgentSkillTarget::Claude,
1533 scope: AgentSkillScope::Project,
1534 force: true,
1535 },
1536 ..
1537 })
1538 ));
1539 }
1540
1541 #[test]
1542 fn test_pin_config_default_max_uv_retries() {
1543 let config = PinConfig {
1544 enforcement: PinEnforcement::Optional,
1545 min_length: 4,
1546 max_retries: 8,
1547 max_uv_retries: 8,
1548 auto_lock_timeout: 0,
1549 };
1550 assert_eq!(config.max_uv_retries, 8);
1551 }
1552
1553 #[test]
1554 fn test_pin_config_validate_success() {
1555 let config = PinConfig {
1556 enforcement: PinEnforcement::Optional,
1557 min_length: 4,
1558 max_retries: 8,
1559 max_uv_retries: 8,
1560 auto_lock_timeout: 0,
1561 };
1562 assert!(config.validate().is_ok());
1563 }
1564
1565 #[test]
1566 fn test_pin_config_validate_zero_max_uv_retries() {
1567 let config = PinConfig {
1568 enforcement: PinEnforcement::Optional,
1569 min_length: 4,
1570 max_retries: 8,
1571 max_uv_retries: 0,
1572 auto_lock_timeout: 0,
1573 };
1574 let result = config.validate();
1575 assert!(result.is_err());
1576 assert!(result.unwrap_err().to_string().contains("max_uv_retries"));
1577 }
1578
1579 #[test]
1580 fn test_pin_config_validate_zero_max_retries() {
1581 let config = PinConfig {
1582 enforcement: PinEnforcement::Optional,
1583 min_length: 4,
1584 max_retries: 0,
1585 max_uv_retries: 8,
1586 auto_lock_timeout: 0,
1587 };
1588 let result = config.validate();
1589 assert!(result.is_err());
1590 assert!(result.unwrap_err().to_string().contains("max_retries"));
1591 }
1592
1593 #[test]
1594 fn test_pin_config_validate_invalid_min_length() {
1595 let config = PinConfig {
1596 enforcement: PinEnforcement::Optional,
1597 min_length: 3,
1598 max_retries: 8,
1599 max_uv_retries: 8,
1600 auto_lock_timeout: 0,
1601 };
1602 let result = config.validate();
1603 assert!(result.is_err());
1604 assert!(result.unwrap_err().to_string().contains("min_length"));
1605 }
1606
1607 #[test]
1608 fn test_canonicalize_path_existing() {
1609 let dir = std::env::temp_dir();
1610 let canonical = BackendConfig::canonicalize_path(&dir);
1611 assert!(canonical.is_absolute());
1612 assert!(canonical.exists());
1613 }
1614
1615 #[test]
1616 fn test_canonicalize_path_nonexistent() {
1617 let base = std::env::temp_dir();
1618 let nonexistent = base.join("passless_test_nonexistent_dir_12345/sub");
1619 let canonical = BackendConfig::canonicalize_path(&nonexistent);
1620 assert!(canonical.is_absolute());
1621 assert!(canonical.starts_with(BackendConfig::canonicalize_path(&base)));
1622 }
1623
1624 #[test]
1625 fn test_canonicalize_path_symlink() {
1626 let dir = tempfile::tempdir().unwrap();
1627 let real = dir.path().join("real");
1628 std::fs::create_dir(&real).unwrap();
1629 let link = dir.path().join("link");
1630 std::os::unix::fs::symlink(&real, &link).unwrap();
1631
1632 let canonical_real = BackendConfig::canonicalize_path(&real);
1633 let canonical_link = BackendConfig::canonicalize_path(&link);
1634 assert_eq!(canonical_real, canonical_link);
1635 }
1636
1637 #[test]
1638 fn test_local_state_path_relative_and_absolute() {
1639 let dir = tempfile::tempdir_in(".").unwrap();
1640 let abs_path = std::fs::canonicalize(dir.path()).unwrap();
1641 let rel_path = dir.path().to_path_buf();
1642
1643 let backend_abs = BackendConfig::Local {
1644 path: abs_path.display().to_string(),
1645 };
1646 let backend_rel = BackendConfig::Local {
1647 path: rel_path.display().to_string(),
1648 };
1649 assert_eq!(backend_abs.state_path(), backend_rel.state_path());
1650 }
1651
1652 #[test]
1653 fn test_pass_state_path_different_subpaths() {
1654 let store = "/tmp/passless_test_store";
1655 let backend_a = BackendConfig::Pass {
1656 store_path: store.to_string(),
1657 path: "fido2".to_string(),
1658 gpg_backend: "gnupg-bin".to_string(),
1659 };
1660 let backend_b = BackendConfig::Pass {
1661 store_path: store.to_string(),
1662 path: "fido2-other".to_string(),
1663 gpg_backend: "gnupg-bin".to_string(),
1664 };
1665 assert_ne!(backend_a.state_path(), backend_b.state_path());
1666 }
1667
1668 #[test]
1669 fn test_different_local_paths_produce_different_identities() {
1670 let backend_a = BackendConfig::Local {
1671 path: "/tmp/passless_a".to_string(),
1672 };
1673 let backend_b = BackendConfig::Local {
1674 path: "/tmp/passless_b".to_string(),
1675 };
1676 assert_ne!(backend_a.state_path(), backend_b.state_path());
1677 }
1678
1679 #[cfg(feature = "agent")]
1680 #[test]
1681 fn test_agent_admin_profile_list() {
1682 let args = Args::try_parse_from(["passless", "agent-admin", "profile", "list"]).unwrap();
1683 assert!(matches!(
1684 args.command,
1685 Some(Commands::AgentAdmin {
1686 action: AgentAdminAction::Profile {
1687 action: AdminProfileAction::List,
1688 },
1689 ..
1690 })
1691 ));
1692 }
1693
1694 #[cfg(feature = "agent")]
1695 #[test]
1696 fn test_agent_admin_credential_delete_without_confirm() {
1697 let args = Args::try_parse_from([
1698 "passless",
1699 "agent-admin",
1700 "credential",
1701 "delete",
1702 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
1703 ])
1704 .unwrap();
1705 assert!(matches!(
1706 args.command,
1707 Some(Commands::AgentAdmin {
1708 action: AgentAdminAction::Credential {
1709 action: AdminCredentialAction::Delete { confirm: false, .. },
1710 },
1711 ..
1712 })
1713 ));
1714 }
1715
1716 #[cfg(feature = "agent")]
1717 #[test]
1718 fn test_agent_admin_credential_delete_with_confirm() {
1719 let args = Args::try_parse_from([
1720 "passless",
1721 "agent-admin",
1722 "credential",
1723 "delete",
1724 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
1725 "--confirm",
1726 ])
1727 .unwrap();
1728 assert!(matches!(
1729 args.command,
1730 Some(Commands::AgentAdmin {
1731 action: AgentAdminAction::Credential {
1732 action: AdminCredentialAction::Delete { confirm: true, .. },
1733 },
1734 ..
1735 })
1736 ));
1737 }
1738
1739 #[cfg(feature = "agent")]
1740 #[test]
1741 fn test_agent_admin_shutdown_hidden() {
1742 let args =
1743 Args::try_parse_from(["passless", "agent-admin", "shutdown", "--confirm"]).unwrap();
1744 assert!(matches!(
1745 args.command,
1746 Some(Commands::AgentAdmin {
1747 action: AgentAdminAction::Shutdown { confirm: true },
1748 ..
1749 })
1750 ));
1751 }
1752
1753 #[cfg(feature = "agent")]
1754 #[test]
1755 fn test_agent_admin_output_default_json() {
1756 let args = Args::try_parse_from(["passless", "agent-admin", "profile", "list"]).unwrap();
1757 match args.command {
1758 Some(Commands::AgentAdmin { output, .. }) => {
1759 assert_eq!(output, OutputFormat::Json);
1760 }
1761 _ => panic!("expected AgentAdmin command"),
1762 }
1763 }
1764
1765 #[cfg(feature = "agent")]
1766 #[test]
1767 fn test_agent_admin_output_plain() {
1768 let args = Args::try_parse_from([
1769 "passless",
1770 "agent-admin",
1771 "--output",
1772 "plain",
1773 "profile",
1774 "list",
1775 ])
1776 .unwrap();
1777 match args.command {
1778 Some(Commands::AgentAdmin { output, .. }) => {
1779 assert_eq!(output, OutputFormat::Plain);
1780 }
1781 _ => panic!("expected AgentAdmin command"),
1782 }
1783 }
1784
1785 #[cfg(feature = "agent")]
1786 #[test]
1787 fn test_agent_doctor_parses() {
1788 let args = Args::try_parse_from(["passless", "agent", "doctor"]).unwrap();
1789 assert!(matches!(
1790 args.command,
1791 Some(Commands::Agent {
1792 action: AgentCommand::Doctor,
1793 ..
1794 })
1795 ));
1796 }
1797
1798 #[cfg(feature = "agent")]
1799 #[test]
1800 fn test_agent_run_with_command() {
1801 let args = Args::try_parse_from([
1802 "passless",
1803 "agent",
1804 "run",
1805 "--profile",
1806 "myprofile",
1807 "--",
1808 "/usr/bin/test",
1809 "arg1",
1810 ])
1811 .unwrap();
1812 match args.command {
1813 Some(Commands::Agent {
1814 action: AgentCommand::Run { profile, command },
1815 ..
1816 }) => {
1817 assert_eq!(profile, "myprofile");
1818 assert_eq!(command.len(), 2);
1819 }
1820 _ => panic!("expected Agent Run command"),
1821 }
1822 }
1823
1824 #[cfg(feature = "agent")]
1825 #[test]
1826 fn test_agent_intent_create_parses() {
1827 let args = Args::try_parse_from([
1828 "passless",
1829 "agent",
1830 "intent",
1831 "create",
1832 "register",
1833 "--rp",
1834 "example.com",
1835 ])
1836 .unwrap();
1837 assert!(matches!(
1838 args.command,
1839 Some(Commands::Agent {
1840 action: AgentCommand::Intent {
1841 action: AgentIntentAction::Create {
1842 action: AgentIntentActionType::Register,
1843 ..
1844 },
1845 },
1846 ..
1847 })
1848 ));
1849 }
1850
1851 #[cfg(feature = "agent")]
1852 #[test]
1853 fn test_agent_output_default_json() {
1854 let args = Args::try_parse_from(["passless", "agent", "doctor"]).unwrap();
1855 match args.command {
1856 Some(Commands::Agent { output, .. }) => {
1857 assert_eq!(output, OutputFormat::Json);
1858 }
1859 _ => panic!("expected Agent command"),
1860 }
1861 }
1862
1863 #[cfg(feature = "agent")]
1864 #[test]
1865 fn test_shell_completions_contain_agent_commands() {
1866 use clap::CommandFactory;
1867
1868 let cmd = Args::command();
1869 let mut buf = Vec::new();
1870 clap_complete::generate(
1871 clap_complete::Shell::Bash,
1872 &mut cmd.clone(),
1873 "passless",
1874 &mut buf,
1875 );
1876 let completion = String::from_utf8(buf).unwrap();
1877
1878 for expected in [
1879 "agent-admin",
1880 "agent",
1881 "install",
1882 "browser-control",
1883 "intent",
1884 "delegation",
1885 "doctor",
1886 "capabilities",
1887 "instructions",
1888 ] {
1889 assert!(
1890 completion.contains(expected),
1891 "bash completion missing '{}'",
1892 expected
1893 );
1894 }
1895 }
1896
1897 #[cfg(feature = "agent")]
1898 #[test]
1899 fn test_shell_completions_zsh_contain_agent_commands() {
1900 use clap::CommandFactory;
1901
1902 let cmd = Args::command();
1903 let mut buf = Vec::new();
1904 clap_complete::generate(
1905 clap_complete::Shell::Zsh,
1906 &mut cmd.clone(),
1907 "passless",
1908 &mut buf,
1909 );
1910 let completion = String::from_utf8(buf).unwrap();
1911
1912 for expected in ["agent-admin", "agent", "install", "browser-control"] {
1913 assert!(
1914 completion.contains(expected),
1915 "zsh completion missing '{}'",
1916 expected
1917 );
1918 }
1919 }
1920
1921 #[cfg(feature = "agent")]
1922 #[test]
1923 fn test_config_print_includes_agent_fields() {
1924 let mut default_args = Args::parse_from(["passless"]);
1925 let config = AppConfig::from(&mut default_args.config);
1926 let toml_output = config.to_toml_with_comments();
1927
1928 assert!(
1929 toml_output.contains("backend_type"),
1930 "config print missing backend_type"
1931 );
1932 assert!(
1933 toml_output.contains("[security]"),
1934 "config print missing [security] section"
1935 );
1936 assert!(
1937 toml_output.contains("[pin]"),
1938 "config print missing [pin] section"
1939 );
1940 assert!(
1941 toml_output.contains("always_uv"),
1942 "config print missing always_uv"
1943 );
1944 assert!(
1945 toml_output.contains("notification_timeout"),
1946 "config print missing notification_timeout"
1947 );
1948 }
1949
1950 #[test]
1951 fn test_config_print_contains_passless_header() {
1952 let mut default_args = Args::parse_from(["passless"]);
1953 let config = AppConfig::from(&mut default_args.config);
1954 let toml_output = config.to_toml_with_comments();
1955
1956 assert!(toml_output.contains("Passless Configuration File"));
1957 assert!(toml_output.contains("~/.config/passless/config.toml"));
1958 }
1959
1960 #[test]
1961 fn test_config_print_contains_local_backend_section() {
1962 let mut default_args = Args::parse_from(["passless"]);
1963 let config = AppConfig::from(&mut default_args.config);
1964 let toml_output = config.to_toml_with_comments();
1965
1966 assert!(toml_output.contains("[local]"));
1967 assert!(toml_output.contains("path"));
1968 }
1969
1970 #[test]
1971 fn test_config_print_contains_pass_backend_section() {
1972 let mut default_args = Args::parse_from(["passless"]);
1973 let config = AppConfig::from(&mut default_args.config);
1974 let toml_output = config.to_toml_with_comments();
1975
1976 assert!(toml_output.contains("[pass]"));
1977 assert!(toml_output.contains("store_path"));
1978 assert!(toml_output.contains("gpg_backend"));
1979 }
1980}