1use std::{
20 path::{Path, PathBuf},
21 process::{Command, Stdio},
22 time::{Duration, Instant},
23};
24
25use anyhow::{bail, Context, Result};
26use serde::{Deserialize, Serialize};
27
28use crate::cli::commands::{
29 DelegateRegistrySignerArgs, MintDeploymentCaArgs, MintRegistryJwtArgs, TrustCommand,
30 VerifyDeploymentArgs,
31};
32
33pub const PIV_ED25519_MIN_FIRMWARE: FirmwareVersion = FirmwareVersion {
35 major: 5,
36 minor: 7,
37 patch: 4,
38};
39
40pub const DEFAULT_PIV_SLOT: &str = "9c";
42
43pub const CEREMONY_MODE_SCHEMA: &str = "hyprstream.deployment-trust-ceremony-mode.v1";
45
46pub const DEV_GRADE_LABEL: &str =
48 "DEV-GRADE — software root, no hardware gating, not for production";
49
50const TOKEN_GATED_GRADE_LABEL: &str = "token-gated deployment root (seed recoverable from bundle)";
55
56const DELEGATION_TTL_SECONDS: u64 = 2_592_000;
58
59const REGISTRY_JWT_TTL_SECONDS: u32 = 3600;
61
62const DETECTION_TIMEOUT: Duration = Duration::from_secs(10);
64
65#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
71pub struct FirmwareVersion {
72 pub major: u8,
73 pub minor: u8,
74 pub patch: u8,
75}
76
77impl FirmwareVersion {
78 #[must_use]
79 pub const fn new(major: u8, minor: u8, patch: u8) -> Self {
80 Self {
81 major,
82 minor,
83 patch,
84 }
85 }
86
87 #[must_use]
89 pub fn parse(text: &str) -> Option<Self> {
90 let mut parts = text.trim().split('.');
91 let major = parts.next()?.parse().ok()?;
92 let minor = parts.next()?.parse().ok()?;
93 let patch = parts.next()?.parse().ok()?;
94 if parts.next().is_some() {
95 return None;
96 }
97 Some(Self::new(major, minor, patch))
98 }
99
100 #[must_use]
102 pub fn supports_piv_ed25519(&self) -> bool {
103 *self >= PIV_ED25519_MIN_FIRMWARE
104 }
105}
106
107impl std::fmt::Display for FirmwareVersion {
108 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109 write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
110 }
111}
112
113#[derive(Clone, Debug, PartialEq, Eq)]
115pub struct DetectedToken {
116 pub model: String,
117 pub firmware: FirmwareVersion,
118 pub serial: String,
119}
120
121impl DetectedToken {
122 #[must_use]
124 pub fn label(&self) -> String {
125 format!(
126 "{} (firmware {}, serial {})",
127 self.model, self.firmware, self.serial
128 )
129 }
130}
131
132#[derive(Clone, Debug, PartialEq, Eq)]
134pub enum DetectionError {
135 ToolMissing { tool: String },
137 Timeout { tool: String, seconds: u64 },
139 Failed { tool: String, detail: String },
141}
142
143impl std::fmt::Display for DetectionError {
144 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
145 match self {
146 Self::ToolMissing { tool } => write!(f, "`{tool}` is not installed"),
147 Self::Timeout { tool, seconds } => {
148 write!(f, "`{tool}` did not answer within {seconds}s")
149 }
150 Self::Failed { tool, detail } => write!(f, "`{tool}` failed: {detail}"),
151 }
152 }
153}
154
155impl std::error::Error for DetectionError {}
156
157pub trait TokenDetector {
162 fn detect(&self) -> Result<Vec<DetectedToken>, DetectionError>;
163}
164
165pub trait AgeYubikeyPlugin {
167 fn generate_identity(&self, name: &str) -> Result<String, DetectionError>;
169 fn export_identity_file(&self, out: &Path) -> Result<(), DetectionError>;
171}
172
173#[derive(Clone, Debug, PartialEq, Eq)]
179pub enum CeremonyMode {
180 HardwarePiv { token: DetectedToken, slot: String },
184 HardwareAgeRecipient { token: DetectedToken },
186 SoftwareDevGrade,
188}
189
190impl CeremonyMode {
191 #[must_use]
192 pub fn is_dev_grade(&self) -> bool {
193 matches!(self, Self::SoftwareDevGrade)
194 }
195
196 #[must_use]
198 pub fn mode_id(&self) -> &'static str {
199 match self {
200 Self::HardwarePiv { .. } => "yubikey-piv",
201 Self::HardwareAgeRecipient { .. } => "yubikey-age-recipient",
202 Self::SoftwareDevGrade => "software-dev-grade",
203 }
204 }
205
206 #[must_use]
207 pub fn grade_label(&self) -> &'static str {
208 if self.is_dev_grade() {
209 DEV_GRADE_LABEL
210 } else {
211 TOKEN_GATED_GRADE_LABEL
212 }
213 }
214
215 #[must_use]
222 pub fn ed25519_confined_to_hardware(&self) -> bool {
223 false
224 }
225
226 #[must_use]
230 pub fn token_gated_signing(&self) -> bool {
231 matches!(self, Self::HardwarePiv { .. })
232 }
233
234 #[must_use]
235 pub fn token(&self) -> Option<&DetectedToken> {
236 match self {
237 Self::HardwarePiv { token, .. } | Self::HardwareAgeRecipient { token } => Some(token),
238 Self::SoftwareDevGrade => None,
239 }
240 }
241}
242
243#[derive(Clone, Debug, PartialEq, Eq)]
245pub enum CeremonyPlan {
246 Skipped { reason: String },
248 Proceed {
250 mode: CeremonyMode,
251 rationale: String,
252 },
253 ChooseToken {
255 tokens: Vec<DetectedToken>,
256 rationale: String,
257 },
258 Blocked { reason: String, remedy: String },
260}
261
262#[derive(Clone, Debug, PartialEq, Eq)]
264pub struct CeremonyRequest {
265 pub enabled: bool,
267 pub interactive: bool,
269 pub force_software: bool,
271 pub serial: Option<String>,
273 pub piv_slot: String,
275}
276
277impl Default for CeremonyRequest {
278 fn default() -> Self {
279 Self {
280 enabled: false,
281 interactive: true,
282 force_software: false,
283 serial: None,
284 piv_slot: DEFAULT_PIV_SLOT.to_owned(),
285 }
286 }
287}
288
289#[must_use]
296pub fn plan_ceremony(
297 request: &CeremonyRequest,
298 detection: &Result<Vec<DetectedToken>, DetectionError>,
299) -> CeremonyPlan {
300 if !request.enabled {
301 return CeremonyPlan::Skipped {
302 reason: "deployment trust not requested; the wizard set up node-local trust only"
303 .to_owned(),
304 };
305 }
306
307 let tokens = match detection {
308 Err(error) => {
309 if request.force_software {
310 return CeremonyPlan::Proceed {
311 mode: CeremonyMode::SoftwareDevGrade,
312 rationale: format!(
313 "token detection failed ({error}) and a software root was explicitly \
314 requested, so the root is {DEV_GRADE_LABEL}"
315 ),
316 };
317 }
318 return CeremonyPlan::Blocked {
319 reason: format!("could not tell whether a hardware token is attached: {error}"),
320 remedy: "install `ykman` (yubikey-manager) and re-run, or pass \
321 --deployment-trust-software to accept a dev-grade software root"
322 .to_owned(),
323 };
324 }
325 Ok(tokens) => tokens,
326 };
327
328 if request.force_software {
329 let rationale = if tokens.is_empty() {
330 format!("a software root was explicitly requested; the root is {DEV_GRADE_LABEL}")
331 } else {
332 format!(
333 "{} hardware token(s) are attached but a software root was explicitly requested; \
334 the root is {DEV_GRADE_LABEL}",
335 tokens.len()
336 )
337 };
338 return CeremonyPlan::Proceed {
339 mode: CeremonyMode::SoftwareDevGrade,
340 rationale,
341 };
342 }
343
344 if tokens.is_empty() {
345 return CeremonyPlan::Proceed {
346 mode: CeremonyMode::SoftwareDevGrade,
347 rationale: format!(
348 "no hardware token is attached, so the root falls back to software recipients: \
349 {DEV_GRADE_LABEL}"
350 ),
351 };
352 }
353
354 let token = match request.serial.as_deref() {
355 Some(serial) => match tokens.iter().find(|token| token.serial == serial) {
356 Some(token) => token,
357 None => {
358 let attached = tokens
359 .iter()
360 .map(|token| token.serial.clone())
361 .collect::<Vec<_>>()
362 .join(", ");
363 return CeremonyPlan::Blocked {
364 reason: format!("no attached token has serial {serial}"),
365 remedy: format!("attached serials are: {attached}"),
366 };
367 }
368 },
369 None => match tokens.split_first() {
370 Some((token, [])) => token,
371 _ => {
372 if request.interactive {
373 return CeremonyPlan::ChooseToken {
374 tokens: tokens.clone(),
375 rationale: format!(
376 "{} hardware tokens are attached; the deployment root must be bound to \
377 exactly one",
378 tokens.len()
379 ),
380 };
381 }
382 let attached = tokens
383 .iter()
384 .map(|token| token.serial.clone())
385 .collect::<Vec<_>>()
386 .join(", ");
387 return CeremonyPlan::Blocked {
388 reason: format!("{} hardware tokens are attached", tokens.len()),
389 remedy: format!(
390 "pass --deployment-trust-serial <SERIAL> to pick one (attached: {attached})"
391 ),
392 };
393 }
394 },
395 };
396
397 select_mode_for_token(request, token)
398}
399
400#[must_use]
405pub fn select_mode_for_token(request: &CeremonyRequest, token: &DetectedToken) -> CeremonyPlan {
406 if !request.interactive {
407 return CeremonyPlan::Blocked {
408 reason: format!(
409 "{} is attached, and a hardware ceremony needs a PIN, a physical touch, and a \
410 break-glass passphrase",
411 token.label()
412 ),
413 remedy: "re-run the wizard without --non-interactive, or pass \
414 --deployment-trust-software to mint a dev-grade software root instead"
415 .to_owned(),
416 };
417 }
418
419 if token.firmware.supports_piv_ed25519() {
420 CeremonyPlan::Proceed {
421 mode: CeremonyMode::HardwarePiv {
422 token: token.clone(),
423 slot: request.piv_slot.clone(),
424 },
425 rationale: format!(
426 "{} runs firmware {} (>= {PIV_ED25519_MIN_FIRMWARE}), so the Ed25519 leg is \
427 imported into PIV slot {} for token-gated signing (PIN + touch). The seed \
428 is stored in the age-encrypted authority bundle and is recoverable by any \
429 bundle recipient — signing convenience is token-gated, not hardware-confined.",
430 token.label(),
431 token.firmware,
432 request.piv_slot
433 ),
434 }
435 } else {
436 CeremonyPlan::Proceed {
437 mode: CeremonyMode::HardwareAgeRecipient {
438 token: token.clone(),
439 },
440 rationale: format!(
441 "{} runs firmware {}, below the {PIV_ED25519_MIN_FIRMWARE} needed for \
442 Ed25519-in-PIV, so the token acts as the age recipient instead: it gates \
443 decryption of the authority bundle, which is briefly in host memory during the \
444 ceremony",
445 token.label(),
446 token.firmware
447 ),
448 }
449 }
450}
451
452#[derive(Clone, Debug, PartialEq, Eq)]
461pub enum BreakGlass {
462 SecondToken { recipient: String },
464 PassphraseEncrypted {
466 identity_file: PathBuf,
467 recipient: String,
468 },
469 PlaintextIdentity {
471 identity_file: PathBuf,
472 recipient: String,
473 },
474}
475
476impl BreakGlass {
477 #[must_use]
478 pub fn recipient(&self) -> &str {
479 match self {
480 Self::SecondToken { recipient }
481 | Self::PassphraseEncrypted { recipient, .. }
482 | Self::PlaintextIdentity { recipient, .. } => recipient,
483 }
484 }
485
486 #[must_use]
487 pub fn kind_id(&self) -> &'static str {
488 match self {
489 Self::SecondToken { .. } => "second-token",
490 Self::PassphraseEncrypted { .. } => "passphrase-encrypted-identity",
491 Self::PlaintextIdentity { .. } => "plaintext-identity",
492 }
493 }
494
495 #[must_use]
496 pub fn is_protected(&self) -> bool {
497 !matches!(self, Self::PlaintextIdentity { .. })
498 }
499}
500
501#[derive(Clone, Copy, Debug, PartialEq, Eq)]
503pub enum PlaintextPolicy {
504 Refuse,
506 AllowedByOverride,
508 AllowedForDevGradeRoot,
510}
511
512pub fn validate_break_glass(
514 break_glass: &BreakGlass,
515 primary_recipient: &str,
516 policy: PlaintextPolicy,
517) -> Result<(), String> {
518 let recipient = break_glass.recipient().trim();
519 if recipient.is_empty() {
520 return Err(
521 "break-glass recipient is empty; paste the `age1…` recipient the backup \
522 identity prints"
523 .to_owned(),
524 );
525 }
526 if !recipient.is_ascii() || recipient.contains(['\n', '\r', '\0']) {
527 return Err(
528 "break-glass recipient contains characters an age recipient cannot hold; \
529 re-copy it without line breaks"
530 .to_owned(),
531 );
532 }
533 if !recipient.starts_with("age1") {
534 return Err(format!(
535 "break-glass value {recipient} is not an age recipient; it must start with `age1`"
536 ));
537 }
538 if recipient == primary_recipient.trim() {
539 return Err(
540 "break-glass recipient is identical to the primary recipient; the root would \
541 then have a single point of loss, which is exactly what the second recipient \
542 exists to prevent"
543 .to_owned(),
544 );
545 }
546 if let BreakGlass::SecondToken { .. } = break_glass {
547 if !recipient.starts_with("age1yubikey1") {
548 return Err(format!(
549 "{recipient} is not an age-plugin-yubikey recipient; a second-token break-glass \
550 recipient starts with `age1yubikey1`"
551 ));
552 }
553 }
554 if !break_glass.is_protected() && policy == PlaintextPolicy::Refuse {
555 return Err(
556 "refusing an unencrypted break-glass identity: a root is exactly as strong as \
557 its weakest recipient, and a bare `age-keygen` file hands the deployment root \
558 to anyone who can read it. Use a second token, or a passphrase-encrypted \
559 identity (`age-keygen | age -p`). Pass \
560 --deployment-trust-allow-plaintext-break-glass only for a throwaway root you \
561 destroy immediately afterwards."
562 .to_owned(),
563 );
564 }
565 Ok(())
566}
567
568#[derive(Clone, Copy, Debug, PartialEq, Eq)]
570pub enum IdentityFileKind {
571 PassphraseEncrypted,
573 PlaintextAgeIdentity,
575 Unconfirmed,
577}
578
579#[must_use]
584pub fn classify_identity_file(contents: &str) -> IdentityFileKind {
585 if contents.contains("AGE-SECRET-KEY-1") {
586 return IdentityFileKind::PlaintextAgeIdentity;
587 }
588 let mut lines = contents.lines();
589 if lines.next().map(str::trim) == Some("age-encryption.org/v1")
590 && lines.any(|line| line.starts_with("-> scrypt "))
591 {
592 return IdentityFileKind::PassphraseEncrypted;
593 }
594 IdentityFileKind::Unconfirmed
595}
596
597#[derive(Clone, Debug, PartialEq, Eq)]
606pub struct CeremonyPaths {
607 dir: PathBuf,
608}
609
610impl CeremonyPaths {
611 pub fn new(dir: impl Into<PathBuf>) -> Result<Self> {
613 let dir = dir.into();
614 if !dir.is_absolute() {
615 bail!(
616 "ceremony directory {} must be an absolute path; the trust commands resolve \
617 bare filenames against the working directory and fail mid-ceremony",
618 dir.display()
619 );
620 }
621 Ok(Self { dir })
622 }
623
624 #[must_use]
625 pub fn dir(&self) -> &Path {
626 &self.dir
627 }
628
629 #[must_use]
630 pub fn public_ca(&self) -> PathBuf {
631 self.dir.join("deployment-ca.hybrid")
632 }
633
634 #[must_use]
635 pub fn authority_key(&self) -> PathBuf {
636 self.dir.join("deployment-ca.age")
637 }
638
639 #[must_use]
640 pub fn authority_log(&self) -> PathBuf {
641 self.dir.join("deployment-authority.log.json")
642 }
643
644 #[must_use]
645 pub fn authority_checkpoint(&self) -> PathBuf {
646 self.dir.join("deployment-authority.head.json")
647 }
648
649 #[must_use]
650 pub fn yubikey_identity(&self) -> PathBuf {
651 self.dir.join("yubikey-identity.txt")
652 }
653
654 #[must_use]
655 pub fn primary_identity(&self) -> PathBuf {
656 self.dir.join("root-primary.key")
657 }
658
659 #[must_use]
660 pub fn break_glass_identity(&self) -> PathBuf {
661 self.dir.join("break-glass.key.age")
662 }
663
664 #[must_use]
665 pub fn online_signer_identity(&self) -> PathBuf {
666 self.dir.join("online-signer.key")
667 }
668
669 #[must_use]
670 pub fn delegated_signer(&self) -> PathBuf {
671 self.dir.join("registry-delegated-signer.age")
672 }
673
674 #[must_use]
675 pub fn delegation(&self) -> PathBuf {
676 self.dir.join("registry-signer.delegation.json")
677 }
678
679 #[must_use]
680 pub fn registry_public_key(&self) -> PathBuf {
681 self.dir.join("registry-service.pub")
682 }
683
684 #[must_use]
685 pub fn registry_jwt(&self) -> PathBuf {
686 self.dir.join("registry-service.jwt")
687 }
688
689 #[must_use]
690 pub fn contract(&self) -> PathBuf {
691 self.dir.join("deployment-trust.contract.json")
692 }
693
694 #[must_use]
695 pub fn mode_record(&self) -> PathBuf {
696 self.dir.join("deployment-trust-mode.json")
697 }
698}
699
700#[derive(Clone, Debug, PartialEq, Eq)]
702pub enum UnlockIdentity {
703 Yubikey(PathBuf),
705 Age(PathBuf),
707}
708
709#[derive(Clone, Debug, PartialEq, Eq)]
711pub struct CeremonyInputs {
712 pub mode: CeremonyMode,
713 pub primary_recipient: String,
715 pub break_glass: BreakGlass,
716 pub unlock_identity: UnlockIdentity,
717 pub signer_recipient: String,
719 pub paths: CeremonyPaths,
720}
721
722pub fn ceremony_commands(inputs: &CeremonyInputs) -> Result<Vec<TrustCommand>> {
728 let policy = if inputs.mode.is_dev_grade() {
729 PlaintextPolicy::AllowedForDevGradeRoot
730 } else {
731 PlaintextPolicy::Refuse
732 };
733 if let Err(reason) =
734 validate_break_glass(&inputs.break_glass, &inputs.primary_recipient, policy)
735 {
736 bail!("{reason}");
737 }
738
739 let (mut recipients, mut yubikey_recipients) = (Vec::new(), Vec::new());
740 for recipient in [
741 inputs.primary_recipient.trim(),
742 inputs.break_glass.recipient().trim(),
743 ] {
744 if recipient.starts_with("age1yubikey1") {
745 yubikey_recipients.push(recipient.to_owned());
746 } else {
747 recipients.push(recipient.to_owned());
748 }
749 }
750
751 let piv_slot = match &inputs.mode {
752 CeremonyMode::HardwarePiv { slot, .. } => Some(slot.clone()),
753 CeremonyMode::HardwareAgeRecipient { .. } | CeremonyMode::SoftwareDevGrade => None,
754 };
755
756 let (identities, yubikey_identities) = match &inputs.unlock_identity {
757 UnlockIdentity::Yubikey(path) => (Vec::new(), vec![path.clone()]),
758 UnlockIdentity::Age(path) => (vec![path.clone()], Vec::new()),
759 };
760
761 Ok(vec![
762 TrustCommand::MintDeploymentCa(MintDeploymentCaArgs {
763 public_ca: inputs.paths.public_ca(),
764 authority_key: inputs.paths.authority_key(),
765 authority_log: inputs.paths.authority_log(),
766 authority_checkpoint: inputs.paths.authority_checkpoint(),
767 recipients,
768 yubikey_recipients,
769 kms_plugin_recipients: Vec::new(),
770 piv_slot,
771 force: false,
772 }),
773 TrustCommand::DelegateRegistrySigner(DelegateRegistrySignerArgs {
774 public_ca: inputs.paths.public_ca(),
775 authority_log: inputs.paths.authority_log(),
776 authority_checkpoint: inputs.paths.authority_checkpoint(),
777 authority_key: inputs.paths.authority_key(),
778 identities: identities.clone(),
779 yubikey_identities: yubikey_identities.clone(),
780 software_recovery: false,
781 signer_recipients: vec![inputs.signer_recipient.trim().to_owned()],
782 delegated_key: inputs.paths.delegated_signer(),
783 delegation: inputs.paths.delegation(),
784 delegation_ttl_seconds: DELEGATION_TTL_SECONDS,
785 force: false,
786 }),
787 TrustCommand::MintRegistryJwt(MintRegistryJwtArgs {
788 public_ca: inputs.paths.public_ca(),
789 authority_key: inputs.paths.authority_key(),
790 identities: vec![inputs.paths.online_signer_identity()],
791 identity_fds: Vec::new(),
792 yubikey_identities: Vec::new(),
793 software_recovery: false,
794 via_delegated_signer: Some(inputs.paths.delegated_signer()),
795 via_delegated_signer_fd: None,
796 delegation: Some(inputs.paths.delegation()),
797 authority_log: inputs.paths.authority_log(),
798 authority_checkpoint: inputs.paths.authority_checkpoint(),
799 root: false,
800 registry_public_key: inputs.paths.registry_public_key(),
801 ttl_seconds: REGISTRY_JWT_TTL_SECONDS,
802 jwt: inputs.paths.registry_jwt(),
803 contract: inputs.paths.contract(),
804 force: false,
805 }),
806 TrustCommand::VerifyDeployment(VerifyDeploymentArgs {
807 public_ca: inputs.paths.public_ca(),
808 jwt: inputs.paths.registry_jwt(),
809 authority_log: inputs.paths.authority_log(),
810 authority_checkpoint: inputs.paths.authority_checkpoint(),
811 contract: Some(inputs.paths.contract()),
812 service_key_attestations: Vec::new(),
813 }),
814 ])
815}
816
817#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
822pub struct CeremonyModeRecord {
823 pub schema: String,
824 pub mode: String,
825 pub grade: String,
826 pub dev_grade: bool,
827 pub ed25519_confined_to_hardware: bool,
828 pub seed_recoverable_from_bundle: bool,
832 pub token_gated_signing: bool,
836 pub token_model: Option<String>,
837 pub token_serial: Option<String>,
838 pub token_firmware: Option<String>,
839 pub piv_slot: Option<String>,
840 pub break_glass: String,
841 pub break_glass_protected: bool,
842 pub rationale: String,
843}
844
845#[must_use]
847pub fn mode_record(
848 mode: &CeremonyMode,
849 break_glass: &BreakGlass,
850 rationale: &str,
851) -> CeremonyModeRecord {
852 let token = mode.token();
853 CeremonyModeRecord {
854 schema: CEREMONY_MODE_SCHEMA.to_owned(),
855 mode: mode.mode_id().to_owned(),
856 grade: mode.grade_label().to_owned(),
857 dev_grade: mode.is_dev_grade(),
858 ed25519_confined_to_hardware: mode.ed25519_confined_to_hardware(),
859 seed_recoverable_from_bundle: true,
860 token_gated_signing: mode.token_gated_signing(),
861 token_model: token.map(|token| token.model.clone()),
862 token_serial: token.map(|token| token.serial.clone()),
863 token_firmware: token.map(|token| token.firmware.to_string()),
864 piv_slot: match mode {
865 CeremonyMode::HardwarePiv { slot, .. } => Some(slot.clone()),
866 CeremonyMode::HardwareAgeRecipient { .. } | CeremonyMode::SoftwareDevGrade => None,
867 },
868 break_glass: break_glass.kind_id().to_owned(),
869 break_glass_protected: break_glass.is_protected(),
870 rationale: rationale.to_owned(),
871 }
872}
873
874#[must_use]
876pub fn required_tools(mode: &CeremonyMode) -> &'static [&'static str] {
877 match mode {
878 CeremonyMode::HardwarePiv { .. } => &["ykman", "yubico-piv-tool", "age-plugin-yubikey"],
879 CeremonyMode::HardwareAgeRecipient { .. } => &["age-plugin-yubikey"],
880 CeremonyMode::SoftwareDevGrade => &["age-keygen", "age"],
881 }
882}
883
884#[must_use]
888pub fn missing_tools(tools: &[&str], probe: impl Fn(&str) -> bool) -> Vec<String> {
889 tools
890 .iter()
891 .filter(|tool| !probe(tool))
892 .map(|tool| (*tool).to_owned())
893 .collect()
894}
895
896#[must_use]
898pub fn tool_on_path(tool: &str) -> bool {
899 let Some(path) = std::env::var_os("PATH") else {
900 return false;
901 };
902 std::env::split_paths(&path).any(|dir| dir.join(tool).is_file())
903}
904
905pub fn parse_ykman_list(stdout: &str) -> Result<Vec<DetectedToken>, DetectionError> {
915 let mut tokens = Vec::new();
916 for line in stdout.lines() {
917 let line = line.trim();
918 if line.is_empty() {
919 continue;
920 }
921 let unreadable = || DetectionError::Failed {
922 tool: "ykman".to_owned(),
923 detail: format!("could not read model, firmware and serial from `{line}`"),
924 };
925 let (model, rest) = line.split_once(" (").ok_or_else(unreadable)?;
926 let (firmware, rest) = rest.split_once(')').ok_or_else(unreadable)?;
927 let firmware = FirmwareVersion::parse(firmware).ok_or_else(unreadable)?;
928 let (_, serial) = rest.split_once("Serial: ").ok_or_else(unreadable)?;
929 let serial = serial.trim();
930 if serial.is_empty() || !serial.chars().all(|c| c.is_ascii_digit()) {
931 return Err(unreadable());
932 }
933 tokens.push(DetectedToken {
934 model: model.trim().to_owned(),
935 firmware,
936 serial: serial.to_owned(),
937 });
938 }
939 Ok(tokens)
940}
941
942#[must_use]
944pub fn parse_age_plugin_recipient(output: &str) -> Option<String> {
945 output
946 .split_whitespace()
947 .find(|word| word.starts_with("age1yubikey1"))
948 .map(str::to_owned)
949}
950
951#[must_use]
953pub fn parse_age_keygen_recipient(output: &str) -> Option<String> {
954 output
955 .split_whitespace()
956 .find(|word| word.starts_with("age1") && !word.starts_with("age1yubikey1"))
957 .map(str::to_owned)
958}
959
960#[derive(Clone, Copy, Debug, Default)]
969pub struct SystemTokenDetector;
970
971impl TokenDetector for SystemTokenDetector {
972 fn detect(&self) -> Result<Vec<DetectedToken>, DetectionError> {
973 if !tool_on_path("ykman") {
974 return Err(DetectionError::ToolMissing {
975 tool: "ykman".to_owned(),
976 });
977 }
978 let stdout = run_with_timeout("ykman", &["list"], DETECTION_TIMEOUT)?;
979 parse_ykman_list(&stdout)
980 }
981}
982
983#[derive(Clone, Copy, Debug, Default)]
985pub struct SystemAgeYubikeyPlugin;
986
987impl AgeYubikeyPlugin for SystemAgeYubikeyPlugin {
988 fn generate_identity(&self, name: &str) -> Result<String, DetectionError> {
989 if !tool_on_path("age-plugin-yubikey") {
990 return Err(DetectionError::ToolMissing {
991 tool: "age-plugin-yubikey".to_owned(),
992 });
993 }
994 let status = Command::new("age-plugin-yubikey")
997 .args(["--generate", "--name"])
998 .arg(name)
999 .args(["--pin-policy", "always", "--touch-policy", "always"])
1000 .stdin(Stdio::inherit())
1001 .stdout(Stdio::inherit())
1002 .stderr(Stdio::inherit())
1003 .status()
1004 .map_err(|error| DetectionError::Failed {
1005 tool: "age-plugin-yubikey".to_owned(),
1006 detail: error.to_string(),
1007 })?;
1008 if !status.success() {
1009 return Err(DetectionError::Failed {
1010 tool: "age-plugin-yubikey".to_owned(),
1011 detail: "identity generation did not complete".to_owned(),
1012 });
1013 }
1014 let listed = run_with_timeout("age-plugin-yubikey", &["--list"], DETECTION_TIMEOUT)?;
1015 parse_age_plugin_recipient(&listed).ok_or_else(|| DetectionError::Failed {
1016 tool: "age-plugin-yubikey".to_owned(),
1017 detail: "no `age1yubikey1…` recipient was listed after generation".to_owned(),
1018 })
1019 }
1020
1021 fn export_identity_file(&self, out: &Path) -> Result<(), DetectionError> {
1022 let identity = run_with_timeout("age-plugin-yubikey", &["--identity"], DETECTION_TIMEOUT)?;
1023 std::fs::write(out, identity).map_err(|error| DetectionError::Failed {
1024 tool: "age-plugin-yubikey".to_owned(),
1025 detail: format!("write identity to {}: {error}", out.display()),
1026 })
1027 }
1028}
1029
1030fn run_with_timeout(tool: &str, args: &[&str], budget: Duration) -> Result<String, DetectionError> {
1032 let mut child = Command::new(tool)
1033 .args(args)
1034 .stdin(Stdio::null())
1035 .stdout(Stdio::piped())
1036 .stderr(Stdio::piped())
1037 .spawn()
1038 .map_err(|error| {
1039 if error.kind() == std::io::ErrorKind::NotFound {
1040 DetectionError::ToolMissing {
1041 tool: tool.to_owned(),
1042 }
1043 } else {
1044 DetectionError::Failed {
1045 tool: tool.to_owned(),
1046 detail: error.to_string(),
1047 }
1048 }
1049 })?;
1050
1051 let started = Instant::now();
1052 loop {
1053 match child.try_wait() {
1054 Ok(Some(_)) => break,
1055 Ok(None) => {
1056 if started.elapsed() >= budget {
1057 let _ = child.kill();
1058 let _ = child.wait();
1059 return Err(DetectionError::Timeout {
1060 tool: tool.to_owned(),
1061 seconds: budget.as_secs(),
1062 });
1063 }
1064 std::thread::sleep(Duration::from_millis(50));
1065 }
1066 Err(error) => {
1067 return Err(DetectionError::Failed {
1068 tool: tool.to_owned(),
1069 detail: error.to_string(),
1070 })
1071 }
1072 }
1073 }
1074
1075 let output = child
1076 .wait_with_output()
1077 .map_err(|error| DetectionError::Failed {
1078 tool: tool.to_owned(),
1079 detail: error.to_string(),
1080 })?;
1081 if !output.status.success() {
1082 return Err(DetectionError::Failed {
1083 tool: tool.to_owned(),
1084 detail: String::from_utf8_lossy(&output.stderr).trim().to_owned(),
1085 });
1086 }
1087 Ok(String::from_utf8_lossy(&output.stdout).into_owned())
1088}
1089
1090pub fn create_ceremony_dir(dir: &Path) -> Result<()> {
1092 use std::os::unix::fs::PermissionsExt as _;
1093 std::fs::create_dir_all(dir)
1094 .with_context(|| format!("create ceremony directory {}", dir.display()))?;
1095 std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
1096 .with_context(|| format!("restrict ceremony directory {} to its owner", dir.display()))
1097}
1098
1099pub fn generate_software_identity(out: &Path) -> Result<String> {
1103 use std::os::unix::fs::PermissionsExt as _;
1104 let output = Command::new("age-keygen")
1105 .arg("-o")
1106 .arg(out)
1107 .stdin(Stdio::null())
1108 .output()
1109 .context("launch age-keygen (install the `age` tools)")?;
1110 if !output.status.success() {
1111 bail!(
1112 "age-keygen failed: {}",
1113 String::from_utf8_lossy(&output.stderr).trim()
1114 );
1115 }
1116 std::fs::set_permissions(out, std::fs::Permissions::from_mode(0o600))
1117 .with_context(|| format!("restrict {} to its owner", out.display()))?;
1118 let printed = format!(
1119 "{}\n{}",
1120 String::from_utf8_lossy(&output.stdout),
1121 String::from_utf8_lossy(&output.stderr)
1122 );
1123 parse_age_keygen_recipient(&printed)
1124 .ok_or_else(|| anyhow::anyhow!("age-keygen printed no `age1…` recipient"))
1125}
1126
1127pub fn generate_passphrase_encrypted_identity(out: &Path) -> Result<String> {
1133 use std::os::unix::fs::PermissionsExt as _;
1134 let mut keygen = Command::new("age-keygen")
1135 .stdin(Stdio::null())
1136 .stdout(Stdio::piped())
1137 .stderr(Stdio::piped())
1138 .spawn()
1139 .context("launch age-keygen (install the `age` tools)")?;
1140 let keygen_stdout = keygen
1141 .stdout
1142 .take()
1143 .ok_or_else(|| anyhow::anyhow!("age-keygen produced no identity stream"))?;
1144 let seal = Command::new("age")
1145 .args(["-p", "-o"])
1146 .arg(out)
1147 .stdin(Stdio::from(keygen_stdout))
1148 .stdout(Stdio::inherit())
1149 .stderr(Stdio::inherit())
1150 .status()
1151 .context("launch age (install the `age` tools)")?;
1152 let keygen = keygen
1153 .wait_with_output()
1154 .context("wait for age-keygen to finish")?;
1155 if !keygen.status.success() {
1156 bail!(
1157 "age-keygen failed: {}",
1158 String::from_utf8_lossy(&keygen.stderr).trim()
1159 );
1160 }
1161 if !seal.success() {
1162 bail!("age -p did not encrypt the break-glass identity; nothing was written");
1163 }
1164 std::fs::set_permissions(out, std::fs::Permissions::from_mode(0o600))
1165 .with_context(|| format!("restrict {} to its owner", out.display()))?;
1166 parse_age_keygen_recipient(&String::from_utf8_lossy(&keygen.stderr))
1167 .ok_or_else(|| anyhow::anyhow!("age-keygen printed no `age1…` recipient"))
1168}
1169
1170pub fn write_registry_public_key(out: &Path, public_key: &[u8; 32]) -> Result<()> {
1172 if let Some(parent) = out.parent() {
1173 std::fs::create_dir_all(parent)
1174 .with_context(|| format!("create ceremony directory {}", parent.display()))?;
1175 }
1176 std::fs::write(out, public_key)
1177 .with_context(|| format!("write registry public key to {}", out.display()))
1178}
1179
1180#[cfg(test)]
1181#[allow(clippy::unwrap_used, clippy::expect_used)]
1182mod tests {
1183 use super::*;
1184
1185 fn token(model: &str, firmware: (u8, u8, u8), serial: &str) -> DetectedToken {
1186 DetectedToken {
1187 model: model.to_owned(),
1188 firmware: FirmwareVersion::new(firmware.0, firmware.1, firmware.2),
1189 serial: serial.to_owned(),
1190 }
1191 }
1192
1193 fn old_token() -> DetectedToken {
1194 token("YubiKey 5C NFC", (5, 4, 3), "11111111")
1195 }
1196
1197 fn new_token() -> DetectedToken {
1198 token("YubiKey 5C NFC", (5, 7, 4), "22222222")
1199 }
1200
1201 fn enabled() -> CeremonyRequest {
1202 CeremonyRequest {
1203 enabled: true,
1204 ..CeremonyRequest::default()
1205 }
1206 }
1207
1208 struct FakeDetector(Result<Vec<DetectedToken>, DetectionError>);
1210
1211 impl TokenDetector for FakeDetector {
1212 fn detect(&self) -> Result<Vec<DetectedToken>, DetectionError> {
1213 self.0.clone()
1214 }
1215 }
1216
1217 #[test]
1220 fn firmware_parses_three_part_versions_only() {
1221 assert_eq!(
1222 FirmwareVersion::parse("5.7.4"),
1223 Some(FirmwareVersion::new(5, 7, 4))
1224 );
1225 assert_eq!(FirmwareVersion::parse("5.7"), None);
1226 assert_eq!(FirmwareVersion::parse("5.7.4.1"), None);
1227 assert_eq!(FirmwareVersion::parse("five.seven.four"), None);
1228 }
1229
1230 #[test]
1231 fn piv_ed25519_support_starts_at_the_documented_firmware() {
1232 assert!(!FirmwareVersion::new(5, 4, 3).supports_piv_ed25519());
1233 assert!(!FirmwareVersion::new(5, 7, 3).supports_piv_ed25519());
1234 assert!(FirmwareVersion::new(5, 7, 4).supports_piv_ed25519());
1235 assert!(FirmwareVersion::new(5, 8, 0).supports_piv_ed25519());
1236 assert!(FirmwareVersion::new(6, 0, 0).supports_piv_ed25519());
1237 assert!(!FirmwareVersion::new(4, 9, 9).supports_piv_ed25519());
1238 }
1239
1240 #[test]
1243 fn ceremony_is_skipped_unless_requested() {
1244 let detection = Ok(vec![new_token()]);
1245 let plan = plan_ceremony(&CeremonyRequest::default(), &detection);
1246 assert!(matches!(plan, CeremonyPlan::Skipped { .. }));
1247 }
1248
1249 #[test]
1250 fn no_token_selects_the_dev_grade_software_root() {
1251 let plan = plan_ceremony(&enabled(), &Ok(Vec::new()));
1252 let CeremonyPlan::Proceed { mode, rationale } = plan else {
1253 panic!("expected a software root, got {plan:?}");
1254 };
1255 assert_eq!(mode, CeremonyMode::SoftwareDevGrade);
1256 assert!(mode.is_dev_grade());
1257 assert!(!mode.ed25519_confined_to_hardware());
1258 assert!(rationale.contains("no hardware token"));
1259 assert!(rationale.contains(DEV_GRADE_LABEL));
1260 }
1261
1262 #[test]
1263 fn old_firmware_selects_the_age_recipient_mode() {
1264 let plan = plan_ceremony(&enabled(), &Ok(vec![old_token()]));
1265 let CeremonyPlan::Proceed { mode, rationale } = plan else {
1266 panic!("expected a hardware mode, got {plan:?}");
1267 };
1268 assert_eq!(
1269 mode,
1270 CeremonyMode::HardwareAgeRecipient { token: old_token() }
1271 );
1272 assert!(!mode.ed25519_confined_to_hardware());
1273 assert!(rationale.contains("5.4.3"));
1274 assert!(rationale.contains("host memory"));
1275 }
1276
1277 #[test]
1278 fn current_firmware_selects_the_piv_slot_mode() {
1279 let plan = plan_ceremony(&enabled(), &Ok(vec![new_token()]));
1280 let CeremonyPlan::Proceed { mode, rationale } = plan else {
1281 panic!("expected a hardware mode, got {plan:?}");
1282 };
1283 assert_eq!(
1284 mode,
1285 CeremonyMode::HardwarePiv {
1286 token: new_token(),
1287 slot: DEFAULT_PIV_SLOT.to_owned(),
1288 }
1289 );
1290 assert!(!mode.ed25519_confined_to_hardware());
1291 assert!(mode.token_gated_signing());
1292 assert!(rationale.contains("token-gated signing"));
1293 }
1294
1295 #[test]
1296 fn several_tokens_ask_the_operator_which_one() {
1297 let plan = plan_ceremony(&enabled(), &Ok(vec![old_token(), new_token()]));
1298 let CeremonyPlan::ChooseToken { tokens, .. } = plan else {
1299 panic!("expected an operator choice, got {plan:?}");
1300 };
1301 assert_eq!(tokens, vec![old_token(), new_token()]);
1302 }
1303
1304 #[test]
1305 fn a_named_serial_picks_its_token_without_prompting() {
1306 let request = CeremonyRequest {
1307 serial: Some(new_token().serial),
1308 ..enabled()
1309 };
1310 let plan = plan_ceremony(&request, &Ok(vec![old_token(), new_token()]));
1311 let CeremonyPlan::Proceed { mode, .. } = plan else {
1312 panic!("expected a hardware mode, got {plan:?}");
1313 };
1314 assert_eq!(mode.token(), Some(&new_token()));
1315 }
1316
1317 #[test]
1318 fn an_unattached_serial_blocks_and_lists_what_is_attached() {
1319 let request = CeremonyRequest {
1320 serial: Some("99999999".to_owned()),
1321 ..enabled()
1322 };
1323 let plan = plan_ceremony(&request, &Ok(vec![old_token(), new_token()]));
1324 let CeremonyPlan::Blocked { reason, remedy } = plan else {
1325 panic!("expected a block, got {plan:?}");
1326 };
1327 assert!(reason.contains("99999999"));
1328 assert!(remedy.contains("11111111") && remedy.contains("22222222"));
1329 }
1330
1331 #[test]
1332 fn detection_failure_blocks_rather_than_falling_back_to_software() {
1333 for error in [
1334 DetectionError::ToolMissing {
1335 tool: "ykman".to_owned(),
1336 },
1337 DetectionError::Timeout {
1338 tool: "ykman".to_owned(),
1339 seconds: 10,
1340 },
1341 DetectionError::Failed {
1342 tool: "ykman".to_owned(),
1343 detail: "unreadable line".to_owned(),
1344 },
1345 ] {
1346 let plan = plan_ceremony(&enabled(), &Err(error.clone()));
1347 let CeremonyPlan::Blocked { reason, remedy } = plan else {
1348 panic!("expected a block for {error:?}");
1349 };
1350 assert!(reason.contains("could not tell whether"));
1351 assert!(remedy.contains("--deployment-trust-software"));
1352 }
1353 }
1354
1355 #[test]
1356 fn detection_failure_may_be_overridden_into_an_explicit_software_root() {
1357 let request = CeremonyRequest {
1358 force_software: true,
1359 ..enabled()
1360 };
1361 let plan = plan_ceremony(
1362 &request,
1363 &Err(DetectionError::ToolMissing {
1364 tool: "ykman".to_owned(),
1365 }),
1366 );
1367 let CeremonyPlan::Proceed { mode, rationale } = plan else {
1368 panic!("expected an explicit software root, got {plan:?}");
1369 };
1370 assert_eq!(mode, CeremonyMode::SoftwareDevGrade);
1371 assert!(rationale.contains("explicitly requested"));
1372 assert!(rationale.contains(DEV_GRADE_LABEL));
1373 }
1374
1375 #[test]
1376 fn software_is_never_chosen_over_present_hardware_without_an_explicit_override() {
1377 for tokens in [
1379 vec![old_token()],
1380 vec![new_token()],
1381 vec![old_token(), new_token()],
1382 ] {
1383 let plan = plan_ceremony(&enabled(), &Ok(tokens.clone()));
1384 assert!(
1385 !matches!(
1386 plan,
1387 CeremonyPlan::Proceed {
1388 mode: CeremonyMode::SoftwareDevGrade,
1389 ..
1390 }
1391 ),
1392 "software root silently selected with {tokens:?} attached"
1393 );
1394 }
1395 }
1396
1397 #[test]
1398 fn an_explicit_override_says_it_overrode_attached_hardware() {
1399 let request = CeremonyRequest {
1400 force_software: true,
1401 ..enabled()
1402 };
1403 let plan = plan_ceremony(&request, &Ok(vec![new_token()]));
1404 let CeremonyPlan::Proceed { mode, rationale } = plan else {
1405 panic!("expected a software root, got {plan:?}");
1406 };
1407 assert_eq!(mode, CeremonyMode::SoftwareDevGrade);
1408 assert!(rationale.contains("hardware token(s) are attached"));
1409 }
1410
1411 #[test]
1414 fn a_scripted_run_never_reaches_a_prompt() {
1415 let scripted = CeremonyRequest {
1416 interactive: false,
1417 ..enabled()
1418 };
1419 for detection in [
1420 Ok(Vec::new()),
1421 Ok(vec![old_token()]),
1422 Ok(vec![new_token()]),
1423 Ok(vec![old_token(), new_token()]),
1424 Err(DetectionError::ToolMissing {
1425 tool: "ykman".to_owned(),
1426 }),
1427 ] {
1428 let plan = plan_ceremony(&scripted, &detection);
1429 assert!(
1430 !matches!(plan, CeremonyPlan::ChooseToken { .. }),
1431 "scripted run would have prompted for {detection:?}"
1432 );
1433 }
1434 }
1435
1436 #[test]
1437 fn a_scripted_run_with_hardware_blocks_with_both_ways_forward() {
1438 let scripted = CeremonyRequest {
1439 interactive: false,
1440 ..enabled()
1441 };
1442 let CeremonyPlan::Blocked { reason, remedy } =
1443 plan_ceremony(&scripted, &Ok(vec![new_token()]))
1444 else {
1445 panic!("expected a block");
1446 };
1447 assert!(reason.contains("physical touch"));
1448 assert!(remedy.contains("--non-interactive"));
1449 assert!(remedy.contains("--deployment-trust-software"));
1450 }
1451
1452 #[test]
1453 fn a_scripted_run_with_several_tokens_asks_for_a_serial() {
1454 let scripted = CeremonyRequest {
1455 interactive: false,
1456 ..enabled()
1457 };
1458 let CeremonyPlan::Blocked { remedy, .. } =
1459 plan_ceremony(&scripted, &Ok(vec![old_token(), new_token()]))
1460 else {
1461 panic!("expected a block");
1462 };
1463 assert!(remedy.contains("--deployment-trust-serial"));
1464 }
1465
1466 #[test]
1467 fn a_scripted_run_without_hardware_still_completes() {
1468 let scripted = CeremonyRequest {
1469 interactive: false,
1470 ..enabled()
1471 };
1472 let CeremonyPlan::Proceed { mode, .. } = plan_ceremony(&scripted, &Ok(Vec::new())) else {
1473 panic!("expected a software root");
1474 };
1475 assert!(mode.is_dev_grade());
1476 }
1477
1478 #[test]
1479 fn a_scripted_run_that_did_not_ask_for_trust_is_skipped_even_with_hardware() {
1480 let scripted = CeremonyRequest {
1481 interactive: false,
1482 ..CeremonyRequest::default()
1483 };
1484 assert!(matches!(
1485 plan_ceremony(&scripted, &Ok(vec![new_token()])),
1486 CeremonyPlan::Skipped { .. }
1487 ));
1488 }
1489
1490 #[test]
1491 fn a_chosen_token_runs_through_the_same_firmware_rule() {
1492 let request = enabled();
1493 let CeremonyPlan::Proceed { mode, .. } = select_mode_for_token(&request, &new_token())
1494 else {
1495 panic!("expected a hardware mode");
1496 };
1497 assert!(!mode.ed25519_confined_to_hardware());
1498 assert!(mode.token_gated_signing());
1499 let CeremonyPlan::Proceed { mode, .. } = select_mode_for_token(&request, &old_token())
1500 else {
1501 panic!("expected a hardware mode");
1502 };
1503 assert!(!mode.ed25519_confined_to_hardware());
1504 }
1505
1506 #[test]
1507 fn the_detector_seam_feeds_the_plan() {
1508 let detector = FakeDetector(Ok(vec![new_token()]));
1509 let plan = plan_ceremony(&enabled(), &detector.detect());
1510 assert!(matches!(
1511 plan,
1512 CeremonyPlan::Proceed {
1513 mode: CeremonyMode::HardwarePiv { .. },
1514 ..
1515 }
1516 ));
1517 }
1518
1519 #[test]
1522 fn a_plaintext_break_glass_is_refused_by_default() {
1523 let break_glass = BreakGlass::PlaintextIdentity {
1524 identity_file: PathBuf::from("/tmp/backup.key"),
1525 recipient: "age1backup".to_owned(),
1526 };
1527 let error =
1528 validate_break_glass(&break_glass, "age1yubikey1primary", PlaintextPolicy::Refuse)
1529 .expect_err("plaintext break-glass must be refused");
1530 assert!(error.contains("weakest recipient"));
1531 assert!(error.contains("--deployment-trust-allow-plaintext-break-glass"));
1532 }
1533
1534 #[test]
1535 fn a_plaintext_break_glass_is_allowed_only_by_override_or_for_a_dev_root() {
1536 let break_glass = BreakGlass::PlaintextIdentity {
1537 identity_file: PathBuf::from("/tmp/backup.key"),
1538 recipient: "age1backup".to_owned(),
1539 };
1540 for policy in [
1541 PlaintextPolicy::AllowedByOverride,
1542 PlaintextPolicy::AllowedForDevGradeRoot,
1543 ] {
1544 assert!(validate_break_glass(&break_glass, "age1yubikey1primary", policy).is_ok());
1545 }
1546 }
1547
1548 #[test]
1549 fn a_passphrase_encrypted_break_glass_is_accepted() {
1550 let break_glass = BreakGlass::PassphraseEncrypted {
1551 identity_file: PathBuf::from("/tmp/backup.key.age"),
1552 recipient: "age1backup".to_owned(),
1553 };
1554 assert!(
1555 validate_break_glass(&break_glass, "age1yubikey1primary", PlaintextPolicy::Refuse)
1556 .is_ok()
1557 );
1558 }
1559
1560 #[test]
1561 fn a_duplicate_break_glass_recipient_is_refused() {
1562 let break_glass = BreakGlass::SecondToken {
1563 recipient: "age1yubikey1primary".to_owned(),
1564 };
1565 let error = validate_break_glass(
1566 &break_glass,
1567 "age1yubikey1primary",
1568 PlaintextPolicy::AllowedByOverride,
1569 )
1570 .expect_err("a duplicated recipient must be refused");
1571 assert!(error.contains("single point of loss"));
1572 }
1573
1574 #[test]
1575 fn a_second_token_break_glass_must_be_a_plugin_recipient() {
1576 let break_glass = BreakGlass::SecondToken {
1577 recipient: "age1software".to_owned(),
1578 };
1579 let error =
1580 validate_break_glass(&break_glass, "age1yubikey1primary", PlaintextPolicy::Refuse)
1581 .expect_err("a software recipient is not a second token");
1582 assert!(error.contains("age1yubikey1"));
1583 }
1584
1585 #[test]
1586 fn malformed_break_glass_recipients_are_refused() {
1587 for recipient in ["", " ", "not-a-recipient", "age1good\nage1evil"] {
1588 let break_glass = BreakGlass::PassphraseEncrypted {
1589 identity_file: PathBuf::from("/tmp/backup.key.age"),
1590 recipient: recipient.to_owned(),
1591 };
1592 assert!(
1593 validate_break_glass(&break_glass, "age1yubikey1primary", PlaintextPolicy::Refuse)
1594 .is_err(),
1595 "accepted malformed recipient {recipient:?}"
1596 );
1597 }
1598 }
1599
1600 #[test]
1601 fn identity_files_are_classified_without_decryption() {
1602 assert_eq!(
1603 classify_identity_file(
1604 "# created: 2026-01-01\n# public key: age1abc\nAGE-SECRET-KEY-1QQQQ\n"
1605 ),
1606 IdentityFileKind::PlaintextAgeIdentity
1607 );
1608 assert_eq!(
1609 classify_identity_file("age-encryption.org/v1\n-> scrypt abcdef 18\nxxxx\n"),
1610 IdentityFileKind::PassphraseEncrypted
1611 );
1612 assert_eq!(
1613 classify_identity_file("age-encryption.org/v1\n-> X25519 abcdef\nxxxx\n"),
1614 IdentityFileKind::Unconfirmed
1615 );
1616 assert_eq!(
1617 classify_identity_file("-----BEGIN AGE ENCRYPTED FILE-----\nYWJj\n"),
1618 IdentityFileKind::Unconfirmed
1619 );
1620 }
1621
1622 fn paths() -> CeremonyPaths {
1625 CeremonyPaths::new("/srv/ceremony").expect("absolute path")
1626 }
1627
1628 fn inputs(mode: CeremonyMode, primary: &str, break_glass: BreakGlass) -> CeremonyInputs {
1629 CeremonyInputs {
1630 mode,
1631 primary_recipient: primary.to_owned(),
1632 break_glass,
1633 unlock_identity: UnlockIdentity::Yubikey(paths().yubikey_identity()),
1634 signer_recipient: "age1deploy".to_owned(),
1635 paths: paths(),
1636 }
1637 }
1638
1639 #[test]
1640 fn a_relative_ceremony_directory_is_refused() {
1641 assert!(CeremonyPaths::new("ceremony").is_err());
1642 }
1643
1644 #[test]
1645 fn the_piv_mode_sets_the_slot_and_keeps_both_recipients() {
1646 let commands = ceremony_commands(&inputs(
1647 CeremonyMode::HardwarePiv {
1648 token: new_token(),
1649 slot: DEFAULT_PIV_SLOT.to_owned(),
1650 },
1651 "age1yubikey1primary",
1652 BreakGlass::PassphraseEncrypted {
1653 identity_file: PathBuf::from("/srv/ceremony/break-glass.key.age"),
1654 recipient: "age1backup".to_owned(),
1655 },
1656 ))
1657 .expect("commands");
1658 let TrustCommand::MintDeploymentCa(args) = &commands[0] else {
1659 panic!("expected the mint step first");
1660 };
1661 assert_eq!(args.piv_slot.as_deref(), Some(DEFAULT_PIV_SLOT));
1662 assert_eq!(args.yubikey_recipients, vec!["age1yubikey1primary"]);
1663 assert_eq!(args.recipients, vec!["age1backup"]);
1664 assert!(args.public_ca.is_absolute());
1665 }
1666
1667 #[test]
1668 fn the_age_recipient_mode_leaves_the_piv_slot_unset() {
1669 let commands = ceremony_commands(&inputs(
1670 CeremonyMode::HardwareAgeRecipient { token: old_token() },
1671 "age1yubikey1primary",
1672 BreakGlass::SecondToken {
1673 recipient: "age1yubikey1backup".to_owned(),
1674 },
1675 ))
1676 .expect("commands");
1677 let TrustCommand::MintDeploymentCa(args) = &commands[0] else {
1678 panic!("expected the mint step first");
1679 };
1680 assert_eq!(args.piv_slot, None);
1681 assert_eq!(
1682 args.yubikey_recipients,
1683 vec!["age1yubikey1primary", "age1yubikey1backup"]
1684 );
1685 assert!(args.recipients.is_empty());
1686 }
1687
1688 #[test]
1689 fn the_software_mode_uses_native_recipients_and_no_slot() {
1690 let mut inputs = inputs(
1691 CeremonyMode::SoftwareDevGrade,
1692 "age1primary",
1693 BreakGlass::PlaintextIdentity {
1694 identity_file: PathBuf::from("/srv/ceremony/break-glass.key"),
1695 recipient: "age1backup".to_owned(),
1696 },
1697 );
1698 inputs.unlock_identity = UnlockIdentity::Age(paths().primary_identity());
1699 let commands = ceremony_commands(&inputs).expect("commands");
1700 let TrustCommand::MintDeploymentCa(args) = &commands[0] else {
1701 panic!("expected the mint step first");
1702 };
1703 assert_eq!(args.piv_slot, None);
1704 assert!(args.yubikey_recipients.is_empty());
1705 assert_eq!(args.recipients, vec!["age1primary", "age1backup"]);
1706
1707 let TrustCommand::DelegateRegistrySigner(args) = &commands[1] else {
1708 panic!("expected the delegation step second");
1709 };
1710 assert!(args.yubikey_identities.is_empty());
1711 assert_eq!(args.identities, vec![paths().primary_identity()]);
1712 }
1713
1714 #[test]
1715 fn the_ceremony_runs_the_documented_four_steps_in_order() {
1716 let commands = ceremony_commands(&inputs(
1717 CeremonyMode::HardwareAgeRecipient { token: old_token() },
1718 "age1yubikey1primary",
1719 BreakGlass::SecondToken {
1720 recipient: "age1yubikey1backup".to_owned(),
1721 },
1722 ))
1723 .expect("commands");
1724 assert_eq!(commands.len(), 4);
1725 assert!(matches!(commands[0], TrustCommand::MintDeploymentCa(_)));
1726 assert!(matches!(
1727 commands[1],
1728 TrustCommand::DelegateRegistrySigner(_)
1729 ));
1730 assert!(matches!(commands[2], TrustCommand::MintRegistryJwt(_)));
1731 assert!(matches!(commands[3], TrustCommand::VerifyDeployment(_)));
1732 }
1733
1734 #[test]
1735 fn the_credential_is_minted_through_the_delegated_signer_not_the_root() {
1736 let commands = ceremony_commands(&inputs(
1737 CeremonyMode::HardwareAgeRecipient { token: old_token() },
1738 "age1yubikey1primary",
1739 BreakGlass::SecondToken {
1740 recipient: "age1yubikey1backup".to_owned(),
1741 },
1742 ))
1743 .expect("commands");
1744 let TrustCommand::MintRegistryJwt(args) = &commands[2] else {
1745 panic!("expected the credential step third");
1746 };
1747 assert!(!args.root);
1748 assert_eq!(
1749 args.via_delegated_signer.as_deref(),
1750 Some(paths().delegated_signer().as_path())
1751 );
1752 assert!(args.yubikey_identities.is_empty());
1753 assert_eq!(args.ttl_seconds, REGISTRY_JWT_TTL_SECONDS);
1754 }
1755
1756 #[test]
1757 fn a_hardware_ceremony_refuses_to_build_around_a_plaintext_break_glass() {
1758 let error = ceremony_commands(&inputs(
1759 CeremonyMode::HardwarePiv {
1760 token: new_token(),
1761 slot: DEFAULT_PIV_SLOT.to_owned(),
1762 },
1763 "age1yubikey1primary",
1764 BreakGlass::PlaintextIdentity {
1765 identity_file: PathBuf::from("/srv/ceremony/break-glass.key"),
1766 recipient: "age1backup".to_owned(),
1767 },
1768 ))
1769 .expect_err("a hardware root must not accept a bare backup identity");
1770 assert!(error.to_string().contains("weakest recipient"));
1771 }
1772
1773 #[test]
1776 fn the_mode_record_labels_a_software_root_as_dev_grade() {
1777 let record = mode_record(
1778 &CeremonyMode::SoftwareDevGrade,
1779 &BreakGlass::PlaintextIdentity {
1780 identity_file: PathBuf::from("/srv/ceremony/break-glass.key"),
1781 recipient: "age1backup".to_owned(),
1782 },
1783 "no hardware token is attached",
1784 );
1785 assert!(record.dev_grade);
1786 assert_eq!(record.grade, DEV_GRADE_LABEL);
1787 assert!(!record.ed25519_confined_to_hardware);
1788 assert!(!record.token_gated_signing);
1789 assert!(record.seed_recoverable_from_bundle);
1790 assert_eq!(record.token_serial, None);
1791 assert_eq!(record.piv_slot, None);
1792 assert!(!record.break_glass_protected);
1793 }
1794
1795 #[test]
1796 fn the_mode_record_keeps_the_token_and_slot_for_a_hardware_root() {
1797 let record = mode_record(
1798 &CeremonyMode::HardwarePiv {
1799 token: new_token(),
1800 slot: DEFAULT_PIV_SLOT.to_owned(),
1801 },
1802 &BreakGlass::SecondToken {
1803 recipient: "age1yubikey1backup".to_owned(),
1804 },
1805 "firmware 5.7.4",
1806 );
1807 assert!(!record.dev_grade);
1808 assert!(!record.ed25519_confined_to_hardware);
1809 assert!(record.token_gated_signing);
1810 assert!(record.seed_recoverable_from_bundle);
1811 assert_eq!(record.token_firmware.as_deref(), Some("5.7.4"));
1812 assert_eq!(record.token_serial.as_deref(), Some("22222222"));
1813 assert_eq!(record.piv_slot.as_deref(), Some(DEFAULT_PIV_SLOT));
1814 assert_eq!(record.schema, CEREMONY_MODE_SCHEMA);
1815 assert!(record.break_glass_protected);
1816 }
1817
1818 #[test]
1819 fn the_mode_record_round_trips_as_json() {
1820 let record = mode_record(
1821 &CeremonyMode::HardwareAgeRecipient { token: old_token() },
1822 &BreakGlass::SecondToken {
1823 recipient: "age1yubikey1backup".to_owned(),
1824 },
1825 "firmware 5.4.3",
1826 );
1827 let json = serde_json::to_string(&record).expect("serialize");
1828 let parsed: CeremonyModeRecord = serde_json::from_str(&json).expect("deserialize");
1829 assert_eq!(parsed, record);
1830 }
1831
1832 #[test]
1835 fn each_mode_declares_the_tools_it_needs() {
1836 assert!(required_tools(&CeremonyMode::HardwarePiv {
1837 token: new_token(),
1838 slot: DEFAULT_PIV_SLOT.to_owned(),
1839 })
1840 .contains(&"yubico-piv-tool"));
1841 assert_eq!(
1842 required_tools(&CeremonyMode::HardwareAgeRecipient { token: old_token() }),
1843 &["age-plugin-yubikey"]
1844 );
1845 assert!(required_tools(&CeremonyMode::SoftwareDevGrade).contains(&"age-keygen"));
1846 }
1847
1848 #[test]
1849 fn missing_tools_are_reported_through_the_probe_seam() {
1850 let tools = required_tools(&CeremonyMode::HardwarePiv {
1851 token: new_token(),
1852 slot: DEFAULT_PIV_SLOT.to_owned(),
1853 });
1854 assert!(missing_tools(tools, |_| true).is_empty());
1855 assert_eq!(missing_tools(tools, |_| false).len(), tools.len());
1856 assert_eq!(
1857 missing_tools(tools, |tool| tool != "yubico-piv-tool"),
1858 vec!["yubico-piv-tool".to_owned()]
1859 );
1860 }
1861
1862 #[test]
1865 fn ykman_output_parses_into_tokens() {
1866 let listed = "YubiKey 5C NFC (5.4.3) [OTP+FIDO+CCID] Serial: 11111111\n\
1867 YubiKey 5 NFC (5.7.4) [OTP+FIDO+CCID] Serial: 22222222\n";
1868 let tokens = parse_ykman_list(listed).expect("parse");
1869 assert_eq!(tokens.len(), 2);
1870 assert_eq!(tokens[0].model, "YubiKey 5C NFC");
1871 assert_eq!(tokens[0].firmware, FirmwareVersion::new(5, 4, 3));
1872 assert_eq!(tokens[1].serial, "22222222");
1873 assert!(tokens[1].firmware.supports_piv_ed25519());
1874 }
1875
1876 #[test]
1877 fn empty_ykman_output_means_nothing_is_attached() {
1878 assert!(parse_ykman_list("").expect("parse").is_empty());
1879 assert!(parse_ykman_list("\n \n").expect("parse").is_empty());
1880 }
1881
1882 #[test]
1883 fn an_unreadable_ykman_line_is_an_error_not_a_missing_token() {
1884 for listed in [
1885 "YubiKey 5C NFC [OTP+FIDO+CCID] Serial: 11111111",
1886 "YubiKey 5C NFC (5.4) [OTP] Serial: 11111111",
1887 "YubiKey 5C NFC (5.4.3) [OTP]",
1888 "YubiKey 5C NFC (5.4.3) [OTP] Serial: none",
1889 ] {
1890 assert!(
1891 parse_ykman_list(listed).is_err(),
1892 "silently dropped token from {listed:?}"
1893 );
1894 }
1895 }
1896
1897 #[test]
1898 fn plugin_and_keygen_recipients_are_told_apart() {
1899 assert_eq!(
1900 parse_age_plugin_recipient("Serial: 1, Slot: 1\n age1yubikey1qabc\n").as_deref(),
1901 Some("age1yubikey1qabc")
1902 );
1903 assert_eq!(parse_age_plugin_recipient("no recipients here"), None);
1904 assert_eq!(
1905 parse_age_keygen_recipient("Public key: age1qsoftware").as_deref(),
1906 Some("age1qsoftware")
1907 );
1908 assert_eq!(
1909 parse_age_keygen_recipient("Public key: age1yubikey1q"),
1910 None
1911 );
1912 }
1913}