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 load(args: &mut Args) -> crate::error::Result<Self> {
633 let default_config_path = dirs::config_dir().map(|p| p.join("passless/config.toml"));
634
635 let config_file_path = args
636 .config_path
637 .as_ref()
638 .or(default_config_path.as_ref())
639 .filter(|p| p.exists());
640
641 if let Some(path) = config_file_path
642 && let Ok(f) = File::open(path)
643 {
644 log::info!("Loading configuration from: {}", path.display());
645 let content = std::io::read_to_string(BufReader::new(f)).unwrap_or_default();
646
647 #[cfg(feature = "agent")]
648 let agent_config = {
649 match toml::from_str::<toml::Table>(&content) {
650 Ok(table) => match table.get("agents") {
651 Some(agents_value) => serde::Deserialize::deserialize(agents_value.clone())
652 .map_err(|e| {
653 Error::Config(format!(
654 "failed to parse [agents] section in {}: {}",
655 path.display(),
656 e
657 ))
658 })?,
659 None => AgentConfig::default(),
660 },
661 Err(e) => {
662 return Err(Error::Config(format!(
663 "failed to parse config file {} as TOML: {}",
664 path.display(),
665 e
666 )));
667 }
668 }
669 };
670
671 match toml::from_str::<<AppConfig as ClapSerde>::Opt>(&content) {
672 Ok(file_config) => {
673 #[allow(unused_mut)]
674 let mut config = AppConfig::from(file_config).merge(&mut args.config);
675 #[cfg(feature = "agent")]
676 {
677 config.agents = agent_config;
678 }
679 return Ok(config);
680 }
681 Err(e) => {
682 return Err(Error::Config(format!(
683 "failed to parse config file {}: {}",
684 path.display(),
685 e
686 )));
687 }
688 }
689 }
690
691 #[allow(unused_mut)]
692 let mut config = AppConfig::from(&mut args.config);
693 #[cfg(feature = "agent")]
694 {
695 config.agents = AgentConfig::default();
696 }
697 Ok(config)
698 }
699
700 pub fn backend(&self) -> crate::error::Result<BackendConfig> {
702 match self.backend_type.as_str() {
703 "local" => Ok(BackendConfig::Local {
704 path: self.local.path.clone(),
705 }),
706 "pass" => Ok(BackendConfig::Pass {
707 store_path: self.pass.store_path.clone(),
708 path: self.pass.path.clone(),
709 gpg_backend: self.pass.gpg_backend.clone(),
710 }),
711 #[cfg(feature = "tpm")]
712 "tpm" => Ok(BackendConfig::Tpm {
713 path: self.tpm.path.clone(),
714 tcti: self.tpm.tcti.clone(),
715 portable: self.tpm.portable,
716 }),
717 _ => Err(crate::error::Error::Config(format!(
718 "Invalid backend_type '{}'. Must be one of: local, pass, tpm",
719 self.backend_type
720 ))),
721 }
722 }
723
724 pub fn apply_security_hardening(&self) -> Result<(), Box<dyn std::error::Error>> {
726 self.security.apply_hardening()
727 }
728
729 pub fn security_config(&self) -> SecurityConfig {
731 self.security.clone()
732 }
733
734 pub fn pin_config(&self) -> PinConfig {
736 self.pin.clone()
737 }
738
739 pub fn validate(&self) -> crate::error::Result<()> {
741 self.pin.validate()?;
742 #[cfg(feature = "agent")]
743 {
744 let human_path = self.backend().ok().map(|b| b.state_path());
745 self.agents.validate(human_path.as_deref())?;
746 }
747 Ok(())
748 }
749}
750
751#[derive(Parser)]
753#[command(author, version, about)]
754pub struct Args {
755 #[arg(short, long, env = "PASSLESS_CONFIG")]
757 pub config_path: Option<PathBuf>,
758
759 #[command(flatten)]
761 pub config: <AppConfig as ClapSerde>::Opt,
762
763 #[command(subcommand)]
765 pub command: Option<Commands>,
766}
767
768#[derive(Debug, Clone, Copy, PartialEq, Eq)]
770pub enum OutputFormat {
771 Plain,
773 Json,
775}
776
777impl std::str::FromStr for OutputFormat {
778 type Err = String;
779
780 fn from_str(s: &str) -> Result<Self, Self::Err> {
781 match s.to_lowercase().as_str() {
782 "plain" => Ok(OutputFormat::Plain),
783 "json" => Ok(OutputFormat::Json),
784 _ => Err(format!(
785 "Invalid output format '{}'. Must be 'plain' or 'json'",
786 s
787 )),
788 }
789 }
790}
791
792impl std::fmt::Display for OutputFormat {
793 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
794 match self {
795 OutputFormat::Plain => write!(f, "plain"),
796 OutputFormat::Json => write!(f, "json"),
797 }
798 }
799}
800
801#[derive(Subcommand, Debug, Clone)]
803pub enum Commands {
804 Config {
806 #[command(subcommand)]
807 action: ConfigAction,
808 },
809 Client {
815 #[arg(short = 'D', long = "device", value_name = "INDEX|NAME", global = true)]
817 device: Option<String>,
818
819 #[arg(
821 short = 'o',
822 long = "output",
823 value_name = "FORMAT",
824 default_value = "plain",
825 global = true
826 )]
827 output: OutputFormat,
828
829 #[command(subcommand)]
830 action: ClientAction,
831 },
832 #[cfg(feature = "agent")]
834 AgentAdmin {
835 #[arg(
837 short = 'o',
838 long = "output",
839 value_name = "FORMAT",
840 default_value = "json",
841 global = true
842 )]
843 output: OutputFormat,
844
845 #[command(subcommand)]
846 action: AgentAdminAction,
847 },
848 #[cfg(feature = "agent")]
850 Agent {
851 #[arg(long, value_name = "PROFILE", global = true)]
853 profile: Option<String>,
854
855 #[arg(
857 short = 'o',
858 long = "output",
859 value_name = "FORMAT",
860 default_value = "json",
861 global = true
862 )]
863 output: OutputFormat,
864
865 #[command(subcommand)]
866 action: crate::AgentCommand,
867 },
868 #[cfg(feature = "tpm")]
870 Tpm {
871 #[command(subcommand)]
872 action: TpmAction,
873 },
874}
875
876#[cfg(feature = "tpm")]
878#[derive(Subcommand, Debug, Clone)]
879pub enum TpmAction {
880 #[command(group(clap::ArgGroup::new("seed-source").args(["generate", "seed_file", "seed_stdin"])))]
882 Provision {
883 #[arg(long)]
885 generate: bool,
886 #[arg(long = "seed-file", value_name = "PATH")]
888 seed_file: Option<PathBuf>,
889 #[arg(long = "seed-stdin")]
891 seed_stdin: bool,
892 #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
894 path: Option<String>,
895 #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
897 tcti: Option<String>,
898 },
899 Status {
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 Remove {
910 #[arg(long)]
912 confirm: bool,
913 #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
915 path: Option<String>,
916 #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
918 tcti: Option<String>,
919 },
920 #[command(group(clap::ArgGroup::new("selection").args(["credential_id", "all"]).required(true)))]
922 Migrate {
923 #[arg(long = "credential-id", value_name = "ID")]
925 credential_id: Option<String>,
926 #[arg(long)]
928 all: bool,
929 #[arg(long)]
931 dry_run: bool,
932 #[arg(long = "backup-dir", value_name = "PATH")]
934 backup_dir: Option<String>,
935 #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
937 path: Option<String>,
938 #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
940 tcti: Option<String>,
941 },
942}
943
944#[derive(Subcommand, Debug, Clone)]
946pub enum ConfigAction {
947 Print,
949}
950
951#[cfg(feature = "agent")]
953#[derive(Subcommand, Debug, Clone)]
954pub enum AgentAdminAction {
955 Install {
957 #[arg(value_enum, default_value_t = AgentSkillTarget::Auto)]
959 target: AgentSkillTarget,
960
961 #[arg(long, value_enum, default_value_t = AgentSkillScope::User)]
963 scope: AgentSkillScope,
964
965 #[arg(long)]
967 force: bool,
968 },
969 InstallNativeMessaging {
971 #[arg(long)]
973 browser: String,
974
975 #[arg(long)]
977 ext_dir: PathBuf,
978
979 #[arg(long, default_value = "/usr/bin/sign-proxy")]
981 sign_proxy: PathBuf,
982 },
983 Profile {
985 #[command(subcommand)]
986 action: AdminProfileAction,
987 },
988 Policy {
990 #[command(subcommand)]
991 action: AdminPolicyAction,
992 },
993 Credential {
995 #[command(subcommand)]
996 action: AdminCredentialAction,
997 },
998 Delegation {
1000 #[command(subcommand)]
1001 action: AdminDelegationAction,
1002 },
1003 Session {
1005 #[command(subcommand)]
1006 action: AdminSessionAction,
1007 },
1008 Browser {
1010 #[command(subcommand)]
1011 action: AdminBrowserAction,
1012 },
1013 Audit {
1015 #[command(subcommand)]
1016 action: AdminAuditAction,
1017 },
1018 #[command(hide = true)]
1020 Shutdown {
1021 #[arg(long)]
1023 confirm: bool,
1024 },
1025}
1026
1027#[cfg(feature = "agent")]
1029#[derive(Subcommand, Debug, Clone)]
1030pub enum AdminProfileAction {
1031 Check {
1033 #[arg(value_name = "PROFILE")]
1035 profile: String,
1036 },
1037 Show {
1039 #[arg(value_name = "PROFILE")]
1041 profile: String,
1042 },
1043 List,
1045 Enable {
1047 #[arg(value_name = "PROFILE")]
1049 profile: String,
1050 },
1051 Disable {
1053 #[arg(value_name = "PROFILE")]
1055 profile: String,
1056 },
1057}
1058
1059#[cfg(feature = "agent")]
1061#[derive(Subcommand, Debug, Clone)]
1062pub enum AdminPolicyAction {
1063 Check {
1065 #[arg(value_name = "PROFILE")]
1067 profile: String,
1068 },
1069 Reload {
1071 #[arg(value_name = "PROFILE")]
1073 profile: String,
1074 },
1075 Show {
1077 #[arg(value_name = "PROFILE")]
1079 profile: String,
1080 },
1081}
1082
1083#[cfg(feature = "agent")]
1085#[derive(Subcommand, Debug, Clone)]
1086pub enum AdminCredentialAction {
1087 List {
1089 #[arg(short = 'd', long = "domain", value_name = "DOMAIN")]
1091 rp_id: Option<String>,
1092 },
1093 Show {
1095 #[arg(value_name = "CREDENTIAL_REF")]
1097 credential_ref: String,
1098 },
1099 Revoke {
1101 #[arg(value_name = "CREDENTIAL_REF")]
1103 credential_ref: String,
1104 #[arg(long)]
1106 confirm: bool,
1107 },
1108 Delete {
1110 #[arg(value_name = "CREDENTIAL_REF")]
1112 credential_ref: String,
1113 #[arg(long)]
1115 confirm: bool,
1116 },
1117}
1118
1119#[cfg(feature = "agent")]
1121#[derive(Subcommand, Debug, Clone)]
1122pub enum AdminDelegationAction {
1123 Show {
1125 #[arg(value_name = "GRANT_ID")]
1127 grant_id: String,
1128 },
1129 List {
1131 #[arg(long, value_name = "PROFILE")]
1133 profile: Option<String>,
1134 },
1135 Revoke {
1137 #[arg(value_name = "GRANT_ID")]
1139 grant_id: String,
1140 #[arg(long)]
1142 confirm: bool,
1143 },
1144 RequestRegistration {
1146 #[arg(long, value_name = "PROFILE")]
1148 profile: String,
1149 #[arg(long, value_name = "RP_ID")]
1151 rp: String,
1152 #[arg(long, value_name = "SECONDS")]
1154 session_ttl: u64,
1155 #[arg(long, value_name = "REASON")]
1157 reason: Option<String>,
1158 },
1159}
1160
1161#[cfg(feature = "agent")]
1163#[derive(Subcommand, Debug, Clone)]
1164pub enum AdminSessionAction {
1165 Show {
1167 #[arg(value_name = "SESSION_ID")]
1169 session_id: String,
1170 },
1171 List {
1173 #[arg(long, value_name = "PROFILE")]
1175 profile: Option<String>,
1176 },
1177 Revoke {
1179 #[arg(value_name = "SESSION_ID")]
1181 session_id: String,
1182 #[arg(long)]
1184 confirm: bool,
1185 },
1186}
1187
1188#[cfg(feature = "agent")]
1190#[derive(Subcommand, Debug, Clone)]
1191pub enum AdminBrowserAction {
1192 Launch {
1194 #[arg(long, value_name = "PROFILE")]
1196 profile: String,
1197 #[arg(long, value_name = "URL")]
1199 url: Option<String>,
1200 },
1201}
1202
1203#[cfg(feature = "agent")]
1205#[derive(Subcommand, Debug, Clone)]
1206pub enum AdminAuditAction {
1207 Status,
1209 Verify,
1211 Export {
1213 #[arg(long, value_enum, default_value_t = AdminAuditExportFormat::Json)]
1215 format: AdminAuditExportFormat,
1216 },
1217}
1218
1219#[cfg(feature = "agent")]
1221#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1222pub enum AdminAuditExportFormat {
1223 Json,
1224 Csv,
1225}
1226
1227#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1229pub enum AgentSkillTarget {
1230 Auto,
1231 Opencode,
1232 Claude,
1233 Pi,
1234}
1235
1236#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1238pub enum AgentSkillScope {
1239 User,
1240 Project,
1241}
1242
1243#[derive(Subcommand, Debug, Clone)]
1245pub enum ClientAction {
1246 Devices,
1248 Info,
1250 Reset {
1252 #[arg(long = "yes-i-really-want-to-reset-my-device", action = ArgAction::Count)]
1254 confirm: u8,
1255 },
1256 List {
1258 #[arg(short = 'd', long = "domain", value_name = "DOMAIN")]
1260 rp_id: Option<String>,
1261 },
1262 Show {
1264 #[arg(value_name = "CREDENTIAL_ID")]
1266 credential_id: String,
1267 },
1268 Delete {
1270 #[arg(value_name = "CREDENTIAL_ID")]
1272 credential_id: String,
1273 },
1274 Rename {
1276 #[arg(value_name = "CREDENTIAL_ID")]
1278 credential_id: String,
1279 #[arg(short = 'u', long = "user-name", value_name = "NAME")]
1281 user_name: Option<String>,
1282 #[arg(short = 'n', long = "display-name", value_name = "NAME")]
1284 display_name: Option<String>,
1285 },
1286 Backup {
1288 #[arg(value_name = "CREDENTIAL_ID")]
1290 credential_id: String,
1291 #[arg(long, value_name = "RECIPIENT")]
1293 recipient: String,
1294 #[arg(long, value_name = "PATH")]
1296 output_file: PathBuf,
1297 #[arg(long = "yes-i-understand-this-exports-a-passkey")]
1299 confirm: bool,
1300 },
1301 Restore {
1303 #[arg(value_name = "PATH")]
1305 input_file: PathBuf,
1306 #[arg(long)]
1308 replace: bool,
1309 #[arg(long = "yes-i-understand-this-restores-a-passkey")]
1311 confirm: bool,
1312 },
1313 Pin {
1315 #[command(subcommand)]
1316 action: PinAction,
1317 },
1318}
1319
1320#[derive(Subcommand, Debug, Clone)]
1322pub enum PinAction {
1323 Set {
1325 #[arg(value_name = "PIN")]
1327 pin: String,
1328 },
1329 Change {
1331 #[arg(value_name = "OLD_PIN")]
1333 old_pin: String,
1334 #[arg(value_name = "NEW_PIN")]
1336 new_pin: String,
1337 },
1338 UvReset,
1340}
1341
1342#[cfg(feature = "agent")]
1344#[derive(Subcommand, Debug, Clone)]
1345pub enum AgentCommand {
1346 Doctor,
1348 Capabilities,
1350 Instructions,
1352 Intent {
1354 #[command(subcommand)]
1355 action: AgentIntentAction,
1356 },
1357 Delegation {
1359 #[command(subcommand)]
1360 action: AgentDelegationAction,
1361 },
1362 Credential {
1364 #[command(subcommand)]
1365 action: AgentCredentialAction,
1366 },
1367 BrowserStatus,
1369 EndpointStatus,
1371 BrowserControl {
1377 #[arg(long, value_name = "JSON", conflicts_with = "request_file")]
1379 request: Option<String>,
1380 #[arg(long, value_name = "PATH", conflicts_with = "request")]
1382 request_file: Option<std::path::PathBuf>,
1383 #[arg(long, value_name = "MS", default_value = "5000")]
1385 timeout_ms: u32,
1386 },
1387 PlaywrightMcp {
1389 #[arg(long, value_name = "PROFILE")]
1391 profile: String,
1392 #[arg(long, value_name = "URL")]
1394 url: Option<String>,
1395 #[arg(last = true, required = true)]
1397 command: Vec<std::path::PathBuf>,
1398 },
1399 Run {
1401 #[arg(long, value_name = "PROFILE")]
1403 profile: String,
1404 #[arg(last = true, required = true)]
1406 command: Vec<std::path::PathBuf>,
1407 },
1408}
1409
1410#[cfg(feature = "agent")]
1412#[derive(Subcommand, Debug, Clone)]
1413pub enum AgentIntentAction {
1414 Create {
1416 #[arg(value_enum)]
1418 action: AgentIntentActionType,
1419 #[arg(long, value_name = "RP_ID")]
1421 rp: String,
1422 #[arg(long, value_name = "CREDENTIAL_REF")]
1424 credential: Option<String>,
1425 #[arg(long, value_name = "REASON")]
1427 reason: Option<String>,
1428 },
1429 Show {
1431 #[arg(value_name = "REQUEST_ID")]
1433 request_id: String,
1434 },
1435 Wait {
1437 #[arg(value_name = "REQUEST_ID")]
1439 request_id: String,
1440 #[arg(long, value_name = "SECONDS")]
1442 timeout: Option<u64>,
1443 #[arg(long, value_name = "MS")]
1445 poll_interval: Option<u64>,
1446 },
1447 Cancel {
1449 #[arg(value_name = "REQUEST_ID")]
1451 request_id: String,
1452 },
1453}
1454
1455#[cfg(feature = "agent")]
1457#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1458pub enum AgentIntentActionType {
1459 Register,
1460 Authenticate,
1461}
1462
1463#[cfg(feature = "agent")]
1465#[derive(Subcommand, Debug, Clone)]
1466pub enum AgentDelegationAction {
1467 Request {
1469 #[arg(long, value_name = "RP_ID")]
1471 rp: String,
1472 #[arg(long, value_name = "CREDENTIAL_REF")]
1474 credential: String,
1475 #[arg(long, value_name = "SECONDS")]
1477 session_ttl: u64,
1478 #[arg(long, value_name = "REASON")]
1480 reason: Option<String>,
1481 },
1482 Show {
1484 #[arg(value_name = "REQUEST_ID")]
1486 request_id: String,
1487 },
1488 Wait {
1490 #[arg(value_name = "REQUEST_ID")]
1492 request_id: String,
1493 #[arg(long, value_name = "SECONDS")]
1495 timeout: Option<u64>,
1496 #[arg(long, value_name = "MS")]
1498 poll_interval: Option<u64>,
1499 },
1500 Cancel {
1502 #[arg(value_name = "REQUEST_ID")]
1504 request_id: String,
1505 },
1506}
1507
1508#[cfg(feature = "agent")]
1510#[derive(Subcommand, Debug, Clone)]
1511pub enum AgentCredentialAction {
1512 List,
1514 Show {
1516 #[arg(value_name = "CREDENTIAL_REF")]
1518 credential_ref: String,
1519 },
1520}
1521
1522#[cfg(test)]
1523mod tests {
1524 use super::*;
1525
1526 #[cfg(feature = "agent")]
1527 #[test]
1528 fn test_agent_admin_install_defaults() {
1529 let args = Args::try_parse_from(["passless", "agent-admin", "install"]).unwrap();
1530 assert!(matches!(
1531 args.command,
1532 Some(Commands::AgentAdmin {
1533 action: AgentAdminAction::Install {
1534 target: AgentSkillTarget::Auto,
1535 scope: AgentSkillScope::User,
1536 force: false,
1537 },
1538 ..
1539 })
1540 ));
1541 }
1542
1543 #[cfg(feature = "agent")]
1544 #[test]
1545 fn test_agent_admin_install_explicit_options() {
1546 let args = Args::try_parse_from([
1547 "passless",
1548 "agent-admin",
1549 "install",
1550 "claude",
1551 "--scope",
1552 "project",
1553 "--force",
1554 ])
1555 .unwrap();
1556 assert!(matches!(
1557 args.command,
1558 Some(Commands::AgentAdmin {
1559 action: AgentAdminAction::Install {
1560 target: AgentSkillTarget::Claude,
1561 scope: AgentSkillScope::Project,
1562 force: true,
1563 },
1564 ..
1565 })
1566 ));
1567 }
1568
1569 #[test]
1570 fn test_pin_config_default_max_uv_retries() {
1571 let config = PinConfig {
1572 enforcement: PinEnforcement::Optional,
1573 min_length: 4,
1574 max_retries: 8,
1575 max_uv_retries: 8,
1576 auto_lock_timeout: 0,
1577 };
1578 assert_eq!(config.max_uv_retries, 8);
1579 }
1580
1581 #[test]
1582 fn test_pin_config_validate_success() {
1583 let config = PinConfig {
1584 enforcement: PinEnforcement::Optional,
1585 min_length: 4,
1586 max_retries: 8,
1587 max_uv_retries: 8,
1588 auto_lock_timeout: 0,
1589 };
1590 assert!(config.validate().is_ok());
1591 }
1592
1593 #[test]
1594 fn test_pin_config_validate_zero_max_uv_retries() {
1595 let config = PinConfig {
1596 enforcement: PinEnforcement::Optional,
1597 min_length: 4,
1598 max_retries: 8,
1599 max_uv_retries: 0,
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_uv_retries"));
1605 }
1606
1607 #[test]
1608 fn test_pin_config_validate_zero_max_retries() {
1609 let config = PinConfig {
1610 enforcement: PinEnforcement::Optional,
1611 min_length: 4,
1612 max_retries: 0,
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("max_retries"));
1619 }
1620
1621 #[test]
1622 fn test_pin_config_validate_invalid_min_length() {
1623 let config = PinConfig {
1624 enforcement: PinEnforcement::Optional,
1625 min_length: 3,
1626 max_retries: 8,
1627 max_uv_retries: 8,
1628 auto_lock_timeout: 0,
1629 };
1630 let result = config.validate();
1631 assert!(result.is_err());
1632 assert!(result.unwrap_err().to_string().contains("min_length"));
1633 }
1634
1635 #[test]
1636 fn test_canonicalize_path_existing() {
1637 let dir = std::env::temp_dir();
1638 let canonical = BackendConfig::canonicalize_path(&dir);
1639 assert!(canonical.is_absolute());
1640 assert!(canonical.exists());
1641 }
1642
1643 #[test]
1644 fn test_canonicalize_path_nonexistent() {
1645 let base = std::env::temp_dir();
1646 let nonexistent = base.join("passless_test_nonexistent_dir_12345/sub");
1647 let canonical = BackendConfig::canonicalize_path(&nonexistent);
1648 assert!(canonical.is_absolute());
1649 assert!(canonical.starts_with(BackendConfig::canonicalize_path(&base)));
1650 }
1651
1652 #[test]
1653 fn test_canonicalize_path_symlink() {
1654 let dir = tempfile::tempdir().unwrap();
1655 let real = dir.path().join("real");
1656 std::fs::create_dir(&real).unwrap();
1657 let link = dir.path().join("link");
1658 std::os::unix::fs::symlink(&real, &link).unwrap();
1659
1660 let canonical_real = BackendConfig::canonicalize_path(&real);
1661 let canonical_link = BackendConfig::canonicalize_path(&link);
1662 assert_eq!(canonical_real, canonical_link);
1663 }
1664
1665 #[test]
1666 fn test_local_state_path_relative_and_absolute() {
1667 let dir = tempfile::tempdir_in(".").unwrap();
1668 let abs_path = std::fs::canonicalize(dir.path()).unwrap();
1669 let rel_path = dir.path().to_path_buf();
1670
1671 let backend_abs = BackendConfig::Local {
1672 path: abs_path.display().to_string(),
1673 };
1674 let backend_rel = BackendConfig::Local {
1675 path: rel_path.display().to_string(),
1676 };
1677 assert_eq!(backend_abs.state_path(), backend_rel.state_path());
1678 }
1679
1680 #[test]
1681 fn test_pass_state_path_different_subpaths() {
1682 let store = "/tmp/passless_test_store";
1683 let backend_a = BackendConfig::Pass {
1684 store_path: store.to_string(),
1685 path: "fido2".to_string(),
1686 gpg_backend: "gnupg-bin".to_string(),
1687 };
1688 let backend_b = BackendConfig::Pass {
1689 store_path: store.to_string(),
1690 path: "fido2-other".to_string(),
1691 gpg_backend: "gnupg-bin".to_string(),
1692 };
1693 assert_ne!(backend_a.state_path(), backend_b.state_path());
1694 }
1695
1696 #[test]
1697 fn test_different_local_paths_produce_different_identities() {
1698 let backend_a = BackendConfig::Local {
1699 path: "/tmp/passless_a".to_string(),
1700 };
1701 let backend_b = BackendConfig::Local {
1702 path: "/tmp/passless_b".to_string(),
1703 };
1704 assert_ne!(backend_a.state_path(), backend_b.state_path());
1705 }
1706
1707 #[cfg(feature = "agent")]
1708 #[test]
1709 fn test_agent_admin_profile_list() {
1710 let args = Args::try_parse_from(["passless", "agent-admin", "profile", "list"]).unwrap();
1711 assert!(matches!(
1712 args.command,
1713 Some(Commands::AgentAdmin {
1714 action: AgentAdminAction::Profile {
1715 action: AdminProfileAction::List,
1716 },
1717 ..
1718 })
1719 ));
1720 }
1721
1722 #[cfg(feature = "agent")]
1723 #[test]
1724 fn test_agent_admin_credential_delete_without_confirm() {
1725 let args = Args::try_parse_from([
1726 "passless",
1727 "agent-admin",
1728 "credential",
1729 "delete",
1730 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
1731 ])
1732 .unwrap();
1733 assert!(matches!(
1734 args.command,
1735 Some(Commands::AgentAdmin {
1736 action: AgentAdminAction::Credential {
1737 action: AdminCredentialAction::Delete { confirm: false, .. },
1738 },
1739 ..
1740 })
1741 ));
1742 }
1743
1744 #[cfg(feature = "agent")]
1745 #[test]
1746 fn test_agent_admin_credential_delete_with_confirm() {
1747 let args = Args::try_parse_from([
1748 "passless",
1749 "agent-admin",
1750 "credential",
1751 "delete",
1752 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
1753 "--confirm",
1754 ])
1755 .unwrap();
1756 assert!(matches!(
1757 args.command,
1758 Some(Commands::AgentAdmin {
1759 action: AgentAdminAction::Credential {
1760 action: AdminCredentialAction::Delete { confirm: true, .. },
1761 },
1762 ..
1763 })
1764 ));
1765 }
1766
1767 #[cfg(feature = "agent")]
1768 #[test]
1769 fn test_agent_admin_shutdown_hidden() {
1770 let args =
1771 Args::try_parse_from(["passless", "agent-admin", "shutdown", "--confirm"]).unwrap();
1772 assert!(matches!(
1773 args.command,
1774 Some(Commands::AgentAdmin {
1775 action: AgentAdminAction::Shutdown { confirm: true },
1776 ..
1777 })
1778 ));
1779 }
1780
1781 #[cfg(feature = "agent")]
1782 #[test]
1783 fn test_agent_admin_output_default_json() {
1784 let args = Args::try_parse_from(["passless", "agent-admin", "profile", "list"]).unwrap();
1785 match args.command {
1786 Some(Commands::AgentAdmin { output, .. }) => {
1787 assert_eq!(output, OutputFormat::Json);
1788 }
1789 _ => panic!("expected AgentAdmin command"),
1790 }
1791 }
1792
1793 #[cfg(feature = "agent")]
1794 #[test]
1795 fn test_agent_admin_output_plain() {
1796 let args = Args::try_parse_from([
1797 "passless",
1798 "agent-admin",
1799 "--output",
1800 "plain",
1801 "profile",
1802 "list",
1803 ])
1804 .unwrap();
1805 match args.command {
1806 Some(Commands::AgentAdmin { output, .. }) => {
1807 assert_eq!(output, OutputFormat::Plain);
1808 }
1809 _ => panic!("expected AgentAdmin command"),
1810 }
1811 }
1812
1813 #[cfg(feature = "agent")]
1814 #[test]
1815 fn test_agent_doctor_parses() {
1816 let args = Args::try_parse_from(["passless", "agent", "doctor"]).unwrap();
1817 assert!(matches!(
1818 args.command,
1819 Some(Commands::Agent {
1820 action: AgentCommand::Doctor,
1821 ..
1822 })
1823 ));
1824 }
1825
1826 #[cfg(feature = "agent")]
1827 #[test]
1828 fn test_agent_run_with_command() {
1829 let args = Args::try_parse_from([
1830 "passless",
1831 "agent",
1832 "run",
1833 "--profile",
1834 "myprofile",
1835 "--",
1836 "/usr/bin/test",
1837 "arg1",
1838 ])
1839 .unwrap();
1840 match args.command {
1841 Some(Commands::Agent {
1842 action: AgentCommand::Run { profile, command },
1843 ..
1844 }) => {
1845 assert_eq!(profile, "myprofile");
1846 assert_eq!(command.len(), 2);
1847 }
1848 _ => panic!("expected Agent Run command"),
1849 }
1850 }
1851
1852 #[cfg(feature = "agent")]
1853 #[test]
1854 fn test_agent_intent_create_parses() {
1855 let args = Args::try_parse_from([
1856 "passless",
1857 "agent",
1858 "intent",
1859 "create",
1860 "register",
1861 "--rp",
1862 "example.com",
1863 ])
1864 .unwrap();
1865 assert!(matches!(
1866 args.command,
1867 Some(Commands::Agent {
1868 action: AgentCommand::Intent {
1869 action: AgentIntentAction::Create {
1870 action: AgentIntentActionType::Register,
1871 ..
1872 },
1873 },
1874 ..
1875 })
1876 ));
1877 }
1878
1879 #[cfg(feature = "agent")]
1880 #[test]
1881 fn test_agent_output_default_json() {
1882 let args = Args::try_parse_from(["passless", "agent", "doctor"]).unwrap();
1883 match args.command {
1884 Some(Commands::Agent { output, .. }) => {
1885 assert_eq!(output, OutputFormat::Json);
1886 }
1887 _ => panic!("expected Agent command"),
1888 }
1889 }
1890
1891 #[cfg(feature = "agent")]
1892 #[test]
1893 fn test_shell_completions_contain_agent_commands() {
1894 use clap::CommandFactory;
1895
1896 let cmd = Args::command();
1897 let mut buf = Vec::new();
1898 clap_complete::generate(
1899 clap_complete::Shell::Bash,
1900 &mut cmd.clone(),
1901 "passless",
1902 &mut buf,
1903 );
1904 let completion = String::from_utf8(buf).unwrap();
1905
1906 for expected in [
1907 "agent-admin",
1908 "agent",
1909 "install",
1910 "browser-control",
1911 "intent",
1912 "delegation",
1913 "doctor",
1914 "capabilities",
1915 "instructions",
1916 ] {
1917 assert!(
1918 completion.contains(expected),
1919 "bash completion missing '{}'",
1920 expected
1921 );
1922 }
1923 }
1924
1925 #[cfg(feature = "agent")]
1926 #[test]
1927 fn test_shell_completions_zsh_contain_agent_commands() {
1928 use clap::CommandFactory;
1929
1930 let cmd = Args::command();
1931 let mut buf = Vec::new();
1932 clap_complete::generate(
1933 clap_complete::Shell::Zsh,
1934 &mut cmd.clone(),
1935 "passless",
1936 &mut buf,
1937 );
1938 let completion = String::from_utf8(buf).unwrap();
1939
1940 for expected in ["agent-admin", "agent", "install", "browser-control"] {
1941 assert!(
1942 completion.contains(expected),
1943 "zsh completion missing '{}'",
1944 expected
1945 );
1946 }
1947 }
1948
1949 #[cfg(feature = "agent")]
1950 #[test]
1951 fn test_config_print_includes_agent_fields() {
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!(
1957 toml_output.contains("backend_type"),
1958 "config print missing backend_type"
1959 );
1960 assert!(
1961 toml_output.contains("[security]"),
1962 "config print missing [security] section"
1963 );
1964 assert!(
1965 toml_output.contains("[pin]"),
1966 "config print missing [pin] section"
1967 );
1968 assert!(
1969 toml_output.contains("always_uv"),
1970 "config print missing always_uv"
1971 );
1972 assert!(
1973 toml_output.contains("notification_timeout"),
1974 "config print missing notification_timeout"
1975 );
1976 }
1977
1978 #[test]
1979 fn test_config_print_contains_passless_header() {
1980 let mut default_args = Args::parse_from(["passless"]);
1981 let config = AppConfig::from(&mut default_args.config);
1982 let toml_output = config.to_toml_with_comments();
1983
1984 assert!(toml_output.contains("Passless Configuration File"));
1985 assert!(toml_output.contains("~/.config/passless/config.toml"));
1986 }
1987
1988 #[test]
1989 fn test_config_print_contains_local_backend_section() {
1990 let mut default_args = Args::parse_from(["passless"]);
1991 let config = AppConfig::from(&mut default_args.config);
1992 let toml_output = config.to_toml_with_comments();
1993
1994 assert!(toml_output.contains("[local]"));
1995 assert!(toml_output.contains("path"));
1996 }
1997
1998 #[test]
1999 fn test_config_print_contains_pass_backend_section() {
2000 let mut default_args = Args::parse_from(["passless"]);
2001 let config = AppConfig::from(&mut default_args.config);
2002 let toml_output = config.to_toml_with_comments();
2003
2004 assert!(toml_output.contains("[pass]"));
2005 assert!(toml_output.contains("store_path"));
2006 assert!(toml_output.contains("gpg_backend"));
2007 }
2008
2009 #[test]
2010 fn test_config_print_produces_valid_toml_without_none_literals() {
2011 let mut default_args = Args::parse_from(["passless"]);
2012 let config = AppConfig::from(&mut default_args.config);
2013 let toml_output = config.to_toml_with_comments();
2014
2015 for (line_no, line) in toml_output.lines().enumerate() {
2016 let trimmed = line.trim();
2017 if trimmed.starts_with('#') || trimmed.is_empty() {
2018 continue;
2019 }
2020 assert!(
2021 !trimmed.contains("= None"),
2022 "Line {} contains invalid TOML 'None' literal: {}",
2023 line_no + 1,
2024 line
2025 );
2026 }
2027
2028 let parse_result: Result<toml::Table, _> = toml_output.parse();
2029 assert!(
2030 parse_result.is_ok(),
2031 "Generated TOML is not valid: {:?}",
2032 parse_result.err()
2033 );
2034 }
2035
2036 #[cfg(feature = "agent")]
2037 #[test]
2038 fn test_config_print_comments_out_none_option_fields() {
2039 let mut default_args = Args::parse_from(["passless"]);
2040 let config = AppConfig::from(&mut default_args.config);
2041 let toml_output = config.to_toml_with_comments();
2042
2043 assert!(
2044 toml_output.contains("# audit_path = <not set>"),
2045 "Option::None field 'audit_path' should be commented out, got:\n{}",
2046 toml_output
2047 );
2048 }
2049}