Skip to main content

hyprstream_core/cli/
trust.rs

1//! Deployment trust-authority minting.
2//!
3//! The root authority is an out-of-band, age-encrypted operator asset. Hourly
4//! registry credentials should be minted by a narrowly scoped delegated signer;
5//! direct root signing exists only for bootstrap and recovery.
6
7#![allow(clippy::print_stdout)]
8
9use crate::auth::age_seal::{AgeIdentities, AgeIdentitySource, AgeRecipients};
10use crate::cli::commands::{
11    DelegateRegistrySignerArgs, EnrollServiceKeyArgs, InstallDeploymentTrustArgs,
12    MintAnchorCapsuleArgs, MintDeploymentCaArgs, MintRegistryJwtArgs, RotateAuthorityArgs,
13    TrustCommand, VerifyDeploymentArgs,
14};
15use anyhow::{anyhow, bail, ensure, Context, Result};
16use base64::{
17    engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD},
18    Engine as _,
19};
20use ed25519_dalek::{pkcs8::EncodePrivateKey as _, Signer as _, SigningKey, VerifyingKey};
21use hyprstream_discovery::did_op::{
22    verify_did_op_log, DidOp, HybridDidOpSignature, HybridRotationKey, DID_OP_SIGNATURE_CONTEXT,
23};
24use hyprstream_discovery::{
25    DeploymentAuthorityCheckpoint as AuthorityCheckpointFile,
26    DeploymentAuthorityLog as AuthorityLogFile, RegistryDelegationArtifact as DelegationArtifact,
27    ServiceKeyEnrollmentArtifact, ServiceKeyEnrollmentSigningBody,
28};
29use hyprstream_pds::at9p::{
30    CapsuleBody, HybridKeyPair, ServiceEndpoint, ServiceEntry, ServiceType, Transport,
31};
32use hyprstream_pds::at9p_sign::{sign_capsule_detached, CapsuleEd25519Signer};
33use hyprstream_rpc::transport::QuicServerAuth;
34use hyprstream_rpc::{
35    auth::ucan::{Did, Ucan, UcanPayload},
36    crypto::{
37        cose_sign::{assemble_composite_nested, inner_tbs, outer_tbs},
38        pq::{
39            ml_dsa_generate_keypair, ml_dsa_sign, ml_dsa_sk_from_seed, ml_dsa_sk_to_seed,
40            ml_dsa_sk_to_vk_bytes, ml_dsa_vk_bytes, ml_dsa_vk_from_bytes, MlDsaSigningKey,
41        },
42    },
43};
44use rand::RngCore as _;
45use serde::{Deserialize, Serialize};
46use sha2::{Digest as _, Sha256};
47use std::{
48    collections::BTreeSet,
49    fs::OpenOptions,
50    io::{Read as _, Write as _},
51    os::fd::{FromRawFd as _, RawFd},
52    os::unix::fs::{MetadataExt as _, OpenOptionsExt as _, PermissionsExt as _},
53    path::{Path, PathBuf},
54    process::{Command, Stdio},
55};
56use zeroize::{Zeroize as _, Zeroizing};
57
58const PUBLIC_CA_BYTES: usize = 32 + 1_952;
59const HYBRID_SIGNATURE_BYTES: usize = 3_309 + 64;
60const REGISTRY_AUDIENCE: &str = "urn:hyprstream:service:registry";
61const REGISTRY_PROFILE: &str = "hyprstream.registry-deployment.v1";
62const AUTHORITY_BUNDLE_SCHEMA: &str = "hyprstream.deployment-authority.v1";
63const AUTHORITY_LOG_SCHEMA: &str = "hyprstream.deployment-authority-log.v1";
64const AUTHORITY_CHECKPOINT_SCHEMA: &str = "hyprstream.deployment-authority-checkpoint.v1";
65const DELEGATION_SCHEMA: &str = "hyprstream.registry-delegation.v1";
66const PUBLISHER_MANIFEST_SCHEMA: &str = "hyprstream.deployment-trust-publisher-manifest.v1";
67/// Capsule service id the DID-anchored resolver requires for deployment reach.
68const ANCHOR_REACH_SERVICE: &str = "#ns";
69const ENROLLMENT_SCHEMA: &str = "hyprstream.service-key-enrollment.v1";
70const ENROLLMENT_KEY_TYPE: &str = "hybrid-ed25519-mldsa65";
71const ENROLLMENT_SIGNATURE_CONTEXT: &[u8] = b"hyprstream.service-key-enrollment.v1";
72const MAX_ENROLLMENT_BYTES: usize = 256 * 1024;
73const MAX_AUTHORITY_LOG_OPERATIONS: usize = 128;
74const MAX_DELEGATION_BYTES: usize = 256 * 1024;
75const MAX_CLOUD_SECRET_BYTES: usize = 64 * 1024;
76const MAX_AGE_CIPHERTEXT_BYTES: usize = 256 * 1024;
77const MAX_AGE_IDENTITY_BYTES: usize = 4 * 1024;
78const PUBLIC_CA_INSTALL_PATH: &str = "/etc/hyprstream/trust/deployment-ca.hybrid";
79const AUTHORITY_LOG_INSTALL_PATH: &str = "/etc/hyprstream/trust/deployment-authority.log.json";
80const AUTHORITY_CHECKPOINT_INSTALL_PATH: &str =
81    "/etc/hyprstream/trust/deployment-authority.head.json";
82const REGISTRY_JWT_INSTALL_PATH: &str = "/run/hyprstream/credentials/registry-service.jwt";
83const DEPLOYMENT_TRUST_DIR: &str = "/etc/hyprstream/trust";
84const DELEGATED_DIR: &str = "/etc/hyprstream/trust/delegated";
85const DELEGATED_SIGNER_INSTALL_PATH: &str =
86    "/etc/hyprstream/trust/delegated/registry-delegated-signer.age";
87const DELEGATION_INSTALL_PATH: &str =
88    "/etc/hyprstream/trust/delegated/registry-signer.delegation.json";
89const REGISTRY_PUBLIC_KEY_INSTALL_PATH: &str =
90    "/etc/hyprstream/trust/delegated/registry-public-key";
91const REFRESH_IDENTITY_INSTALL_PATH: &str = "/etc/hyprstream/trust/delegated/refresh-identity";
92const TRUST_REFRESH_SERVICE_UNIT_PATH: &str =
93    "/etc/systemd/system/hyprstream-trust-refresh.service";
94const TRUST_REFRESH_TIMER_UNIT_PATH: &str = "/etc/systemd/system/hyprstream-trust-refresh.timer";
95const CREDENTIALS_RUN_DIR: &str = "/run/hyprstream/credentials";
96
97#[cfg(test)]
98static SECRET_BUNDLE_DROPS: [std::sync::atomic::AtomicUsize; 3] = [
99    std::sync::atomic::AtomicUsize::new(0),
100    std::sync::atomic::AtomicUsize::new(0),
101    std::sync::atomic::AtomicUsize::new(0),
102];
103
104#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
105#[serde(rename_all = "snake_case")]
106enum AuthorityPurpose {
107    Root,
108    RotatedAuthority,
109    RegistryDelegatedSigner,
110}
111
112#[derive(Debug, Serialize, Deserialize)]
113#[serde(tag = "kind", rename_all = "snake_case")]
114enum Ed25519Secret {
115    Software {
116        seed_b64: String,
117        public_b64: String,
118    },
119    YubikeyPiv {
120        slot: String,
121        public_b64: String,
122        recovery_seed_b64: String,
123    },
124}
125
126impl Drop for Ed25519Secret {
127    fn drop(&mut self) {
128        match self {
129            Self::Software { seed_b64, .. } => seed_b64.zeroize(),
130            Self::YubikeyPiv {
131                recovery_seed_b64, ..
132            } => recovery_seed_b64.zeroize(),
133        }
134    }
135}
136
137#[derive(Debug, Serialize, Deserialize)]
138#[serde(deny_unknown_fields)]
139struct AuthorityBundle {
140    schema: String,
141    purpose: AuthorityPurpose,
142    deployment_domain: String,
143    public_key_sha256: String,
144    ed25519: Ed25519Secret,
145    ml_dsa_65_seed_b64: String,
146    recipient_count: usize,
147}
148
149impl Drop for AuthorityBundle {
150    fn drop(&mut self) {
151        self.ml_dsa_65_seed_b64.zeroize();
152        #[cfg(test)]
153        SECRET_BUNDLE_DROPS[match &self.purpose {
154            AuthorityPurpose::Root => 0,
155            AuthorityPurpose::RotatedAuthority => 1,
156            AuthorityPurpose::RegistryDelegatedSigner => 2,
157        }]
158        .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
159    }
160}
161
162#[derive(Debug, Serialize)]
163struct CaMintOutput {
164    schema: &'static str,
165    deployment_domain: String,
166    authority_log_did: String,
167    authority_log_sequence: u64,
168    authority_log_head_cid: String,
169    authority_log_path: String,
170    authority_log_install_path: &'static str,
171    authority_checkpoint_path: String,
172    authority_checkpoint_install_path: &'static str,
173    public_ca_path: String,
174    public_ca_install_path: &'static str,
175    public_ca_bytes: usize,
176    public_ca_base64: String,
177    public_ca_sha256: String,
178    authority_key_path: String,
179    authority_key_export_allowed: bool,
180    recipient_count: usize,
181}
182
183#[derive(Clone, Debug, Serialize, Deserialize)]
184#[serde(deny_unknown_fields)]
185struct PublisherArtifact {
186    local_path: String,
187    install_path: String,
188    encoding: String,
189    base64: String,
190    sha256: String,
191    size_bytes: usize,
192    cloud_secret_store: bool,
193}
194
195#[derive(Clone, Debug, Serialize, Deserialize)]
196#[serde(deny_unknown_fields)]
197struct PublisherManifest {
198    schema: String,
199    deployment_domain: String,
200    profile: String,
201    audience: String,
202    expires_at: i64,
203    public_ca: PublisherArtifact,
204    authority_log: PublisherArtifact,
205    authority_checkpoint: PublisherArtifact,
206    registry_jwt: PublisherArtifact,
207    private_authority_exported: bool,
208    terraform_state_may_contain_private_authority: bool,
209}
210
211enum LoadedEdSigner {
212    Software(SigningKey),
213    YubikeyPiv { slot: String, public: VerifyingKey },
214}
215
216impl LoadedEdSigner {
217    fn verifying_key(&self) -> VerifyingKey {
218        match self {
219            Self::Software(key) => key.verifying_key(),
220            Self::YubikeyPiv { public, .. } => *public,
221        }
222    }
223
224    fn sign(&self, message: &[u8]) -> Result<[u8; 64]> {
225        match self {
226            Self::Software(key) => Ok(key.sign(message).to_bytes()),
227            Self::YubikeyPiv { slot, public } => piv_sign(slot, public, message),
228        }
229    }
230}
231
232impl CapsuleEd25519Signer for LoadedEdSigner {
233    fn verifying_key(&self) -> VerifyingKey {
234        Self::verifying_key(self)
235    }
236
237    fn sign_detached(&self, tbs: &[u8]) -> Result<[u8; 64]> {
238        self.sign(tbs)
239    }
240}
241
242struct LoadedAuthority {
243    bundle: AuthorityBundle,
244    ed: LoadedEdSigner,
245    pq: MlDsaSigningKey,
246}
247
248impl LoadedAuthority {
249    fn public_bytes(&self) -> Vec<u8> {
250        public_pair_bytes(&self.ed.verifying_key(), &self.pq)
251    }
252}
253
254/// Dispatch one early-startup trust command.
255pub fn handle_trust_command(command: TrustCommand) -> Result<()> {
256    match command {
257        TrustCommand::HashMacBootPolicy(args) => {
258            crate::mac::bootload::hash_reviewed_boot_policy(&args)
259        }
260        TrustCommand::SignMacBootPolicy(args) => {
261            crate::mac::bootload::sign_reviewed_boot_policy(&args)
262        }
263        TrustCommand::ReconcileMacBootEnrollment(args) => {
264            let report = crate::mac::enrollment_reconcile::reconcile_enrollment(
265                &args.journal_dir,
266                &args.current_policy,
267                args.expected_generation,
268                &args.expected_hash,
269                &args.output_dir,
270            )?;
271            use std::io::Write as _;
272            writeln!(
273                std::io::stdout().lock(),
274                "new_generation={} new_hash={} applied={} excluded={} conflicts={}\nnext: {}",
275                report.new_generation,
276                report.new_policy_hash,
277                report.applied.len(),
278                report.excluded.len(),
279                report.conflicts.len(),
280                report.hash_command,
281            )?;
282            Ok(())
283        }
284        TrustCommand::MintDeploymentCa(args) => mint_deployment_ca(&args),
285        TrustCommand::DelegateRegistrySigner(args) => delegate_registry_signer(&args),
286        TrustCommand::MintRegistryJwt(args) => mint_registry_jwt(&args),
287        TrustCommand::EnrollServiceKey(args) => enroll_service_key(&args),
288        TrustCommand::VerifyDeployment(args) => verify_deployment(&args),
289        TrustCommand::RotateAuthority(args) => rotate_authority(&args),
290        TrustCommand::Install(args) => install_deployment_trust(&args),
291        TrustCommand::MintAnchorCapsule(args) => mint_anchor_capsule(&args),
292    }
293}
294
295fn mint_deployment_ca(args: &MintDeploymentCaArgs) -> Result<()> {
296    preflight_outputs(
297        [
298            &args.public_ca,
299            &args.authority_key,
300            &args.authority_log,
301            &args.authority_checkpoint,
302        ],
303        args.force,
304    )?;
305    let recipients = root_recipient_ring(args)?;
306
307    let (ed_secret, ed_signer) = match args.piv_slot.as_deref() {
308        Some(slot) => {
309            // Destructive overwrite guard: ykman piv keys import silently
310            // replaces whatever is in the slot. Check first and refuse unless
311            // --force was given, so a daily-driver YubiKey's existing key
312            // (SSH, PIV cert, age identity) is not destroyed behind a
313            // routine-looking touch prompt.
314            if !args.force && piv_slot_occupied(slot)? {
315                anyhow::bail!(
316                    "PIV slot {slot} already contains a key or certificate. \
317                     Re-running will IRREVERSIBLY overwrite it. Pass --force to \
318                     confirm the overwrite."
319                );
320            }
321            if args.force {
322                println!(
323                    "  WARNING: --force bypasses the PIV slot occupancy check. \
324                     Any existing key in slot {slot} will be IRREVERSIBLY destroyed."
325                );
326            }
327            let recovery_key = SigningKey::generate(&mut rand::rngs::OsRng);
328            let (slot, public) = piv_import_ed25519(slot, &recovery_key)?;
329            (
330                Ed25519Secret::YubikeyPiv {
331                    slot: slot.clone(),
332                    public_b64: STANDARD.encode(public.as_bytes()),
333                    recovery_seed_b64: encode_ed25519_seed_b64(&recovery_key),
334                },
335                LoadedEdSigner::YubikeyPiv { slot, public },
336            )
337        }
338        None => {
339            let key = SigningKey::generate(&mut rand::rngs::OsRng);
340            (
341                Ed25519Secret::Software {
342                    seed_b64: encode_ed25519_seed_b64(&key),
343                    public_b64: STANDARD.encode(key.verifying_key().as_bytes()),
344                },
345                LoadedEdSigner::Software(key),
346            )
347        }
348    };
349    let (pq, _) = ml_dsa_generate_keypair();
350    let public_ca = public_pair_bytes(&ed_signer.verifying_key(), &pq);
351    ensure!(
352        public_ca.len() == PUBLIC_CA_BYTES,
353        "internal public-root layout error"
354    );
355    let deployment_domain = hyprstream_discovery::verify_deployment_public_ca(&public_ca)
356        .context("production HybridDeploymentCa rejected generated public root")?;
357
358    let root_key = HybridRotationKey::new(
359        ed_signer.verifying_key().to_bytes(),
360        ml_dsa_sk_to_vk_bytes(&pq),
361    )?;
362    let genesis = sign_did_op(
363        DidOp {
364            sequence: 0,
365            prev: None,
366            rotation_keys: vec![root_key],
367            signature: placeholder_did_signature(),
368        },
369        &ed_signer,
370        &pq,
371    )?;
372    let authority_log = authority_log_from_ops(&deployment_domain, vec![genesis])?;
373    let verified_log = validate_authority_log_root(&public_ca, &authority_log)?;
374    let checkpoint = authority_checkpoint(&deployment_domain, &verified_log);
375    validate_authority_log(&public_ca, &authority_log, &checkpoint)?;
376
377    let bundle = AuthorityBundle {
378        schema: AUTHORITY_BUNDLE_SCHEMA.to_owned(),
379        purpose: AuthorityPurpose::Root,
380        deployment_domain: deployment_domain.clone(),
381        public_key_sha256: sha256_hex(&public_ca),
382        ed25519: ed_secret,
383        ml_dsa_65_seed_b64: encode_ml_dsa_seed_b64(&pq),
384        recipient_count: recipients.len(),
385    };
386    let plaintext = serialize_secret_json(&bundle).context("encode authority bundle")?;
387    let encrypted = encrypt_age(&plaintext, &recipients)?;
388
389    commit_outputs(vec![
390        PendingOutput::new(&args.public_ca, public_ca.clone(), 0o644),
391        PendingOutput::new(&args.authority_key, encrypted, 0o600),
392        PendingOutput::new(
393            &args.authority_log,
394            pretty_json_bytes(&authority_log)?,
395            0o644,
396        ),
397        PendingOutput::new(
398            &args.authority_checkpoint,
399            pretty_json_bytes(&checkpoint)?,
400            0o644,
401        ),
402    ])?;
403
404    let output = CaMintOutput {
405        schema: "hyprstream.deployment-ca-mint-output.v1",
406        deployment_domain,
407        authority_log_did: authority_log.did,
408        authority_log_sequence: checkpoint.sequence,
409        authority_log_head_cid: checkpoint.head_cid,
410        authority_log_path: display_path(&args.authority_log),
411        authority_log_install_path: AUTHORITY_LOG_INSTALL_PATH,
412        authority_checkpoint_path: display_path(&args.authority_checkpoint),
413        authority_checkpoint_install_path: AUTHORITY_CHECKPOINT_INSTALL_PATH,
414        public_ca_path: display_path(&args.public_ca),
415        public_ca_install_path: PUBLIC_CA_INSTALL_PATH,
416        public_ca_bytes: public_ca.len(),
417        public_ca_base64: STANDARD.encode(&public_ca),
418        public_ca_sha256: sha256_hex(&public_ca),
419        authority_key_path: display_path(&args.authority_key),
420        authority_key_export_allowed: false,
421        recipient_count: recipients.len(),
422    };
423    println!("{}", serde_json::to_string_pretty(&output)?);
424    Ok(())
425}
426
427fn delegate_registry_signer(args: &DelegateRegistrySignerArgs) -> Result<()> {
428    preflight_outputs([&args.delegated_key, &args.delegation], args.force)?;
429    ensure!(
430        !args.signer_recipients.is_empty(),
431        "at least one --signer-recipient is required for the rotatable online signer"
432    );
433    let signer_recipients = distinct_recipients(args.signer_recipients.clone())?;
434    let public_ca = read_limited(&args.public_ca, PUBLIC_CA_BYTES)?;
435    let log: AuthorityLogFile = read_json_limited(&args.authority_log, MAX_CLOUD_SECRET_BYTES)?;
436    let checkpoint: AuthorityCheckpointFile =
437        read_json_limited(&args.authority_checkpoint, MAX_CLOUD_SECRET_BYTES)?;
438    let active = validate_authority_log(&public_ca, &log, &checkpoint)?;
439
440    let identities = combined_identities(&args.identities, &args.yubikey_identities)?;
441    let authority = decrypt_authority(&args.authority_key, &identities, args.software_recovery)?;
442    ensure!(
443        authority.bundle.purpose != AuthorityPurpose::RegistryDelegatedSigner,
444        "a delegated signer cannot delegate another registry signer"
445    );
446    ensure_active_authority(&authority, &active)?;
447
448    let delegated_ed = SigningKey::generate(&mut rand::rngs::OsRng);
449    let (delegated_pq, _) = ml_dsa_generate_keypair();
450    let delegated_public = public_pair_bytes(&delegated_ed.verifying_key(), &delegated_pq);
451
452    let now = now_unix_u64()?;
453    let expiration = now
454        .checked_add(args.delegation_ttl_seconds)
455        .ok_or_else(|| anyhow!("delegation expiration overflow"))?;
456    // hyprstream#1562: one artifact, one delegated signer — the delegation
457    // carries both the registry-mint and the service-key-enrollment scope.
458    // Capability construction lives in hyprstream-discovery (H3) so the mint
459    // and the production verifier can never drift apart.
460    let delegated_public_b64 = STANDARD.encode(&delegated_public);
461    let capabilities = vec![
462        hyprstream_discovery::registry_mint_capability(
463            &authority.bundle.deployment_domain,
464            &delegated_public_b64,
465        ),
466        hyprstream_discovery::service_key_enrollment_capability(
467            &authority.bundle.deployment_domain,
468            &delegated_public_b64,
469        ),
470    ];
471    let payload = UcanPayload {
472        issuer: Did::from_ed25519(&authority.ed.verifying_key().to_bytes()),
473        audience: Did::from_ed25519(&delegated_ed.verifying_key().to_bytes()),
474        capabilities,
475        not_before: Some(now),
476        expiration: Some(expiration),
477        nonce: random_bytes(16),
478    };
479    let ucan = sign_ucan(payload, &authority.ed, &authority.pq)?;
480    hyprstream_discovery::validate_delegation_ucan(
481        &ucan,
482        &authority.bundle.deployment_domain,
483        &delegated_public_b64,
484        &active.rotation_keys,
485        now,
486    )?;
487
488    let delegated_bundle = AuthorityBundle {
489        schema: AUTHORITY_BUNDLE_SCHEMA.to_owned(),
490        purpose: AuthorityPurpose::RegistryDelegatedSigner,
491        deployment_domain: authority.bundle.deployment_domain.clone(),
492        public_key_sha256: sha256_hex(&delegated_public),
493        ed25519: Ed25519Secret::Software {
494            seed_b64: encode_ed25519_seed_b64(&delegated_ed),
495            public_b64: STANDARD.encode(delegated_ed.verifying_key().as_bytes()),
496        },
497        ml_dsa_65_seed_b64: encode_ml_dsa_seed_b64(&delegated_pq),
498        recipient_count: signer_recipients.len(),
499    };
500    let plaintext = serialize_secret_json(&delegated_bundle)?;
501    let encrypted = encrypt_age(&plaintext, &signer_recipients)?;
502
503    let artifact = DelegationArtifact {
504        schema: DELEGATION_SCHEMA.to_owned(),
505        deployment_domain: authority.bundle.deployment_domain.clone(),
506        authority_log_did: log.did.clone(),
507        delegated_public_key_b64: delegated_public_b64,
508        ucan_b64: STANDARD.encode(ucan.to_cbor()?),
509    };
510    hyprstream_discovery::validate_registry_delegation(
511        &public_ca,
512        &log,
513        &checkpoint,
514        &artifact,
515        now,
516    )?;
517    commit_outputs(vec![
518        PendingOutput::new(&args.delegated_key, encrypted, 0o600),
519        PendingOutput::new(&args.delegation, pretty_json_bytes(&artifact)?, 0o644),
520    ])?;
521    println!(
522        "{}",
523        serde_json::to_string_pretty(&serde_json::json!({
524            "schema": "hyprstream.registry-delegation-output.v1",
525            "deployment_domain": artifact.deployment_domain,
526            "delegated_key_path": display_path(&args.delegated_key),
527            "delegation_path": display_path(&args.delegation),
528            "delegation_expires_at": expiration,
529            "scope": {
530                "sub": "service:registry",
531                "aud": REGISTRY_AUDIENCE,
532                "profile": REGISTRY_PROFILE,
533                "max_ttl_seconds": 3600
534            },
535            "enrollment_scope": {
536                "allowed_services": hyprstream_discovery::SERVICE_KEY_ENROLLMENT_ALLOWED_SERVICES,
537                "key_type": ENROLLMENT_KEY_TYPE,
538                "max_attestation_ttl_seconds": 3600
539            }
540        }))?
541    );
542    Ok(())
543}
544
545fn mint_registry_jwt(args: &MintRegistryJwtArgs) -> Result<()> {
546    preflight_outputs([&args.jwt, &args.contract], args.force)?;
547    let public_ca = read_limited(&args.public_ca, PUBLIC_CA_BYTES)?;
548    let root_domain = hyprstream_discovery::verify_deployment_public_ca(&public_ca)?;
549    let registry_key: [u8; 32] = read_limited(&args.registry_public_key, 32)?
550        .try_into()
551        .map_err(|_| anyhow!("registry public key must be exactly 32 bytes"))?;
552    VerifyingKey::from_bytes(&registry_key).context("invalid registry Ed25519 public key")?;
553    let identities = mint_identities(args)?;
554    let authority_log_bytes = read_limited(&args.authority_log, MAX_CLOUD_SECRET_BYTES)?;
555    let installed_log: AuthorityLogFile =
556        serde_json::from_slice(&authority_log_bytes).context("decode installed authority log")?;
557    let authority_checkpoint_bytes =
558        read_limited(&args.authority_checkpoint, MAX_CLOUD_SECRET_BYTES)?;
559    let installed_checkpoint: AuthorityCheckpointFile =
560        serde_json::from_slice(&authority_checkpoint_bytes)
561            .context("decode installed authority checkpoint")?;
562    let active = validate_authority_log(&public_ca, &installed_log, &installed_checkpoint)?;
563
564    let (signer, delegation_b64) = if args.root {
565        let authority =
566            decrypt_authority(&args.authority_key, &identities, args.software_recovery)?;
567        ensure!(
568            authority.bundle.purpose == AuthorityPurpose::Root,
569            "--root accepts only the original root authority bundle"
570        );
571        ensure!(
572            authority.public_bytes() == public_ca,
573            "root authority does not match the pinned public CA"
574        );
575        ensure_active_authority(&authority, &active)?;
576        (authority, None)
577    } else {
578        let artifact_path = args
579            .delegation
580            .as_ref()
581            .ok_or_else(|| anyhow!("--delegation is required"))?;
582        let artifact: DelegationArtifact = read_json_limited(artifact_path, MAX_DELEGATION_BYTES)?;
583        hyprstream_discovery::validate_registry_delegation(
584            &public_ca,
585            &installed_log,
586            &installed_checkpoint,
587            &artifact,
588            now_unix_u64()?,
589        )?;
590        let delegated = match (
591            args.via_delegated_signer.as_deref(),
592            args.via_delegated_signer_fd,
593        ) {
594            (Some(delegated_path), None) => {
595                decrypt_authority(delegated_path, &identities, args.software_recovery)?
596            }
597            (None, Some(fd)) => {
598                let ciphertext = read_fd_limited(fd, MAX_AGE_CIPHERTEXT_BYTES, "delegated signer")?;
599                decrypt_authority_ciphertext(&ciphertext, &identities, args.software_recovery)?
600            }
601            // Clap requires exactly one signer source unless --root; this arm
602            // only fires if that invariant is bypassed programmatically.
603            _ => bail!("--via-delegated-signer or --via-delegated-signer-fd is required"),
604        };
605        ensure!(
606            delegated.bundle.purpose == AuthorityPurpose::RegistryDelegatedSigner,
607            "selected key is not a registry delegated signer"
608        );
609        let declared = STANDARD
610            .decode(&artifact.delegated_public_key_b64)
611            .context("decode delegated public key")?;
612        ensure!(
613            delegated.public_bytes() == declared,
614            "delegated private key does not match the root-authorized delegation"
615        );
616        let artifact_json = serde_json::to_vec(&artifact)?;
617        (delegated, Some(URL_SAFE_NO_PAD.encode(artifact_json)))
618    };
619    ensure!(
620        signer.bundle.deployment_domain == root_domain,
621        "signer is bound to a different deployment domain"
622    );
623
624    let now = chrono::Utc::now().timestamp();
625    let exp = now
626        .checked_add(i64::from(args.ttl_seconds))
627        .ok_or_else(|| anyhow!("credential expiration overflow"))?;
628    let token = encode_registry_jwt(&signer, &registry_key, now, exp, delegation_b64.as_deref())?;
629    ensure!(
630        token.len() <= MAX_CLOUD_SECRET_BYTES,
631        "registry JWT exceeds the 64 KiB cloud-secret contract"
632    );
633    let verified = hyprstream_discovery::verify_deployment_artifacts_with_authority_log(
634        &public_ca,
635        &authority_log_bytes,
636        &authority_checkpoint_bytes,
637        &token,
638    )
639    .context("production deployment verifier rejected minted credential")?;
640    ensure!(
641        verified.registry_public_key == registry_key && verified.deployment_domain == root_domain,
642        "production verification result does not match minted inputs"
643    );
644
645    let jwt_bytes = token.as_bytes();
646    let contract = PublisherManifest {
647        schema: PUBLISHER_MANIFEST_SCHEMA.to_owned(),
648        deployment_domain: root_domain,
649        profile: REGISTRY_PROFILE.to_owned(),
650        audience: REGISTRY_AUDIENCE.to_owned(),
651        expires_at: exp,
652        public_ca: PublisherArtifact {
653            local_path: display_path(&args.public_ca),
654            install_path: PUBLIC_CA_INSTALL_PATH.to_owned(),
655            encoding: "raw".to_owned(),
656            base64: STANDARD.encode(&public_ca),
657            sha256: sha256_hex(&public_ca),
658            size_bytes: public_ca.len(),
659            cloud_secret_store: true,
660        },
661        authority_log: PublisherArtifact {
662            local_path: display_path(&args.authority_log),
663            install_path: AUTHORITY_LOG_INSTALL_PATH.to_owned(),
664            encoding: "json".to_owned(),
665            base64: STANDARD.encode(&authority_log_bytes),
666            sha256: sha256_hex(&authority_log_bytes),
667            size_bytes: authority_log_bytes.len(),
668            cloud_secret_store: true,
669        },
670        authority_checkpoint: PublisherArtifact {
671            local_path: display_path(&args.authority_checkpoint),
672            install_path: AUTHORITY_CHECKPOINT_INSTALL_PATH.to_owned(),
673            encoding: "json".to_owned(),
674            base64: STANDARD.encode(&authority_checkpoint_bytes),
675            sha256: sha256_hex(&authority_checkpoint_bytes),
676            size_bytes: authority_checkpoint_bytes.len(),
677            cloud_secret_store: true,
678        },
679        registry_jwt: PublisherArtifact {
680            local_path: display_path(&args.jwt),
681            install_path: REGISTRY_JWT_INSTALL_PATH.to_owned(),
682            encoding: "utf8".to_owned(),
683            base64: STANDARD.encode(jwt_bytes),
684            sha256: sha256_hex(jwt_bytes),
685            size_bytes: jwt_bytes.len(),
686            cloud_secret_store: true,
687        },
688        private_authority_exported: false,
689        terraform_state_may_contain_private_authority: false,
690    };
691    commit_outputs(vec![
692        PendingOutput::new(&args.jwt, token.into_bytes(), 0o600),
693        PendingOutput::new(&args.contract, pretty_json_bytes(&contract)?, 0o600),
694    ])?;
695    println!("{}", serde_json::to_string_pretty(&contract)?);
696    Ok(())
697}
698
699/// Mint a chain-signed service-key enrollment attestation (hyprstream#1562).
700///
701/// Same trust anchors and post-mint self-verify through the production
702/// verifier as `mint_registry_jwt`; the input contract is public-only — the
703/// 1984-byte hybrid sidecar, never the service's seed.
704fn enroll_service_key(args: &EnrollServiceKeyArgs) -> Result<()> {
705    preflight_outputs([&args.attestation], args.force)?;
706    ensure!(
707        hyprstream_discovery::SERVICE_KEY_ENROLLMENT_ALLOWED_SERVICES
708            .contains(&args.service.as_str()),
709        "service is outside the fixed discovery/policy enrollment allowlist"
710    );
711    let public_ca = read_limited(&args.public_ca, PUBLIC_CA_BYTES)?;
712    let root_domain = hyprstream_discovery::verify_deployment_public_ca(&public_ca)?;
713    let service_public_key = read_limited(&args.service_public_key, PUBLIC_CA_BYTES)?;
714    ensure!(
715        service_public_key.len() == PUBLIC_CA_BYTES,
716        "service public key must be exactly {PUBLIC_CA_BYTES} bytes \
717         (32-byte Ed25519 followed by 1952-byte ML-DSA-65; key type {ENROLLMENT_KEY_TYPE})"
718    );
719    let identities = inherited_identities(
720        &args.identities,
721        &args.identity_fds,
722        &args.yubikey_identities,
723    )?;
724    let authority_log_bytes = read_limited(&args.authority_log, MAX_CLOUD_SECRET_BYTES)?;
725    let installed_log: AuthorityLogFile =
726        serde_json::from_slice(&authority_log_bytes).context("decode installed authority log")?;
727    let authority_checkpoint_bytes =
728        read_limited(&args.authority_checkpoint, MAX_CLOUD_SECRET_BYTES)?;
729    let installed_checkpoint: AuthorityCheckpointFile =
730        serde_json::from_slice(&authority_checkpoint_bytes)
731            .context("decode installed authority checkpoint")?;
732
733    let artifact: DelegationArtifact = read_json_limited(&args.delegation, MAX_DELEGATION_BYTES)?;
734    let now = now_unix_u64()?;
735    let grants_enrollment = hyprstream_discovery::validate_registry_delegation(
736        &public_ca,
737        &installed_log,
738        &installed_checkpoint,
739        &artifact,
740        now,
741    )?
742    .grants_service_key_enrollment;
743    ensure!(
744        grants_enrollment,
745        "delegation does not carry the service-key-enrollment capability"
746    );
747    let delegated = match (
748        args.via_delegated_signer.as_deref(),
749        args.via_delegated_signer_fd,
750    ) {
751        (Some(delegated_path), None) => {
752            decrypt_authority(delegated_path, &identities, args.software_recovery)?
753        }
754        (None, Some(fd)) => {
755            let ciphertext = read_fd_limited(fd, MAX_AGE_CIPHERTEXT_BYTES, "delegated signer")?;
756            decrypt_authority_ciphertext(&ciphertext, &identities, args.software_recovery)?
757        }
758        // Clap requires exactly one signer source. This arm only fires if the
759        // invariant is bypassed programmatically.
760        _ => bail!("--via-delegated-signer or --via-delegated-signer-fd is required"),
761    };
762    ensure!(
763        delegated.bundle.purpose == AuthorityPurpose::RegistryDelegatedSigner,
764        "selected key is not a registry delegated signer"
765    );
766    let declared = STANDARD
767        .decode(&artifact.delegated_public_key_b64)
768        .context("decode delegated public key")?;
769    ensure!(
770        delegated.public_bytes() == declared,
771        "delegated private key does not match the root-authorized delegation"
772    );
773    ensure!(
774        delegated.bundle.deployment_domain == root_domain,
775        "signer is bound to a different deployment domain"
776    );
777
778    let expires_at = now
779        .checked_add(u64::from(args.ttl_seconds))
780        .ok_or_else(|| anyhow!("attestation expiration overflow"))?;
781    let body = ServiceKeyEnrollmentSigningBody {
782        schema: ENROLLMENT_SCHEMA.to_owned(),
783        deployment_domain: root_domain.clone(),
784        service: args.service.clone(),
785        hybrid_public_key_b64: STANDARD.encode(&service_public_key),
786        not_before: i64::try_from(now).context("system clock precedes Unix epoch")?,
787        expires_at: i64::try_from(expires_at).context("attestation expiry conversion")?,
788        delegation: artifact,
789    };
790    let mut attestation = ServiceKeyEnrollmentArtifact::unsigned(body);
791    let signature = sign_nested(
792        &attestation.signing_bytes()?,
793        ENROLLMENT_SIGNATURE_CONTEXT,
794        &delegated.ed,
795        &delegated.pq,
796    )?;
797    attestation.signature_b64 = STANDARD.encode(&signature);
798    let attestation_json = pretty_json_bytes(&attestation)?;
799    ensure!(
800        attestation_json.len() <= MAX_ENROLLMENT_BYTES,
801        "attestation exceeds the 256 KiB enrollment contract"
802    );
803    let verified = hyprstream_discovery::verify_service_key_enrollment(
804        &public_ca,
805        &authority_log_bytes,
806        &authority_checkpoint_bytes,
807        &attestation_json,
808    )
809    .context("production enrollment verifier rejected minted attestation")?;
810    ensure!(
811        verified.service == args.service
812            && verified.hybrid_public_key == service_public_key
813            && verified.deployment_domain == root_domain,
814        "production verification result does not match minted inputs"
815    );
816
817    commit_outputs(vec![PendingOutput::new(
818        &args.attestation,
819        attestation_json,
820        0o644,
821    )])?;
822    println!(
823        "{}",
824        serde_json::to_string_pretty(&serde_json::json!({
825            "schema": "hyprstream.service-key-enrollment-output.v1",
826            "deployment_domain": root_domain,
827            "service": args.service,
828            "attestation_path": display_path(&args.attestation),
829            "attestation_expires_at": expires_at,
830            "key_type": ENROLLMENT_KEY_TYPE,
831        }))?
832    );
833    Ok(())
834}
835
836fn verify_deployment(args: &VerifyDeploymentArgs) -> Result<()> {
837    let public_ca = read_limited(&args.public_ca, PUBLIC_CA_BYTES)?;
838    let token_bytes = read_limited(&args.jwt, MAX_CLOUD_SECRET_BYTES)?;
839    let token = String::from_utf8(token_bytes.clone()).context("registry JWT is not UTF-8")?;
840    ensure!(
841        !token.is_empty() && !token.bytes().any(|byte| byte.is_ascii_whitespace()),
842        "registry JWT must be compact with no surrounding or embedded whitespace"
843    );
844    let contract = args
845        .contract
846        .as_ref()
847        .map(|path| read_json_limited::<PublisherManifest>(path, 1024 * 1024))
848        .transpose()?;
849    let authority_log = read_limited(&args.authority_log, MAX_CLOUD_SECRET_BYTES)?;
850    let authority_checkpoint = read_limited(&args.authority_checkpoint, MAX_CLOUD_SECRET_BYTES)?;
851    let verified = hyprstream_discovery::verify_deployment_artifacts_with_authority_log(
852        &public_ca,
853        &authority_log,
854        &authority_checkpoint,
855        &token,
856    )?;
857    if let Some(contract) = contract {
858        ensure!(
859            contract.schema == PUBLISHER_MANIFEST_SCHEMA,
860            "unsupported contract schema"
861        );
862        ensure!(
863            contract.deployment_domain == verified.deployment_domain,
864            "contract deployment domain does not match authenticated JWT/root"
865        );
866        ensure!(
867            contract.profile == REGISTRY_PROFILE,
868            "contract profile does not match the fixed deployment profile"
869        );
870        ensure!(
871            contract.audience == REGISTRY_AUDIENCE,
872            "contract audience does not match the fixed registry audience"
873        );
874        ensure!(
875            contract.expires_at == verified.expires_at,
876            "contract expiry does not equal the authenticated JWT exp"
877        );
878        verify_publisher_artifact(
879            &contract.public_ca,
880            &public_ca,
881            &display_path(&args.public_ca),
882            PUBLIC_CA_INSTALL_PATH,
883            "raw",
884        )?;
885        verify_publisher_artifact(
886            &contract.authority_log,
887            &authority_log,
888            &display_path(&args.authority_log),
889            AUTHORITY_LOG_INSTALL_PATH,
890            "json",
891        )?;
892        verify_publisher_artifact(
893            &contract.authority_checkpoint,
894            &authority_checkpoint,
895            &display_path(&args.authority_checkpoint),
896            AUTHORITY_CHECKPOINT_INSTALL_PATH,
897            "json",
898        )?;
899        verify_publisher_artifact(
900            &contract.registry_jwt,
901            &token_bytes,
902            &display_path(&args.jwt),
903            REGISTRY_JWT_INSTALL_PATH,
904            "utf8",
905        )?;
906        ensure!(
907            !contract.private_authority_exported
908                && !contract.terraform_state_may_contain_private_authority,
909            "contract permits private authority export"
910        );
911    }
912    // hyprstream#1562 H3: each supplied service-key enrollment attestation must
913    // verify against the same chain — fail closed on the first that does not.
914    let mut enrollments = Vec::with_capacity(args.service_key_attestations.len());
915    for attestation_path in &args.service_key_attestations {
916        let attestation = read_limited(attestation_path, MAX_ENROLLMENT_BYTES)?;
917        let enrollment = hyprstream_discovery::verify_service_key_enrollment(
918            &public_ca,
919            &authority_log,
920            &authority_checkpoint,
921            &attestation,
922        )
923        .with_context(|| {
924            format!(
925                "service-key attestation {} rejected",
926                display_path(attestation_path)
927            )
928        })?;
929        enrollments.push(enrollment);
930    }
931    println!(
932        "{}",
933        serde_json::to_string_pretty(&serde_json::json!({
934            "valid": true,
935            "deployment_domain": verified.deployment_domain,
936            "registry_public_key_base64": STANDARD.encode(verified.registry_public_key),
937            "public_ca_bytes": public_ca.len(),
938            "profile": REGISTRY_PROFILE,
939            "audience": REGISTRY_AUDIENCE,
940            "service_key_enrollments": enrollments
941                .iter()
942                .map(|enrollment| serde_json::json!({
943                    "service": enrollment.service,
944                    "deployment_domain": enrollment.deployment_domain,
945                    "hybrid_public_key_base64": STANDARD.encode(&enrollment.hybrid_public_key),
946                    "expires_at": enrollment.expires_at,
947                }))
948                .collect::<Vec<_>>()
949        }))?
950    );
951    Ok(())
952}
953
954fn verify_publisher_artifact(
955    artifact: &PublisherArtifact,
956    expected_bytes: &[u8],
957    expected_local_path: &str,
958    expected_install_path: &str,
959    expected_encoding: &str,
960) -> Result<()> {
961    ensure!(
962        artifact.local_path == expected_local_path,
963        "contract artifact local path does not match the verified input"
964    );
965    ensure!(
966        artifact.install_path == expected_install_path,
967        "contract artifact install path is not the fixed deployment path"
968    );
969    ensure!(
970        artifact.encoding == expected_encoding,
971        "contract artifact encoding is not the fixed deployment encoding"
972    );
973    ensure!(
974        artifact.cloud_secret_store,
975        "contract artifact unexpectedly forbids cloud secret-store publication"
976    );
977    let decoded = STANDARD
978        .decode(&artifact.base64)
979        .context("decode contract artifact base64")?;
980    ensure!(
981        STANDARD.encode(&decoded) == artifact.base64,
982        "contract artifact base64 is not canonical"
983    );
984    ensure!(
985        decoded == expected_bytes,
986        "contract artifact bytes do not match the verified input"
987    );
988    ensure!(
989        artifact.size_bytes == decoded.len(),
990        "contract artifact size does not match authenticated bytes"
991    );
992    ensure!(
993        artifact.sha256 == sha256_hex(&decoded),
994        "contract artifact SHA-256 does not match authenticated bytes"
995    );
996    Ok(())
997}
998
999/// Nothing else in the repository installs the OS-owned trust directory or
1000/// keeps the 1-hour registry credential refreshed — every
1001/// prior `trust mint-*` command only produces local artifacts under the
1002/// operator's ceremony directory. This command projects those artifacts onto
1003/// the fixed paths `hyprstream-discovery::service::read_trusted_artifact`
1004/// actually reads, and, when delegated-signer material is supplied,
1005/// additionally installs and enables a systemd timer that keeps the registry
1006/// credential minted within its TTL.
1007fn install_deployment_trust(args: &InstallDeploymentTrustArgs) -> Result<()> {
1008    ensure!(
1009        nix::unistd::Uid::effective().is_root(),
1010        "trust install must run as root: the fixed paths under {DEPLOYMENT_TRUST_DIR} must be \
1011         root-owned (see hyprstream-discovery's read_trusted_artifact), and this command does not \
1012         attempt to chown files it does not itself own"
1013    );
1014    validate_refresh_interval(&args.refresh_interval)?;
1015
1016    let public_ca = read_limited(&args.public_ca, PUBLIC_CA_BYTES)?;
1017    ensure!(
1018        public_ca.len() == PUBLIC_CA_BYTES,
1019        "public_ca must be exactly {PUBLIC_CA_BYTES} bytes"
1020    );
1021    hyprstream_discovery::verify_deployment_public_ca(&public_ca)
1022        .context("public_ca is not a valid production deployment CA")?;
1023    let authority_log: AuthorityLogFile =
1024        read_json_limited(&args.authority_log, MAX_CLOUD_SECRET_BYTES)?;
1025    let authority_checkpoint: AuthorityCheckpointFile =
1026        read_json_limited(&args.authority_checkpoint, MAX_CLOUD_SECRET_BYTES)?;
1027    validate_authority_log(&public_ca, &authority_log, &authority_checkpoint)
1028        .context("authority log/checkpoint do not verify against public_ca")?;
1029
1030    ensure_root_owned_dir(Path::new(DEPLOYMENT_TRUST_DIR), 0o755)?;
1031
1032    let public_ca_dest = PathBuf::from(PUBLIC_CA_INSTALL_PATH);
1033    let authority_log_dest = PathBuf::from(AUTHORITY_LOG_INSTALL_PATH);
1034    let authority_checkpoint_dest = PathBuf::from(AUTHORITY_CHECKPOINT_INSTALL_PATH);
1035    preflight_outputs(
1036        [
1037            &public_ca_dest,
1038            &authority_log_dest,
1039            &authority_checkpoint_dest,
1040        ],
1041        args.force,
1042    )?;
1043    commit_outputs(vec![
1044        PendingOutput::new(&public_ca_dest, public_ca.clone(), 0o644),
1045        PendingOutput::new(
1046            &authority_log_dest,
1047            pretty_json_bytes(&authority_log)?,
1048            0o644,
1049        ),
1050        PendingOutput::new(
1051            &authority_checkpoint_dest,
1052            pretty_json_bytes(&authority_checkpoint)?,
1053            0o644,
1054        ),
1055    ])?;
1056
1057    let mut refresher_enabled = false;
1058    if let Some(delegated_key) = &args.delegated_key {
1059        let delegation = args
1060            .delegation
1061            .as_ref()
1062            .ok_or_else(|| anyhow!("--delegation is required with --delegated-key"))?;
1063        let registry_public_key = args
1064            .registry_public_key
1065            .as_ref()
1066            .ok_or_else(|| anyhow!("--registry-public-key is required with --delegated-key"))?;
1067        let refresh_identity = args
1068            .refresh_identity
1069            .as_ref()
1070            .ok_or_else(|| anyhow!("--refresh-identity is required with --delegated-key"))?;
1071        install_trust_refresher(
1072            args,
1073            &public_ca,
1074            &authority_log,
1075            &authority_checkpoint,
1076            delegated_key,
1077            delegation,
1078            registry_public_key,
1079            refresh_identity,
1080        )?;
1081        refresher_enabled = true;
1082    }
1083
1084    println!(
1085        "{}",
1086        serde_json::to_string_pretty(&serde_json::json!({
1087            "schema": "hyprstream.deployment-trust-install-output.v1",
1088            "installed": [
1089                PUBLIC_CA_INSTALL_PATH,
1090                AUTHORITY_LOG_INSTALL_PATH,
1091                AUTHORITY_CHECKPOINT_INSTALL_PATH,
1092            ],
1093            "refresher_enabled": refresher_enabled,
1094        }))?
1095    );
1096    Ok(())
1097}
1098
1099/// `mkdir -p` with the given mode on the leaf. Every component of the path —
1100/// not just the leaf — is inspected with `symlink_metadata` and must be a
1101/// non-symlink directory owned by root (or by the given owner) and writable by
1102/// nobody else, mirroring the fail-closed posture `read_trusted_artifact`
1103/// requires of every ancestor of a trust path it reads. Guarantee: at the
1104/// moment each component was inspected it was a root/owner-owned real
1105/// directory no other user could write into. Not guaranteed: the
1106/// checks are lstat-based, not O_NOFOLLOW-handle-based, so a component
1107/// swapped between inspection and use is not detected (TOCTOU).
1108fn ensure_root_owned_dir(dir: &Path, mode: u32) -> Result<()> {
1109    ensure_owned_dir(dir, mode, 0)
1110}
1111
1112fn ensure_owned_dir(dir: &Path, mode: u32, owner_uid: u32) -> Result<()> {
1113    let mut ancestors: Vec<&Path> = dir.ancestors().collect();
1114    ancestors.reverse();
1115    for component in ancestors {
1116        if component.as_os_str().is_empty() {
1117            continue;
1118        }
1119        let is_leaf = component == dir;
1120        match std::fs::symlink_metadata(component) {
1121            Ok(metadata) => {
1122                ensure!(
1123                    !metadata.file_type().is_symlink(),
1124                    "refusing to install through a symlinked path component: {}",
1125                    component.display()
1126                );
1127                ensure!(
1128                    metadata.is_dir(),
1129                    "install path component exists and is not a directory: {}",
1130                    component.display()
1131                );
1132                let uid = metadata.uid();
1133                ensure!(
1134                    uid == 0 || uid == owner_uid,
1135                    "install path component {} is owned by uid {uid}, not root; refusing to \
1136                     install trust material under a directory another user controls",
1137                    component.display()
1138                );
1139                let mode = metadata.mode();
1140                ensure!(
1141                    mode & 0o022 == 0,
1142                    "install path component {} is group/world writable (mode {:04o}); refusing \
1143                     to install trust material under a directory other users can modify",
1144                    component.display(),
1145                    mode & 0o7777
1146                );
1147            }
1148            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
1149                std::fs::create_dir(component)
1150                    .with_context(|| format!("create directory {}", component.display()))?;
1151                if !is_leaf {
1152                    std::fs::set_permissions(component, std::fs::Permissions::from_mode(0o755))
1153                        .with_context(|| format!("set permissions on {}", component.display()))?;
1154                }
1155            }
1156            Err(error) => {
1157                return Err(error)
1158                    .with_context(|| format!("inspect directory {}", component.display()))
1159            }
1160        }
1161        if is_leaf {
1162            std::fs::set_permissions(component, std::fs::Permissions::from_mode(mode))
1163                .with_context(|| format!("set permissions on {}", component.display()))?;
1164        }
1165    }
1166    Ok(())
1167}
1168
1169/// Fail closed if the `age` binary is not on `PATH`, the refresh identity
1170/// cannot decrypt the delegated signer ciphertext, the decrypted bundle is not
1171/// a `RegistryDelegatedSigner`, or its public bytes do not match the
1172/// root-authorized delegation artifact. Every condition is checked before the
1173/// installer writes any output or enables the timer, so a misconfigured
1174/// deployment is reported immediately rather than discovered by the first
1175/// unattended timer firing.
1176fn trial_decrypt_delegated_signer(
1177    delegated_key: &Path,
1178    refresh_identity: &Path,
1179    artifact: &DelegationArtifact,
1180) -> Result<()> {
1181    // The refresher shells out to the `age` binary; a host without it cannot
1182    // honor the timer, so fail closed early with a clear message.
1183    let age_probe = std::process::Command::new("age")
1184        .arg("--version")
1185        .stdin(Stdio::null())
1186        .stdout(Stdio::null())
1187        .stderr(Stdio::null())
1188        .status()
1189        .context(
1190            "the `age` binary is not installed or not executable; the trust refresher requires it",
1191        )?;
1192    ensure!(
1193        age_probe.success(),
1194        "the `age` binary is not installed or not executable; the trust refresher requires it"
1195    );
1196
1197    // Reproduce the exact decrypt path the refresher's ExecStart follows:
1198    // `age --decrypt --identity <refresh_identity>` on the delegated signer.
1199    // decrypt_authority reconstructs the full LoadedAuthority and asserts the
1200    // bundle's own public-key fingerprint, so the public-bytes comparison uses
1201    // the identical derivation path the refresher will exercise on every timer
1202    // firing. software_recovery is false because the refresher ExecStart never
1203    // passes --software-recovery.
1204    let identities = AgeIdentities::new(vec![refresh_identity.to_path_buf()])?;
1205    let trial = decrypt_authority(delegated_key, &identities, false)
1206        .context("refresh identity cannot decrypt the delegated signer ciphertext")?;
1207    ensure!(
1208        trial.bundle.purpose == AuthorityPurpose::RegistryDelegatedSigner,
1209        "decrypted delegated signer is not a RegistryDelegatedSigner; the \
1210         refresher ExecStart rejects any other purpose"
1211    );
1212    let trial_public = trial.public_bytes();
1213    let declared = STANDARD
1214        .decode(&artifact.delegated_public_key_b64)
1215        .context("decode delegated public key from delegation artifact")?;
1216    ensure!(
1217        trial_public == declared,
1218        "decrypted delegated signer public key does not match the root-authorized delegation"
1219    );
1220    Ok(())
1221}
1222
1223#[allow(clippy::too_many_arguments)]
1224fn install_trust_refresher(
1225    args: &InstallDeploymentTrustArgs,
1226    public_ca: &[u8],
1227    authority_log: &AuthorityLogFile,
1228    authority_checkpoint: &AuthorityCheckpointFile,
1229    delegated_key: &Path,
1230    delegation: &Path,
1231    registry_public_key: &Path,
1232    refresh_identity: &Path,
1233) -> Result<()> {
1234    let delegated_key_bytes = read_limited(delegated_key, MAX_AGE_CIPHERTEXT_BYTES)?;
1235    let delegation_artifact: DelegationArtifact =
1236        read_json_limited(delegation, MAX_DELEGATION_BYTES)?;
1237    // Full cryptographic validation against the just-verified authority log:
1238    // an expired, tampered, or wrong-deployment delegation must fail install
1239    // rather than be discovered by the first unattended refresh.
1240    hyprstream_discovery::validate_registry_delegation(
1241        public_ca,
1242        authority_log,
1243        authority_checkpoint,
1244        &delegation_artifact,
1245        now_unix_u64()?,
1246    )
1247    .context("delegation artifact does not verify against the installed authority log")?;
1248    let registry_public_key_bytes = read_limited(registry_public_key, 32)?;
1249    let registry_public_key_array: [u8; 32] = registry_public_key_bytes
1250        .clone()
1251        .try_into()
1252        .map_err(|_| anyhow!("registry_public_key must be exactly 32 bytes"))?;
1253    VerifyingKey::from_bytes(&registry_public_key_array)
1254        .context("invalid registry Ed25519 public key")?;
1255    let refresh_identity_bytes = read_limited(refresh_identity, MAX_AGE_IDENTITY_BYTES)?;
1256    validate_age_identity_contents(&refresh_identity_bytes)
1257        .with_context(|| format!("refresh identity {}", refresh_identity.display()))?;
1258
1259    // Trial-decrypt the delegated signer with the refresh identity before
1260    // writing any outputs or enabling the timer. If the identity cannot open
1261    // the ciphertext, or the decrypted public key does not match the root-
1262    // authorized delegation, the install must fail closed here rather than
1263    // silently succeed and then fail on every timer firing.
1264    trial_decrypt_delegated_signer(delegated_key, refresh_identity, &delegation_artifact)
1265        .context("trial decrypt of the delegated signer with the refresh identity failed")?;
1266
1267    ensure_root_owned_dir(Path::new(DELEGATED_DIR), 0o750)?;
1268    ensure_root_owned_dir(Path::new(CREDENTIALS_RUN_DIR), 0o750)?;
1269
1270    let delegated_key_dest = PathBuf::from(DELEGATED_SIGNER_INSTALL_PATH);
1271    let delegation_dest = PathBuf::from(DELEGATION_INSTALL_PATH);
1272    let registry_public_key_dest = PathBuf::from(REGISTRY_PUBLIC_KEY_INSTALL_PATH);
1273    let refresh_identity_dest = PathBuf::from(REFRESH_IDENTITY_INSTALL_PATH);
1274    preflight_outputs(
1275        [
1276            &delegated_key_dest,
1277            &delegation_dest,
1278            &registry_public_key_dest,
1279            &refresh_identity_dest,
1280        ],
1281        args.force,
1282    )?;
1283    commit_outputs(vec![
1284        PendingOutput::new(&delegated_key_dest, delegated_key_bytes, 0o600),
1285        PendingOutput::new(
1286            &delegation_dest,
1287            pretty_json_bytes(&delegation_artifact)?,
1288            0o644,
1289        ),
1290        PendingOutput::new(&registry_public_key_dest, registry_public_key_bytes, 0o644),
1291        PendingOutput::new(&refresh_identity_dest, refresh_identity_bytes, 0o600),
1292    ])?;
1293
1294    let service_dest = PathBuf::from(TRUST_REFRESH_SERVICE_UNIT_PATH);
1295    let timer_dest = PathBuf::from(TRUST_REFRESH_TIMER_UNIT_PATH);
1296    preflight_outputs([&service_dest, &timer_dest], true)?;
1297    commit_outputs(vec![
1298        PendingOutput::new(
1299            &service_dest,
1300            trust_refresh_service_unit().into_bytes(),
1301            0o644,
1302        ),
1303        PendingOutput::new(
1304            &timer_dest,
1305            trust_refresh_timer_unit(&args.refresh_interval).into_bytes(),
1306            0o644,
1307        ),
1308    ])?;
1309
1310    if !args.no_enable {
1311        run_systemctl(&["daemon-reload"])?;
1312        run_systemctl(&["enable", "--now", "hyprstream-trust-refresh.timer"])?;
1313    }
1314    Ok(())
1315}
1316
1317fn run_systemctl(args: &[&str]) -> Result<()> {
1318    let status = Command::new("systemctl")
1319        .args(args)
1320        .status()
1321        .with_context(|| format!("run systemctl {}", args.join(" ")))?;
1322    ensure!(
1323        status.success(),
1324        "systemctl {} failed: {status}",
1325        args.join(" ")
1326    );
1327    Ok(())
1328}
1329
1330/// Refuse a refresh interval that is not a plain systemd time span of the
1331/// form `<positive integer><s|min|h>`. The value is interpolated verbatim
1332/// into the generated timer unit, so anything containing whitespace or
1333/// control characters could inject unit directives, and a typo would only
1334/// surface as a late systemd parse failure instead of failing the install.
1335fn validate_refresh_interval(interval: &str) -> Result<()> {
1336    let digits_ok = |digits: &str| {
1337        !digits.is_empty()
1338            && !digits.starts_with('0')
1339            && digits.bytes().all(|byte| byte.is_ascii_digit())
1340    };
1341    let valid = interval
1342        .strip_suffix("min")
1343        .or_else(|| interval.strip_suffix('s'))
1344        .or_else(|| interval.strip_suffix('h'))
1345        .is_some_and(digits_ok);
1346    ensure!(
1347        valid,
1348        "invalid --refresh-interval {interval:?}: use a positive integer with an s, min, or h \
1349         suffix and no whitespace (for example 30min)"
1350    );
1351    Ok(())
1352}
1353
1354/// The refresh identity is passed by path to `age --decrypt --identity`, which
1355/// expects a plaintext identity file: optional `#` comment or blank lines plus
1356/// at least one native X25519 identity line. Encrypted or plugin identities
1357/// would make the unattended refresher fail at its first timer firing, so
1358/// they are rejected at install time.
1359fn validate_age_identity_contents(bytes: &[u8]) -> Result<()> {
1360    let text = std::str::from_utf8(bytes).context("age identity file is not UTF-8 text")?;
1361    let mut has_identity = false;
1362    for line in text.lines() {
1363        let line = line.trim();
1364        if line.is_empty() || line.starts_with('#') {
1365            continue;
1366        }
1367        ensure!(
1368            line.starts_with("AGE-SECRET-KEY-1"),
1369            "age identity file must contain only comment lines and plaintext \
1370             AGE-SECRET-KEY-1... identity lines"
1371        );
1372        has_identity = true;
1373    }
1374    ensure!(
1375        has_identity,
1376        "age identity file contains no AGE-SECRET-KEY-1... identity line"
1377    );
1378    Ok(())
1379}
1380
1381/// The refresher only ever needs the delegated (non-root) signer: it must
1382/// never be able to sign directly with the root authority, matching the
1383/// least-privilege split the ceremony (docs/deployment-trust-ceremony.md)
1384/// establishes between minting and day-to-day operation. The installed
1385/// refresh identity enforces the same split at the encryption layer: it is a
1386/// `--signer-recipient` of the delegated signer only, so even with the unit's
1387/// read access to the trust directory it can never open the operator-held
1388/// root authority bundle, which is sealed to a disjoint recipient ring.
1389fn trust_refresh_service_unit() -> String {
1390    // The unit assumes the packaged binary location; the installer does not
1391    // encode its own (possibly temporary) executable path into the unit.
1392    format!(
1393        r#"[Unit]
1394Description=Hyprstream registry deployment credential refresh
1395After=network-online.target
1396Wants=network-online.target
1397ConditionPathExists={DEPLOYMENT_TRUST_DIR}/deployment-ca.hybrid
1398
1399[Service]
1400Type=oneshot
1401ExecStart=/usr/bin/hyprstream trust mint-registry-jwt \
1402  --public-ca {PUBLIC_CA_INSTALL_PATH} \
1403  --authority-log {AUTHORITY_LOG_INSTALL_PATH} \
1404  --authority-checkpoint {AUTHORITY_CHECKPOINT_INSTALL_PATH} \
1405  --via-delegated-signer {DELEGATED_SIGNER_INSTALL_PATH} \
1406  --delegation {DELEGATION_INSTALL_PATH} \
1407  --registry-public-key {REGISTRY_PUBLIC_KEY_INSTALL_PATH} \
1408  --identity {REFRESH_IDENTITY_INSTALL_PATH} \
1409  --jwt {REGISTRY_JWT_INSTALL_PATH} \
1410  --contract {CREDENTIALS_RUN_DIR}/deployment-trust.contract.json \
1411  --force
1412# mint-registry-jwt writes {REGISTRY_JWT_INSTALL_PATH} through the same
1413# staged-file-then-rename commit path every other trust artifact uses, so a
1414# concurrent reader never observes a partially-written credential.
1415# RuntimeDirectory recreates the tmpfs-backed credentials directory after a
1416# reboot (ReadWritePaths sandbox setup fails if it is missing); Preserve keeps
1417# the minted credential alive after this oneshot unit exits.
1418RuntimeDirectory=hyprstream/credentials
1419RuntimeDirectoryMode=0750
1420RuntimeDirectoryPreserve=yes
1421ProtectSystem=strict
1422ReadWritePaths={CREDENTIALS_RUN_DIR}
1423ReadOnlyPaths={DEPLOYMENT_TRUST_DIR}
1424NoNewPrivileges=yes
1425"#
1426    )
1427}
1428
1429fn trust_refresh_timer_unit(refresh_interval: &str) -> String {
1430    format!(
1431        r#"[Unit]
1432Description=Periodic refresh of the Hyprstream registry deployment credential
1433
1434[Timer]
1435OnBootSec=30s
1436OnUnitActiveSec={refresh_interval}
1437AccuracySec=1min
1438Persistent=true
1439
1440[Install]
1441WantedBy=timers.target
1442"#
1443    )
1444}
1445
1446fn rotate_authority(args: &RotateAuthorityArgs) -> Result<()> {
1447    ensure!(
1448        args.add ^ args.replace,
1449        "select exactly one rotation mode: --add or --replace"
1450    );
1451    preflight_outputs(
1452        [
1453            &args.new_authority_key,
1454            &args.new_public_key,
1455            &args.authority_log_out,
1456            &args.authority_checkpoint_out,
1457        ],
1458        args.force,
1459    )?;
1460    let recipients = distinct_recipients(args.recipients.clone())?;
1461    ensure!(
1462        recipients.len() >= 2,
1463        "authority rotation requires at least two distinct age recipients"
1464    );
1465    let public_ca = read_limited(&args.public_ca, PUBLIC_CA_BYTES)?;
1466    let log: AuthorityLogFile = read_json_limited(&args.authority_log, MAX_CLOUD_SECRET_BYTES)?;
1467    let checkpoint: AuthorityCheckpointFile =
1468        read_json_limited(&args.authority_checkpoint, MAX_CLOUD_SECRET_BYTES)?;
1469    let active = validate_authority_log(&public_ca, &log, &checkpoint)?;
1470    let identities = combined_identities(&args.identities, &args.yubikey_identities)?;
1471    let current = decrypt_authority(&args.authority_key, &identities, args.software_recovery)?;
1472    ensure_active_authority(&current, &active)?;
1473
1474    let new_ed = SigningKey::generate(&mut rand::rngs::OsRng);
1475    let (new_pq, _) = ml_dsa_generate_keypair();
1476    let new_public = public_pair_bytes(&new_ed.verifying_key(), &new_pq);
1477    let new_rotation_key = HybridRotationKey::new(
1478        new_ed.verifying_key().to_bytes(),
1479        ml_dsa_sk_to_vk_bytes(&new_pq),
1480    )?;
1481    let next_keys = if args.add {
1482        let mut keys = active.rotation_keys.clone();
1483        ensure!(
1484            keys.len() < hyprstream_discovery::did_op::MAX_ROTATION_KEYS,
1485            "authority set is already at its maximum size"
1486        );
1487        keys.push(new_rotation_key);
1488        keys
1489    } else {
1490        vec![new_rotation_key]
1491    };
1492    let operations = decode_authority_operations(&log)?;
1493    let previous = operations
1494        .last()
1495        .ok_or_else(|| anyhow!("authority log is empty"))?;
1496    let next = sign_did_op(
1497        DidOp {
1498            sequence: previous
1499                .sequence
1500                .checked_add(1)
1501                .ok_or_else(|| anyhow!("authority sequence overflow"))?,
1502            prev: Some(previous.cid().encode()),
1503            rotation_keys: next_keys,
1504            signature: placeholder_did_signature(),
1505        },
1506        &current.ed,
1507        &current.pq,
1508    )?;
1509    let mut operations = operations;
1510    operations.push(next);
1511    let next_log = authority_log_from_ops(&log.deployment_domain, operations)?;
1512    let next_verified = validate_authority_log_root(&public_ca, &next_log)?;
1513    let expected_sequence = checkpoint
1514        .sequence
1515        .checked_add(1)
1516        .ok_or_else(|| anyhow!("authority checkpoint sequence overflow"))?;
1517    ensure!(
1518        next_verified.did == checkpoint.did && next_verified.sequence == expected_sequence,
1519        "authority rotation did not advance the trusted checkpoint exactly once"
1520    );
1521    let next_checkpoint = authority_checkpoint(&next_log.deployment_domain, &next_verified);
1522    validate_authority_log(&public_ca, &next_log, &next_checkpoint)?;
1523
1524    let new_bundle = AuthorityBundle {
1525        schema: AUTHORITY_BUNDLE_SCHEMA.to_owned(),
1526        purpose: AuthorityPurpose::RotatedAuthority,
1527        deployment_domain: log.deployment_domain.clone(),
1528        public_key_sha256: sha256_hex(&new_public),
1529        ed25519: Ed25519Secret::Software {
1530            seed_b64: encode_ed25519_seed_b64(&new_ed),
1531            public_b64: STANDARD.encode(new_ed.verifying_key().as_bytes()),
1532        },
1533        ml_dsa_65_seed_b64: encode_ml_dsa_seed_b64(&new_pq),
1534        recipient_count: recipients.len(),
1535    };
1536    let plaintext = serialize_secret_json(&new_bundle)?;
1537    let encrypted = encrypt_age(&plaintext, &recipients)?;
1538
1539    commit_outputs(vec![
1540        PendingOutput::new(&args.new_public_key, new_public, 0o644),
1541        PendingOutput::new(&args.new_authority_key, encrypted, 0o600),
1542        PendingOutput::new(
1543            &args.authority_log_out,
1544            pretty_json_bytes(&next_log)?,
1545            0o644,
1546        ),
1547        PendingOutput::new(
1548            &args.authority_checkpoint_out,
1549            pretty_json_bytes(&next_checkpoint)?,
1550            0o644,
1551        ),
1552    ])?;
1553    println!(
1554        "{}",
1555        serde_json::to_string_pretty(&serde_json::json!({
1556            "schema": "hyprstream.authority-rotation-output.v1",
1557            "deployment_domain": next_log.deployment_domain,
1558            "authority_log_did": next_log.did,
1559            "sequence": next_checkpoint.sequence,
1560            "head_cid": next_checkpoint.head_cid,
1561            "mode": if args.add { "add" } else { "replace" },
1562            "new_public_key_path": display_path(&args.new_public_key),
1563            "new_authority_key_path": display_path(&args.new_authority_key),
1564            "authority_log_path": display_path(&args.authority_log_out),
1565            "authority_checkpoint_path": display_path(&args.authority_checkpoint_out)
1566        }))?
1567    );
1568    Ok(())
1569}
1570
1571/// Mint the deployment anchor capsule plus the `did:web` document that vouches
1572/// for it.
1573///
1574/// The two outputs are inseparable: the `did:at9p` identifier IS the BLAKE3-512
1575/// CID of the capsule, and the document must name that exact identifier back.
1576/// Both are re-verified through the production DID-anchored resolver before
1577/// anything is written.
1578fn mint_anchor_capsule(args: &MintAnchorCapsuleArgs) -> Result<()> {
1579    preflight_outputs([&args.capsule_out, &args.did_json_out], args.force)?;
1580    ensure!(
1581        args.did_web.starts_with("did:web:"),
1582        "--did-web must be a did:web identifier (for example did:web:staging.example.com)"
1583    );
1584    let reach = anchor_reach_endpoint(args)?;
1585
1586    let public_ca = read_limited(&args.public_ca, PUBLIC_CA_BYTES)?;
1587    let log: AuthorityLogFile = read_json_limited(&args.authority_log, MAX_CLOUD_SECRET_BYTES)?;
1588    let checkpoint: AuthorityCheckpointFile =
1589        read_json_limited(&args.authority_checkpoint, MAX_CLOUD_SECRET_BYTES)?;
1590    let active = validate_authority_log(&public_ca, &log, &checkpoint)?;
1591
1592    let identities = combined_identities(&args.identities, &args.yubikey_identities)?;
1593    let authority = decrypt_authority(&args.authority_key, &identities, args.software_recovery)?;
1594    ensure_anchor_authority(&authority, &public_ca, &active)?;
1595
1596    let minted = build_anchor_material(args, &reach, &authority)?;
1597    commit_outputs(vec![
1598        PendingOutput::new(&args.capsule_out, minted.capsule_bytes.clone(), 0o644),
1599        PendingOutput::new(
1600            &args.did_json_out,
1601            pretty_json_bytes(&minted.document)?,
1602            0o644,
1603        ),
1604    ])?;
1605    println!(
1606        "{}",
1607        serde_json::to_string_pretty(&serde_json::json!({
1608            "schema": "hyprstream.deployment-anchor-capsule-output.v1",
1609            "deployment_domain": authority.bundle.deployment_domain,
1610            "cluster_at9p_did": minted.at9p_did,
1611            "cluster_did_web": args.did_web,
1612            "capsule_path": display_path(&args.capsule_out),
1613            "capsule_bytes": minted.capsule_bytes.len(),
1614            "capsule_sha256": sha256_hex(&minted.capsule_bytes),
1615            "did_json_path": display_path(&args.did_json_out),
1616            "publish": {
1617                "capsule": format!(".well-known/at9p/{}.cbor", minted.cid512),
1618                "document": ".well-known/did.json",
1619            },
1620            "reach": reach.summary,
1621            "mesh_material_published": args.mesh_pq.is_some(),
1622        }))?
1623    );
1624    Ok(())
1625}
1626
1627/// A minted, self-verified anchor pair, before it touches the filesystem.
1628struct MintedAnchor {
1629    capsule_bytes: Vec<u8>,
1630    cid512: String,
1631    at9p_did: String,
1632    document: serde_json::Value,
1633}
1634
1635/// Build and self-verify the anchor capsule and its document.
1636///
1637/// The capsule publishes the deployment authority as its primary subject key —
1638/// that key IS the deployment CA the resolver installs — and signs itself with
1639/// that same authority under pinned Hybrid.
1640fn build_anchor_material(
1641    args: &MintAnchorCapsuleArgs,
1642    reach: &AnchorReach,
1643    authority: &LoadedAuthority,
1644) -> Result<MintedAnchor> {
1645    let subject_key = HybridKeyPair::new(
1646        authority.ed.verifying_key().to_bytes(),
1647        ml_dsa_sk_to_vk_bytes(&authority.pq),
1648    )
1649    .context("deployment authority is not a valid at9p hybrid subject key")?;
1650    let service = ServiceEntry::new(
1651        ANCHOR_REACH_SERVICE,
1652        ServiceType::NinePExport,
1653        reach.endpoint.clone(),
1654    )
1655    .context("build the deployment-reach service entry")?;
1656    let mut body = CapsuleBody::new(vec![subject_key], vec![service])
1657        .context("build the anchor capsule body")?;
1658    body.also_known_as = Some(vec![args.did_web.clone()]);
1659    let capsule = sign_capsule_detached(body, &authority.ed, &authority.pq)
1660        .context("hybrid-sign the anchor capsule")?;
1661    let capsule_bytes = capsule.to_dag_cbor()?;
1662    let cid512 = capsule.cid512()?;
1663    let at9p_did = format!("did:at9p:{cid512}");
1664    let document = anchor_did_document(args, &at9p_did, &authority.ed.verifying_key(), reach)?;
1665
1666    // Publishing material the production resolver would reject is the one
1667    // failure this command exists to prevent: check before anything is written.
1668    let verified =
1669        verify_anchor_material_offline(&at9p_did, &args.did_web, &document, &capsule_bytes)
1670            .context(
1671                "the minted anchor pair was rejected by the production DID-anchored verifier; \
1672                 nothing was written",
1673            )?;
1674    ensure!(
1675        verified.deployment_ca_public == authority.public_bytes(),
1676        "verified anchor capsule yields a different deployment CA than the signing authority"
1677    );
1678
1679    Ok(MintedAnchor {
1680        capsule_bytes,
1681        cid512,
1682        at9p_did,
1683        document,
1684    })
1685}
1686
1687/// The capsule's deployment-reach entry plus the document-side mechanics that
1688/// must describe the same endpoint.
1689struct AnchorReach {
1690    endpoint: ServiceEndpoint,
1691    /// Optional `did:web` transport service entry contributing channel
1692    /// mechanics (SNI, WebPKI policy, cert pins) for the capsule-bound socket.
1693    document_service: Option<serde_json::Value>,
1694    summary: serde_json::Value,
1695}
1696
1697/// Build the `#ns` endpoint from the operator-supplied anchor-node reach.
1698fn anchor_reach_endpoint(args: &MintAnchorCapsuleArgs) -> Result<AnchorReach> {
1699    match (args.iroh_node_id.as_deref(), args.quic_endpoint) {
1700        (Some(node_id), None) => {
1701            let node_id = node_id.strip_prefix("did:key:").unwrap_or(node_id);
1702            hyprstream_rpc::did_key::decode_ed25519_multikey(node_id)
1703                .context("--iroh-node-id must be an Ed25519 Multikey (z6Mk...)")?;
1704            let mut endpoint = ServiceEndpoint::new(Transport::Iroh, format!("iroh://{node_id}"))
1705                .context("build the iroh deployment-reach endpoint")?;
1706            endpoint.node_id = Some(node_id.to_owned());
1707            endpoint.relay = args.iroh_relay.clone();
1708            Ok(AnchorReach {
1709                endpoint,
1710                document_service: None,
1711                summary: serde_json::json!({
1712                    "transport": "iroh",
1713                    "node_id": node_id,
1714                    "relay": args.iroh_relay,
1715                }),
1716            })
1717        }
1718        (None, Some(address)) => {
1719            let endpoint = ServiceEndpoint::new(Transport::Quic, format!("quic://{address}"))
1720                .context("build the QUIC deployment-reach endpoint")?;
1721            let pins = args
1722                .quic_cert_sha256
1723                .iter()
1724                .map(|pin| {
1725                    let raw = hex::decode(pin.trim())
1726                        .with_context(|| format!("--quic-cert-sha256 {pin} is not hex"))?;
1727                    let raw: [u8; 32] = raw.try_into().map_err(|_| {
1728                        anyhow!("--quic-cert-sha256 {pin} is not a 32-byte SHA-256 digest")
1729                    })?;
1730                    Ok(raw)
1731                })
1732                .collect::<Result<Vec<_>>>()?;
1733            let sni = args
1734                .quic_sni
1735                .clone()
1736                .unwrap_or_else(|| address.ip().to_string());
1737            let auth = if pins.is_empty() {
1738                ensure!(
1739                    args.quic_web_pki,
1740                    "a QUIC anchor reach needs channel mechanics: pass --quic-cert-sha256 \
1741                     for a pinned leaf certificate, or --quic-web-pki with --quic-sni for \
1742                     a WebPKI-terminated endpoint"
1743                );
1744                QuicServerAuth::web_pki()
1745            } else if args.quic_web_pki {
1746                QuicServerAuth::web_pki_pinned(pins)?
1747            } else {
1748                QuicServerAuth::pinned(pins)?
1749            };
1750            let document_service = Some(serde_json::json!({
1751                "id": format!("{}#quic", args.did_web),
1752                "type": "QuicTransport",
1753                "serviceEndpoint": hyprstream_rpc::service_entry::encode_quic(
1754                    &format!("https://{sni}:{}", address.port()),
1755                    &auth,
1756                    &["hyprstream-rpc/1"],
1757                ),
1758            }));
1759            Ok(AnchorReach {
1760                endpoint,
1761                document_service,
1762                summary: serde_json::json!({
1763                    "transport": "quic",
1764                    "address": address.to_string(),
1765                    "sni": sni,
1766                    "cert_pins": args.quic_cert_sha256.len(),
1767                    "web_pki": args.quic_web_pki,
1768                }),
1769            })
1770        }
1771        _ => bail!(
1772            "exactly one anchor reach is required: pass --iroh-node-id <MULTIKEY> or \
1773             --quic-endpoint <IP:PORT>"
1774        ),
1775    }
1776}
1777
1778/// Render the deployment `did:web` document that reciprocally vouches for the
1779/// anchor capsule.
1780///
1781/// The reciprocal `alsoKnownAs` is what the resolver checks; the `#mesh-kem`
1782/// keyAgreement and the single `#mesh-pq` verification method are what a
1783/// remote-node bootstrap additionally requires, and they belong to the
1784/// Discovery service the capsule's reach points at — not to the CA.
1785fn anchor_did_document(
1786    args: &MintAnchorCapsuleArgs,
1787    at9p_did: &str,
1788    ca_ed: &VerifyingKey,
1789    reach: &AnchorReach,
1790) -> Result<serde_json::Value> {
1791    let did_web = &args.did_web;
1792    let mut verification_method = vec![serde_json::json!({
1793        "id": format!("{did_web}#deployment-ca"),
1794        "type": "Multikey",
1795        "controller": did_web,
1796        "publicKeyMultibase": hyprstream_rpc::did_key::ed25519_to_did_key(ca_ed.as_bytes())
1797            .strip_prefix("did:key:")
1798            .unwrap_or_default()
1799            .to_owned(),
1800    })];
1801    let mut key_agreement = Vec::new();
1802    if let (Some(pq), Some(x25519), Some(mlkem)) = (
1803        args.mesh_pq.as_deref(),
1804        args.mesh_kem_x25519.as_deref(),
1805        args.mesh_kem_mlkem768.as_deref(),
1806    ) {
1807        verification_method.push(serde_json::json!({
1808            "id": format!("{did_web}#mesh-pq"),
1809            "type": "Multikey",
1810            "controller": did_web,
1811            "publicKeyMultibase": pq,
1812        }));
1813        key_agreement.push(serde_json::json!({
1814            "id": format!("{did_web}#mesh-kem-x25519"),
1815            "type": "Multikey",
1816            "controller": did_web,
1817            "publicKeyMultibase": x25519,
1818        }));
1819        key_agreement.push(serde_json::json!({
1820            "id": format!("{did_web}#mesh-kem-mlkem768"),
1821            "type": "Multikey",
1822            "controller": did_web,
1823            "publicKeyMultibase": mlkem,
1824        }));
1825    }
1826    let service: Vec<serde_json::Value> = reach.document_service.clone().into_iter().collect();
1827    let document = serde_json::json!({
1828        "@context": [
1829            "https://www.w3.org/ns/did/v1",
1830            "https://w3id.org/security/multikey/v1",
1831        ],
1832        "id": did_web,
1833        "alsoKnownAs": [at9p_did],
1834        "verificationMethod": verification_method,
1835        "keyAgreement": key_agreement,
1836        "service": service,
1837    });
1838
1839    // Re-parse the rendered document with the production extractors: material
1840    // that decodes to nothing here would leave a remote-node bootstrap without
1841    // an encryption recipient or a response-authentication anchor.
1842    if args.mesh_pq.is_some() {
1843        ensure!(
1844            hyprstream_rpc::did_web::mesh_kem_recipient(&document).is_some(),
1845            "--mesh-kem-x25519 / --mesh-kem-mlkem768 did not decode to an x25519 + ML-KEM-768 \
1846             hybrid recipient; pass the Discovery service's multibase #mesh-kem keys"
1847        );
1848        let pq_keys = hyprstream_rpc::did_web::verification_method_ml_dsa_65_keys(&document);
1849        ensure!(
1850            pq_keys.len() == 1,
1851            "--mesh-pq must decode to exactly one ML-DSA-65 Multikey (decoded {})",
1852            pq_keys.len()
1853        );
1854    }
1855    Ok(document)
1856}
1857
1858/// Round-trip a freshly minted capsule/document pair through the production
1859/// DID-anchored verifier, serving the capsule from memory instead of the
1860/// deployment's well-known endpoint.
1861fn verify_anchor_material_offline(
1862    at9p_did: &str,
1863    did_web: &str,
1864    document: &serde_json::Value,
1865    capsule_bytes: &[u8],
1866) -> Result<hyprstream_discovery::VerifiedAnchorMaterial> {
1867    struct MintedCapsule(Vec<u8>);
1868
1869    #[async_trait::async_trait]
1870    impl hyprstream_discovery::at9p_resolver::CapsuleSource for MintedCapsule {
1871        async fn fetch_capsule(&self, _did: &str) -> Result<Vec<u8>> {
1872            Ok(self.0.clone())
1873        }
1874    }
1875
1876    let anchors = match hyprstream_discovery::DeploymentTrustSource::from_anchors(
1877        Some(at9p_did),
1878        Some(did_web),
1879    )? {
1880        hyprstream_discovery::DeploymentTrustSource::DidAnchored(anchors) => anchors,
1881        hyprstream_discovery::DeploymentTrustSource::OsOwnedFiles => {
1882            bail!("minted anchors did not select the DID-anchored trust source")
1883        }
1884    };
1885    let source = std::sync::Arc::new(MintedCapsule(capsule_bytes.to_vec()));
1886    tokio::runtime::Builder::new_current_thread()
1887        .enable_all()
1888        .build()
1889        .context("build the verification runtime")?
1890        .block_on(hyprstream_discovery::verify_anchor_material(
1891            &anchors, document, source,
1892        ))
1893}
1894
1895fn root_recipient_ring(args: &MintDeploymentCaArgs) -> Result<Vec<String>> {
1896    for recipient in &args.yubikey_recipients {
1897        ensure!(
1898            recipient.starts_with("age1yubikey1"),
1899            "--yubikey value is not an age-plugin-yubikey recipient"
1900        );
1901    }
1902    let all = args
1903        .recipients
1904        .iter()
1905        .chain(&args.yubikey_recipients)
1906        .chain(&args.kms_plugin_recipients)
1907        .cloned()
1908        .collect();
1909    let recipients = distinct_recipients(all)?;
1910    ensure!(
1911        recipients.len() >= 2,
1912        "root authority requires at least two distinct age recipients \
1913         (primary + backup/break-glass); a sole YubiKey is forbidden"
1914    );
1915    Ok(recipients)
1916}
1917
1918fn distinct_recipients(recipients: Vec<String>) -> Result<Vec<String>> {
1919    let mut unique = BTreeSet::new();
1920    for recipient in recipients {
1921        let recipient = recipient.trim();
1922        ensure!(!recipient.is_empty(), "age recipient is empty");
1923        ensure!(
1924            recipient.is_ascii() && !recipient.contains(['\n', '\r', '\0']),
1925            "age recipient contains invalid characters"
1926        );
1927        unique.insert(recipient.to_owned());
1928    }
1929    Ok(unique.into_iter().collect())
1930}
1931
1932fn combined_identities(generic: &[PathBuf], yubikey: &[PathBuf]) -> Result<AgeIdentities> {
1933    let identities: Vec<_> = generic.iter().chain(yubikey).cloned().collect();
1934    ensure!(
1935        !identities.is_empty(),
1936        "at least one --identity or --yubikey-identity is required"
1937    );
1938    AgeIdentities::new(identities)
1939}
1940
1941/// Resolve the mint identity set: either the on-disk path forms (existing
1942/// ceremony tooling) or the inherited-FD form used by the staging stack
1943/// (systemd `LoadCredentialEncrypted` + podman `--preserve-fds`), which clap
1944/// makes mutually exclusive with `--identity`. FD identity bytes are validated
1945/// and size-capped here, then handed to the `age` child through anonymous
1946/// memfds so plaintext never touches a filesystem path.
1947fn mint_identities(args: &MintRegistryJwtArgs) -> Result<AgeIdentities> {
1948    inherited_identities(
1949        &args.identities,
1950        &args.identity_fds,
1951        &args.yubikey_identities,
1952    )
1953}
1954
1955/// Resolve either path-backed or inherited-FD age identities. FD bytes remain
1956/// zeroized while `AgeIdentities` materializes anonymous memfds for the age
1957/// child; they are never reopened through a credential pathname.
1958fn inherited_identities(
1959    generic: &[PathBuf],
1960    identity_fds: &[RawFd],
1961    yubikey: &[PathBuf],
1962) -> Result<AgeIdentities> {
1963    if identity_fds.is_empty() {
1964        return combined_identities(generic, yubikey);
1965    }
1966    let mut bytes = Vec::with_capacity(identity_fds.len());
1967    for &fd in identity_fds {
1968        bytes.push(Zeroizing::new(read_fd_limited(
1969            fd,
1970            MAX_AGE_IDENTITY_BYTES,
1971            "age identity",
1972        )?));
1973    }
1974    if yubikey.is_empty() {
1975        return AgeIdentities::new_in_memory(bytes);
1976    }
1977    // YubiKey path identities may be mixed in, exactly like the path forms.
1978    let mut sources: Vec<_> = yubikey
1979        .iter()
1980        .cloned()
1981        .map(AgeIdentitySource::Path)
1982        .collect();
1983    sources.extend(bytes.into_iter().map(AgeIdentitySource::InMemory));
1984    AgeIdentities::from_sources(sources)
1985}
1986
1987fn encrypt_age(plaintext: &[u8], recipients: &[String]) -> Result<Vec<u8>> {
1988    AgeRecipients::new(recipients.to_vec())?
1989        .seal(plaintext, MAX_AGE_CIPHERTEXT_BYTES)
1990        .context("encrypt authority through deployment age seam")
1991}
1992
1993const MAX_AGE_PLAINTEXT_BYTES: usize = 128 * 1024;
1994
1995fn decrypt_age(path: &Path, identities: &AgeIdentities) -> Result<Zeroizing<Vec<u8>>> {
1996    identities
1997        .open_file(path, MAX_AGE_PLAINTEXT_BYTES)
1998        .context("decrypt authority through deployment age seam")
1999}
2000
2001fn decrypt_age_bytes(ciphertext: &[u8], identities: &AgeIdentities) -> Result<Zeroizing<Vec<u8>>> {
2002    identities
2003        .open(ciphertext, MAX_AGE_PLAINTEXT_BYTES)
2004        .context("decrypt authority through deployment age seam")
2005}
2006
2007fn decrypt_authority(
2008    path: &Path,
2009    identities: &AgeIdentities,
2010    software_recovery: bool,
2011) -> Result<LoadedAuthority> {
2012    let plaintext = decrypt_age(path, identities)?;
2013    decode_authority(&plaintext, software_recovery)
2014}
2015
2016/// Decrypt an age ciphertext already held in memory (inherited-FD form).
2017fn decrypt_authority_ciphertext(
2018    ciphertext: &[u8],
2019    identities: &AgeIdentities,
2020    software_recovery: bool,
2021) -> Result<LoadedAuthority> {
2022    let plaintext = decrypt_age_bytes(ciphertext, identities)?;
2023    decode_authority(&plaintext, software_recovery)
2024}
2025
2026fn decode_authority(plaintext: &[u8], software_recovery: bool) -> Result<LoadedAuthority> {
2027    let bundle: AuthorityBundle =
2028        serde_json::from_slice(plaintext).context("decode authority bundle")?;
2029    ensure!(
2030        bundle.schema == AUTHORITY_BUNDLE_SCHEMA,
2031        "unsupported authority bundle schema"
2032    );
2033    let pq_seed = decode_fixed_b64::<32>(&bundle.ml_dsa_65_seed_b64, "ML-DSA-65 seed")?;
2034    let pq = ml_dsa_sk_from_seed(&pq_seed);
2035    let ed = match &bundle.ed25519 {
2036        Ed25519Secret::Software {
2037            seed_b64,
2038            public_b64,
2039        } => {
2040            ensure!(
2041                !software_recovery,
2042                "--software-recovery applies only to a PIV-backed authority"
2043            );
2044            let seed = decode_fixed_b64::<32>(seed_b64, "Ed25519 seed")?;
2045            let key = SigningKey::from_bytes(&seed);
2046            ensure!(
2047                STANDARD.decode(public_b64)? == key.verifying_key().as_bytes(),
2048                "authority Ed25519 public key does not match seed"
2049            );
2050            LoadedEdSigner::Software(key)
2051        }
2052        Ed25519Secret::YubikeyPiv {
2053            slot,
2054            public_b64,
2055            recovery_seed_b64,
2056        } => {
2057            validate_piv_slot(slot)?;
2058            let public_bytes = decode_fixed_b64::<32>(public_b64, "PIV Ed25519 public key")?;
2059            let public =
2060                VerifyingKey::from_bytes(&public_bytes).context("invalid PIV public key")?;
2061            if software_recovery {
2062                let seed = decode_fixed_b64::<32>(recovery_seed_b64, "PIV recovery Ed25519 seed")?;
2063                let key = SigningKey::from_bytes(&seed);
2064                ensure!(
2065                    key.verifying_key() == public,
2066                    "PIV recovery seed does not match the recorded public key"
2067                );
2068                LoadedEdSigner::Software(key)
2069            } else {
2070                LoadedEdSigner::YubikeyPiv {
2071                    slot: slot.clone(),
2072                    public,
2073                }
2074            }
2075        }
2076    };
2077    let loaded = LoadedAuthority { bundle, ed, pq };
2078    let public = loaded.public_bytes();
2079    ensure!(
2080        sha256_hex(&public) == loaded.bundle.public_key_sha256,
2081        "authority public-key fingerprint mismatch"
2082    );
2083    Ok(loaded)
2084}
2085
2086fn public_pair_bytes(ed: &VerifyingKey, pq: &MlDsaSigningKey) -> Vec<u8> {
2087    let mut output = Vec::with_capacity(PUBLIC_CA_BYTES);
2088    output.extend_from_slice(ed.as_bytes());
2089    output.extend_from_slice(&ml_dsa_sk_to_vk_bytes(pq));
2090    output
2091}
2092
2093fn parse_public_pair(
2094    bytes: &[u8],
2095) -> Result<(VerifyingKey, hyprstream_rpc::crypto::pq::MlDsaVerifyingKey)> {
2096    ensure!(
2097        bytes.len() == PUBLIC_CA_BYTES,
2098        "hybrid public key must be exactly {PUBLIC_CA_BYTES} bytes"
2099    );
2100    let ed_bytes: [u8; 32] = bytes[..32]
2101        .try_into()
2102        .map_err(|_| anyhow!("invalid Ed25519 public-key length"))?;
2103    let ed = VerifyingKey::from_bytes(&ed_bytes).context("invalid Ed25519 public key")?;
2104    let pq = ml_dsa_vk_from_bytes(&bytes[32..])?;
2105    Ok((ed, pq))
2106}
2107
2108fn encode_registry_jwt(
2109    signer: &LoadedAuthority,
2110    registry_key: &[u8; 32],
2111    now: i64,
2112    exp: i64,
2113    delegation_b64: Option<&str>,
2114) -> Result<String> {
2115    let signer_ed = signer.ed.verifying_key();
2116    let signer_pq = ml_dsa_vk_from_bytes(&ml_dsa_sk_to_vk_bytes(&signer.pq))?;
2117    let kid = hyprstream_rpc::auth::composite_kid(&signer_pq, &signer_ed);
2118    let protected = serde_json::json!({
2119        "alg": "ML-DSA-65-Ed25519",
2120        "typ": "wit+jwt",
2121        "kid": kid
2122    });
2123    let mut claims = serde_json::Map::new();
2124    claims.insert(
2125        "iss".to_owned(),
2126        serde_json::Value::String(format!(
2127            "urn:hyprstream:deployment:{}",
2128            signer.bundle.deployment_domain
2129        )),
2130    );
2131    claims.insert(
2132        "sub".to_owned(),
2133        serde_json::Value::String("service:registry".to_owned()),
2134    );
2135    claims.insert(
2136        "aud".to_owned(),
2137        serde_json::Value::String(REGISTRY_AUDIENCE.to_owned()),
2138    );
2139    claims.insert("exp".to_owned(), serde_json::Value::Number(exp.into()));
2140    claims.insert("nbf".to_owned(), serde_json::Value::Number(now.into()));
2141    claims.insert("iat".to_owned(), serde_json::Value::Number(now.into()));
2142    claims.insert(
2143        "deployment_domain".to_owned(),
2144        serde_json::Value::String(signer.bundle.deployment_domain.clone()),
2145    );
2146    claims.insert(
2147        "profile".to_owned(),
2148        serde_json::Value::String(REGISTRY_PROFILE.to_owned()),
2149    );
2150    claims.insert(
2151        "cnf".to_owned(),
2152        serde_json::json!({
2153            "jwk": {
2154                "kty": "OKP",
2155                "crv": "Ed25519",
2156                "x": URL_SAFE_NO_PAD.encode(registry_key)
2157            }
2158        }),
2159    );
2160    if let Some(delegation) = delegation_b64 {
2161        claims.insert(
2162            "delegation".to_owned(),
2163            serde_json::Value::String(delegation.to_owned()),
2164        );
2165    }
2166    let protected_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&protected)?);
2167    let claims_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims)?);
2168    let signing_input = format!("{protected_b64}.{claims_b64}");
2169    let pq_signature = ml_dsa_sign(&signer.pq, signing_input.as_bytes());
2170    let ed_signature = signer.ed.sign(signing_input.as_bytes())?;
2171    let mut signature = Vec::with_capacity(HYBRID_SIGNATURE_BYTES);
2172    signature.extend_from_slice(&pq_signature);
2173    signature.extend_from_slice(&ed_signature);
2174    ensure!(
2175        signature.len() == HYBRID_SIGNATURE_BYTES,
2176        "internal hybrid JWT signature length error"
2177    );
2178    Ok(format!(
2179        "{signing_input}.{}",
2180        URL_SAFE_NO_PAD.encode(signature)
2181    ))
2182}
2183
2184fn sign_ucan(payload: UcanPayload, ed: &LoadedEdSigner, pq: &MlDsaSigningKey) -> Result<Ucan> {
2185    let payload_bytes = payload.signing_bytes()?;
2186    let signature = sign_nested(
2187        &payload_bytes,
2188        hyprstream_rpc::auth::ucan::token::UCAN_AAD,
2189        ed,
2190        pq,
2191    )?;
2192    Ok(Ucan {
2193        payload,
2194        proofs: Vec::new(),
2195        signature,
2196    })
2197}
2198
2199fn sign_nested(
2200    payload: &[u8],
2201    aad: &[u8],
2202    ed: &LoadedEdSigner,
2203    pq: &MlDsaSigningKey,
2204) -> Result<Vec<u8>> {
2205    let ed_public = ed.verifying_key();
2206    let pq_public = ml_dsa_vk_from_bytes(&ml_dsa_sk_to_vk_bytes(pq))?;
2207    let ed_tbs = inner_tbs(ed_public.to_bytes().to_vec(), payload, aad, true);
2208    let ed_signature = ed.sign(&ed_tbs)?;
2209    let pq_tbs = outer_tbs(ml_dsa_vk_bytes(&pq_public), payload, &ed_signature, aad);
2210    let pq_signature = ml_dsa_sign(pq, &pq_tbs);
2211    assemble_composite_nested(
2212        (ed_public.to_bytes().to_vec(), ed_signature.to_vec()),
2213        Some((ml_dsa_vk_bytes(&pq_public), pq_signature)),
2214    )
2215}
2216
2217fn sign_did_op(mut op: DidOp, ed: &LoadedEdSigner, pq: &MlDsaSigningKey) -> Result<DidOp> {
2218    let composite = sign_nested(&op.signable_bytes(), DID_OP_SIGNATURE_CONTEXT, ed, pq)?;
2219    let (ed_signature, pq_signature) =
2220        hyprstream_rpc::crypto::cose_sign::split_composite(&composite)?;
2221    op.signature = HybridDidOpSignature {
2222        ed25519: ed_signature,
2223        mldsa65: pq_signature.ok_or_else(|| anyhow!("missing ML-DSA signature"))?,
2224    };
2225    DidOp::from_dag_cbor(&op.to_dag_cbor()).context("self-verify signed DID operation")
2226}
2227
2228fn placeholder_did_signature() -> HybridDidOpSignature {
2229    HybridDidOpSignature {
2230        ed25519: vec![0; 64],
2231        mldsa65: vec![0; 3_309],
2232    }
2233}
2234
2235fn authority_log_from_ops(
2236    deployment_domain: &str,
2237    operations: Vec<DidOp>,
2238) -> Result<AuthorityLogFile> {
2239    ensure!(!operations.is_empty(), "authority log cannot be empty");
2240    ensure!(
2241        operations.len() <= MAX_AUTHORITY_LOG_OPERATIONS,
2242        "authority log has too many operations"
2243    );
2244    let did = operations[0].genesis_did()?;
2245    verify_did_op_log(&did, &operations)?;
2246    let log = AuthorityLogFile {
2247        schema: AUTHORITY_LOG_SCHEMA.to_owned(),
2248        deployment_domain: deployment_domain.to_owned(),
2249        did,
2250        operations_b64: operations
2251            .iter()
2252            .map(|op| STANDARD.encode(op.to_dag_cbor()))
2253            .collect(),
2254    };
2255    ensure!(
2256        pretty_json_bytes(&log)?.len() <= MAX_CLOUD_SECRET_BYTES,
2257        "authority log exceeds the 64 KiB cloud-secret contract"
2258    );
2259    Ok(log)
2260}
2261
2262fn decode_authority_operations(log: &AuthorityLogFile) -> Result<Vec<DidOp>> {
2263    ensure!(
2264        log.schema == AUTHORITY_LOG_SCHEMA,
2265        "unsupported authority-log schema"
2266    );
2267    ensure!(
2268        !log.operations_b64.is_empty() && log.operations_b64.len() <= MAX_AUTHORITY_LOG_OPERATIONS,
2269        "authority log operation count is invalid"
2270    );
2271    log.operations_b64
2272        .iter()
2273        .map(|encoded| {
2274            let bytes = STANDARD
2275                .decode(encoded)
2276                .context("decode authority operation")?;
2277            DidOp::from_dag_cbor(&bytes)
2278        })
2279        .collect()
2280}
2281
2282fn validate_authority_log_root(
2283    public_ca: &[u8],
2284    log: &AuthorityLogFile,
2285) -> Result<hyprstream_discovery::did_op::VerifiedDidOpLog> {
2286    let root_domain = hyprstream_discovery::verify_deployment_public_ca(public_ca)?;
2287    ensure!(
2288        log.deployment_domain == root_domain,
2289        "authority log deployment domain does not match pinned root"
2290    );
2291    let operations = decode_authority_operations(log)?;
2292    let verified = verify_did_op_log(&log.did, &operations)?;
2293    let (root_ed, root_pq) = parse_public_pair(public_ca)?;
2294    let genesis = operations
2295        .first()
2296        .ok_or_else(|| anyhow!("authority log is empty"))?;
2297    let genesis_composite = assemble_composite_nested(
2298        (
2299            root_ed.to_bytes().to_vec(),
2300            genesis.signature.ed25519.clone(),
2301        ),
2302        Some((ml_dsa_vk_bytes(&root_pq), genesis.signature.mldsa65.clone())),
2303    )?;
2304    hyprstream_rpc::crypto::cose_sign::verify_composite(
2305        &genesis_composite,
2306        &root_ed,
2307        Some(&root_pq),
2308        &genesis.signable_bytes(),
2309        DID_OP_SIGNATURE_CONTEXT,
2310        true,
2311    )
2312    .context("authority-log genesis was not signed by the pinned root")?;
2313    ensure!(
2314        genesis.rotation_keys.iter().any(|key| {
2315            key.ed25519_pub == root_ed.to_bytes() && key.mldsa65_pub == ml_dsa_vk_bytes(&root_pq)
2316        }),
2317        "authority log genesis is not anchored by the pinned public root"
2318    );
2319    Ok(verified)
2320}
2321
2322fn authority_checkpoint(
2323    deployment_domain: &str,
2324    verified: &hyprstream_discovery::did_op::VerifiedDidOpLog,
2325) -> AuthorityCheckpointFile {
2326    AuthorityCheckpointFile {
2327        schema: AUTHORITY_CHECKPOINT_SCHEMA.to_owned(),
2328        deployment_domain: deployment_domain.to_owned(),
2329        did: verified.did.clone(),
2330        sequence: verified.sequence,
2331        head_cid: verified.head_cid.clone(),
2332    }
2333}
2334
2335fn validate_authority_log(
2336    public_ca: &[u8],
2337    log: &AuthorityLogFile,
2338    checkpoint: &AuthorityCheckpointFile,
2339) -> Result<hyprstream_discovery::did_op::VerifiedDidOpLog> {
2340    let verified = validate_authority_log_root(public_ca, log)?;
2341    ensure!(
2342        checkpoint.schema == AUTHORITY_CHECKPOINT_SCHEMA,
2343        "unsupported authority-checkpoint schema"
2344    );
2345    ensure!(
2346        checkpoint.deployment_domain == log.deployment_domain,
2347        "authority checkpoint deployment domain does not match log"
2348    );
2349    ensure!(
2350        checkpoint.did == log.did
2351            && checkpoint.did == verified.did
2352            && checkpoint.sequence == verified.sequence
2353            && checkpoint.head_cid == verified.head_cid,
2354        "authority-log head does not match the independently trusted checkpoint"
2355    );
2356    Ok(verified)
2357}
2358
2359fn ensure_active_authority(
2360    authority: &LoadedAuthority,
2361    active: &hyprstream_discovery::did_op::VerifiedDidOpLog,
2362) -> Result<()> {
2363    let public = authority.public_bytes();
2364    ensure!(
2365        active
2366            .rotation_keys
2367            .iter()
2368            .any(|key| { public[..32] == key.ed25519_pub && public[32..] == key.mldsa65_pub }),
2369        "authority key is not active at the rotation-log head"
2370    );
2371    Ok(())
2372}
2373
2374/// Verify that `authority` is the deployment root that the resolver pins and is
2375/// therefore permitted to mint an anchor capsule.
2376///
2377/// This bundles the three guard checks `mint_anchor_capsule` runs before it
2378/// builds the capsule body: purpose (not a delegated signer), CA-binding (key
2379/// matches the pinned root), and rotation-log activeness. It is the seam the
2380/// minter's self-check tests exercise so removing any single guard turns the
2381/// test red.
2382fn ensure_anchor_authority(
2383    authority: &LoadedAuthority,
2384    public_ca: &[u8],
2385    active: &hyprstream_discovery::did_op::VerifiedDidOpLog,
2386) -> Result<()> {
2387    ensure!(
2388        authority.bundle.purpose != AuthorityPurpose::RegistryDelegatedSigner,
2389        "the anchor capsule must be signed by the deployment authority itself; \
2390         a registry-scoped delegated signer cannot anchor a deployment"
2391    );
2392    ensure!(
2393        authority.public_bytes() == public_ca,
2394        "anchor capsule signing authority does not match the pinned public CA; \
2395         only the deployment root that the resolver pins may anchor a deployment"
2396    );
2397    ensure_active_authority(authority, active)?;
2398    Ok(())
2399}
2400
2401/// `ykman` argv (after the program name) that asks whether a PIV slot holds
2402/// a private key, plus the stderr marker it prints when the slot has none.
2403///
2404/// `{slot}` is substituted with the validated slot id.
2405const PIV_KEY_PROBE: PivProbe = PivProbe {
2406    argv: &["piv", "keys", "info", "{slot}"],
2407    absent_marker: "No key stored in slot",
2408};
2409
2410/// `ykman` argv that asks whether a PIV slot holds a certificate object,
2411/// plus the stderr marker it prints when the slot has none. `-` sends any
2412/// certificate found to stdout, which the probe discards.
2413const PIV_CERT_PROBE: PivProbe = PivProbe {
2414    argv: &["piv", "certificates", "export", "{slot}", "-"],
2415    absent_marker: "No certificate found",
2416};
2417
2418/// A single `ykman` presence probe: what to run, and how to recognise a
2419/// definitive "nothing is here" answer.
2420#[derive(Clone, Copy, Debug)]
2421struct PivProbe {
2422    argv: &'static [&'static str],
2423    absent_marker: &'static str,
2424}
2425
2426/// Decide whether a probe definitively reported an empty slot.
2427///
2428/// `ykman` signals absence as exit 1 with a specific message on stderr.
2429/// Every other outcome is indeterminate and must NOT read as absent:
2430/// exit 0 (the object exists), a different exit-1 message (PCSC failure,
2431/// no token present, locked slot), exit 2 (argument or subcommand error —
2432/// including a subcommand that does not exist), or no exit code at all
2433/// (killed by signal). Refusing a destructive import on an indeterminate
2434/// answer is recoverable; permitting one is not.
2435fn probe_reports_absent(probe: PivProbe, exit_code: Option<i32>, stderr: &str) -> bool {
2436    exit_code == Some(1) && stderr.contains(probe.absent_marker)
2437}
2438
2439/// Combine both probe results into the occupancy decision.
2440///
2441/// The slot is occupied unless BOTH probes definitively reported absence.
2442/// Split out from [`piv_slot_occupied`] so the decision — including the
2443/// fail-closed handling of every indeterminate outcome — is unit-testable
2444/// against the exact exit codes and stderr text the real binary emits.
2445fn slot_occupied_from_probes(key: (Option<i32>, &str), cert: (Option<i32>, &str)) -> bool {
2446    !probe_reports_absent(PIV_KEY_PROBE, key.0, key.1)
2447        || !probe_reports_absent(PIV_CERT_PROBE, cert.0, cert.1)
2448}
2449
2450/// Run one `ykman` presence probe and return its exit code and stderr.
2451///
2452/// A failure to launch `ykman` at all is returned as an error rather than
2453/// as a probe result: the caller propagates it, which aborts the mint
2454/// before anything destructive runs.
2455fn run_piv_probe(probe: PivProbe, slot: &str) -> Result<(Option<i32>, String)> {
2456    let mut command = Command::new("ykman");
2457    for arg in probe.argv {
2458        command.arg(if *arg == "{slot}" { slot } else { arg });
2459    }
2460    let output = command
2461        .stdin(Stdio::null())
2462        .stdout(Stdio::null())
2463        .stderr(Stdio::piped())
2464        .output()
2465        .with_context(|| format!("launch ykman {}", probe.argv.join(" ")))?;
2466    let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
2467    Ok((output.status.code(), stderr))
2468}
2469
2470/// Check whether a PIV slot already holds a key or certificate.
2471///
2472/// `ykman piv keys import` silently overwrites slot contents; this check
2473/// gives the caller a chance to warn or refuse before the import runs.
2474///
2475/// Probes BOTH objects, because either alone misses a real state:
2476/// - `ykman piv keys info <slot>` reports key metadata regardless of
2477///   certificate state, which is what catches the key-but-no-certificate
2478///   slot [`piv_import_ed25519`] leaves behind.
2479/// - `ykman piv certificates export <slot> -` catches a slot holding a
2480///   certificate whose private key lives elsewhere or has been deleted.
2481///
2482/// Any outcome that is not a definitive "absent" — PCSC failure, token
2483/// removed, locked slot, unexpected exit status — reads as occupied. If
2484/// `ykman` cannot be launched at all this returns an error, which also
2485/// stops the import.
2486fn piv_slot_occupied(slot: &str) -> Result<bool> {
2487    let slot = validate_piv_slot(slot)?;
2488    let key = run_piv_probe(PIV_KEY_PROBE, &slot)?;
2489    // Short-circuit: a key is the object the guard exists to protect, so
2490    // there is no reason to touch the card a second time once one is
2491    // known (or suspected) to be present.
2492    if !probe_reports_absent(PIV_KEY_PROBE, key.0, &key.1) {
2493        return Ok(true);
2494    }
2495    let cert = run_piv_probe(PIV_CERT_PROBE, &slot)?;
2496    Ok(slot_occupied_from_probes(
2497        (key.0, &key.1),
2498        (cert.0, &cert.1),
2499    ))
2500}
2501
2502fn piv_import_ed25519(slot: &str, key: &SigningKey) -> Result<(String, VerifyingKey)> {
2503    let slot = validate_piv_slot(slot)?;
2504    let private_der = key
2505        .to_pkcs8_der()
2506        .context("encode Ed25519 key for PIV import")?;
2507    let mut child = Command::new("ykman")
2508        .args([
2509            "piv",
2510            "keys",
2511            "import",
2512            "--pin-policy",
2513            "ALWAYS",
2514            "--touch-policy",
2515            "ALWAYS",
2516        ])
2517        .arg(&slot)
2518        .arg("-")
2519        .stdin(Stdio::piped())
2520        .stdout(Stdio::inherit())
2521        .stderr(Stdio::inherit())
2522        .spawn()
2523        .context("launch ykman PIV import (YubiKey 5.7.4+ is required)")?;
2524    child
2525        .stdin
2526        .take()
2527        .ok_or_else(|| anyhow!("ykman stdin unavailable"))?
2528        .write_all(private_der.as_bytes())
2529        .context("write Ed25519 PKCS#8 key to ykman")?;
2530    let status = child.wait().context("wait for ykman PIV import")?;
2531    ensure!(status.success(), "ykman PIV Ed25519 import failed");
2532    let public = key.verifying_key();
2533    piv_sign(
2534        &slot,
2535        &public,
2536        b"hyprstream deployment authority PIV import self-check",
2537    )
2538    .context("PIV import self-check")?;
2539    Ok((slot, public))
2540}
2541
2542fn piv_sign(slot: &str, public: &VerifyingKey, message: &[u8]) -> Result<[u8; 64]> {
2543    validate_piv_slot(slot)?;
2544    let input = tempfile::NamedTempFile::new().context("create PIV signing input")?;
2545    let output = tempfile::NamedTempFile::new().context("create PIV signing output")?;
2546    std::fs::write(input.path(), message).context("write PIV signing input")?;
2547    let status = Command::new("yubico-piv-tool")
2548        .args(["-a", "verify-pin", "--sign", "-s"])
2549        .arg(slot)
2550        .args(["-A", "ED25519", "-i"])
2551        .arg(input.path())
2552        .arg("-o")
2553        .arg(output.path())
2554        .stdin(Stdio::inherit())
2555        .stdout(Stdio::inherit())
2556        .stderr(Stdio::inherit())
2557        .status()
2558        .context("launch yubico-piv-tool")?;
2559    ensure!(status.success(), "YubiKey PIV signing failed");
2560    let signature: [u8; 64] = std::fs::read(output.path())?
2561        .try_into()
2562        .map_err(|_| anyhow!("YubiKey returned a non-64-byte Ed25519 signature"))?;
2563    public
2564        .verify_strict(message, &ed25519_dalek::Signature::from_bytes(&signature))
2565        .context("YubiKey signature self-check failed")?;
2566    Ok(signature)
2567}
2568
2569fn validate_piv_slot(slot: &str) -> Result<String> {
2570    let slot = slot.trim().to_ascii_lowercase();
2571    let allowed = matches!(
2572        slot.as_str(),
2573        "9a" | "9c"
2574            | "9d"
2575            | "9e"
2576            | "82"
2577            | "83"
2578            | "84"
2579            | "85"
2580            | "86"
2581            | "87"
2582            | "88"
2583            | "89"
2584            | "8a"
2585            | "8b"
2586            | "8c"
2587            | "8d"
2588            | "8e"
2589            | "8f"
2590            | "90"
2591            | "91"
2592            | "92"
2593            | "93"
2594            | "94"
2595            | "95"
2596    );
2597    ensure!(allowed, "unsupported or unsafe PIV slot {slot:?}");
2598    Ok(slot)
2599}
2600
2601fn preflight_outputs<'a>(paths: impl IntoIterator<Item = &'a PathBuf>, force: bool) -> Result<()> {
2602    let mut seen = BTreeSet::new();
2603    for path in paths {
2604        ensure!(
2605            seen.insert(path.clone()),
2606            "duplicate output path {}",
2607            path.display()
2608        );
2609        match std::fs::symlink_metadata(path) {
2610            Ok(metadata) => {
2611                ensure!(
2612                    force,
2613                    "refusing to replace existing output {} without --force",
2614                    path.display()
2615                );
2616                ensure!(
2617                    metadata.file_type().is_file() && !metadata.file_type().is_symlink(),
2618                    "refusing non-regular or symlink output target {}",
2619                    path.display()
2620                );
2621            }
2622            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
2623            Err(error) => {
2624                return Err(error)
2625                    .with_context(|| format!("inspect output target {}", path.display()));
2626            }
2627        }
2628        let parent = path.parent().unwrap_or_else(|| Path::new("."));
2629        let parent_metadata = std::fs::metadata(parent)
2630            .with_context(|| format!("inspect output parent {}", parent.display()))?;
2631        ensure!(
2632            parent_metadata.is_dir(),
2633            "output parent is not a directory: {}",
2634            parent.display()
2635        );
2636    }
2637    Ok(())
2638}
2639
2640fn pretty_json_bytes(value: &impl Serialize) -> Result<Vec<u8>> {
2641    let mut bytes = serde_json::to_vec_pretty(value)?;
2642    bytes.push(b'\n');
2643    Ok(bytes)
2644}
2645
2646fn serialize_secret_json(value: &impl Serialize) -> Result<Zeroizing<Vec<u8>>> {
2647    let mut plaintext = Zeroizing::new(Vec::new());
2648    serde_json::to_writer(&mut *plaintext, value)?;
2649    Ok(plaintext)
2650}
2651
2652struct PendingOutput<'a> {
2653    path: &'a Path,
2654    bytes: Vec<u8>,
2655    mode: u32,
2656}
2657
2658impl<'a> PendingOutput<'a> {
2659    fn new(path: &'a Path, bytes: Vec<u8>, mode: u32) -> Self {
2660        Self { path, bytes, mode }
2661    }
2662}
2663
2664#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2665enum CommitOperation {
2666    StageCreate(usize),
2667    StagePermissions(usize),
2668    StageWrite(usize),
2669    StageSync(usize),
2670    StageKeep(usize),
2671    BackupMetadata(usize),
2672    BackupCreate(usize),
2673    BackupPlaceholderKeep(usize),
2674    BackupPlaceholderRemove(usize),
2675    BackupRename(usize),
2676    BackupParentsSync,
2677    CommitRename(usize),
2678    CommitParentsSync,
2679    BackupDelete(usize),
2680    CleanupParentsSync,
2681    RollbackRemove(usize),
2682    RollbackRestore(usize),
2683    RollbackParentsSync,
2684    StageCleanup(usize),
2685}
2686
2687#[derive(Default)]
2688struct CommitFaultInjector {
2689    #[cfg(test)]
2690    faults: std::collections::VecDeque<CommitOperation>,
2691}
2692
2693impl CommitFaultInjector {
2694    fn check(&mut self, operation: CommitOperation) -> Result<()> {
2695        #[cfg(test)]
2696        if self.faults.front() == Some(&operation) {
2697            self.faults.pop_front();
2698            bail!("injected transaction fault at {operation:?}");
2699        }
2700        let _ = operation;
2701        Ok(())
2702    }
2703
2704    #[cfg(test)]
2705    fn with_faults(faults: impl IntoIterator<Item = CommitOperation>) -> Self {
2706        Self {
2707            faults: faults.into_iter().collect(),
2708        }
2709    }
2710}
2711
2712/// Stage every output before moving any destination, then roll back the whole
2713/// set if any subsequent operation fails. Each rename is filesystem-atomic;
2714/// every fallible step after the first retained staging path is routed through
2715/// the same rollback/cleanup path.
2716fn commit_outputs(outputs: Vec<PendingOutput<'_>>) -> Result<()> {
2717    commit_outputs_with_faults(outputs, &mut CommitFaultInjector::default())
2718}
2719
2720fn destination_exists_for_backup(
2721    output: &PendingOutput<'_>,
2722    index: usize,
2723    faults: &mut CommitFaultInjector,
2724) -> Result<bool> {
2725    faults.check(CommitOperation::BackupMetadata(index))?;
2726    match std::fs::symlink_metadata(output.path) {
2727        Ok(metadata) => {
2728            ensure!(
2729                metadata.file_type().is_file() && !metadata.file_type().is_symlink(),
2730                "refusing non-regular or symlink output target {}",
2731                output.path.display()
2732            );
2733            Ok(true)
2734        }
2735        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
2736        Err(error) => {
2737            Err(error).with_context(|| format!("inspect output target {}", output.path.display()))
2738        }
2739    }
2740}
2741
2742fn commit_outputs_with_faults(
2743    outputs: Vec<PendingOutput<'_>>,
2744    faults: &mut CommitFaultInjector,
2745) -> Result<()> {
2746    let mut staged = Vec::with_capacity(outputs.len());
2747    for (index, output) in outputs.iter().enumerate() {
2748        let parent = output.path.parent().unwrap_or_else(|| Path::new("."));
2749        let staged_result = (|| -> Result<PathBuf> {
2750            faults.check(CommitOperation::StageCreate(index))?;
2751            let mut temp = tempfile::NamedTempFile::new_in(parent)
2752                .with_context(|| format!("create staged output for {}", output.path.display()))?;
2753            faults.check(CommitOperation::StagePermissions(index))?;
2754            temp.as_file_mut()
2755                .set_permissions(std::fs::Permissions::from_mode(output.mode))?;
2756            faults.check(CommitOperation::StageWrite(index))?;
2757            temp.write_all(&output.bytes)?;
2758            faults.check(CommitOperation::StageSync(index))?;
2759            temp.as_file_mut().sync_all()?;
2760            faults.check(CommitOperation::StageKeep(index))?;
2761            let (_file, path) = temp.keep().context("retain staged output")?;
2762            Ok(path)
2763        })();
2764        match staged_result {
2765            Ok(path) => staged.push(path),
2766            Err(error) => {
2767                return Err(transaction_failure(
2768                    error,
2769                    format!("stage {}", output.path.display()),
2770                    Ok(()),
2771                    cleanup_paths(&staged, faults),
2772                ));
2773            }
2774        }
2775    }
2776
2777    let mut backups: Vec<Option<PathBuf>> = vec![None; outputs.len()];
2778    for (index, output) in outputs.iter().enumerate() {
2779        let destination_exists = match destination_exists_for_backup(output, index, faults) {
2780            Ok(exists) => exists,
2781            Err(error) => {
2782                return Err(transaction_failure(
2783                    error,
2784                    format!("inspect existing {}", output.path.display()),
2785                    restore_outputs(&outputs, &backups, 0, faults),
2786                    cleanup_paths(&staged, faults),
2787                ));
2788            }
2789        };
2790        if destination_exists {
2791            let parent = output.path.parent().unwrap_or_else(|| Path::new("."));
2792            let backup = (|| -> Result<PathBuf> {
2793                faults.check(CommitOperation::BackupCreate(index))?;
2794                let placeholder = tempfile::Builder::new()
2795                    .prefix(".hyprstream-backup-")
2796                    .tempfile_in(parent)
2797                    .with_context(|| format!("stage backup for {}", output.path.display()))?;
2798                faults.check(CommitOperation::BackupPlaceholderKeep(index))?;
2799                let (_file, backup) = placeholder.keep().with_context(|| {
2800                    format!("retain backup placeholder for {}", output.path.display())
2801                })?;
2802                let removal = faults
2803                    .check(CommitOperation::BackupPlaceholderRemove(index))
2804                    .and_then(|()| {
2805                        std::fs::remove_file(&backup).with_context(|| {
2806                            format!("remove backup placeholder {}", backup.display())
2807                        })
2808                    });
2809                if let Err(error) = removal {
2810                    bail!(
2811                        "backup placeholder removal failed; preserved empty recovery marker at {}: {error:#}",
2812                        backup.display()
2813                    );
2814                }
2815                Ok(backup)
2816            })();
2817            let backup = match backup {
2818                Ok(backup) => backup,
2819                Err(error) => {
2820                    return Err(transaction_failure(
2821                        error,
2822                        format!("reserve backup for {}", output.path.display()),
2823                        restore_outputs(&outputs, &backups, 0, faults),
2824                        cleanup_paths(&staged, faults),
2825                    ));
2826                }
2827            };
2828            let rename = faults
2829                .check(CommitOperation::BackupRename(index))
2830                .and_then(|()| {
2831                    std::fs::rename(output.path, &backup)
2832                        .with_context(|| format!("back up existing {}", output.path.display()))
2833                });
2834            if let Err(error) = rename {
2835                return Err(transaction_failure(
2836                    error,
2837                    format!("back up existing {}", output.path.display()),
2838                    restore_outputs(&outputs, &backups, 0, faults),
2839                    cleanup_paths(&staged, faults),
2840                ));
2841            }
2842            backups[index] = Some(backup);
2843        }
2844    }
2845    if let Err(error) = sync_output_parents(&outputs, faults, CommitOperation::BackupParentsSync) {
2846        return Err(transaction_failure(
2847            error,
2848            "durably record output backups".to_owned(),
2849            restore_outputs(&outputs, &backups, 0, faults),
2850            cleanup_paths(&staged, faults),
2851        ));
2852    }
2853
2854    for (index, output) in outputs.iter().enumerate() {
2855        let rename = faults
2856            .check(CommitOperation::CommitRename(index))
2857            .and_then(|()| {
2858                std::fs::rename(&staged[index], output.path)
2859                    .with_context(|| format!("commit {}", output.path.display()))
2860            });
2861        if let Err(error) = rename {
2862            return Err(transaction_failure(
2863                error,
2864                format!("commit {}", output.path.display()),
2865                restore_outputs(&outputs, &backups, index, faults),
2866                cleanup_paths(&staged[index..], faults),
2867            ));
2868        }
2869    }
2870    if let Err(error) = sync_output_parents(&outputs, faults, CommitOperation::CommitParentsSync) {
2871        return Err(transaction_failure(
2872            error,
2873            "durably record committed outputs".to_owned(),
2874            restore_outputs(&outputs, &backups, outputs.len(), faults),
2875            Ok(()),
2876        ));
2877    }
2878
2879    let mut cleanup_errors = Vec::new();
2880    for (index, backup) in backups.into_iter().enumerate() {
2881        if let Some(backup) = backup {
2882            let removal = faults
2883                .check(CommitOperation::BackupDelete(index))
2884                .and_then(|()| {
2885                    std::fs::remove_file(&backup)
2886                        .with_context(|| format!("remove backup {}", backup.display()))
2887                });
2888            if let Err(error) = removal {
2889                cleanup_errors.push(format!("{error:#}"));
2890            }
2891        }
2892    }
2893    if let Err(error) = sync_output_parents(&outputs, faults, CommitOperation::CleanupParentsSync) {
2894        cleanup_errors.push(format!("durably record backup deletion: {error:#}"));
2895    }
2896    ensure!(
2897        cleanup_errors.is_empty(),
2898        "outputs committed, but transaction cleanup was incomplete; preserved backup state where possible: {}",
2899        cleanup_errors.join("; ")
2900    );
2901    Ok(())
2902}
2903
2904fn transaction_failure(
2905    primary: anyhow::Error,
2906    context: String,
2907    rollback: Result<()>,
2908    staged_cleanup: Result<()>,
2909) -> anyhow::Error {
2910    let mut message = format!("{context}: {primary:#}");
2911    if let Err(error) = rollback {
2912        message.push_str(&format!(
2913            "; ROLLBACK INCOMPLETE (backup state preserved where possible): {error:#}"
2914        ));
2915    }
2916    if let Err(error) = staged_cleanup {
2917        message.push_str(&format!("; staged-output cleanup incomplete: {error:#}"));
2918    }
2919    anyhow!(message)
2920}
2921
2922fn restore_outputs(
2923    outputs: &[PendingOutput<'_>],
2924    backups: &[Option<PathBuf>],
2925    committed: usize,
2926    faults: &mut CommitFaultInjector,
2927) -> Result<()> {
2928    let mut errors = Vec::new();
2929    for (index, output) in outputs.iter().take(committed).enumerate() {
2930        let removal = faults
2931            .check(CommitOperation::RollbackRemove(index))
2932            .and_then(|()| {
2933                std::fs::remove_file(output.path)
2934                    .with_context(|| format!("remove newly committed {}", output.path.display()))
2935            });
2936        if let Err(error) = removal {
2937            errors.push(format!(
2938                "remove newly committed {}: {error:#}",
2939                output.path.display(),
2940            ));
2941        }
2942    }
2943    for (index, (output, backup)) in outputs.iter().zip(backups).enumerate().rev() {
2944        if let Some(backup) = backup {
2945            let restore = faults
2946                .check(CommitOperation::RollbackRestore(index))
2947                .and_then(|()| {
2948                    std::fs::rename(backup, output.path).with_context(|| {
2949                        format!(
2950                            "restore {} from {}",
2951                            output.path.display(),
2952                            backup.display()
2953                        )
2954                    })
2955                });
2956            if let Err(error) = restore {
2957                errors.push(format!(
2958                    "restore {} from {}: {error:#}",
2959                    output.path.display(),
2960                    backup.display(),
2961                ));
2962            }
2963        }
2964    }
2965    if let Err(error) = sync_output_parents(outputs, faults, CommitOperation::RollbackParentsSync) {
2966        errors.push(format!("durably record rollback: {error:#}"));
2967    }
2968    ensure!(errors.is_empty(), "{}", errors.join("; "));
2969    Ok(())
2970}
2971
2972fn cleanup_paths(paths: &[PathBuf], faults: &mut CommitFaultInjector) -> Result<()> {
2973    let mut errors = Vec::new();
2974    for (index, path) in paths.iter().enumerate() {
2975        if let Err(error) = faults.check(CommitOperation::StageCleanup(index)) {
2976            errors.push(format!("remove staged {}: {error:#}", path.display()));
2977            continue;
2978        }
2979        match std::fs::remove_file(path) {
2980            Ok(()) => {}
2981            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
2982            Err(error) => {
2983                errors.push(format!("remove staged {}: {error}", path.display()));
2984            }
2985        }
2986    }
2987    ensure!(errors.is_empty(), "{}", errors.join("; "));
2988    Ok(())
2989}
2990
2991fn sync_output_parents(
2992    outputs: &[PendingOutput<'_>],
2993    faults: &mut CommitFaultInjector,
2994    operation: CommitOperation,
2995) -> Result<()> {
2996    faults.check(operation)?;
2997    let parents: BTreeSet<_> = outputs
2998        .iter()
2999        .map(|output| {
3000            output
3001                .path
3002                .parent()
3003                .unwrap_or_else(|| Path::new("."))
3004                .to_path_buf()
3005        })
3006        .collect();
3007    for parent in parents {
3008        let directory = std::fs::File::open(&parent)
3009            .with_context(|| format!("open output directory {}", parent.display()))?;
3010        directory
3011            .sync_all()
3012            .with_context(|| format!("fsync output directory {}", parent.display()))?;
3013    }
3014    Ok(())
3015}
3016
3017fn read_limited(path: &Path, max: usize) -> Result<Vec<u8>> {
3018    let metadata = std::fs::metadata(path).with_context(|| format!("stat {}", path.display()))?;
3019    ensure!(
3020        metadata.is_file(),
3021        "{} is not a regular file",
3022        path.display()
3023    );
3024    ensure!(
3025        metadata.len() <= u64::try_from(max).unwrap_or(u64::MAX),
3026        "{} exceeds {max} bytes",
3027        path.display()
3028    );
3029    let file = OpenOptions::new()
3030        .read(true)
3031        .custom_flags(libc::O_NOFOLLOW)
3032        .open(path)
3033        .with_context(|| format!("open {}", path.display()))?;
3034    let mut bytes = Vec::with_capacity(metadata.len() as usize);
3035    file.take(u64::try_from(max + 1).unwrap_or(u64::MAX))
3036        .read_to_end(&mut bytes)?;
3037    ensure!(bytes.len() <= max, "{} exceeds {max} bytes", path.display());
3038    Ok(bytes)
3039}
3040
3041fn read_json_limited<T: for<'de> Deserialize<'de>>(path: &Path, max: usize) -> Result<T> {
3042    serde_json::from_slice(&read_limited(path, max)?)
3043        .with_context(|| format!("decode JSON {}", path.display()))
3044}
3045
3046/// Read an inherited credential file descriptor to EOF under a hard size cap.
3047///
3048/// The descriptor is duplicated first so the caller's fd stays open; the read
3049/// then consumes the exact byte stream (pipe-friendly, no seek assumptions).
3050/// Any I/O error, short read, EOF error, or over-cap stream fails closed.
3051/// Used by the systemd `LoadCredentialEncrypted` / podman `--preserve-fds`
3052/// interface so plaintext credentials never touch a filesystem path.
3053fn read_fd_limited(fd: RawFd, max: usize, description: &str) -> Result<Vec<u8>> {
3054    let duped = unsafe { libc::dup(fd) };
3055    if duped < 0 {
3056        return Err(std::io::Error::last_os_error())
3057            .with_context(|| format!("dup inherited {description} fd {fd}"));
3058    }
3059    let file = unsafe { std::fs::File::from_raw_fd(duped) };
3060    let mut bytes = Vec::new();
3061    file.take(u64::try_from(max + 1).unwrap_or(u64::MAX))
3062        .read_to_end(&mut bytes)
3063        .with_context(|| format!("read inherited {description} fd {fd}"))?;
3064    ensure!(
3065        bytes.len() <= max,
3066        "inherited {description} fd {fd} exceeds {max} bytes"
3067    );
3068    Ok(bytes)
3069}
3070
3071fn decode_fixed_b64<const N: usize>(value: &str, description: &str) -> Result<Zeroizing<[u8; N]>> {
3072    let decoded = Zeroizing::new(
3073        STANDARD
3074            .decode(value)
3075            .with_context(|| format!("decode {description}"))?,
3076    );
3077    ensure!(
3078        decoded.len() == N,
3079        "{description} must decode to exactly {N} bytes"
3080    );
3081    let mut fixed = Zeroizing::new([0; N]);
3082    fixed.copy_from_slice(&decoded);
3083    Ok(fixed)
3084}
3085
3086fn encode_secret_b64<const N: usize>(secret: Zeroizing<[u8; N]>) -> String {
3087    STANDARD.encode(secret.as_ref())
3088}
3089
3090fn encode_ed25519_seed_b64(key: &SigningKey) -> String {
3091    encode_secret_b64(Zeroizing::new(key.to_bytes()))
3092}
3093
3094fn encode_ml_dsa_seed_b64(key: &MlDsaSigningKey) -> String {
3095    encode_secret_b64(Zeroizing::new(ml_dsa_sk_to_seed(key)))
3096}
3097
3098fn sha256_hex(bytes: &[u8]) -> String {
3099    Sha256::digest(bytes)
3100        .iter()
3101        .map(|byte| format!("{byte:02x}"))
3102        .collect()
3103}
3104
3105fn display_path(path: &Path) -> String {
3106    path.canonicalize()
3107        .unwrap_or_else(|_| {
3108            path.parent()
3109                .unwrap_or_else(|| Path::new("."))
3110                .canonicalize()
3111                .ok()
3112                .and_then(|parent| path.file_name().map(|name| parent.join(name)))
3113                .unwrap_or_else(|| path.to_path_buf())
3114        })
3115        .display()
3116        .to_string()
3117}
3118
3119fn random_bytes(len: usize) -> Vec<u8> {
3120    let mut bytes = vec![0; len];
3121    rand::rngs::OsRng.fill_bytes(&mut bytes);
3122    bytes
3123}
3124
3125fn now_unix_u64() -> Result<u64> {
3126    chrono::Utc::now()
3127        .timestamp()
3128        .try_into()
3129        .map_err(|_| anyhow!("system clock precedes Unix epoch"))
3130}
3131
3132#[cfg(test)]
3133// `print_stderr` is exempted alongside unwrap/expect so a test that has to
3134// skip (external binary absent) can say so instead of passing silently.
3135#[allow(clippy::unwrap_used, clippy::expect_used, clippy::print_stderr)]
3136mod tests {
3137    use super::*;
3138    use hyprstream_rpc::auth::ucan::{Ability, Capability, CaveatValue, Resource};
3139    use std::os::fd::AsRawFd as _;
3140
3141    fn test_authority(
3142        purpose: AuthorityPurpose,
3143        deployment_domain: Option<String>,
3144    ) -> LoadedAuthority {
3145        let ed = SigningKey::generate(&mut rand::rngs::OsRng);
3146        let (pq, _) = ml_dsa_generate_keypair();
3147        let public = public_pair_bytes(&ed.verifying_key(), &pq);
3148        let domain = deployment_domain
3149            .unwrap_or_else(|| hyprstream_discovery::verify_deployment_public_ca(&public).unwrap());
3150        LoadedAuthority {
3151            bundle: AuthorityBundle {
3152                schema: AUTHORITY_BUNDLE_SCHEMA.to_owned(),
3153                purpose,
3154                deployment_domain: domain,
3155                public_key_sha256: sha256_hex(&public),
3156                ed25519: Ed25519Secret::Software {
3157                    seed_b64: encode_ed25519_seed_b64(&ed),
3158                    public_b64: STANDARD.encode(ed.verifying_key().as_bytes()),
3159                },
3160                ml_dsa_65_seed_b64: encode_ml_dsa_seed_b64(&pq),
3161                recipient_count: 2,
3162            },
3163            ed: LoadedEdSigner::Software(ed),
3164            pq,
3165        }
3166    }
3167
3168    fn checkpoint_for(log: &AuthorityLogFile) -> AuthorityCheckpointFile {
3169        let operations = decode_authority_operations(log).unwrap();
3170        let verified = verify_did_op_log(&log.did, &operations).unwrap();
3171        authority_checkpoint(&log.deployment_domain, &verified)
3172    }
3173
3174    fn verify_with_log(
3175        public_ca: &[u8],
3176        log: &AuthorityLogFile,
3177        checkpoint: &AuthorityCheckpointFile,
3178        token: &str,
3179    ) -> Result<hyprstream_discovery::VerifiedDeploymentArtifacts> {
3180        hyprstream_discovery::verify_deployment_artifacts_with_authority_log(
3181            public_ca,
3182            &serde_json::to_vec(log)?,
3183            &serde_json::to_vec(checkpoint)?,
3184            token,
3185        )
3186    }
3187
3188    fn transaction_fault_case(
3189        faults: impl IntoIterator<Item = CommitOperation>,
3190    ) -> (tempfile::TempDir, PathBuf, PathBuf, Result<()>) {
3191        let directory = tempfile::tempdir().unwrap();
3192        let first = directory.path().join("first");
3193        let second = directory.path().join("second");
3194        std::fs::write(&first, b"old-first").unwrap();
3195        std::fs::write(&second, b"old-second").unwrap();
3196        let result = commit_outputs_with_faults(
3197            vec![
3198                PendingOutput::new(&first, b"new-first".to_vec(), 0o600),
3199                PendingOutput::new(&second, b"new-second".to_vec(), 0o600),
3200            ],
3201            &mut CommitFaultInjector::with_faults(faults),
3202        );
3203        (directory, first, second, result)
3204    }
3205
3206    fn directory_entries(directory: &Path) -> Vec<String> {
3207        let mut entries: Vec<_> = std::fs::read_dir(directory)
3208            .unwrap()
3209            .map(|entry| {
3210                entry
3211                    .unwrap()
3212                    .file_name()
3213                    .into_string()
3214                    .expect("test path is UTF-8")
3215            })
3216            .collect();
3217        entries.sort();
3218        entries
3219    }
3220
3221    #[test]
3222    fn generated_secret_bundles_zeroize_on_error_for_every_authority_purpose() {
3223        let purposes = [
3224            (AuthorityPurpose::Root, 0),
3225            (AuthorityPurpose::RotatedAuthority, 1),
3226            (AuthorityPurpose::RegistryDelegatedSigner, 2),
3227        ];
3228        for (purpose, counter) in purposes {
3229            let before = SECRET_BUNDLE_DROPS[counter].load(std::sync::atomic::Ordering::SeqCst);
3230            let result = (|| -> Result<()> {
3231                let _authority = test_authority(purpose, None);
3232                bail!("injected error after guarded seed encoding");
3233            })();
3234            assert!(result.is_err());
3235            assert!(
3236                SECRET_BUNDLE_DROPS[counter].load(std::sync::atomic::Ordering::SeqCst) > before,
3237                "secret bundle did not run its wiping drop on the error path"
3238            );
3239        }
3240
3241        let guarded = Zeroizing::new([0xA5; 32]);
3242        assert_eq!(
3243            STANDARD.decode(encode_secret_b64(guarded)).unwrap(),
3244            vec![0xA5; 32]
3245        );
3246    }
3247
3248    #[test]
3249    fn transaction_faults_before_durable_commit_restore_the_complete_old_set() {
3250        let faults = [
3251            CommitOperation::StageCreate(1),
3252            CommitOperation::StagePermissions(1),
3253            CommitOperation::StageWrite(1),
3254            CommitOperation::StageSync(1),
3255            CommitOperation::StageKeep(1),
3256            CommitOperation::BackupMetadata(1),
3257            CommitOperation::BackupCreate(1),
3258            CommitOperation::BackupPlaceholderKeep(1),
3259            CommitOperation::BackupRename(0),
3260            CommitOperation::BackupRename(1),
3261            CommitOperation::BackupParentsSync,
3262            CommitOperation::CommitRename(0),
3263            CommitOperation::CommitRename(1),
3264            CommitOperation::CommitParentsSync,
3265        ];
3266        for fault in faults {
3267            let (directory, first, second, result) = transaction_fault_case([fault]);
3268            assert!(result.is_err(), "{fault:?} unexpectedly succeeded");
3269            assert_eq!(
3270                std::fs::read(&first).unwrap(),
3271                b"old-first",
3272                "{fault:?} did not restore the first output"
3273            );
3274            assert_eq!(
3275                std::fs::read(&second).unwrap(),
3276                b"old-second",
3277                "{fault:?} did not restore the second output"
3278            );
3279            assert_eq!(
3280                directory_entries(directory.path()),
3281                vec!["first", "second"],
3282                "{fault:?} left unreported transaction state"
3283            );
3284        }
3285    }
3286
3287    #[test]
3288    fn transaction_cleanup_faults_return_error_with_recovery_state() {
3289        let (directory, first, second, result) =
3290            transaction_fault_case([CommitOperation::BackupDelete(0)]);
3291        let error = result.unwrap_err().to_string();
3292        assert!(error.contains("transaction cleanup was incomplete"));
3293        assert_eq!(std::fs::read(&first).unwrap(), b"new-first");
3294        assert_eq!(std::fs::read(&second).unwrap(), b"new-second");
3295        assert!(
3296            directory_entries(directory.path())
3297                .iter()
3298                .any(|name| name.starts_with(".hyprstream-backup-")),
3299            "failed backup deletion did not preserve the recovery file"
3300        );
3301
3302        let (directory, first, second, result) =
3303            transaction_fault_case([CommitOperation::CleanupParentsSync]);
3304        assert!(result
3305            .unwrap_err()
3306            .to_string()
3307            .contains("durably record backup deletion"));
3308        assert_eq!(std::fs::read(&first).unwrap(), b"new-first");
3309        assert_eq!(std::fs::read(&second).unwrap(), b"new-second");
3310        assert_eq!(directory_entries(directory.path()), vec!["first", "second"]);
3311    }
3312
3313    #[test]
3314    fn transaction_reports_and_preserves_incomplete_rollback_or_staging_cleanup() {
3315        let (directory, first, second, result) = transaction_fault_case([
3316            CommitOperation::CommitRename(1),
3317            CommitOperation::RollbackRemove(0),
3318        ]);
3319        assert!(result
3320            .unwrap_err()
3321            .to_string()
3322            .contains("ROLLBACK INCOMPLETE"));
3323        assert_eq!(std::fs::read(&first).unwrap(), b"old-first");
3324        assert_eq!(std::fs::read(&second).unwrap(), b"old-second");
3325        assert_eq!(directory_entries(directory.path()), vec!["first", "second"]);
3326
3327        let (directory, first, second, result) = transaction_fault_case([
3328            CommitOperation::CommitRename(1),
3329            CommitOperation::RollbackRestore(1),
3330        ]);
3331        assert!(result
3332            .unwrap_err()
3333            .to_string()
3334            .contains("ROLLBACK INCOMPLETE"));
3335        assert_eq!(std::fs::read(&first).unwrap(), b"old-first");
3336        assert!(!second.exists());
3337        assert!(
3338            directory_entries(directory.path())
3339                .iter()
3340                .any(|name| name.starts_with(".hyprstream-backup-")),
3341            "failed restoration did not preserve its backup"
3342        );
3343
3344        let (_directory, first, second, result) = transaction_fault_case([
3345            CommitOperation::CommitRename(1),
3346            CommitOperation::RollbackParentsSync,
3347        ]);
3348        assert!(result
3349            .unwrap_err()
3350            .to_string()
3351            .contains("ROLLBACK INCOMPLETE"));
3352        assert_eq!(std::fs::read(&first).unwrap(), b"old-first");
3353        assert_eq!(std::fs::read(&second).unwrap(), b"old-second");
3354
3355        let (directory, first, second, result) = transaction_fault_case([
3356            CommitOperation::StageCreate(1),
3357            CommitOperation::StageCleanup(0),
3358        ]);
3359        assert!(result
3360            .unwrap_err()
3361            .to_string()
3362            .contains("staged-output cleanup incomplete"));
3363        assert_eq!(std::fs::read(&first).unwrap(), b"old-first");
3364        assert_eq!(std::fs::read(&second).unwrap(), b"old-second");
3365        assert_eq!(directory_entries(directory.path()).len(), 3);
3366
3367        let (directory, first, second, result) =
3368            transaction_fault_case([CommitOperation::BackupPlaceholderRemove(1)]);
3369        let error = result.unwrap_err().to_string();
3370        assert!(error.contains("preserved empty recovery marker"));
3371        assert_eq!(std::fs::read(&first).unwrap(), b"old-first");
3372        assert_eq!(std::fs::read(&second).unwrap(), b"old-second");
3373        let entries = directory_entries(directory.path());
3374        assert_eq!(entries.len(), 3);
3375        assert!(
3376            entries
3377                .iter()
3378                .any(|name| name.starts_with(".hyprstream-backup-")),
3379            "failed placeholder unlink did not preserve and expose its path"
3380        );
3381    }
3382
3383    #[test]
3384    fn recipient_ring_rejects_duplicates_and_singletons() {
3385        let one = distinct_recipients(vec!["age1one".to_owned(), "age1one".to_owned()]).unwrap();
3386        assert_eq!(one.len(), 1);
3387        let args = MintDeploymentCaArgs {
3388            public_ca: "ca".into(),
3389            authority_key: "key".into(),
3390            authority_log: "log".into(),
3391            authority_checkpoint: "head".into(),
3392            recipients: vec!["age1one".to_owned(), "age1one".to_owned()],
3393            yubikey_recipients: vec![],
3394            kms_plugin_recipients: vec![],
3395            piv_slot: None,
3396            force: false,
3397        };
3398        assert!(root_recipient_ring(&args).is_err());
3399    }
3400
3401    #[test]
3402    fn public_pair_layout_is_ed_then_ml_dsa() {
3403        let ed = SigningKey::generate(&mut rand::rngs::OsRng);
3404        let (pq, _) = ml_dsa_generate_keypair();
3405        let bytes = public_pair_bytes(&ed.verifying_key(), &pq);
3406        assert_eq!(bytes.len(), PUBLIC_CA_BYTES);
3407        assert_eq!(&bytes[..32], ed.verifying_key().as_bytes());
3408        assert_eq!(&bytes[32..], ml_dsa_sk_to_vk_bytes(&pq));
3409        assert!(hyprstream_discovery::verify_deployment_public_ca(&bytes).is_ok());
3410    }
3411
3412    #[test]
3413    fn exact_registry_capability_cannot_widen() {
3414        let (pq, _) = ml_dsa_generate_keypair();
3415        let ed = SigningKey::generate(&mut rand::rngs::OsRng);
3416        let public = public_pair_bytes(&ed.verifying_key(), &pq);
3417        let capability =
3418            hyprstream_discovery::registry_mint_capability("domain", &STANDARD.encode(&public));
3419        assert_eq!(capability.ability.as_str(), "mint-registry-jwt");
3420        assert!(!capability.resource.as_str().contains('*'));
3421        assert_eq!(
3422            capability.caveats.0["max_ttl_seconds"],
3423            CaveatValue::Int(3600)
3424        );
3425    }
3426
3427    fn test_genesis(
3428        root: &LoadedAuthority,
3429    ) -> (Vec<u8>, AuthorityLogFile, AuthorityCheckpointFile) {
3430        let root_rotation_key = HybridRotationKey::new(
3431            root.ed.verifying_key().to_bytes(),
3432            ml_dsa_sk_to_vk_bytes(&root.pq),
3433        )
3434        .unwrap();
3435        let genesis = sign_did_op(
3436            DidOp {
3437                sequence: 0,
3438                prev: None,
3439                rotation_keys: vec![root_rotation_key],
3440                signature: placeholder_did_signature(),
3441            },
3442            &root.ed,
3443            &root.pq,
3444        )
3445        .unwrap();
3446        let log = authority_log_from_ops(&root.bundle.deployment_domain, vec![genesis]).unwrap();
3447        let checkpoint = checkpoint_for(&log);
3448        (root.public_bytes(), log, checkpoint)
3449    }
3450
3451    fn delegation_ucan(
3452        root: &LoadedAuthority,
3453        delegated: &LoadedAuthority,
3454        capabilities: Vec<Capability>,
3455        now: u64,
3456    ) -> Ucan {
3457        sign_ucan(
3458            UcanPayload {
3459                issuer: Did::from_ed25519(&root.ed.verifying_key().to_bytes()),
3460                audience: Did::from_ed25519(&delegated.ed.verifying_key().to_bytes()),
3461                capabilities,
3462                not_before: Some(now),
3463                expiration: Some(now + 3_600),
3464                nonce: random_bytes(16),
3465            },
3466            &root.ed,
3467            &root.pq,
3468        )
3469        .unwrap()
3470    }
3471
3472    fn delegation_artifact(
3473        root: &LoadedAuthority,
3474        log: &AuthorityLogFile,
3475        delegated: &LoadedAuthority,
3476        capabilities: Vec<Capability>,
3477        now: u64,
3478    ) -> DelegationArtifact {
3479        let ucan = delegation_ucan(root, delegated, capabilities, now);
3480        DelegationArtifact {
3481            schema: DELEGATION_SCHEMA.to_owned(),
3482            deployment_domain: root.bundle.deployment_domain.clone(),
3483            authority_log_did: log.did.clone(),
3484            delegated_public_key_b64: STANDARD.encode(delegated.public_bytes()),
3485            ucan_b64: STANDARD.encode(ucan.to_cbor().unwrap()),
3486        }
3487    }
3488
3489    fn registry_and_enrollment_capabilities(
3490        root: &LoadedAuthority,
3491        delegated: &LoadedAuthority,
3492    ) -> (Vec<Capability>, Vec<Capability>) {
3493        let delegated_b64 = STANDARD.encode(delegated.public_bytes());
3494        let registry = vec![hyprstream_discovery::registry_mint_capability(
3495            &root.bundle.deployment_domain,
3496            &delegated_b64,
3497        )];
3498        let dual = vec![
3499            registry[0].clone(),
3500            hyprstream_discovery::service_key_enrollment_capability(
3501                &root.bundle.deployment_domain,
3502                &delegated_b64,
3503            ),
3504        ];
3505        (registry, dual)
3506    }
3507
3508    fn enrollment_fixture() -> (
3509        LoadedAuthority,
3510        LoadedAuthority,
3511        Vec<u8>,
3512        AuthorityLogFile,
3513        AuthorityCheckpointFile,
3514        Vec<u8>,
3515        u64,
3516    ) {
3517        let root = test_authority(AuthorityPurpose::Root, None);
3518        let delegated = test_authority(
3519            AuthorityPurpose::RegistryDelegatedSigner,
3520            Some(root.bundle.deployment_domain.clone()),
3521        );
3522        let (public_ca, log, checkpoint) = test_genesis(&root);
3523        let service_ed = SigningKey::generate(&mut rand::rngs::OsRng);
3524        let (service_pq, _) = ml_dsa_generate_keypair();
3525        let service_public = public_pair_bytes(&service_ed.verifying_key(), &service_pq);
3526        let now = now_unix_u64().unwrap();
3527        (
3528            root,
3529            delegated,
3530            public_ca,
3531            log,
3532            checkpoint,
3533            service_public,
3534            now,
3535        )
3536    }
3537
3538    fn mint_test_attestation(
3539        delegated: &LoadedAuthority,
3540        artifact: DelegationArtifact,
3541        service: &str,
3542        service_public_key: &[u8],
3543        now: u64,
3544        ttl_seconds: u64,
3545    ) -> ServiceKeyEnrollmentArtifact {
3546        let body = ServiceKeyEnrollmentSigningBody {
3547            schema: ENROLLMENT_SCHEMA.to_owned(),
3548            deployment_domain: delegated.bundle.deployment_domain.clone(),
3549            service: service.to_owned(),
3550            hybrid_public_key_b64: STANDARD.encode(service_public_key),
3551            not_before: i64::try_from(now).unwrap(),
3552            expires_at: i64::try_from(now + ttl_seconds).unwrap(),
3553            delegation: artifact,
3554        };
3555        let mut attestation = ServiceKeyEnrollmentArtifact::unsigned(body);
3556        let signature = sign_nested(
3557            &attestation.signing_bytes().unwrap(),
3558            ENROLLMENT_SIGNATURE_CONTEXT,
3559            &delegated.ed,
3560            &delegated.pq,
3561        )
3562        .unwrap();
3563        attestation.signature_b64 = STANDARD.encode(&signature);
3564        attestation
3565    }
3566
3567    fn verify_test_attestation(
3568        public_ca: &[u8],
3569        log: &AuthorityLogFile,
3570        checkpoint: &AuthorityCheckpointFile,
3571        attestation: &ServiceKeyEnrollmentArtifact,
3572    ) -> Result<hyprstream_discovery::VerifiedServiceKeyEnrollment> {
3573        hyprstream_discovery::verify_service_key_enrollment(
3574            public_ca,
3575            &serde_json::to_vec(log)?,
3576            &serde_json::to_vec(checkpoint)?,
3577            &serde_json::to_vec(attestation)?,
3578        )
3579    }
3580
3581    #[test]
3582    fn legacy_single_capability_delegation_still_validates() {
3583        let (root, delegated, public_ca, log, checkpoint, _service, now) = enrollment_fixture();
3584        let (legacy, _dual) = registry_and_enrollment_capabilities(&root, &delegated);
3585        let active = validate_authority_log(&public_ca, &log, &checkpoint).unwrap();
3586        // The exact single-capability delegation shape minted 2026-08-30 and
3587        // live in production staging inputs must keep validating.
3588        let ucan = delegation_ucan(&root, &delegated, legacy.clone(), now);
3589        let validated = hyprstream_discovery::validate_delegation_ucan(
3590            &ucan,
3591            &root.bundle.deployment_domain,
3592            &STANDARD.encode(delegated.public_bytes()),
3593            &active.rotation_keys,
3594            now,
3595        )
3596        .unwrap();
3597        assert!(
3598            !validated.grants_service_key_enrollment,
3599            "legacy delegation must not grant enrollment"
3600        );
3601        let artifact = delegation_artifact(&root, &log, &delegated, legacy, now);
3602        let validated = hyprstream_discovery::validate_registry_delegation(
3603            &public_ca,
3604            &log,
3605            &checkpoint,
3606            &artifact,
3607            now,
3608        )
3609        .unwrap();
3610        assert!(!validated.grants_service_key_enrollment);
3611    }
3612
3613    #[test]
3614    fn dual_capability_delegation_validates() {
3615        let (root, delegated, public_ca, log, checkpoint, _service, now) = enrollment_fixture();
3616        let (_legacy, dual) = registry_and_enrollment_capabilities(&root, &delegated);
3617        let active = validate_authority_log(&public_ca, &log, &checkpoint).unwrap();
3618        let ucan = delegation_ucan(&root, &delegated, dual.clone(), now);
3619        let validated = hyprstream_discovery::validate_delegation_ucan(
3620            &ucan,
3621            &root.bundle.deployment_domain,
3622            &STANDARD.encode(delegated.public_bytes()),
3623            &active.rotation_keys,
3624            now,
3625        )
3626        .unwrap();
3627        assert!(
3628            validated.grants_service_key_enrollment,
3629            "two-capability delegation must grant enrollment"
3630        );
3631        let artifact = delegation_artifact(&root, &log, &delegated, dual, now);
3632        let validated = hyprstream_discovery::validate_registry_delegation(
3633            &public_ca,
3634            &log,
3635            &checkpoint,
3636            &artifact,
3637            now,
3638        )
3639        .unwrap();
3640        assert!(validated.grants_service_key_enrollment);
3641        // A delegated registry JWT carrying the two-capability artifact still
3642        // passes the production verifier.
3643        let registry = SigningKey::generate(&mut rand::rngs::OsRng);
3644        let token = encode_registry_jwt(
3645            &delegated,
3646            registry.verifying_key().as_bytes(),
3647            i64::try_from(now).unwrap(),
3648            i64::try_from(now + 60).unwrap(),
3649            Some(&URL_SAFE_NO_PAD.encode(serde_json::to_vec(&artifact).unwrap())),
3650        )
3651        .unwrap();
3652        verify_with_log(&public_ca, &log, &checkpoint, &token).unwrap();
3653    }
3654
3655    #[test]
3656    fn delegation_capability_set_rejects_non_exact_sets() {
3657        let (root, delegated, public_ca, log, checkpoint, _service, now) = enrollment_fixture();
3658        let (legacy, dual) = registry_and_enrollment_capabilities(&root, &delegated);
3659        let active = validate_authority_log(&public_ca, &log, &checkpoint).unwrap();
3660        let validate = |capabilities: Vec<Capability>| {
3661            let ucan = delegation_ucan(&root, &delegated, capabilities, now);
3662            hyprstream_discovery::validate_delegation_ucan(
3663                &ucan,
3664                &root.bundle.deployment_domain,
3665                &STANDARD.encode(delegated.public_bytes()),
3666                &active.rotation_keys,
3667                now,
3668            )
3669        };
3670        // Enrollment without the registry scope is not an exact set.
3671        assert!(validate(vec![dual[1].clone()]).is_err());
3672        // Registry plus an unrelated extra capability widens the scope.
3673        assert!(validate(vec![
3674            legacy[0].clone(),
3675            Capability::new(
3676                Resource::new("hyprstream://deployment/domain/service/other"),
3677                Ability::new("admin")
3678            ),
3679        ])
3680        .is_err());
3681        // An enrollment capability with a widened allowlist differs from the
3682        // exact fixed-allowlist capability.
3683        let mut widened = hyprstream_discovery::service_key_enrollment_capability(
3684            &root.bundle.deployment_domain,
3685            &STANDARD.encode(delegated.public_bytes()),
3686        );
3687        widened.caveats.0.insert(
3688            "allowed_services".to_owned(),
3689            CaveatValue::List(vec![
3690                "discovery".to_owned(),
3691                "policy".to_owned(),
3692                "registry".to_owned(),
3693            ]),
3694        );
3695        assert!(validate(vec![legacy[0].clone(), widened]).is_err());
3696    }
3697
3698    #[test]
3699    fn enrollment_capability_is_exact_and_fixed() {
3700        let (pq, _) = ml_dsa_generate_keypair();
3701        let ed = SigningKey::generate(&mut rand::rngs::OsRng);
3702        let public = public_pair_bytes(&ed.verifying_key(), &pq);
3703        let capability = hyprstream_discovery::service_key_enrollment_capability(
3704            "domain",
3705            &STANDARD.encode(&public),
3706        );
3707        assert_eq!(capability.ability.as_str(), "enroll-service-key");
3708        assert_eq!(
3709            capability.resource.as_str(),
3710            "hyprstream://deployment/domain/service-key-enrollment"
3711        );
3712        assert!(!capability.resource.as_str().contains('*'));
3713        assert_eq!(
3714            capability.caveats.0["allowed_services"],
3715            CaveatValue::List(vec!["discovery".to_owned(), "policy".to_owned()])
3716        );
3717        assert_eq!(
3718            capability.caveats.0["key_type"],
3719            CaveatValue::Text(ENROLLMENT_KEY_TYPE.to_owned())
3720        );
3721        assert_eq!(
3722            capability.caveats.0["max_attestation_ttl_seconds"],
3723            CaveatValue::Int(3_600)
3724        );
3725    }
3726
3727    #[test]
3728    fn service_key_enrollment_artifact_schema_round_trip() {
3729        let (root, delegated, _public_ca, log, _checkpoint, service_public, now) =
3730            enrollment_fixture();
3731        let (_legacy, dual) = registry_and_enrollment_capabilities(&root, &delegated);
3732        let artifact = delegation_artifact(&root, &log, &delegated, dual, now);
3733        let attestation = mint_test_attestation(
3734            &delegated,
3735            artifact,
3736            "discovery",
3737            &service_public,
3738            now,
3739            3_600,
3740        );
3741        let bytes = serde_json::to_vec(&attestation).unwrap();
3742        let decoded: ServiceKeyEnrollmentArtifact = serde_json::from_slice(&bytes).unwrap();
3743        assert_eq!(decoded, attestation);
3744        assert_eq!(decoded.schema, ENROLLMENT_SCHEMA);
3745        // Canonical signing bytes are stable across a round trip.
3746        assert_eq!(
3747            decoded.signing_bytes().unwrap(),
3748            attestation.signing_bytes().unwrap()
3749        );
3750        // Unknown fields are rejected.
3751        let mut value = serde_json::to_value(&attestation).unwrap();
3752        value
3753            .as_object_mut()
3754            .unwrap()
3755            .insert("attacker".to_owned(), serde_json::json!(true));
3756        assert!(serde_json::from_value::<ServiceKeyEnrollmentArtifact>(value).is_err());
3757    }
3758
3759    #[test]
3760    fn service_key_enrollment_mint_verifies_through_production_verifier() {
3761        let (root, delegated, public_ca, log, checkpoint, service_public, now) =
3762            enrollment_fixture();
3763        let (_legacy, dual) = registry_and_enrollment_capabilities(&root, &delegated);
3764        let artifact = delegation_artifact(&root, &log, &delegated, dual, now);
3765        let attestation =
3766            mint_test_attestation(&delegated, artifact, "policy", &service_public, now, 3_600);
3767        let verified =
3768            verify_test_attestation(&public_ca, &log, &checkpoint, &attestation).unwrap();
3769        assert_eq!(verified.service, "policy");
3770        assert_eq!(verified.hybrid_public_key, service_public);
3771        assert_eq!(verified.deployment_domain, root.bundle.deployment_domain);
3772        assert_eq!(verified.expires_at, i64::try_from(now + 3_600).unwrap());
3773    }
3774
3775    #[test]
3776    fn service_key_enrollment_rejects_wrong_service_key_type_and_ttl() {
3777        let (root, delegated, public_ca, log, checkpoint, service_public, now) =
3778            enrollment_fixture();
3779        let (legacy, dual) = registry_and_enrollment_capabilities(&root, &delegated);
3780        let dual_artifact = || delegation_artifact(&root, &log, &delegated, dual.clone(), now);
3781        // Wrong service: outside the fixed discovery/policy allowlist.
3782        let wrong_service = mint_test_attestation(
3783            &delegated,
3784            dual_artifact(),
3785            "registry",
3786            &service_public,
3787            now,
3788            3_600,
3789        );
3790        assert!(
3791            verify_test_attestation(&public_ca, &log, &checkpoint, &wrong_service).is_err(),
3792            "enrollment of a non-allowlisted service was accepted"
3793        );
3794        // Wrong key type: a classical-only 32-byte key, not the 1984-byte hybrid.
3795        let classical_only = mint_test_attestation(
3796            &delegated,
3797            dual_artifact(),
3798            "discovery",
3799            &service_public[..32],
3800            now,
3801            3_600,
3802        );
3803        assert!(
3804            verify_test_attestation(&public_ca, &log, &checkpoint, &classical_only).is_err(),
3805            "enrollment of a classical-only key was accepted"
3806        );
3807        // TTL above the one-hour capability ceiling.
3808        let over_ttl = mint_test_attestation(
3809            &delegated,
3810            dual_artifact(),
3811            "discovery",
3812            &service_public,
3813            now,
3814            3_601,
3815        );
3816        assert!(
3817            verify_test_attestation(&public_ca, &log, &checkpoint, &over_ttl).is_err(),
3818            "enrollment with TTL > 3600 was accepted"
3819        );
3820        // A legacy registry-only delegation never authorizes enrollment.
3821        let legacy_artifact = delegation_artifact(&root, &log, &delegated, legacy, now);
3822        let legacy_scope = mint_test_attestation(
3823            &delegated,
3824            legacy_artifact,
3825            "discovery",
3826            &service_public,
3827            now,
3828            3_600,
3829        );
3830        assert!(
3831            verify_test_attestation(&public_ca, &log, &checkpoint, &legacy_scope).is_err(),
3832            "enrollment under a registry-only delegation was accepted"
3833        );
3834        // Any tampering breaks the hybrid signature.
3835        let mut tampered = mint_test_attestation(
3836            &delegated,
3837            dual_artifact(),
3838            "discovery",
3839            &service_public,
3840            now,
3841            3_600,
3842        );
3843        let mut signature = STANDARD.decode(&tampered.signature_b64).unwrap();
3844        signature[0] ^= 0x01;
3845        tampered.signature_b64 = STANDARD.encode(&signature);
3846        assert!(
3847            verify_test_attestation(&public_ca, &log, &checkpoint, &tampered).is_err(),
3848            "enrollment with a corrupted signature was accepted"
3849        );
3850    }
3851
3852    // ─── H3: verify-deployment --service-key-attestation ────────────────────
3853
3854    fn delegated_registry_token(
3855        delegated: &LoadedAuthority,
3856        artifact: &DelegationArtifact,
3857        now: u64,
3858    ) -> String {
3859        let registry = SigningKey::generate(&mut rand::rngs::OsRng);
3860        encode_registry_jwt(
3861            delegated,
3862            registry.verifying_key().as_bytes(),
3863            i64::try_from(now).unwrap(),
3864            i64::try_from(now + 60).unwrap(),
3865            Some(&URL_SAFE_NO_PAD.encode(serde_json::to_vec(artifact).unwrap())),
3866        )
3867        .unwrap()
3868    }
3869
3870    fn verify_deployment_args(
3871        dir: &std::path::Path,
3872        public_ca: &[u8],
3873        log: &AuthorityLogFile,
3874        checkpoint: &AuthorityCheckpointFile,
3875        token: &str,
3876    ) -> VerifyDeploymentArgs {
3877        let write = |name: &str, bytes: &[u8]| {
3878            let path = dir.join(name);
3879            std::fs::write(&path, bytes).unwrap();
3880            path
3881        };
3882        VerifyDeploymentArgs {
3883            public_ca: write("deployment-ca.hybrid", public_ca),
3884            jwt: write("registry-service.jwt", token.as_bytes()),
3885            authority_log: write(
3886                "deployment-authority.log.json",
3887                &serde_json::to_vec(log).unwrap(),
3888            ),
3889            authority_checkpoint: write(
3890                "deployment-authority.head.json",
3891                &serde_json::to_vec(checkpoint).unwrap(),
3892            ),
3893            contract: None,
3894            service_key_attestations: Vec::new(),
3895        }
3896    }
3897
3898    fn write_attestation(
3899        dir: &std::path::Path,
3900        attestation: &ServiceKeyEnrollmentArtifact,
3901    ) -> std::path::PathBuf {
3902        let path = dir.join(format!("{}.json", attestation.service));
3903        std::fs::write(&path, serde_json::to_vec(attestation).unwrap()).unwrap();
3904        path
3905    }
3906
3907    #[test]
3908    fn verify_deployment_attests_service_key_enrollments() {
3909        let (root, delegated, public_ca, log, checkpoint, service_public, now) =
3910            enrollment_fixture();
3911        let (_legacy, dual) = registry_and_enrollment_capabilities(&root, &delegated);
3912        let artifact = delegation_artifact(&root, &log, &delegated, dual, now);
3913        let token = delegated_registry_token(&delegated, &artifact, now);
3914        let dir = tempfile::tempdir().unwrap();
3915        let mut args = verify_deployment_args(dir.path(), &public_ca, &log, &checkpoint, &token);
3916        // No attestations supplied: the pre-H3 behavior is unchanged.
3917        verify_deployment(&args).unwrap();
3918        // Both allowlisted services attest against the same chain.
3919        for service in ["discovery", "policy"] {
3920            let attestation = mint_test_attestation(
3921                &delegated,
3922                artifact.clone(),
3923                service,
3924                &service_public,
3925                now,
3926                3_600,
3927            );
3928            args.service_key_attestations
3929                .push(write_attestation(dir.path(), &attestation));
3930        }
3931        verify_deployment(&args).unwrap();
3932    }
3933
3934    #[test]
3935    fn verify_deployment_service_key_attestation_fails_closed() {
3936        let (root, delegated, public_ca, log, checkpoint, service_public, now) =
3937            enrollment_fixture();
3938        let (legacy, dual) = registry_and_enrollment_capabilities(&root, &delegated);
3939        let dual_artifact = delegation_artifact(&root, &log, &delegated, dual, now);
3940        let token = delegated_registry_token(&delegated, &dual_artifact, now);
3941        let dir = tempfile::tempdir().unwrap();
3942        let args = |attestations: Vec<std::path::PathBuf>| {
3943            let mut args =
3944                verify_deployment_args(dir.path(), &public_ca, &log, &checkpoint, &token);
3945            args.service_key_attestations = attestations;
3946            args
3947        };
3948        // A missing attestation file fails the command.
3949        assert!(verify_deployment(&args(vec![dir.path().join("absent.json")])).is_err());
3950        // An attestation minted under a legacy registry-only delegation is not
3951        // an enrollment and must fail closed.
3952        let legacy_artifact = delegation_artifact(&root, &log, &delegated, legacy, now);
3953        let legacy_scope = mint_test_attestation(
3954            &delegated,
3955            legacy_artifact,
3956            "discovery",
3957            &service_public,
3958            now,
3959            3_600,
3960        );
3961        assert!(
3962            verify_deployment(&args(vec![write_attestation(dir.path(), &legacy_scope)])).is_err()
3963        );
3964        // An attestation whose lifetime exceeds the one-hour capability ceiling
3965        // is rejected by the production verifier.
3966        let over_ttl = mint_test_attestation(
3967            &delegated,
3968            dual_artifact,
3969            "discovery",
3970            &service_public,
3971            now,
3972            3_601,
3973        );
3974        assert!(verify_deployment(&args(vec![write_attestation(dir.path(), &over_ttl)])).is_err());
3975    }
3976
3977    // ─── H3: fail-closed OsOwnedFiles enrollment consumption ────────────────
3978
3979    static TRUST_DIR_ENV_LOCK: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
3980
3981    /// RAII guard restoring the previous value of a process env var on drop.
3982    struct TrustDirEnvGuard {
3983        prev: Option<std::ffi::OsString>,
3984    }
3985    impl TrustDirEnvGuard {
3986        fn set(path: &std::path::Path) -> Self {
3987            const VAR: &str = "HYPRSTREAM_DEPLOYMENT_TRUST_DIR";
3988            let prev = std::env::var_os(VAR);
3989            std::env::set_var(VAR, path);
3990            Self { prev }
3991        }
3992    }
3993    impl Drop for TrustDirEnvGuard {
3994        fn drop(&mut self) {
3995            const VAR: &str = "HYPRSTREAM_DEPLOYMENT_TRUST_DIR";
3996            match &self.prev {
3997                Some(value) => std::env::set_var(VAR, value),
3998                None => std::env::remove_var(VAR),
3999            }
4000        }
4001    }
4002
4003    #[test]
4004    fn os_owned_bootstrap_enrollment_round_trip() {
4005        use crate::auth::identity_store::{
4006            ensure_bootstrap_pubkeys_enrolled, write_bootstrap_pubkeys_hybrid, BootstrapPubkey,
4007            BOOTSTRAP_PUBKEYS_ENROLLMENT_DIR,
4008        };
4009
4010        let _serial = TRUST_DIR_ENV_LOCK.lock();
4011        let (root, delegated, public_ca, log, checkpoint, _unused, now) = enrollment_fixture();
4012        let (_legacy, dual) = registry_and_enrollment_capabilities(&root, &delegated);
4013        let artifact = delegation_artifact(&root, &log, &delegated, dual, now);
4014        let service_ed = SigningKey::generate(&mut rand::rngs::OsRng);
4015        let (service_pq, _) = ml_dsa_generate_keypair();
4016        let service_pq_vk = ml_dsa_vk_from_bytes(&ml_dsa_sk_to_vk_bytes(&service_pq)).unwrap();
4017        let service_public = public_pair_bytes(&service_ed.verifying_key(), &service_pq);
4018        let attestation = mint_test_attestation(
4019            &delegated,
4020            artifact,
4021            "discovery",
4022            &service_public,
4023            now,
4024            3_600,
4025        );
4026
4027        // The OS-owned trust dir must satisfy the discovery crate's
4028        // trusted-artifact metadata policy (real directories, no
4029        // group/world-writable component), so it lives under the crate dir
4030        // like the discovery crate's own trusted-artifact tests.
4031        let trust_dir = tempfile::Builder::new()
4032            .prefix(".h3-trust-test-")
4033            .tempdir_in(env!("CARGO_MANIFEST_DIR"))
4034            .unwrap();
4035        std::fs::write(trust_dir.path().join("deployment-ca.hybrid"), &public_ca).unwrap();
4036        std::fs::write(
4037            trust_dir.path().join("deployment-authority.log.json"),
4038            serde_json::to_vec(&log).unwrap(),
4039        )
4040        .unwrap();
4041        std::fs::write(
4042            trust_dir.path().join("deployment-authority.head.json"),
4043            serde_json::to_vec(&checkpoint).unwrap(),
4044        )
4045        .unwrap();
4046        let _env = TrustDirEnvGuard::set(trust_dir.path());
4047
4048        let entry = || BootstrapPubkey::hybrid(service_ed.verifying_key(), service_pq_vk.clone());
4049        let credentials = tempfile::tempdir().unwrap();
4050        let mut entries = std::collections::HashMap::new();
4051        entries.insert("discovery".to_owned(), entry());
4052        write_bootstrap_pubkeys_hybrid(credentials.path(), &entries).unwrap();
4053
4054        // Missing attestation directory: fail closed.
4055        assert!(ensure_bootstrap_pubkeys_enrolled(credentials.path(), &entries).is_err());
4056
4057        // Enrolled: the attestation verifies against the chain and matches the
4058        // entry.
4059        let enrollment_dir = credentials.path().join(BOOTSTRAP_PUBKEYS_ENROLLMENT_DIR);
4060        std::fs::create_dir(&enrollment_dir).unwrap();
4061        std::fs::write(
4062            enrollment_dir.join("discovery.json"),
4063            serde_json::to_vec(&attestation).unwrap(),
4064        )
4065        .unwrap();
4066        ensure_bootstrap_pubkeys_enrolled(credentials.path(), &entries).unwrap();
4067
4068        // A bootstrap entry the attestation does not name (rotated without
4069        // re-enrollment) fails closed.
4070        let other_ed = SigningKey::generate(&mut rand::rngs::OsRng);
4071        let (other_pq, _) = ml_dsa_generate_keypair();
4072        let other_pq_vk = ml_dsa_vk_from_bytes(&ml_dsa_sk_to_vk_bytes(&other_pq)).unwrap();
4073        let mut rotated = std::collections::HashMap::new();
4074        rotated.insert(
4075            "discovery".to_owned(),
4076            BootstrapPubkey::hybrid(other_ed.verifying_key(), other_pq_vk),
4077        );
4078        write_bootstrap_pubkeys_hybrid(credentials.path(), &rotated).unwrap();
4079        assert!(ensure_bootstrap_pubkeys_enrolled(credentials.path(), &rotated).is_err());
4080    }
4081
4082    #[test]
4083    fn publisher_manifest_has_no_authority_key_field() {
4084        let value = serde_json::to_value(PublisherManifest {
4085            schema: PUBLISHER_MANIFEST_SCHEMA.to_owned(),
4086            deployment_domain: "d".to_owned(),
4087            profile: REGISTRY_PROFILE.to_owned(),
4088            audience: REGISTRY_AUDIENCE.to_owned(),
4089            expires_at: 1,
4090            public_ca: PublisherArtifact {
4091                local_path: "ca".to_owned(),
4092                install_path: "ca".to_owned(),
4093                encoding: "raw".to_owned(),
4094                base64: "x".to_owned(),
4095                sha256: "x".to_owned(),
4096                size_bytes: 1,
4097                cloud_secret_store: true,
4098            },
4099            authority_log: PublisherArtifact {
4100                local_path: "log".to_owned(),
4101                install_path: AUTHORITY_LOG_INSTALL_PATH.to_owned(),
4102                encoding: "json".to_owned(),
4103                base64: "eA==".to_owned(),
4104                sha256: sha256_hex(b"x"),
4105                size_bytes: 1,
4106                cloud_secret_store: true,
4107            },
4108            authority_checkpoint: PublisherArtifact {
4109                local_path: "head".to_owned(),
4110                install_path: AUTHORITY_CHECKPOINT_INSTALL_PATH.to_owned(),
4111                encoding: "json".to_owned(),
4112                base64: "eA==".to_owned(),
4113                sha256: sha256_hex(b"x"),
4114                size_bytes: 1,
4115                cloud_secret_store: true,
4116            },
4117            registry_jwt: PublisherArtifact {
4118                local_path: "jwt".to_owned(),
4119                install_path: "jwt".to_owned(),
4120                encoding: "utf8".to_owned(),
4121                base64: "x".to_owned(),
4122                sha256: "x".to_owned(),
4123                size_bytes: 1,
4124                cloud_secret_store: true,
4125            },
4126            private_authority_exported: false,
4127            terraform_state_may_contain_private_authority: false,
4128        })
4129        .unwrap();
4130        let object = value.as_object().unwrap();
4131        assert!(!object.contains_key("authority_key"));
4132        assert_eq!(object["private_authority_exported"], false);
4133    }
4134
4135    #[test]
4136    fn publisher_artifact_verification_covers_every_contract_field() {
4137        let bytes = b"authenticated artifact bytes";
4138        let valid = PublisherArtifact {
4139            local_path: "/operator/artifact".to_owned(),
4140            install_path: PUBLIC_CA_INSTALL_PATH.to_owned(),
4141            encoding: "raw".to_owned(),
4142            base64: STANDARD.encode(bytes),
4143            sha256: sha256_hex(bytes),
4144            size_bytes: bytes.len(),
4145            cloud_secret_store: true,
4146        };
4147        verify_publisher_artifact(
4148            &valid,
4149            bytes,
4150            "/operator/artifact",
4151            PUBLIC_CA_INSTALL_PATH,
4152            "raw",
4153        )
4154        .unwrap();
4155
4156        let mutations: [(&str, fn(&mut PublisherArtifact)); 7] = [
4157            ("local_path", |artifact| {
4158                artifact.local_path = "/attacker".to_owned();
4159            }),
4160            ("install_path", |artifact| {
4161                artifact.install_path = "/tmp/attacker".to_owned();
4162            }),
4163            ("encoding", |artifact| {
4164                artifact.encoding = "utf8".to_owned();
4165            }),
4166            ("base64", |artifact| {
4167                artifact.base64 = STANDARD.encode(b"attacker");
4168            }),
4169            ("sha256", |artifact| {
4170                artifact.sha256 = "00".repeat(32);
4171            }),
4172            ("size_bytes", |artifact| {
4173                artifact.size_bytes += 1;
4174            }),
4175            ("cloud_secret_store", |artifact| {
4176                artifact.cloud_secret_store = false;
4177            }),
4178        ];
4179        for (field, mutate) in mutations {
4180            let mut changed = valid.clone();
4181            mutate(&mut changed);
4182            assert!(
4183                verify_publisher_artifact(
4184                    &changed,
4185                    bytes,
4186                    "/operator/artifact",
4187                    PUBLIC_CA_INSTALL_PATH,
4188                    "raw",
4189                )
4190                .is_err(),
4191                "modified contract field {field} was accepted"
4192            );
4193        }
4194    }
4195
4196    #[test]
4197    fn delegated_credential_follows_add_then_fails_after_replace() {
4198        let root = test_authority(AuthorityPurpose::Root, None);
4199        let public_ca = root.public_bytes();
4200        let root_rotation_key = HybridRotationKey::new(
4201            root.ed.verifying_key().to_bytes(),
4202            ml_dsa_sk_to_vk_bytes(&root.pq),
4203        )
4204        .unwrap();
4205        let genesis = sign_did_op(
4206            DidOp {
4207                sequence: 0,
4208                prev: None,
4209                rotation_keys: vec![root_rotation_key.clone()],
4210                signature: placeholder_did_signature(),
4211            },
4212            &root.ed,
4213            &root.pq,
4214        )
4215        .unwrap();
4216        let genesis_log =
4217            authority_log_from_ops(&root.bundle.deployment_domain, vec![genesis.clone()]).unwrap();
4218        let genesis_checkpoint = checkpoint_for(&genesis_log);
4219
4220        let delegated = test_authority(
4221            AuthorityPurpose::RegistryDelegatedSigner,
4222            Some(root.bundle.deployment_domain.clone()),
4223        );
4224        let delegated_public = delegated.public_bytes();
4225        let now = now_unix_u64().unwrap();
4226        let ucan = sign_ucan(
4227            UcanPayload {
4228                issuer: Did::from_ed25519(&root.ed.verifying_key().to_bytes()),
4229                audience: Did::from_ed25519(&delegated.ed.verifying_key().to_bytes()),
4230                capabilities: vec![hyprstream_discovery::registry_mint_capability(
4231                    &root.bundle.deployment_domain,
4232                    &STANDARD.encode(&delegated_public),
4233                )],
4234                not_before: Some(now),
4235                expiration: Some(now + 3_600),
4236                nonce: random_bytes(16),
4237            },
4238            &root.ed,
4239            &root.pq,
4240        )
4241        .unwrap();
4242        let artifact = DelegationArtifact {
4243            schema: DELEGATION_SCHEMA.to_owned(),
4244            deployment_domain: root.bundle.deployment_domain.clone(),
4245            authority_log_did: genesis_log.did.clone(),
4246            delegated_public_key_b64: STANDARD.encode(&delegated_public),
4247            ucan_b64: STANDARD.encode(ucan.to_cbor().unwrap()),
4248        };
4249        let registry = SigningKey::generate(&mut rand::rngs::OsRng);
4250        let direct_token = encode_registry_jwt(
4251            &root,
4252            registry.verifying_key().as_bytes(),
4253            i64::try_from(now).unwrap(),
4254            i64::try_from(now + 60).unwrap(),
4255            None,
4256        )
4257        .unwrap();
4258        let token = encode_registry_jwt(
4259            &delegated,
4260            registry.verifying_key().as_bytes(),
4261            i64::try_from(now).unwrap(),
4262            i64::try_from(now + 60).unwrap(),
4263            Some(&URL_SAFE_NO_PAD.encode(serde_json::to_vec(&artifact).unwrap())),
4264        )
4265        .unwrap();
4266        verify_with_log(&public_ca, &genesis_log, &genesis_checkpoint, &direct_token).unwrap();
4267        verify_with_log(&public_ca, &genesis_log, &genesis_checkpoint, &token).unwrap();
4268
4269        let added = test_authority(
4270            AuthorityPurpose::RotatedAuthority,
4271            Some(root.bundle.deployment_domain.clone()),
4272        );
4273        let added_rotation_key = HybridRotationKey::new(
4274            added.ed.verifying_key().to_bytes(),
4275            ml_dsa_sk_to_vk_bytes(&added.pq),
4276        )
4277        .unwrap();
4278        let add = sign_did_op(
4279            DidOp {
4280                sequence: 1,
4281                prev: Some(genesis.cid().encode()),
4282                rotation_keys: vec![root_rotation_key, added_rotation_key.clone()],
4283                signature: placeholder_did_signature(),
4284            },
4285            &root.ed,
4286            &root.pq,
4287        )
4288        .unwrap();
4289        let add_log = authority_log_from_ops(
4290            &root.bundle.deployment_domain,
4291            vec![genesis.clone(), add.clone()],
4292        )
4293        .unwrap();
4294        let add_checkpoint = checkpoint_for(&add_log);
4295        verify_with_log(&public_ca, &add_log, &add_checkpoint, &token).unwrap();
4296
4297        let replace = sign_did_op(
4298            DidOp {
4299                sequence: 2,
4300                prev: Some(add.cid().encode()),
4301                rotation_keys: vec![added_rotation_key],
4302                signature: placeholder_did_signature(),
4303            },
4304            &root.ed,
4305            &root.pq,
4306        )
4307        .unwrap();
4308        let replace_log =
4309            authority_log_from_ops(&root.bundle.deployment_domain, vec![genesis, add, replace])
4310                .unwrap();
4311        let replace_checkpoint = checkpoint_for(&replace_log);
4312        assert!(
4313            verify_with_log(&public_ca, &genesis_log, &replace_checkpoint, &token,).is_err(),
4314            "historical authority-log prefix matched against a newer checkpoint"
4315        );
4316        assert!(verify_with_log(&public_ca, &replace_log, &replace_checkpoint, &token,).is_err());
4317        assert!(
4318            verify_with_log(&public_ca, &replace_log, &replace_checkpoint, &direct_token,).is_err()
4319        );
4320    }
4321
4322    #[test]
4323    fn compact_registry_jwt_rejects_any_whitespace() {
4324        let root = test_authority(AuthorityPurpose::Root, None);
4325        let registry = SigningKey::generate(&mut rand::rngs::OsRng);
4326        let now = chrono::Utc::now().timestamp();
4327        let token = encode_registry_jwt(
4328            &root,
4329            registry.verifying_key().as_bytes(),
4330            now,
4331            now + 60,
4332            None,
4333        )
4334        .unwrap();
4335        assert!(hyprstream_discovery::verify_genesis_deployment_artifacts(
4336            &root.public_bytes(),
4337            &token
4338        )
4339        .is_ok());
4340        assert!(
4341            hyprstream_discovery::verify_deployment_artifacts_with_authority_log(
4342                &root.public_bytes(),
4343                b"",
4344                b"",
4345                &token,
4346            )
4347            .is_err(),
4348            "enrolled verification inferred direct-root genesis mode from omitted trust files"
4349        );
4350        assert!(hyprstream_discovery::verify_genesis_deployment_artifacts(
4351            &root.public_bytes(),
4352            &format!("{token}\n")
4353        )
4354        .is_err());
4355    }
4356
4357    #[test]
4358    fn trust_refresh_service_unit_only_uses_the_delegated_signer() {
4359        let unit = trust_refresh_service_unit();
4360        assert!(unit.contains(
4361            "--via-delegated-signer /etc/hyprstream/trust/delegated/registry-delegated-signer.age"
4362        ));
4363        assert!(unit.contains(
4364            "--delegation /etc/hyprstream/trust/delegated/registry-signer.delegation.json"
4365        ));
4366        assert!(unit.contains("--identity /etc/hyprstream/trust/delegated/refresh-identity"));
4367        assert!(unit.contains("--jwt /run/hyprstream/credentials/registry-service.jwt"));
4368        assert!(unit.contains("--force"));
4369        assert!(
4370            !unit.contains("--root") && !unit.contains("deployment-ca.age"),
4371            "refresher unit must never reference the root authority — only the delegated signer"
4372        );
4373    }
4374
4375    #[test]
4376    fn trust_refresh_service_unit_recreates_the_runtime_credentials_directory() {
4377        let unit = trust_refresh_service_unit();
4378        assert!(unit.contains("RuntimeDirectory=hyprstream/credentials"));
4379        assert!(unit.contains("RuntimeDirectoryMode=0750"));
4380        assert!(unit.contains("RuntimeDirectoryPreserve=yes"));
4381        assert!(unit.contains("ReadWritePaths=/run/hyprstream/credentials"));
4382    }
4383
4384    #[test]
4385    fn trust_refresh_timer_unit_uses_the_requested_interval() {
4386        let unit = trust_refresh_timer_unit("30min");
4387        assert!(unit.contains("OnUnitActiveSec=30min"));
4388        assert!(unit.contains("WantedBy=timers.target"));
4389    }
4390
4391    #[test]
4392    fn refresh_interval_accepts_only_plain_time_spans() {
4393        for valid in ["30min", "45s", "1h", "90s"] {
4394            validate_refresh_interval(valid).unwrap();
4395        }
4396        for invalid in [
4397            "",
4398            "30",
4399            "30 min",
4400            "0s",
4401            "015min",
4402            "30m",
4403            "5hr",
4404            "-5min",
4405            "30min\nOnCalendar=*-*-* *:*:*",
4406            "30min\n[Install]\nWantedBy=multi-user.target",
4407        ] {
4408            assert!(
4409                validate_refresh_interval(invalid).is_err(),
4410                "interval {invalid:?} was accepted"
4411            );
4412        }
4413    }
4414
4415    #[test]
4416    fn refresh_identity_must_be_a_plaintext_age_identity() {
4417        validate_age_identity_contents(
4418            b"# created: 2026-01-01\n# public key: age1example\nAGE-SECRET-KEY-1EXAMPLE\n",
4419        )
4420        .unwrap();
4421        for invalid in [
4422            &b""[..],
4423            b"# only comments\n",
4424            b"age-encryption.org/v1\n-> X25519 ciphertext",
4425            b"AGE-PLUGIN-YUBIKEY-1EXAMPLE\n",
4426            b"\xff\xfe not utf-8 \xff",
4427        ] {
4428            assert!(
4429                validate_age_identity_contents(invalid).is_err(),
4430                "identity contents {invalid:?} were accepted"
4431            );
4432        }
4433    }
4434
4435    fn current_uid() -> u32 {
4436        nix::unistd::Uid::effective().as_raw()
4437    }
4438
4439    /// A tempdir under the crate directory rather than the system temp dir:
4440    /// ensure_owned_dir inspects every ancestor of the install path, and the
4441    /// sticky world-writable system temp dir would be rejected as an ancestor.
4442    fn owned_ancestry_tempdir() -> tempfile::TempDir {
4443        tempfile::Builder::new()
4444            .prefix("trust-install-test-")
4445            .tempdir_in(env!("CARGO_MANIFEST_DIR"))
4446            .unwrap()
4447    }
4448
4449    #[test]
4450    fn ensure_owned_dir_creates_missing_directory_with_mode() {
4451        let base = owned_ancestry_tempdir();
4452        let target = base.path().join("a/b/c");
4453        ensure_owned_dir(&target, 0o750, current_uid()).unwrap();
4454        let metadata = std::fs::metadata(&target).unwrap();
4455        assert!(metadata.is_dir());
4456        assert_eq!(metadata.permissions().mode() & 0o777, 0o750);
4457        // Idempotent: a second call against the same real directory succeeds.
4458        ensure_owned_dir(&target, 0o750, current_uid()).unwrap();
4459    }
4460
4461    #[test]
4462    fn ensure_owned_dir_rejects_symlinked_target() {
4463        let base = owned_ancestry_tempdir();
4464        let real = base.path().join("real");
4465        std::fs::create_dir(&real).unwrap();
4466        let link = base.path().join("link");
4467        std::os::unix::fs::symlink(&real, &link).unwrap();
4468        assert!(ensure_owned_dir(&link, 0o755, current_uid()).is_err());
4469    }
4470
4471    #[test]
4472    fn ensure_owned_dir_rejects_group_writable_existing_component() {
4473        let base = owned_ancestry_tempdir();
4474        let mid = base.path().join("mid");
4475        std::fs::create_dir(&mid).unwrap();
4476        std::fs::set_permissions(&mid, std::fs::Permissions::from_mode(0o775)).unwrap();
4477        let error = ensure_owned_dir(&mid.join("leaf"), 0o755, current_uid()).unwrap_err();
4478        assert!(
4479            error.to_string().contains("group/world writable"),
4480            "unexpected rejection: {error}"
4481        );
4482    }
4483
4484    #[test]
4485    fn ensure_owned_dir_rejects_symlinked_intermediate_component() {
4486        let base = owned_ancestry_tempdir();
4487        let real = base.path().join("real");
4488        std::fs::create_dir_all(real.join("leaf")).unwrap();
4489        let mid = base.path().join("mid");
4490        std::os::unix::fs::symlink(&real, &mid).unwrap();
4491        // The full path exists and its leaf is a real directory, but it is
4492        // reached through a symlinked intermediate component.
4493        let through_link = mid.join("leaf");
4494        assert!(std::fs::metadata(&through_link).unwrap().is_dir());
4495        assert!(ensure_owned_dir(&through_link, 0o755, current_uid()).is_err());
4496    }
4497
4498    /// Generate a fresh age identity/recipient pair via `age-keygen`, returning
4499    /// (identity_lines, recipient_string). Returns None when the `age-keygen`
4500    /// binary is not available (CI without age installed).
4501    fn age_keypair() -> Option<(String, String)> {
4502        let output = std::process::Command::new("age-keygen")
4503            .stdout(Stdio::piped())
4504            .stderr(Stdio::piped())
4505            .output()
4506            .ok()?;
4507        if !output.status.success() {
4508            return None;
4509        }
4510        let text = String::from_utf8(output.stdout).ok()?;
4511        let recipient = text
4512            .lines()
4513            .find_map(|line| line.strip_prefix("# public key: ").map(str::to_owned))?;
4514        let identity = text
4515            .lines()
4516            .find(|line| line.starts_with("AGE-SECRET-KEY-1"))?
4517            .to_owned();
4518        Some((identity, recipient))
4519    }
4520
4521    /// Return true when the `age` binary is available on PATH.
4522    fn age_available() -> bool {
4523        std::process::Command::new("age")
4524            .arg("--version")
4525            .stdin(Stdio::null())
4526            .stdout(Stdio::null())
4527            .stderr(Stdio::null())
4528            .status()
4529            .is_ok()
4530    }
4531
4532    /// Build a temp-dir fixture: encrypts a delegated authority bundle to the
4533    /// given recipient, writes the ciphertext and identity to temp files, and
4534    /// returns (delegated_key_path, identity_path, public_bytes).
4535    fn trial_fixture(
4536        dir: &Path,
4537        authority: &LoadedAuthority,
4538        identity: &str,
4539        recipient: &str,
4540    ) -> (PathBuf, PathBuf, Vec<u8>) {
4541        let public_bytes = authority.public_bytes();
4542        let plaintext = serialize_secret_json(&authority.bundle).unwrap();
4543        let encrypted = encrypt_age(&plaintext, &[recipient.to_owned()]).unwrap();
4544        let delegated_key_path = dir.join("delegated.age");
4545        std::fs::write(&delegated_key_path, &encrypted).unwrap();
4546        let identity_path = dir.join("identity");
4547        std::fs::write(&identity_path, identity).unwrap();
4548        (delegated_key_path, identity_path, public_bytes)
4549    }
4550
4551    fn placeholder_artifact(domain: &str, public_bytes: &[u8]) -> DelegationArtifact {
4552        DelegationArtifact {
4553            schema: DELEGATION_SCHEMA.to_owned(),
4554            deployment_domain: domain.to_owned(),
4555            authority_log_did: "did:web:placeholder".to_owned(),
4556            delegated_public_key_b64: STANDARD.encode(public_bytes),
4557            ucan_b64: STANDARD.encode(b"placeholder"),
4558        }
4559    }
4560
4561    #[test]
4562    fn trial_decrypt_succeeds_when_identity_matches() {
4563        if !age_available() {
4564            eprintln!("skipping: age binary not on PATH");
4565            return;
4566        }
4567        let Some((identity, recipient)) = age_keypair() else {
4568            eprintln!("skipping: age-keygen binary not on PATH");
4569            return;
4570        };
4571
4572        let dir = tempfile::tempdir().unwrap();
4573        let authority = test_authority(AuthorityPurpose::RegistryDelegatedSigner, None);
4574        let (delegated_key_path, identity_path, public_bytes) =
4575            trial_fixture(dir.path(), &authority, &identity, &recipient);
4576        let artifact = placeholder_artifact(&authority.bundle.deployment_domain, &public_bytes);
4577
4578        trial_decrypt_delegated_signer(&delegated_key_path, &identity_path, &artifact)
4579            .expect("matching identity and artifact must pass trial decrypt");
4580    }
4581
4582    #[test]
4583    fn trial_decrypt_fails_when_identity_does_not_match() {
4584        if !age_available() {
4585            eprintln!("skipping: age binary not on PATH");
4586            return;
4587        }
4588        let Some((identity, recipient)) = age_keypair() else {
4589            eprintln!("skipping: age-keygen binary not on PATH");
4590            return;
4591        };
4592
4593        let dir = tempfile::tempdir().unwrap();
4594        let authority = test_authority(AuthorityPurpose::RegistryDelegatedSigner, None);
4595        let (delegated_key_path, _identity_path, public_bytes) =
4596            trial_fixture(dir.path(), &authority, &identity, &recipient);
4597
4598        // A different identity that cannot decrypt the ciphertext.
4599        let wrong_identity = age_keypair().expect("age-keygen available").0;
4600        let wrong_identity_path = dir.path().join("wrong-identity");
4601        std::fs::write(&wrong_identity_path, &wrong_identity).unwrap();
4602
4603        let artifact = placeholder_artifact(&authority.bundle.deployment_domain, &public_bytes);
4604
4605        let err =
4606            trial_decrypt_delegated_signer(&delegated_key_path, &wrong_identity_path, &artifact)
4607                .unwrap_err();
4608        assert!(
4609            err.to_string().contains("cannot decrypt"),
4610            "expected decrypt failure, got: {err}"
4611        );
4612    }
4613
4614    #[test]
4615    fn trial_decrypt_fails_when_public_key_mismatch() {
4616        if !age_available() {
4617            eprintln!("skipping: age binary not on PATH");
4618            return;
4619        }
4620        let Some((identity, recipient)) = age_keypair() else {
4621            eprintln!("skipping: age-keygen binary not on PATH");
4622            return;
4623        };
4624
4625        let dir = tempfile::tempdir().unwrap();
4626        let authority = test_authority(AuthorityPurpose::RegistryDelegatedSigner, None);
4627        let (delegated_key_path, identity_path, _public_bytes) =
4628            trial_fixture(dir.path(), &authority, &identity, &recipient);
4629
4630        // Artifact claims a different public key than the one encrypted in the
4631        // delegated signer ciphertext.
4632        let other = test_authority(AuthorityPurpose::RegistryDelegatedSigner, None);
4633        let artifact =
4634            placeholder_artifact(&authority.bundle.deployment_domain, &other.public_bytes());
4635
4636        let err = trial_decrypt_delegated_signer(&delegated_key_path, &identity_path, &artifact)
4637            .unwrap_err();
4638        assert!(
4639            err.to_string().contains("does not match"),
4640            "expected public-key mismatch, got: {err}"
4641        );
4642    }
4643
4644    #[test]
4645    fn trial_decrypt_fails_when_bundle_is_not_a_delegated_signer() {
4646        if !age_available() {
4647            eprintln!("skipping: age binary not on PATH");
4648            return;
4649        }
4650        let Some((identity, recipient)) = age_keypair() else {
4651            eprintln!("skipping: age-keygen binary not on PATH");
4652            return;
4653        };
4654
4655        let dir = tempfile::tempdir().unwrap();
4656        // Root authority accidentally installed as the delegated signer.
4657        let authority = test_authority(AuthorityPurpose::Root, None);
4658        let (delegated_key_path, identity_path, public_bytes) =
4659            trial_fixture(dir.path(), &authority, &identity, &recipient);
4660        let artifact = placeholder_artifact(&authority.bundle.deployment_domain, &public_bytes);
4661
4662        let err = trial_decrypt_delegated_signer(&delegated_key_path, &identity_path, &artifact)
4663            .unwrap_err();
4664        assert!(
4665            err.to_string().contains("not a RegistryDelegatedSigner"),
4666            "expected purpose mismatch, got: {err}"
4667        );
4668    }
4669
4670    fn multibase(codec: [u8; 2], key: &[u8]) -> String {
4671        let mut payload = Vec::with_capacity(2 + key.len());
4672        payload.extend_from_slice(&codec);
4673        payload.extend_from_slice(key);
4674        format!("z{}", bs58::encode(payload).into_string())
4675    }
4676
4677    /// Anchor-minting arguments for an iroh-reachable deployment whose
4678    /// Discovery service is `discovery`, with paths that are never written
4679    /// (these tests exercise the material, not the commit).
4680    fn anchor_args(did_web: &str, node_id: &str, discovery: &SigningKey) -> MintAnchorCapsuleArgs {
4681        let kem = hyprstream_rpc::node_identity::derive_mesh_kem_recipient(discovery)
4682            .unwrap()
4683            .public();
4684        let mesh_pq = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(discovery);
4685        MintAnchorCapsuleArgs {
4686            public_ca: PathBuf::from("deployment-ca.hybrid"),
4687            authority_key: PathBuf::from("deployment-ca.age"),
4688            authority_log: PathBuf::from("deployment-authority.log.json"),
4689            authority_checkpoint: PathBuf::from("deployment-authority.head.json"),
4690            identities: Vec::new(),
4691            yubikey_identities: Vec::new(),
4692            software_recovery: false,
4693            did_web: did_web.to_owned(),
4694            iroh_node_id: Some(node_id.to_owned()),
4695            iroh_relay: None,
4696            quic_endpoint: None,
4697            quic_sni: None,
4698            quic_cert_sha256: Vec::new(),
4699            quic_web_pki: false,
4700            mesh_kem_x25519: Some(multibase([0xec, 0x01], &kem.eks[0])),
4701            mesh_kem_mlkem768: Some(multibase([0x8c, 0x24], &kem.eks[1])),
4702            mesh_pq: Some(multibase([0x91, 0x24], &ml_dsa_sk_to_vk_bytes(&mesh_pq))),
4703            capsule_out: PathBuf::from("anchor-capsule.cbor"),
4704            did_json_out: PathBuf::from("did.json"),
4705            force: false,
4706        }
4707    }
4708
4709    /// The whole point of the minter: what it emits must survive the same
4710    /// resolution the DID-anchored bootstrap performs, and must hand back the
4711    /// deployment CA that signed it.
4712    #[test]
4713    fn minted_anchor_pair_verifies_through_the_production_resolver() {
4714        let authority = test_authority(AuthorityPurpose::Root, None);
4715        let carrier = SigningKey::generate(&mut rand::rngs::OsRng);
4716        let discovery = SigningKey::generate(&mut rand::rngs::OsRng);
4717        let node_id =
4718            hyprstream_rpc::did_key::ed25519_to_did_key(carrier.verifying_key().as_bytes())
4719                .strip_prefix("did:key:")
4720                .unwrap()
4721                .to_owned();
4722        let args = anchor_args("did:web:staging.example.com", &node_id, &discovery);
4723        let reach = anchor_reach_endpoint(&args).unwrap();
4724
4725        let minted = build_anchor_material(&args, &reach, &authority).unwrap();
4726
4727        // Independently re-run the production verifier over the emitted bytes.
4728        let verified = verify_anchor_material_offline(
4729            &minted.at9p_did,
4730            &args.did_web,
4731            &minted.document,
4732            &minted.capsule_bytes,
4733        )
4734        .expect("minted anchor capsule must verify through the production resolver");
4735        assert_eq!(verified.at9p_did, minted.at9p_did);
4736        assert_eq!(verified.deployment_ca_public, authority.public_bytes());
4737        assert_eq!(
4738            verified.discovery_transport.endpoint,
4739            hyprstream_rpc::transport::EndpointType::Iroh {
4740                node_id: carrier.verifying_key().to_bytes(),
4741                direct_addrs: Vec::new(),
4742                relay_url: None,
4743            }
4744        );
4745
4746        // The document half carries what a remote-node bootstrap additionally
4747        // demands: a hybrid KEM recipient and exactly one ML-DSA-65 anchor.
4748        assert_eq!(
4749            hyprstream_rpc::did_web::mesh_kem_recipient(&minted.document),
4750            Some(
4751                hyprstream_rpc::node_identity::derive_mesh_kem_recipient(&discovery)
4752                    .unwrap()
4753                    .public()
4754            )
4755        );
4756        assert_eq!(
4757            hyprstream_rpc::did_web::verification_method_ml_dsa_65_keys(&minted.document).len(),
4758            1
4759        );
4760    }
4761
4762    /// A node identity capsule (no deployment-reach entry) must be refused, and
4763    /// the refusal must name the command that produces a usable one.
4764    #[test]
4765    fn capsule_without_deployment_reach_is_refused_with_minting_guidance() {
4766        let did_web = "did:web:staging.example.com";
4767        let ed = SigningKey::generate(&mut rand::rngs::OsRng);
4768        let (pq, _) = ml_dsa_generate_keypair();
4769        let subject =
4770            HybridKeyPair::new(ed.verifying_key().to_bytes(), ml_dsa_sk_to_vk_bytes(&pq)).unwrap();
4771        let endpoint =
4772            ServiceEndpoint::new(Transport::Https, "https://staging.example.com").unwrap();
4773        let service = ServiceEntry::new("#pds", ServiceType::AtprotoPds, endpoint).unwrap();
4774        let mut body = CapsuleBody::new(vec![subject], vec![service]).unwrap();
4775        body.also_known_as = Some(vec![did_web.to_owned()]);
4776        let capsule = sign_capsule_detached(body, &ed, &pq).unwrap();
4777        let bytes = capsule.to_dag_cbor().unwrap();
4778        let at9p_did = format!("did:at9p:{}", capsule.cid512().unwrap());
4779        let document = serde_json::json!({
4780            "id": did_web,
4781            "alsoKnownAs": [at9p_did],
4782        });
4783
4784        let error = verify_anchor_material_offline(&at9p_did, did_web, &document, &bytes)
4785            .expect_err("a capsule with no deployment reach must not verify");
4786        let rendered = format!("{error:#}");
4787        assert!(
4788            rendered.contains("closed deployment-anchor profile violation"),
4789            "a node capsule must be rejected by the closed anchor profile: {rendered}"
4790        );
4791        assert!(
4792            rendered.contains("mint-anchor-capsule"),
4793            "rejection must tell the operator how to mint a usable anchor: {rendered}"
4794        );
4795    }
4796
4797    /// A rotated authority whose key differs from the pinned root CA must not
4798    /// be able to mint an anchor capsule — the capsule subject key would not
4799    /// be the key the resolver pins from `deployment-ca.hybrid`.
4800    #[test]
4801    fn rotated_authority_not_matching_pinned_ca_is_rejected_for_anchor_mint() {
4802        let root = test_authority(AuthorityPurpose::Root, None);
4803        let public_ca = root.public_bytes();
4804
4805        // A rotated authority with a different key.
4806        let rotated = test_authority(
4807            AuthorityPurpose::RotatedAuthority,
4808            Some(root.bundle.deployment_domain.clone()),
4809        );
4810        assert_ne!(
4811            rotated.public_bytes(),
4812            public_ca,
4813            "test setup: rotated key must differ from root"
4814        );
4815
4816        // Build the authority log so that the rotated key is active.
4817        let root_rotation_key = HybridRotationKey::new(
4818            root.ed.verifying_key().to_bytes(),
4819            ml_dsa_sk_to_vk_bytes(&root.pq),
4820        )
4821        .unwrap();
4822        let rotated_rotation_key = HybridRotationKey::new(
4823            rotated.ed.verifying_key().to_bytes(),
4824            ml_dsa_sk_to_vk_bytes(&rotated.pq),
4825        )
4826        .unwrap();
4827        let genesis = sign_did_op(
4828            DidOp {
4829                sequence: 0,
4830                prev: None,
4831                rotation_keys: vec![root_rotation_key],
4832                signature: placeholder_did_signature(),
4833            },
4834            &root.ed,
4835            &root.pq,
4836        )
4837        .unwrap();
4838        let add_rotation = sign_did_op(
4839            DidOp {
4840                sequence: 1,
4841                prev: Some(genesis.cid().encode()),
4842                rotation_keys: vec![rotated_rotation_key],
4843                signature: placeholder_did_signature(),
4844            },
4845            &root.ed,
4846            &root.pq,
4847        )
4848        .unwrap();
4849        let log =
4850            authority_log_from_ops(&root.bundle.deployment_domain, vec![genesis, add_rotation])
4851                .unwrap();
4852        let verified = validate_authority_log(&public_ca, &log, &checkpoint_for(&log)).unwrap();
4853
4854        // The rotated key IS active in the rotation log ...
4855        ensure_active_authority(&rotated, &verified).unwrap();
4856
4857        // ... but it does NOT match the pinned public CA, so the anchor mint
4858        // guard (the same one `mint_anchor_capsule` runs before it builds the
4859        // capsule body) must refuse it. Routing through `ensure_anchor_authority`
4860        // makes the test causal: remove the CA-binding `ensure!` inside it and
4861        // this assertion fails.
4862        assert!(
4863            rotated.bundle.purpose != AuthorityPurpose::RegistryDelegatedSigner,
4864            "test setup: rotated must pass the purpose guard"
4865        );
4866        assert_ne!(
4867            rotated.public_bytes(),
4868            public_ca,
4869            "the CA-binding check would not fire if the keys matched"
4870        );
4871        let error = ensure_anchor_authority(&rotated, &public_ca, &verified)
4872            .expect_err("a rotated authority not matching the pinned CA must be refused");
4873        assert!(
4874            format!("{error:#}").contains("does not match the pinned public CA"),
4875            "rejection must name the CA-binding mismatch: {error:#}"
4876        );
4877    }
4878
4879    /// A QUIC anchor reach with --quic-web-pki and no pins must emit a
4880    /// QuicTransport service entry (WebPKI without cert pinning).
4881    #[test]
4882    fn quic_web_pki_without_pins_emits_transport_entry() {
4883        let discovery = SigningKey::generate(&mut rand::rngs::OsRng);
4884        let node_id =
4885            hyprstream_rpc::did_key::ed25519_to_did_key(discovery.verifying_key().as_bytes())
4886                .strip_prefix("did:key:")
4887                .unwrap()
4888                .to_owned();
4889        let mut args = anchor_args("did:web:staging.example.com", &node_id, &discovery);
4890        args.iroh_node_id = None;
4891        args.quic_endpoint = Some("203.0.113.5:443".parse().unwrap());
4892        args.quic_web_pki = true;
4893        args.quic_sni = Some("staging.example.com".to_owned());
4894        // No quic_cert_sha256 — pure WebPKI mode.
4895
4896        let reach = anchor_reach_endpoint(&args).unwrap();
4897        let doc_service = reach
4898            .document_service
4899            .as_ref()
4900            .expect("WebPKI-without-pins must still emit a QuicTransport entry");
4901        let service_endpoint = doc_service
4902            .get("serviceEndpoint")
4903            .expect("entry must have a serviceEndpoint");
4904        let uri = service_endpoint
4905            .get("uri")
4906            .and_then(|v| v.as_str())
4907            .expect("entry must have a uri");
4908        assert!(
4909            uri.contains("staging.example.com"),
4910            "uri must carry the SNI hostname: {uri}"
4911        );
4912        let webpki = service_endpoint
4913            .get("webpki")
4914            .and_then(serde_json::Value::as_bool)
4915            .expect("entry must have a webpki flag");
4916        assert!(webpki, "webpki must be true for a --quic-web-pki reach");
4917        let cert_hashes = service_endpoint
4918            .get("certHashes")
4919            .and_then(|v| v.as_array())
4920            .expect("entry must have a certHashes array");
4921        assert!(
4922            cert_hashes.is_empty(),
4923            "certHashes must be empty when no pins were supplied"
4924        );
4925    }
4926
4927    /// A QUIC anchor reach with hostname SNI and pins must produce a document
4928    /// service entry whose URI uses the hostname, so that the resolver can
4929    /// match it against the capsule's QUIC socket address by port.
4930    #[test]
4931    fn quic_hostname_sni_with_pins_produces_matchable_entry() {
4932        let discovery = SigningKey::generate(&mut rand::rngs::OsRng);
4933        let node_id =
4934            hyprstream_rpc::did_key::ed25519_to_did_key(discovery.verifying_key().as_bytes())
4935                .strip_prefix("did:key:")
4936                .unwrap()
4937                .to_owned();
4938        let mut args = anchor_args("did:web:staging.example.com", &node_id, &discovery);
4939        args.iroh_node_id = None;
4940        args.quic_endpoint = Some("203.0.113.5:443".parse().unwrap());
4941        args.quic_sni = Some("staging.example.com".to_owned());
4942        args.quic_cert_sha256 = vec!["aa".repeat(32)];
4943        args.quic_web_pki = true;
4944
4945        let reach = anchor_reach_endpoint(&args).unwrap();
4946        let doc_service = reach
4947            .document_service
4948            .as_ref()
4949            .expect("hostname-SNI with pins must emit a QuicTransport entry");
4950        let uri = doc_service
4951            .get("serviceEndpoint")
4952            .and_then(|v| v.get("uri"))
4953            .and_then(|v| v.as_str())
4954            .expect("entry must have a uri");
4955        assert!(
4956            uri.contains("staging.example.com"),
4957            "uri must use the SNI hostname, not the IP: {uri}"
4958        );
4959    }
4960
4961    // ---- PIV slot occupancy guard ------------------------------------
4962
4963    /// Verbatim stderr from `ykman piv keys info 9c` against a YubiKey
4964    /// whose slot holds no key.
4965    const YKMAN_NO_KEY: &str = "ERROR: No key stored in slot 9C (SIGNATURE).\n";
4966    /// Verbatim stderr from `ykman piv certificates export 9c -` against a
4967    /// YubiKey whose slot holds no certificate.
4968    const YKMAN_NO_CERT: &str = "ERROR: No certificate found.\n";
4969
4970    /// The only state that permits a destructive import: both objects
4971    /// definitively reported absent.
4972    #[test]
4973    fn piv_slot_empty_only_when_both_probes_report_absent() {
4974        assert!(!slot_occupied_from_probes(
4975            (Some(1), YKMAN_NO_KEY),
4976            (Some(1), YKMAN_NO_CERT),
4977        ));
4978    }
4979
4980    /// The primary scenario the guard exists for: `piv_import_ed25519`
4981    /// imports a key without minting a certificate, so a certificate-only
4982    /// probe reads that slot as empty. The key probe must catch it.
4983    #[test]
4984    fn piv_slot_with_key_but_no_certificate_is_occupied() {
4985        assert!(slot_occupied_from_probes(
4986            (Some(0), ""),
4987            (Some(1), YKMAN_NO_CERT),
4988        ));
4989    }
4990
4991    /// The mirror case: a certificate whose private key lives elsewhere.
4992    #[test]
4993    fn piv_slot_with_certificate_but_no_key_is_occupied() {
4994        assert!(slot_occupied_from_probes(
4995            (Some(1), YKMAN_NO_KEY),
4996            (Some(0), "")
4997        ));
4998    }
4999
5000    /// Exit 1 carrying a message OTHER than the absence marker is a
5001    /// transient failure, not an empty slot. Either probe failing this
5002    /// way must refuse the import.
5003    #[test]
5004    fn piv_slot_transient_failure_is_not_absence() {
5005        let transient = "ERROR: Failed to connect to YubiKey.\n";
5006        assert!(slot_occupied_from_probes(
5007            (Some(1), transient),
5008            (Some(1), YKMAN_NO_CERT),
5009        ));
5010        assert!(slot_occupied_from_probes(
5011            (Some(1), YKMAN_NO_KEY),
5012            (Some(1), transient),
5013        ));
5014    }
5015
5016    /// Exit 2 is how `ykman` reports a subcommand or argument it does not
5017    /// recognise. It must never read as "slot is empty" — that inversion
5018    /// is exactly how a wrong command name turns the guard into a
5019    /// rubber stamp.
5020    #[test]
5021    fn piv_slot_argument_error_is_not_absence() {
5022        assert!(slot_occupied_from_probes(
5023            (Some(2), "Error: No such command 'list'.\n"),
5024            (Some(1), YKMAN_NO_CERT),
5025        ));
5026    }
5027
5028    /// Absence requires BOTH the exit code and the marker. Matching the
5029    /// marker alone would let any failure that happens to quote the
5030    /// message — a usage error echoing it, a wrapper relaying it —
5031    /// clear the guard.
5032    #[test]
5033    fn piv_slot_absence_marker_alone_is_not_absence() {
5034        assert!(slot_occupied_from_probes(
5035            (Some(2), "Usage error near: No key stored in slot 9C\n"),
5036            (Some(1), YKMAN_NO_CERT),
5037        ));
5038        assert!(slot_occupied_from_probes(
5039            (Some(1), YKMAN_NO_KEY),
5040            (Some(2), "Usage error near: No certificate found\n"),
5041        ));
5042    }
5043
5044    /// A probe killed by a signal reports no exit code at all.
5045    #[test]
5046    fn piv_slot_signal_kill_is_not_absence() {
5047        assert!(slot_occupied_from_probes(
5048            (None, ""),
5049            (Some(1), YKMAN_NO_CERT)
5050        ));
5051    }
5052
5053    /// The classification tests above all feed the probes synthetic
5054    /// output, so none of them can catch the failure that actually
5055    /// shipped: an argv naming a subcommand `ykman` does not have. This
5056    /// test runs the real binary and asserts each probe's subcommand is
5057    /// recognised — `ykman` exits 0 on `--help` for a command it has and
5058    /// 2 for one it does not, without touching a YubiKey.
5059    ///
5060    /// Skipped when `ykman` is not installed, so the suite stays
5061    /// hermetic; on any host that has it, a renamed or invented
5062    /// subcommand fails here instead of silently inverting the guard.
5063    #[test]
5064    fn ykman_probe_subcommands_exist_in_the_real_binary() {
5065        for probe in [PIV_KEY_PROBE, PIV_CERT_PROBE] {
5066            // Everything up to the slot placeholder is the subcommand path.
5067            let subcommand: Vec<&str> = probe
5068                .argv
5069                .iter()
5070                .copied()
5071                .take_while(|arg| *arg != "{slot}")
5072                .collect();
5073            let mut command = Command::new("ykman");
5074            let status = command
5075                .args(&subcommand)
5076                .arg("--help")
5077                .stdin(Stdio::null())
5078                .stdout(Stdio::null())
5079                .stderr(Stdio::null())
5080                .status();
5081            let Ok(status) = status else {
5082                eprintln!("ykman not installed; skipping subcommand existence check");
5083                return;
5084            };
5085            assert_eq!(
5086                status.code(),
5087                Some(0),
5088                "ykman does not recognise the subcommand `{}` used by the PIV \
5089                 slot probe",
5090                subcommand.join(" ")
5091            );
5092        }
5093    }
5094
5095    // ---- inherited-FD credential interface (#1561) ---------------------
5096
5097    /// Write `bytes` into a pipe and return the read end, emulating an
5098    /// inherited, non-seekable credential fd (systemd LoadCredentialEncrypted
5099    /// + podman --preserve-fds).
5100    fn fd_pipe(bytes: &[u8]) -> std::fs::File {
5101        let mut fds = [0_i32; 2];
5102        assert_eq!(unsafe { libc::pipe(fds.as_mut_ptr()) }, 0, "pipe failed");
5103        let mut writer = unsafe { std::fs::File::from_raw_fd(fds[1]) };
5104        writer.write_all(bytes).expect("write pipe");
5105        drop(writer); // closing the write end gives the reader a clean EOF
5106        unsafe { std::fs::File::from_raw_fd(fds[0]) }
5107    }
5108
5109    // TEST-ONLY static age key material for the FD-interface fixture. The
5110    // rust-builder merge-gate container has no `age-keygen` binary, so the
5111    // tests must not launch one; these keys protect only ephemeral tempdir
5112    // artifacts and must never be used for a real deployment.
5113    const TEST_ONLY_ROOT_IDENTITY: &str =
5114        "AGE-SECRET-KEY-18DUYV5CM8FZ2DPGXFFN0NPA5QZVW6L245K04YN74FGYUDJU2DVYQUL97GF\n";
5115    const TEST_ONLY_ROOT_RECIPIENT: &str =
5116        "age1lpty3rrqge6ql2qu3ppyx2xxvwdwau593v88ffsgjt0lgu5jayqqrzhgqx";
5117    const TEST_ONLY_BACKUP_RECIPIENT: &str =
5118        "age1tvwjdr4gpg97ys63y34m78n2cmh5yvvc40em3ute8ztwml6hvfgssl9jqv";
5119    const TEST_ONLY_SIGNER_IDENTITY: &str =
5120        "AGE-SECRET-KEY-14JDHVJAXQKXE9YV9EG3GN2ZAMR37CKJF4VJHZDZDDCRATE2EGZ7QRM86RV\n";
5121    const TEST_ONLY_SIGNER_RECIPIENT: &str =
5122        "age1w886v3ltxtmc4vls30227nlf72sxcdgag60gup9j50srw2jgx93spxpwkk";
5123
5124    struct MintFdFixture {
5125        // Holds the tempdir open for the fixture's lifetime.
5126        _dir: tempfile::TempDir,
5127        public_ca: PathBuf,
5128        authority_key: PathBuf,
5129        authority_log: PathBuf,
5130        authority_checkpoint: PathBuf,
5131        delegation: PathBuf,
5132        registry_public_key: PathBuf,
5133        delegated_key_bytes: Vec<u8>,
5134        signer_identity_bytes: Vec<u8>,
5135        registry_key_bytes: [u8; 32],
5136    }
5137
5138    /// Run the real path-form ceremony (mint-deployment-ca +
5139    /// delegate-registry-signer) into a tempdir, returning everything the
5140    /// FD-form mint needs. Requires the `age` binary (production mint shells
5141    /// out to it); callers skip when it is absent, matching the
5142    /// `trial_decrypt_*` convention.
5143    fn mint_fd_fixture() -> MintFdFixture {
5144        let dir = tempfile::tempdir().unwrap();
5145        let root_identity = dir.path().join("root.identity");
5146        std::fs::write(&root_identity, TEST_ONLY_ROOT_IDENTITY).unwrap();
5147
5148        let public_ca = dir.path().join("deployment-ca.hybrid");
5149        let authority_key = dir.path().join("deployment-ca.age");
5150        let authority_log = dir.path().join("deployment-authority.log.json");
5151        let authority_checkpoint = dir.path().join("deployment-authority.head.json");
5152        mint_deployment_ca(&MintDeploymentCaArgs {
5153            public_ca: public_ca.clone(),
5154            authority_key: authority_key.clone(),
5155            authority_log: authority_log.clone(),
5156            authority_checkpoint: authority_checkpoint.clone(),
5157            recipients: vec![
5158                TEST_ONLY_ROOT_RECIPIENT.to_owned(),
5159                TEST_ONLY_BACKUP_RECIPIENT.to_owned(),
5160            ],
5161            yubikey_recipients: vec![],
5162            kms_plugin_recipients: vec![],
5163            piv_slot: None,
5164            force: false,
5165        })
5166        .unwrap();
5167
5168        let delegated_key = dir.path().join("registry-delegated-signer.age");
5169        let delegation = dir.path().join("registry-signer.delegation.json");
5170        delegate_registry_signer(&DelegateRegistrySignerArgs {
5171            public_ca: public_ca.clone(),
5172            authority_log: authority_log.clone(),
5173            authority_checkpoint: authority_checkpoint.clone(),
5174            authority_key: authority_key.clone(),
5175            identities: vec![root_identity],
5176            yubikey_identities: vec![],
5177            software_recovery: false,
5178            signer_recipients: vec![TEST_ONLY_SIGNER_RECIPIENT.to_owned()],
5179            delegated_key: delegated_key.clone(),
5180            delegation: delegation.clone(),
5181            delegation_ttl_seconds: 2_592_000,
5182            force: false,
5183        })
5184        .unwrap();
5185
5186        let registry_key = SigningKey::generate(&mut rand::rngs::OsRng);
5187        let registry_public_key = dir.path().join("registry-public-key");
5188        std::fs::write(
5189            &registry_public_key,
5190            registry_key.verifying_key().as_bytes(),
5191        )
5192        .unwrap();
5193
5194        MintFdFixture {
5195            delegated_key_bytes: std::fs::read(&delegated_key).unwrap(),
5196            signer_identity_bytes: TEST_ONLY_SIGNER_IDENTITY.as_bytes().to_vec(),
5197            registry_key_bytes: registry_key.verifying_key().to_bytes(),
5198            _dir: dir,
5199            public_ca,
5200            authority_key,
5201            authority_log,
5202            authority_checkpoint,
5203            delegation,
5204            registry_public_key,
5205        }
5206    }
5207
5208    fn mint_fd_args(
5209        fixture: &MintFdFixture,
5210        signer_fd: RawFd,
5211        identity_fd: RawFd,
5212        out: &Path,
5213    ) -> MintRegistryJwtArgs {
5214        MintRegistryJwtArgs {
5215            public_ca: fixture.public_ca.clone(),
5216            authority_key: fixture.authority_key.clone(),
5217            identities: vec![],
5218            identity_fds: vec![identity_fd],
5219            yubikey_identities: vec![],
5220            software_recovery: false,
5221            via_delegated_signer: None,
5222            via_delegated_signer_fd: Some(signer_fd),
5223            delegation: Some(fixture.delegation.clone()),
5224            authority_log: fixture.authority_log.clone(),
5225            authority_checkpoint: fixture.authority_checkpoint.clone(),
5226            root: false,
5227            registry_public_key: fixture.registry_public_key.clone(),
5228            ttl_seconds: 3600,
5229            jwt: out.join("registry-service.jwt"),
5230            contract: out.join("deployment-trust.contract.json"),
5231            force: false,
5232        }
5233    }
5234
5235    fn enrollment_fd_args(
5236        fixture: &MintFdFixture,
5237        signer_fd: RawFd,
5238        identity_fd: RawFd,
5239        service_public_key: PathBuf,
5240        attestation: PathBuf,
5241    ) -> EnrollServiceKeyArgs {
5242        EnrollServiceKeyArgs {
5243            public_ca: fixture.public_ca.clone(),
5244            authority_log: fixture.authority_log.clone(),
5245            authority_checkpoint: fixture.authority_checkpoint.clone(),
5246            identities: vec![],
5247            identity_fds: vec![identity_fd],
5248            yubikey_identities: vec![],
5249            software_recovery: false,
5250            via_delegated_signer: None,
5251            via_delegated_signer_fd: Some(signer_fd),
5252            delegation: fixture.delegation.clone(),
5253            service: "discovery".to_owned(),
5254            service_public_key,
5255            ttl_seconds: 3_600,
5256            attestation,
5257            force: false,
5258        }
5259    }
5260
5261    #[test]
5262    fn mint_registry_jwt_via_inherited_fds_round_trips_through_production_verifier() {
5263        // Production mint shells out to `age`; skip where it is absent (the
5264        // rust-builder merge-gate container), matching the trial_decrypt_*
5265        // convention. The static TEST-ONLY key material above means
5266        // `age-keygen` is never needed.
5267        if !age_available() {
5268            eprintln!("skipping: age binary not on PATH");
5269            return;
5270        }
5271        let fixture = mint_fd_fixture();
5272        let out = tempfile::tempdir().unwrap();
5273        let signer = fd_pipe(&fixture.delegated_key_bytes);
5274        let identity = fd_pipe(&fixture.signer_identity_bytes);
5275        let args = mint_fd_args(
5276            &fixture,
5277            signer.as_raw_fd(),
5278            identity.as_raw_fd(),
5279            out.path(),
5280        );
5281        mint_registry_jwt(&args).expect("FD-form mint must succeed");
5282
5283        // The same production verifier the registry runs at boot must accept
5284        // the credential minted purely from inherited fds.
5285        let token = std::fs::read_to_string(out.path().join("registry-service.jwt")).unwrap();
5286        let verified = hyprstream_discovery::verify_deployment_artifacts_with_authority_log(
5287            &std::fs::read(&fixture.public_ca).unwrap(),
5288            &std::fs::read(&fixture.authority_log).unwrap(),
5289            &std::fs::read(&fixture.authority_checkpoint).unwrap(),
5290            &token,
5291        )
5292        .expect("production verifier must accept the FD-minted credential");
5293        assert_eq!(verified.registry_public_key, fixture.registry_key_bytes);
5294    }
5295
5296    #[test]
5297    fn enroll_service_key_via_inherited_fds_round_trips_through_production_verifier() {
5298        // The same real age seam as staging is used here: a non-seekable
5299        // signer credential and identity are consumed directly from inherited
5300        // FDs, never reopened through /proc/self/fd/N.
5301        if !age_available() {
5302            eprintln!("skipping: age binary not on PATH");
5303            return;
5304        }
5305        let fixture = mint_fd_fixture();
5306        let out = tempfile::tempdir().unwrap();
5307        let service_public_key = out.path().join("service-pubkey.hybrid");
5308        let service = test_authority(AuthorityPurpose::Root, None);
5309        std::fs::write(&service_public_key, service.public_bytes()).unwrap();
5310        let attestation = out.path().join("service-key-enrollment.json");
5311        let signer = fd_pipe(&fixture.delegated_key_bytes);
5312        let identity = fd_pipe(&fixture.signer_identity_bytes);
5313        let args = enrollment_fd_args(
5314            &fixture,
5315            signer.as_raw_fd(),
5316            identity.as_raw_fd(),
5317            service_public_key,
5318            attestation.clone(),
5319        );
5320
5321        enroll_service_key(&args).expect("FD-form enrollment must succeed");
5322
5323        let verified = hyprstream_discovery::verify_service_key_enrollment(
5324            &std::fs::read(&fixture.public_ca).unwrap(),
5325            &std::fs::read(&fixture.authority_log).unwrap(),
5326            &std::fs::read(&fixture.authority_checkpoint).unwrap(),
5327            &std::fs::read(&attestation).unwrap(),
5328        )
5329        .expect("production verifier must accept the FD-minted attestation");
5330        assert_eq!(verified.service, "discovery");
5331        assert_eq!(verified.hybrid_public_key, service.public_bytes());
5332    }
5333
5334    #[test]
5335    fn enroll_service_key_fd_flags_reject_incomplete_or_mixed_forms() {
5336        use clap::Subcommand as _;
5337        let parse = |extra: &[&str]| {
5338            TrustCommand::augment_subcommands(clap::Command::new("hyprstream"))
5339                .try_get_matches_from(
5340                    ["hyprstream", "enroll-service-key"]
5341                        .into_iter()
5342                        .chain(extra.iter().copied()),
5343                )
5344        };
5345        let required = [
5346            "--delegation",
5347            "d.json",
5348            "--service",
5349            "discovery",
5350            "--service-public-key",
5351            "service-pubkey.hybrid",
5352        ];
5353        // A signer input is mandatory; there is no implicit path fallback.
5354        assert!(parse(&[
5355            "--identity",
5356            "id",
5357            "--delegation",
5358            "d.json",
5359            "--service",
5360            "discovery",
5361            "--service-public-key",
5362            "service-pubkey.hybrid",
5363        ])
5364        .is_err());
5365        // Path and inherited-FD signer forms are exclusive.
5366        assert!(parse(&[
5367            "--via-delegated-signer",
5368            "signer.age",
5369            "--via-delegated-signer-fd",
5370            "10",
5371            "--identity",
5372            "id",
5373            "--delegation",
5374            "d.json",
5375            "--service",
5376            "discovery",
5377            "--service-public-key",
5378            "service-pubkey.hybrid",
5379        ])
5380        .is_err());
5381        // Path and inherited-FD identity forms are exclusive.
5382        assert!(parse(&[
5383            "--via-delegated-signer-fd",
5384            "10",
5385            "--identity",
5386            "id",
5387            "--identity-fd",
5388            "11",
5389            "--delegation",
5390            "d.json",
5391            "--service",
5392            "discovery",
5393            "--service-public-key",
5394            "service-pubkey.hybrid",
5395        ])
5396        .is_err());
5397        // The pure inherited-FD form parses and has no pathname credential.
5398        let mut fd_form = vec!["--via-delegated-signer-fd", "10", "--identity-fd", "11"];
5399        fd_form.extend(required);
5400        assert!(parse(&fd_form).is_ok());
5401        // The established path form remains accepted.
5402        assert!(parse(&[
5403            "--via-delegated-signer",
5404            "signer.age",
5405            "--identity",
5406            "id",
5407            "--delegation",
5408            "d.json",
5409            "--service",
5410            "discovery",
5411            "--service-public-key",
5412            "service-pubkey.hybrid",
5413        ])
5414        .is_ok());
5415    }
5416
5417    #[test]
5418    fn mint_registry_jwt_fd_flags_conflict_with_path_forms() {
5419        use clap::Subcommand as _;
5420        let parse = |extra: &[&str]| {
5421            TrustCommand::augment_subcommands(clap::Command::new("hyprstream"))
5422                .try_get_matches_from(
5423                    ["hyprstream", "mint-registry-jwt"]
5424                        .into_iter()
5425                        .chain(extra.iter().copied()),
5426                )
5427        };
5428        // Signer path + signer fd conflict.
5429        assert!(parse(&[
5430            "--via-delegated-signer",
5431            "k.age",
5432            "--via-delegated-signer-fd",
5433            "3",
5434            "--identity",
5435            "id",
5436        ])
5437        .is_err());
5438        // Identity path + identity fd conflict.
5439        assert!(parse(&[
5440            "--via-delegated-signer",
5441            "k.age",
5442            "--identity",
5443            "id",
5444            "--identity-fd",
5445            "4",
5446        ])
5447        .is_err());
5448        // --root + signer fd conflict.
5449        assert!(parse(&[
5450            "--root",
5451            "--via-delegated-signer-fd",
5452            "3",
5453            "--identity",
5454            "id"
5455        ])
5456        .is_err());
5457        // --root + signer path conflict (behavior carried over from main).
5458        assert!(parse(&[
5459            "--root",
5460            "--via-delegated-signer",
5461            "k.age",
5462            "--identity",
5463            "id",
5464            "--registry-public-key",
5465            "r",
5466        ])
5467        .is_err());
5468        // Exactly one signer source is required unless --root.
5469        assert!(parse(&["--identity", "id"]).is_err());
5470        // The --root bootstrap path parses WITHOUT any signer flag; on main
5471        // --via-delegated-signer was required_unless_present = "root", and
5472        // clap does not waive a required ArgGroup for a conflicting flag, so
5473        // this case pins the restored semantics against that regression.
5474        if let Err(error) = parse(&["--root", "--identity", "id", "--registry-public-key", "r"]) {
5475            panic!("--root bootstrap form must parse: {error}");
5476        }
5477        // The pure FD form parses.
5478        if let Err(error) = parse(&[
5479            "--via-delegated-signer-fd",
5480            "3",
5481            "--identity-fd",
5482            "4",
5483            "--delegation",
5484            "d.json",
5485            "--registry-public-key",
5486            "r",
5487        ]) {
5488            panic!("FD form must parse: {error}");
5489        }
5490        // The path forms are unchanged.
5491        assert!(parse(&[
5492            "--via-delegated-signer",
5493            "k.age",
5494            "--identity",
5495            "id",
5496            "--delegation",
5497            "d.json",
5498            "--registry-public-key",
5499            "r",
5500        ])
5501        .is_ok());
5502    }
5503
5504    #[test]
5505    fn mint_registry_jwt_fd_read_failures_fail_closed() {
5506        // Identity-fd read failures abort during identity resolution, before
5507        // any authority-log/delegation validation or `age` subprocess runs, so
5508        // these cases hold even where the age binary is absent (the
5509        // rust-builder merge-gate container).
5510        let stage = tempfile::tempdir().unwrap();
5511        let authority = test_authority(AuthorityPurpose::Root, None);
5512        let public_ca = stage.path().join("ca");
5513        std::fs::write(&public_ca, authority.public_bytes()).unwrap();
5514        let registry_public_key = stage.path().join("registry-pub");
5515        std::fs::write(
5516            &registry_public_key,
5517            SigningKey::generate(&mut rand::rngs::OsRng)
5518                .verifying_key()
5519                .as_bytes(),
5520        )
5521        .unwrap();
5522        let identity_fail_args = |identity_fd: RawFd, out: &Path| MintRegistryJwtArgs {
5523            public_ca: public_ca.clone(),
5524            authority_key: stage.path().join("unused.age"),
5525            identities: vec![],
5526            identity_fds: vec![identity_fd],
5527            yubikey_identities: vec![],
5528            software_recovery: false,
5529            via_delegated_signer: None,
5530            via_delegated_signer_fd: Some(0),
5531            delegation: Some(stage.path().join("unused.json")),
5532            authority_log: stage.path().join("unused.log"),
5533            authority_checkpoint: stage.path().join("unused.head"),
5534            root: false,
5535            registry_public_key: registry_public_key.clone(),
5536            ttl_seconds: 3600,
5537            jwt: out.join("registry-service.jwt"),
5538            contract: out.join("deployment-trust.contract.json"),
5539            force: false,
5540        };
5541        for (name, bytes) in [
5542            ("oversize", vec![b'x'; MAX_AGE_IDENTITY_BYTES + 1]),
5543            ("empty", Vec::new()),
5544        ] {
5545            let out = tempfile::tempdir().unwrap();
5546            let identity = fd_pipe(&bytes);
5547            let args = identity_fail_args(identity.as_raw_fd(), out.path());
5548            assert!(
5549                mint_registry_jwt(&args).is_err(),
5550                "{name} identity fd must fail closed"
5551            );
5552            assert!(
5553                !out.path().join("registry-service.jwt").exists(),
5554                "{name} identity fd left a partial JWT artifact"
5555            );
5556        }
5557
5558        // The remaining cases exercise signer-fd reads and age decryption,
5559        // which need the full ceremony fixture and therefore the age binary;
5560        // skip them where it is absent (trial_decrypt_* convention).
5561        if !age_available() {
5562            eprintln!("skipping age-dependent cases: age binary not on PATH");
5563            return;
5564        }
5565        let fixture = mint_fd_fixture();
5566        let run = |signer_fd: RawFd, identity_fd: RawFd| {
5567            let out = tempfile::tempdir().unwrap();
5568            let args = mint_fd_args(&fixture, signer_fd, identity_fd, out.path());
5569            let result = mint_registry_jwt(&args);
5570            (out, result)
5571        };
5572
5573        // An invalid descriptor must fail the mint, not fall back anywhere.
5574        let identity = fd_pipe(&fixture.signer_identity_bytes);
5575        let (out, result) = run(-1, identity.as_raw_fd());
5576        assert!(result.is_err(), "invalid signer fd must fail closed");
5577        assert!(!out.path().join("registry-service.jwt").exists());
5578
5579        // A write-only descriptor yields a read error, not an empty secret.
5580        let write_only = OpenOptions::new().write(true).open("/dev/null").unwrap();
5581        let identity = fd_pipe(&fixture.signer_identity_bytes);
5582        let (out, result) = run(write_only.as_raw_fd(), identity.as_raw_fd());
5583        assert!(result.is_err(), "unreadable signer fd must fail closed");
5584        assert!(!out.path().join("registry-service.jwt").exists());
5585
5586        // An over-cap identity stream is rejected before decryption.
5587        let signer = fd_pipe(&fixture.delegated_key_bytes);
5588        let oversize = fd_pipe(vec![b'x'; MAX_AGE_IDENTITY_BYTES + 1].as_slice());
5589        let (out, result) = run(signer.as_raw_fd(), oversize.as_raw_fd());
5590        assert!(result.is_err(), "oversize identity fd must fail closed");
5591        assert!(!out.path().join("registry-service.jwt").exists());
5592
5593        // An empty identity stream is rejected before decryption.
5594        let signer = fd_pipe(&fixture.delegated_key_bytes);
5595        let empty = fd_pipe(b"");
5596        let (out, result) = run(signer.as_raw_fd(), empty.as_raw_fd());
5597        assert!(result.is_err(), "empty identity fd must fail closed");
5598        assert!(!out.path().join("registry-service.jwt").exists());
5599
5600        // A truncated signer ciphertext (short read / EOF mid-stream) must not
5601        // mint a partial credential.
5602        let truncated =
5603            fd_pipe(&fixture.delegated_key_bytes[..fixture.delegated_key_bytes.len() / 2]);
5604        let identity = fd_pipe(&fixture.signer_identity_bytes);
5605        let (out, result) = run(truncated.as_raw_fd(), identity.as_raw_fd());
5606        assert!(result.is_err(), "truncated signer fd must fail closed");
5607        assert!(!out.path().join("registry-service.jwt").exists());
5608
5609        // Identity bytes that cannot open the ciphertext fail in age.
5610        let signer = fd_pipe(&fixture.delegated_key_bytes);
5611        let wrong = fd_pipe(b"# not an identity\n");
5612        let (out, result) = run(signer.as_raw_fd(), wrong.as_raw_fd());
5613        assert!(
5614            result.is_err(),
5615            "non-decrypting identity fd must fail closed"
5616        );
5617        assert!(!out.path().join("registry-service.jwt").exists());
5618    }
5619}