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 InstallNativeMessaging {
957 #[arg(long)]
959 browser: String,
960
961 #[arg(long)]
963 ext_dir: PathBuf,
964
965 #[arg(long, default_value = "/usr/bin/sign-proxy")]
967 sign_proxy: PathBuf,
968 },
969 Profile {
971 #[command(subcommand)]
972 action: AdminProfileAction,
973 },
974 Policy {
976 #[command(subcommand)]
977 action: AdminPolicyAction,
978 },
979 Credential {
981 #[command(subcommand)]
982 action: AdminCredentialAction,
983 },
984 Delegation {
986 #[command(subcommand)]
987 action: AdminDelegationAction,
988 },
989 Session {
991 #[command(subcommand)]
992 action: AdminSessionAction,
993 },
994 Browser {
996 #[command(subcommand)]
997 action: AdminBrowserAction,
998 },
999 Audit {
1001 #[command(subcommand)]
1002 action: AdminAuditAction,
1003 },
1004 #[command(hide = true)]
1006 Shutdown {
1007 #[arg(long)]
1009 confirm: bool,
1010 },
1011}
1012
1013#[cfg(feature = "agent")]
1015#[derive(Subcommand, Debug, Clone)]
1016pub enum AdminProfileAction {
1017 Check {
1019 #[arg(value_name = "PROFILE")]
1021 profile: String,
1022 },
1023 Show {
1025 #[arg(value_name = "PROFILE")]
1027 profile: String,
1028 },
1029 List,
1031 Enable {
1033 #[arg(value_name = "PROFILE")]
1035 profile: String,
1036 },
1037 Disable {
1039 #[arg(value_name = "PROFILE")]
1041 profile: String,
1042 },
1043}
1044
1045#[cfg(feature = "agent")]
1047#[derive(Subcommand, Debug, Clone)]
1048pub enum AdminPolicyAction {
1049 Check {
1051 #[arg(value_name = "PROFILE")]
1053 profile: String,
1054 },
1055 Reload {
1057 #[arg(value_name = "PROFILE")]
1059 profile: String,
1060 },
1061 Show {
1063 #[arg(value_name = "PROFILE")]
1065 profile: String,
1066 },
1067}
1068
1069#[cfg(feature = "agent")]
1071#[derive(Subcommand, Debug, Clone)]
1072pub enum AdminCredentialAction {
1073 List {
1075 #[arg(short = 'd', long = "domain", value_name = "DOMAIN")]
1077 rp_id: Option<String>,
1078 },
1079 Show {
1081 #[arg(value_name = "CREDENTIAL_REF")]
1083 credential_ref: String,
1084 },
1085 Revoke {
1087 #[arg(value_name = "CREDENTIAL_REF")]
1089 credential_ref: String,
1090 #[arg(long)]
1092 confirm: bool,
1093 },
1094 Delete {
1096 #[arg(value_name = "CREDENTIAL_REF")]
1098 credential_ref: String,
1099 #[arg(long)]
1101 confirm: bool,
1102 },
1103}
1104
1105#[cfg(feature = "agent")]
1107#[derive(Subcommand, Debug, Clone)]
1108pub enum AdminDelegationAction {
1109 Show {
1111 #[arg(value_name = "GRANT_ID")]
1113 grant_id: String,
1114 },
1115 List {
1117 #[arg(long, value_name = "PROFILE")]
1119 profile: Option<String>,
1120 },
1121 Revoke {
1123 #[arg(value_name = "GRANT_ID")]
1125 grant_id: String,
1126 #[arg(long)]
1128 confirm: bool,
1129 },
1130 RequestRegistration {
1132 #[arg(long, value_name = "PROFILE")]
1134 profile: String,
1135 #[arg(long, value_name = "RP_ID")]
1137 rp: String,
1138 #[arg(long, value_name = "SECONDS")]
1140 session_ttl: u64,
1141 #[arg(long, value_name = "REASON")]
1143 reason: Option<String>,
1144 },
1145}
1146
1147#[cfg(feature = "agent")]
1149#[derive(Subcommand, Debug, Clone)]
1150pub enum AdminSessionAction {
1151 Show {
1153 #[arg(value_name = "SESSION_ID")]
1155 session_id: String,
1156 },
1157 List {
1159 #[arg(long, value_name = "PROFILE")]
1161 profile: Option<String>,
1162 },
1163 Revoke {
1165 #[arg(value_name = "SESSION_ID")]
1167 session_id: String,
1168 #[arg(long)]
1170 confirm: bool,
1171 },
1172}
1173
1174#[cfg(feature = "agent")]
1176#[derive(Subcommand, Debug, Clone)]
1177pub enum AdminBrowserAction {
1178 Launch {
1180 #[arg(long, value_name = "PROFILE")]
1182 profile: String,
1183 #[arg(long, value_name = "URL")]
1185 url: Option<String>,
1186 },
1187}
1188
1189#[cfg(feature = "agent")]
1191#[derive(Subcommand, Debug, Clone)]
1192pub enum AdminAuditAction {
1193 Status,
1195 Verify,
1197 Export {
1199 #[arg(long, value_enum, default_value_t = AdminAuditExportFormat::Json)]
1201 format: AdminAuditExportFormat,
1202 },
1203}
1204
1205#[cfg(feature = "agent")]
1207#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1208pub enum AdminAuditExportFormat {
1209 Json,
1210 Csv,
1211}
1212
1213#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1215pub enum AgentSkillTarget {
1216 Auto,
1217 Opencode,
1218 Claude,
1219 Pi,
1220}
1221
1222#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1224pub enum AgentSkillScope {
1225 User,
1226 Project,
1227}
1228
1229#[derive(Subcommand, Debug, Clone)]
1231pub enum ClientAction {
1232 Devices,
1234 Info,
1236 Reset {
1238 #[arg(long = "yes-i-really-want-to-reset-my-device", action = ArgAction::Count)]
1240 confirm: u8,
1241 },
1242 List {
1244 #[arg(short = 'd', long = "domain", value_name = "DOMAIN")]
1246 rp_id: Option<String>,
1247 },
1248 Show {
1250 #[arg(value_name = "CREDENTIAL_ID")]
1252 credential_id: String,
1253 },
1254 Delete {
1256 #[arg(value_name = "CREDENTIAL_ID")]
1258 credential_id: String,
1259 },
1260 Rename {
1262 #[arg(value_name = "CREDENTIAL_ID")]
1264 credential_id: String,
1265 #[arg(short = 'u', long = "user-name", value_name = "NAME")]
1267 user_name: Option<String>,
1268 #[arg(short = 'n', long = "display-name", value_name = "NAME")]
1270 display_name: Option<String>,
1271 },
1272 Backup {
1274 #[arg(value_name = "CREDENTIAL_ID")]
1276 credential_id: String,
1277 #[arg(long, value_name = "RECIPIENT")]
1279 recipient: String,
1280 #[arg(long, value_name = "PATH")]
1282 output_file: PathBuf,
1283 #[arg(long = "yes-i-understand-this-exports-a-passkey")]
1285 confirm: bool,
1286 },
1287 Restore {
1289 #[arg(value_name = "PATH")]
1291 input_file: PathBuf,
1292 #[arg(long)]
1294 replace: bool,
1295 #[arg(long = "yes-i-understand-this-restores-a-passkey")]
1297 confirm: bool,
1298 },
1299 Pin {
1301 #[command(subcommand)]
1302 action: PinAction,
1303 },
1304}
1305
1306#[derive(Subcommand, Debug, Clone)]
1308pub enum PinAction {
1309 Set {
1311 #[arg(value_name = "PIN")]
1313 pin: String,
1314 },
1315 Change {
1317 #[arg(value_name = "OLD_PIN")]
1319 old_pin: String,
1320 #[arg(value_name = "NEW_PIN")]
1322 new_pin: String,
1323 },
1324 UvReset,
1326}
1327
1328#[cfg(feature = "agent")]
1330#[derive(Subcommand, Debug, Clone)]
1331pub enum AgentCommand {
1332 Doctor,
1334 Capabilities,
1336 Instructions,
1338 Intent {
1340 #[command(subcommand)]
1341 action: AgentIntentAction,
1342 },
1343 Delegation {
1345 #[command(subcommand)]
1346 action: AgentDelegationAction,
1347 },
1348 Credential {
1350 #[command(subcommand)]
1351 action: AgentCredentialAction,
1352 },
1353 BrowserStatus,
1355 EndpointStatus,
1357 BrowserControl {
1363 #[arg(long, value_name = "JSON", conflicts_with = "request_file")]
1365 request: Option<String>,
1366 #[arg(long, value_name = "PATH", conflicts_with = "request")]
1368 request_file: Option<std::path::PathBuf>,
1369 #[arg(long, value_name = "MS", default_value = "5000")]
1371 timeout_ms: u32,
1372 },
1373 PlaywrightMcp {
1375 #[arg(long, value_name = "PROFILE")]
1377 profile: String,
1378 #[arg(long, value_name = "URL")]
1380 url: Option<String>,
1381 #[arg(last = true, required = true)]
1383 command: Vec<std::path::PathBuf>,
1384 },
1385 Run {
1387 #[arg(long, value_name = "PROFILE")]
1389 profile: String,
1390 #[arg(last = true, required = true)]
1392 command: Vec<std::path::PathBuf>,
1393 },
1394}
1395
1396#[cfg(feature = "agent")]
1398#[derive(Subcommand, Debug, Clone)]
1399pub enum AgentIntentAction {
1400 Create {
1402 #[arg(value_enum)]
1404 action: AgentIntentActionType,
1405 #[arg(long, value_name = "RP_ID")]
1407 rp: String,
1408 #[arg(long, value_name = "CREDENTIAL_REF")]
1410 credential: Option<String>,
1411 #[arg(long, value_name = "REASON")]
1413 reason: Option<String>,
1414 },
1415 Show {
1417 #[arg(value_name = "REQUEST_ID")]
1419 request_id: String,
1420 },
1421 Wait {
1423 #[arg(value_name = "REQUEST_ID")]
1425 request_id: String,
1426 #[arg(long, value_name = "SECONDS")]
1428 timeout: Option<u64>,
1429 #[arg(long, value_name = "MS")]
1431 poll_interval: Option<u64>,
1432 },
1433 Cancel {
1435 #[arg(value_name = "REQUEST_ID")]
1437 request_id: String,
1438 },
1439}
1440
1441#[cfg(feature = "agent")]
1443#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1444pub enum AgentIntentActionType {
1445 Register,
1446 Authenticate,
1447}
1448
1449#[cfg(feature = "agent")]
1451#[derive(Subcommand, Debug, Clone)]
1452pub enum AgentDelegationAction {
1453 Request {
1455 #[arg(long, value_name = "RP_ID")]
1457 rp: String,
1458 #[arg(long, value_name = "CREDENTIAL_REF")]
1460 credential: String,
1461 #[arg(long, value_name = "SECONDS")]
1463 session_ttl: u64,
1464 #[arg(long, value_name = "REASON")]
1466 reason: Option<String>,
1467 },
1468 Show {
1470 #[arg(value_name = "REQUEST_ID")]
1472 request_id: String,
1473 },
1474 Wait {
1476 #[arg(value_name = "REQUEST_ID")]
1478 request_id: String,
1479 #[arg(long, value_name = "SECONDS")]
1481 timeout: Option<u64>,
1482 #[arg(long, value_name = "MS")]
1484 poll_interval: Option<u64>,
1485 },
1486 Cancel {
1488 #[arg(value_name = "REQUEST_ID")]
1490 request_id: String,
1491 },
1492}
1493
1494#[cfg(feature = "agent")]
1496#[derive(Subcommand, Debug, Clone)]
1497pub enum AgentCredentialAction {
1498 List,
1500 Show {
1502 #[arg(value_name = "CREDENTIAL_REF")]
1504 credential_ref: String,
1505 },
1506}
1507
1508#[cfg(test)]
1509mod tests {
1510 use super::*;
1511
1512 #[cfg(feature = "agent")]
1513 #[test]
1514 fn test_agent_admin_install_defaults() {
1515 let args = Args::try_parse_from(["passless", "agent-admin", "install"]).unwrap();
1516 assert!(matches!(
1517 args.command,
1518 Some(Commands::AgentAdmin {
1519 action: AgentAdminAction::Install {
1520 target: AgentSkillTarget::Auto,
1521 scope: AgentSkillScope::User,
1522 force: false,
1523 },
1524 ..
1525 })
1526 ));
1527 }
1528
1529 #[cfg(feature = "agent")]
1530 #[test]
1531 fn test_agent_admin_install_explicit_options() {
1532 let args = Args::try_parse_from([
1533 "passless",
1534 "agent-admin",
1535 "install",
1536 "claude",
1537 "--scope",
1538 "project",
1539 "--force",
1540 ])
1541 .unwrap();
1542 assert!(matches!(
1543 args.command,
1544 Some(Commands::AgentAdmin {
1545 action: AgentAdminAction::Install {
1546 target: AgentSkillTarget::Claude,
1547 scope: AgentSkillScope::Project,
1548 force: true,
1549 },
1550 ..
1551 })
1552 ));
1553 }
1554
1555 #[test]
1556 fn test_pin_config_default_max_uv_retries() {
1557 let config = PinConfig {
1558 enforcement: PinEnforcement::Optional,
1559 min_length: 4,
1560 max_retries: 8,
1561 max_uv_retries: 8,
1562 auto_lock_timeout: 0,
1563 };
1564 assert_eq!(config.max_uv_retries, 8);
1565 }
1566
1567 #[test]
1568 fn test_pin_config_validate_success() {
1569 let config = PinConfig {
1570 enforcement: PinEnforcement::Optional,
1571 min_length: 4,
1572 max_retries: 8,
1573 max_uv_retries: 8,
1574 auto_lock_timeout: 0,
1575 };
1576 assert!(config.validate().is_ok());
1577 }
1578
1579 #[test]
1580 fn test_pin_config_validate_zero_max_uv_retries() {
1581 let config = PinConfig {
1582 enforcement: PinEnforcement::Optional,
1583 min_length: 4,
1584 max_retries: 8,
1585 max_uv_retries: 0,
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_uv_retries"));
1591 }
1592
1593 #[test]
1594 fn test_pin_config_validate_zero_max_retries() {
1595 let config = PinConfig {
1596 enforcement: PinEnforcement::Optional,
1597 min_length: 4,
1598 max_retries: 0,
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("max_retries"));
1605 }
1606
1607 #[test]
1608 fn test_pin_config_validate_invalid_min_length() {
1609 let config = PinConfig {
1610 enforcement: PinEnforcement::Optional,
1611 min_length: 3,
1612 max_retries: 8,
1613 max_uv_retries: 8,
1614 auto_lock_timeout: 0,
1615 };
1616 let result = config.validate();
1617 assert!(result.is_err());
1618 assert!(result.unwrap_err().to_string().contains("min_length"));
1619 }
1620
1621 #[test]
1622 fn test_canonicalize_path_existing() {
1623 let dir = std::env::temp_dir();
1624 let canonical = BackendConfig::canonicalize_path(&dir);
1625 assert!(canonical.is_absolute());
1626 assert!(canonical.exists());
1627 }
1628
1629 #[test]
1630 fn test_canonicalize_path_nonexistent() {
1631 let base = std::env::temp_dir();
1632 let nonexistent = base.join("passless_test_nonexistent_dir_12345/sub");
1633 let canonical = BackendConfig::canonicalize_path(&nonexistent);
1634 assert!(canonical.is_absolute());
1635 assert!(canonical.starts_with(BackendConfig::canonicalize_path(&base)));
1636 }
1637
1638 #[test]
1639 fn test_canonicalize_path_symlink() {
1640 let dir = tempfile::tempdir().unwrap();
1641 let real = dir.path().join("real");
1642 std::fs::create_dir(&real).unwrap();
1643 let link = dir.path().join("link");
1644 std::os::unix::fs::symlink(&real, &link).unwrap();
1645
1646 let canonical_real = BackendConfig::canonicalize_path(&real);
1647 let canonical_link = BackendConfig::canonicalize_path(&link);
1648 assert_eq!(canonical_real, canonical_link);
1649 }
1650
1651 #[test]
1652 fn test_local_state_path_relative_and_absolute() {
1653 let dir = tempfile::tempdir_in(".").unwrap();
1654 let abs_path = std::fs::canonicalize(dir.path()).unwrap();
1655 let rel_path = dir.path().to_path_buf();
1656
1657 let backend_abs = BackendConfig::Local {
1658 path: abs_path.display().to_string(),
1659 };
1660 let backend_rel = BackendConfig::Local {
1661 path: rel_path.display().to_string(),
1662 };
1663 assert_eq!(backend_abs.state_path(), backend_rel.state_path());
1664 }
1665
1666 #[test]
1667 fn test_pass_state_path_different_subpaths() {
1668 let store = "/tmp/passless_test_store";
1669 let backend_a = BackendConfig::Pass {
1670 store_path: store.to_string(),
1671 path: "fido2".to_string(),
1672 gpg_backend: "gnupg-bin".to_string(),
1673 };
1674 let backend_b = BackendConfig::Pass {
1675 store_path: store.to_string(),
1676 path: "fido2-other".to_string(),
1677 gpg_backend: "gnupg-bin".to_string(),
1678 };
1679 assert_ne!(backend_a.state_path(), backend_b.state_path());
1680 }
1681
1682 #[test]
1683 fn test_different_local_paths_produce_different_identities() {
1684 let backend_a = BackendConfig::Local {
1685 path: "/tmp/passless_a".to_string(),
1686 };
1687 let backend_b = BackendConfig::Local {
1688 path: "/tmp/passless_b".to_string(),
1689 };
1690 assert_ne!(backend_a.state_path(), backend_b.state_path());
1691 }
1692
1693 #[cfg(feature = "agent")]
1694 #[test]
1695 fn test_agent_admin_profile_list() {
1696 let args = Args::try_parse_from(["passless", "agent-admin", "profile", "list"]).unwrap();
1697 assert!(matches!(
1698 args.command,
1699 Some(Commands::AgentAdmin {
1700 action: AgentAdminAction::Profile {
1701 action: AdminProfileAction::List,
1702 },
1703 ..
1704 })
1705 ));
1706 }
1707
1708 #[cfg(feature = "agent")]
1709 #[test]
1710 fn test_agent_admin_credential_delete_without_confirm() {
1711 let args = Args::try_parse_from([
1712 "passless",
1713 "agent-admin",
1714 "credential",
1715 "delete",
1716 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
1717 ])
1718 .unwrap();
1719 assert!(matches!(
1720 args.command,
1721 Some(Commands::AgentAdmin {
1722 action: AgentAdminAction::Credential {
1723 action: AdminCredentialAction::Delete { confirm: false, .. },
1724 },
1725 ..
1726 })
1727 ));
1728 }
1729
1730 #[cfg(feature = "agent")]
1731 #[test]
1732 fn test_agent_admin_credential_delete_with_confirm() {
1733 let args = Args::try_parse_from([
1734 "passless",
1735 "agent-admin",
1736 "credential",
1737 "delete",
1738 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
1739 "--confirm",
1740 ])
1741 .unwrap();
1742 assert!(matches!(
1743 args.command,
1744 Some(Commands::AgentAdmin {
1745 action: AgentAdminAction::Credential {
1746 action: AdminCredentialAction::Delete { confirm: true, .. },
1747 },
1748 ..
1749 })
1750 ));
1751 }
1752
1753 #[cfg(feature = "agent")]
1754 #[test]
1755 fn test_agent_admin_shutdown_hidden() {
1756 let args =
1757 Args::try_parse_from(["passless", "agent-admin", "shutdown", "--confirm"]).unwrap();
1758 assert!(matches!(
1759 args.command,
1760 Some(Commands::AgentAdmin {
1761 action: AgentAdminAction::Shutdown { confirm: true },
1762 ..
1763 })
1764 ));
1765 }
1766
1767 #[cfg(feature = "agent")]
1768 #[test]
1769 fn test_agent_admin_output_default_json() {
1770 let args = Args::try_parse_from(["passless", "agent-admin", "profile", "list"]).unwrap();
1771 match args.command {
1772 Some(Commands::AgentAdmin { output, .. }) => {
1773 assert_eq!(output, OutputFormat::Json);
1774 }
1775 _ => panic!("expected AgentAdmin command"),
1776 }
1777 }
1778
1779 #[cfg(feature = "agent")]
1780 #[test]
1781 fn test_agent_admin_output_plain() {
1782 let args = Args::try_parse_from([
1783 "passless",
1784 "agent-admin",
1785 "--output",
1786 "plain",
1787 "profile",
1788 "list",
1789 ])
1790 .unwrap();
1791 match args.command {
1792 Some(Commands::AgentAdmin { output, .. }) => {
1793 assert_eq!(output, OutputFormat::Plain);
1794 }
1795 _ => panic!("expected AgentAdmin command"),
1796 }
1797 }
1798
1799 #[cfg(feature = "agent")]
1800 #[test]
1801 fn test_agent_doctor_parses() {
1802 let args = Args::try_parse_from(["passless", "agent", "doctor"]).unwrap();
1803 assert!(matches!(
1804 args.command,
1805 Some(Commands::Agent {
1806 action: AgentCommand::Doctor,
1807 ..
1808 })
1809 ));
1810 }
1811
1812 #[cfg(feature = "agent")]
1813 #[test]
1814 fn test_agent_run_with_command() {
1815 let args = Args::try_parse_from([
1816 "passless",
1817 "agent",
1818 "run",
1819 "--profile",
1820 "myprofile",
1821 "--",
1822 "/usr/bin/test",
1823 "arg1",
1824 ])
1825 .unwrap();
1826 match args.command {
1827 Some(Commands::Agent {
1828 action: AgentCommand::Run { profile, command },
1829 ..
1830 }) => {
1831 assert_eq!(profile, "myprofile");
1832 assert_eq!(command.len(), 2);
1833 }
1834 _ => panic!("expected Agent Run command"),
1835 }
1836 }
1837
1838 #[cfg(feature = "agent")]
1839 #[test]
1840 fn test_agent_intent_create_parses() {
1841 let args = Args::try_parse_from([
1842 "passless",
1843 "agent",
1844 "intent",
1845 "create",
1846 "register",
1847 "--rp",
1848 "example.com",
1849 ])
1850 .unwrap();
1851 assert!(matches!(
1852 args.command,
1853 Some(Commands::Agent {
1854 action: AgentCommand::Intent {
1855 action: AgentIntentAction::Create {
1856 action: AgentIntentActionType::Register,
1857 ..
1858 },
1859 },
1860 ..
1861 })
1862 ));
1863 }
1864
1865 #[cfg(feature = "agent")]
1866 #[test]
1867 fn test_agent_output_default_json() {
1868 let args = Args::try_parse_from(["passless", "agent", "doctor"]).unwrap();
1869 match args.command {
1870 Some(Commands::Agent { output, .. }) => {
1871 assert_eq!(output, OutputFormat::Json);
1872 }
1873 _ => panic!("expected Agent command"),
1874 }
1875 }
1876
1877 #[cfg(feature = "agent")]
1878 #[test]
1879 fn test_shell_completions_contain_agent_commands() {
1880 use clap::CommandFactory;
1881
1882 let cmd = Args::command();
1883 let mut buf = Vec::new();
1884 clap_complete::generate(
1885 clap_complete::Shell::Bash,
1886 &mut cmd.clone(),
1887 "passless",
1888 &mut buf,
1889 );
1890 let completion = String::from_utf8(buf).unwrap();
1891
1892 for expected in [
1893 "agent-admin",
1894 "agent",
1895 "install",
1896 "browser-control",
1897 "intent",
1898 "delegation",
1899 "doctor",
1900 "capabilities",
1901 "instructions",
1902 ] {
1903 assert!(
1904 completion.contains(expected),
1905 "bash completion missing '{}'",
1906 expected
1907 );
1908 }
1909 }
1910
1911 #[cfg(feature = "agent")]
1912 #[test]
1913 fn test_shell_completions_zsh_contain_agent_commands() {
1914 use clap::CommandFactory;
1915
1916 let cmd = Args::command();
1917 let mut buf = Vec::new();
1918 clap_complete::generate(
1919 clap_complete::Shell::Zsh,
1920 &mut cmd.clone(),
1921 "passless",
1922 &mut buf,
1923 );
1924 let completion = String::from_utf8(buf).unwrap();
1925
1926 for expected in ["agent-admin", "agent", "install", "browser-control"] {
1927 assert!(
1928 completion.contains(expected),
1929 "zsh completion missing '{}'",
1930 expected
1931 );
1932 }
1933 }
1934
1935 #[cfg(feature = "agent")]
1936 #[test]
1937 fn test_config_print_includes_agent_fields() {
1938 let mut default_args = Args::parse_from(["passless"]);
1939 let config = AppConfig::from(&mut default_args.config);
1940 let toml_output = config.to_toml_with_comments();
1941
1942 assert!(
1943 toml_output.contains("backend_type"),
1944 "config print missing backend_type"
1945 );
1946 assert!(
1947 toml_output.contains("[security]"),
1948 "config print missing [security] section"
1949 );
1950 assert!(
1951 toml_output.contains("[pin]"),
1952 "config print missing [pin] section"
1953 );
1954 assert!(
1955 toml_output.contains("always_uv"),
1956 "config print missing always_uv"
1957 );
1958 assert!(
1959 toml_output.contains("notification_timeout"),
1960 "config print missing notification_timeout"
1961 );
1962 }
1963
1964 #[test]
1965 fn test_config_print_contains_passless_header() {
1966 let mut default_args = Args::parse_from(["passless"]);
1967 let config = AppConfig::from(&mut default_args.config);
1968 let toml_output = config.to_toml_with_comments();
1969
1970 assert!(toml_output.contains("Passless Configuration File"));
1971 assert!(toml_output.contains("~/.config/passless/config.toml"));
1972 }
1973
1974 #[test]
1975 fn test_config_print_contains_local_backend_section() {
1976 let mut default_args = Args::parse_from(["passless"]);
1977 let config = AppConfig::from(&mut default_args.config);
1978 let toml_output = config.to_toml_with_comments();
1979
1980 assert!(toml_output.contains("[local]"));
1981 assert!(toml_output.contains("path"));
1982 }
1983
1984 #[test]
1985 fn test_config_print_contains_pass_backend_section() {
1986 let mut default_args = Args::parse_from(["passless"]);
1987 let config = AppConfig::from(&mut default_args.config);
1988 let toml_output = config.to_toml_with_comments();
1989
1990 assert!(toml_output.contains("[pass]"));
1991 assert!(toml_output.contains("store_path"));
1992 assert!(toml_output.contains("gpg_backend"));
1993 }
1994}