Skip to main content

hoike_sign/
orchestrate.rs

1//! Bundle-production orchestration shared by the CLI signer loop and the admin
2//! signing API.
3//!
4//! This module turns a `(Config, CaConfig, RevocationSource)` into signed,
5//! CMS-sealed bundle bytes — handling revocation snapshotting, anti-rollback
6//! epoch derivation, signing-key source dispatch (ECDSA / ML-DSA × file / demo /
7//! PKCS#11), seal materials, and responder-cert loading.
8//!
9//! It deliberately contains no interactive I/O: PKCS#11 PINs are resolved only
10//! from config or the environment, never a terminal prompt. The CLI keeps its
11//! own interactive PIN path for the one-shot `hoike sign` subcommand.
12
13use std::collections::HashMap;
14use std::path::PathBuf;
15
16use hoike_core::config::{CaConfig, Config};
17use sha2::Digest as _;
18use tracing::{info, warn};
19
20use crate::{CaIdentity, CrlSource, GenerationConfig, RevocationSource, SealKey};
21
22/// Producer ID stamped into combined-mode bundles.
23///
24/// This string is part of the anti-rollback high-water-mark key, so the
25/// background signer loop and the on-demand admin handler MUST use the same
26/// value or they will derive divergent epochs for the same scope.
27pub const COMBINED_PRODUCER_ID: &str = "hoike-combined";
28
29/// Map of CA label → persistent revocation source. Stateful sources (DogtagSync)
30/// retain their in-memory snapshot and sync cookie across signer passes and must
31/// be shared, not rebuilt, between the background loop and on-demand signing.
32pub type PersistentSources = HashMap<String, Box<dyn RevocationSource>>;
33
34/// Outcome of signing one CA scope.
35#[derive(Debug, Clone)]
36pub struct SignedScope {
37    pub label: String,
38    /// Serialized, CMS-sealed bundle bytes.
39    pub bytes: Vec<u8>,
40    pub entry_count: usize,
41    /// Epoch assigned to this generation (persisted high-water + 1).
42    pub epoch: u64,
43}
44
45/// Build the persistent revocation sources for a config. Only stateful sources
46/// (DogtagSync) are created here; stateless sources (CRL) are resolved fresh at
47/// signing time.
48#[allow(unused_mut)]
49#[allow(unused_variables)]
50// Without `dogtag-sync`, the match reduces to `_ => continue` (all arms diverge),
51// making the trailing insert unreachable. It IS reached when the feature is on.
52#[cfg_attr(not(feature = "dogtag-sync"), allow(unreachable_code))]
53pub fn create_persistent_sources(
54    config: &Config,
55) -> std::result::Result<PersistentSources, String> {
56    let mut sources = PersistentSources::new();
57    for ca_config in &config.ca {
58        let source_config = match &ca_config.source {
59            Some(s) => s,
60            None => continue,
61        };
62        let source: Box<dyn RevocationSource> = match source_config {
63            #[cfg(feature = "dogtag-sync")]
64            hoike_core::config::SourceConfig::DogtagSync {
65                ldap_url,
66                base_dn,
67                bind_dn,
68                bind_password,
69                bind_password_env,
70                cookie_path,
71                filter,
72                tls,
73                ca_cert,
74            } => {
75                let password =
76                    resolve_ldap_password(bind_password.as_deref(), bind_password_env.as_deref())?;
77                let cookie = cookie_path.clone().unwrap_or_else(|| {
78                    config
79                        .storage
80                        .state_db
81                        .join(format!("sync-{}.json", ca_config.label))
82                });
83                let sync_config = crate::DogtagSyncConfig {
84                    ldap_url: ldap_url.clone(),
85                    base_dn: base_dn.clone(),
86                    bind_dn: bind_dn.clone(),
87                    bind_password: password,
88                    cookie_path: cookie,
89                    filter: filter
90                        .clone()
91                        .unwrap_or_else(|| "(objectClass=certificateRecord)".into()),
92                    tls: tls.clone(),
93                    ca_cert: ca_cert.clone(),
94                };
95                Box::new(crate::DogtagSyncSource::new(sync_config))
96            }
97            // CRL and other stateless sources are created fresh each pass.
98            _ => continue,
99        };
100        sources.insert(ca_config.label.clone(), source);
101    }
102    Ok(sources)
103}
104
105/// Resolve the revocation source for a CA: prefer the shared persistent source,
106/// otherwise build a fresh stateless one (CRL). Returns an owned box for the
107/// fresh case so the caller can hold it alongside the borrowed persistent case.
108fn resolve_source<'a>(
109    ca_config: &CaConfig,
110    persistent_sources: &'a PersistentSources,
111    fresh_holder: &'a mut Option<Box<dyn RevocationSource>>,
112) -> std::result::Result<&'a dyn RevocationSource, String> {
113    if let Some(ps) = persistent_sources.get(&ca_config.label) {
114        return Ok(ps.as_ref());
115    }
116
117    let source_config = ca_config
118        .source
119        .as_ref()
120        .ok_or_else(|| format!("CA '{}': no revocation source configured", ca_config.label))?;
121
122    let fresh: Box<dyn RevocationSource> = match source_config {
123        hoike_core::config::SourceConfig::Crl { path, issuer_cert } => {
124            let crl_data = std::fs::read(path)
125                .map_err(|e| format!("failed to read CRL {}: {e}", path.display()))?;
126            let source = if crl_data.starts_with(b"-----BEGIN") {
127                let pem =
128                    String::from_utf8(crl_data).map_err(|e| format!("CRL not valid UTF-8: {e}"))?;
129                CrlSource::from_pem(&pem).map_err(|e| format!("CRL parse: {e}"))?
130            } else {
131                CrlSource::from_der(crl_data).map_err(|e| format!("CRL parse: {e}"))?
132            };
133            let issuer_path = issuer_cert.as_ref().ok_or_else(|| {
134                format!(
135                    "CA '{}': CRL source requires issuer_cert for authentication",
136                    ca_config.label
137                )
138            })?;
139            let issuer =
140                std::fs::read(issuer_path).map_err(|e| format!("read issuer certificate: {e}"))?;
141            Box::new(
142                source
143                    .with_issuer_certificate(&issuer)
144                    .map_err(|e| format!("issuer certificate: {e}"))?,
145            )
146        }
147        #[cfg(feature = "dogtag-sync")]
148        hoike_core::config::SourceConfig::DogtagSync { .. } => {
149            return Err(format!(
150                "CA '{}': DogtagSync source must be persistent but was not found",
151                ca_config.label
152            ));
153        }
154        #[cfg(not(feature = "dogtag-sync"))]
155        hoike_core::config::SourceConfig::DogtagSync { .. } => {
156            return Err("dogtag-sync requires the 'dogtag-sync' feature flag".into());
157        }
158    };
159    *fresh_holder = Some(fresh);
160    Ok(fresh_holder.as_ref().unwrap().as_ref())
161}
162
163/// Produce a signed bundle for one CA scope from an already-resolved revocation
164/// source. Pure with respect to the filesystem for the *bundle* (does not write
165/// the `.ahu`); it does read the state store to derive the epoch.
166pub fn sign_ca_scope(
167    config: &Config,
168    ca_config: &CaConfig,
169    source: &dyn RevocationSource,
170) -> std::result::Result<SignedScope, String> {
171    let ca = CaIdentity {
172        label: ca_config.label.clone(),
173        issuer_name_der: decode_issuer_name(ca_config)?,
174        issuer_key_bytes: decode_issuer_key(ca_config)?,
175    };
176
177    let snapshot = source
178        .snapshot(&ca)
179        .map_err(|e| format!("snapshot failed for {}: {e}", ca_config.label))?;
180
181    // Derive epoch from the persisted high-water mark — never from wall-clock
182    // time, which can step backward (NTP correction, VM restore) and permanently
183    // lock out mirrors.
184    let epoch = {
185        let state_db_path = config.storage.state_db.join("state.json");
186        let store = hoike_core::StateStore::open(&state_db_path)
187            .map_err(|e| format!("state store: {e}"))?;
188        let issuer_key_hash_hex = hex::encode(sha2::Sha256::digest(&ca.issuer_key_bytes));
189        store
190            .get_high_water(COMBINED_PRODUCER_ID, &issuer_key_hash_hex)
191            .unwrap_or(0)
192            .saturating_add(1)
193    };
194
195    let gen_config = GenerationConfig {
196        producer_id: COMBINED_PRODUCER_ID.into(),
197        epoch,
198        validity_secs: ca_config.validity_secs,
199        jitter_secs: ca_config.jitter_secs,
200        certid_compat: crate::CertIdCompat::parse(&ca_config.certid_compat)?,
201        completeness: match ca_config.completeness.as_str() {
202            "authoritative-complete" if source.is_authoritative_complete() => {
203                ahu::Completeness::AuthoritativeComplete
204            }
205            "authoritative-complete" => {
206                return Err(format!(
207                    "CA '{}': source cannot prove authoritative completeness; configure partial",
208                    ca_config.label
209                ));
210            }
211            "partial" => ahu::Completeness::Partial,
212            other => return Err(format!("unknown completeness: {other}")),
213        },
214        archive_cutoff_secs: ca_config.archive_cutoff_secs,
215        ..Default::default()
216    };
217
218    // Also protect on-demand generation against invalid live key/cert replacements.
219    if ca_config.nonce_policy == "live" {
220        crate::live::load_live_material(ca_config)?;
221    }
222    let responder_cert_der = load_responder_cert(ca_config)?;
223    let (seal_key, seal_cert_der) = load_seal_materials(ca_config)?;
224
225    let bundle_bytes = produce_scope_bundle(
226        ca_config,
227        &ca,
228        &snapshot,
229        &gen_config,
230        &seal_key,
231        &seal_cert_der,
232        responder_cert_der.as_deref(),
233    )?;
234
235    Ok(SignedScope {
236        label: ca_config.label.clone(),
237        entry_count: snapshot.entries.len(),
238        epoch,
239        bytes: bundle_bytes,
240    })
241}
242
243/// Snapshot a CA scope and return the set of currently-revoked serials, without
244/// signing or writing anything. Used by the signer loop's urgent-revocation
245/// detector to diff against the previously-known revoked set between scheduled
246/// passes. Reuses the shared persistent source so a syncrepl cookie is not reset.
247pub fn revoked_serials_for_scope(
248    ca_config: &CaConfig,
249    persistent_sources: &PersistentSources,
250) -> std::result::Result<std::collections::BTreeSet<crate::source::SerialBytes>, String> {
251    let ca = CaIdentity {
252        label: ca_config.label.clone(),
253        issuer_name_der: decode_issuer_name(ca_config)?,
254        issuer_key_bytes: decode_issuer_key(ca_config)?,
255    };
256    let mut fresh_holder: Option<Box<dyn RevocationSource>> = None;
257    let source = resolve_source(ca_config, persistent_sources, &mut fresh_holder)?;
258    let snapshot = source
259        .snapshot(&ca)
260        .map_err(|e| format!("snapshot failed for {}: {e}", ca_config.label))?;
261    Ok(snapshot
262        .entries
263        .into_iter()
264        .filter_map(|(serial, status)| {
265            matches!(status, crate::CertificateStatus::Revoked { .. }).then_some(serial)
266        })
267        .collect())
268}
269
270/// Sign one CA scope by label, resolving its source, and write the resulting
271/// `.ahu` to the configured bundle directory. Used by the on-demand admin API.
272pub fn sign_and_write_scope(
273    config: &Config,
274    persistent_sources: &PersistentSources,
275    ca_config: &CaConfig,
276) -> std::result::Result<SignedScope, String> {
277    let mut fresh_holder: Option<Box<dyn RevocationSource>> = None;
278    let source = resolve_source(ca_config, persistent_sources, &mut fresh_holder)?;
279    let signed = sign_ca_scope(config, ca_config, source)?;
280    let path = write_bundle(config, &signed.label, &signed.bytes)?;
281    info!(
282        ca = signed.label,
283        epoch = signed.epoch,
284        entries = signed.entry_count,
285        size = signed.bytes.len(),
286        path = %path.display(),
287        "bundle produced (CMS sealed)"
288    );
289    Ok(signed)
290}
291
292/// Sign every configured CA that has a revocation source, writing each `.ahu`.
293/// CAs without a source are skipped. Returns the list of signed scopes.
294pub fn sign_and_write_all(
295    config: &Config,
296    persistent_sources: &PersistentSources,
297) -> std::result::Result<Vec<SignedScope>, String> {
298    let mut out = Vec::new();
299    for ca_config in &config.ca {
300        if ca_config.source.is_none() {
301            continue;
302        }
303        out.push(sign_and_write_scope(config, persistent_sources, ca_config)?);
304    }
305    Ok(out)
306}
307
308/// Write bundle bytes to the configured destination for `label`, creating
309/// the directory if needed. Returns the written path. Signer and importer
310/// share the same `Config::bundle_destination` resolution and the same
311/// durable `write_atomic` publication primitive (design §S5).
312pub fn write_bundle(
313    config: &Config,
314    label: &str,
315    bytes: &[u8],
316) -> std::result::Result<PathBuf, String> {
317    let path = config
318        .bundle_destination(label)
319        .map_err(|e| e.to_string())?;
320    write_bundle_atomic(&path, bytes)?;
321    Ok(path)
322}
323
324/// Durable replacement: readers see either complete old or complete new
325/// bytes. Delegates to the consolidated `hoike-core` implementation; a
326/// directory-fsync failure after the rename surfaces as the typed
327/// `DurabilityUncertain` error text.
328pub fn write_bundle_atomic(
329    path: &std::path::Path,
330    bytes: &[u8],
331) -> std::result::Result<(), String> {
332    hoike_core::storage::write_atomic(path, bytes)
333        .map_err(|e| format!("publish {}: {e}", path.display()))
334}
335
336/// Dispatch bundle production over the CA's configured signing-key source and
337/// algorithm. This is the single place the ECDSA/ML-DSA × file/demo/PKCS#11
338/// matrix lives.
339#[allow(clippy::too_many_arguments)]
340fn produce_scope_bundle(
341    ca_config: &CaConfig,
342    ca: &CaIdentity,
343    snapshot: &crate::StatusSnapshot,
344    gen_config: &GenerationConfig,
345    seal_key: &SealKey,
346    seal_cert_der: &[u8],
347    responder_cert_der: Option<&[u8]>,
348) -> std::result::Result<Vec<u8>, String> {
349    let bundle_bytes = if ca_config.is_ml_dsa() {
350        match &ca_config.signing_key {
351            Some(hoike_core::config::SigningKeyConfig::File { path }) => {
352                let mut v =
353                    crate::load_ml_dsa_key(path).map_err(|e| format!("signing key: {e}"))?;
354                if v.algorithm_name() != ca_config.sig_alg {
355                    return Err(format!(
356                        "CA '{}': key is {} but sig_alg is {}",
357                        ca_config.label,
358                        v.algorithm_name(),
359                        ca_config.sig_alg
360                    ));
361                }
362                info!(ca = ca_config.label, key = %path.display(), alg = v.algorithm_name(), "using file-based ML-DSA signing key");
363                let sk = seal_key.clone();
364                let sc = seal_cert_der.to_vec();
365                v.sign_bundle(
366                    ca,
367                    snapshot,
368                    gen_config,
369                    move |m| crate::create_cms_seal(m, &sk, &sc),
370                    responder_cert_der,
371                )
372            }
373            Some(hoike_core::config::SigningKeyConfig::Demo) => {
374                warn!(ca = ca_config.label, "using demo ML-DSA key — NOT FOR PRODUCTION");
375                let mut v = crate::MlDsaSignerVariant::demo(&ca_config.sig_alg)
376                    .map_err(|e| format!("CA '{}': {e}", ca_config.label))?;
377                let sk = seal_key.clone();
378                let sc = seal_cert_der.to_vec();
379                v.sign_bundle(
380                    ca,
381                    snapshot,
382                    gen_config,
383                    move |m| crate::create_cms_seal(m, &sk, &sc),
384                    responder_cert_der,
385                )
386            }
387            #[cfg(feature = "pkcs11")]
388            Some(hoike_core::config::SigningKeyConfig::Pkcs11 { .. }) => {
389                let pkcs11_config = resolve_pkcs11_config(ca_config)?;
390                let (param_set, oid) = ml_dsa_pkcs11_params(&ca_config.sig_alg)?;
391                let inner = crate::Pkcs11MlDsaSigner::new(&pkcs11_config, param_set, oid)
392                    .map_err(|e| format!("PKCS#11 ML-DSA init: {e}"))?;
393                let mut bridge = crate::Pkcs11MlDsaSignerBridge::new(inner);
394                let sk = seal_key.clone();
395                let sc = seal_cert_der.to_vec();
396                crate::produce_bundle::<_, crate::Pkcs11MlDsaSignature>(
397                    ca,
398                    snapshot,
399                    gen_config,
400                    &mut bridge,
401                    move |m| {
402                        crate::create_cms_seal(m, &sk, &sc)
403                            .map_err(|e| crate::SignError::Seal(e.to_string()))
404                    },
405                    responder_cert_der,
406                )
407            }
408            #[cfg(not(feature = "pkcs11"))]
409            Some(hoike_core::config::SigningKeyConfig::Pkcs11 { .. }) => {
410                return Err(format!(
411                    "CA '{}' requires PKCS#11 but hoike was built without 'pkcs11' feature",
412                    ca_config.label
413                ));
414            }
415            None => {
416                return Err(format!("CA '{}': no signing_key configured", ca_config.label));
417            }
418        }
419    } else {
420        match &ca_config.signing_key {
421            Some(hoike_core::config::SigningKeyConfig::File { path }) => {
422                let mut signing_key = crate::EcdsaP256Signer::new(
423                    crate::load_ecdsa_p256_key(path).map_err(|e| format!("signing key: {e}"))?,
424                );
425                info!(ca = ca_config.label, key = %path.display(), "using file-based signing key");
426                // F07: prove the OCSP signing key is not the seal key before
427                // producing anything — the same key under different file
428                // names is still rejected.
429                crate::ensure_distinct_ecdsa_seal_key::<_, crate::EcdsaSignatureBytes>(
430                    &signing_key,
431                    seal_key,
432                )
433                .map_err(|e| format!("CA '{}': {e}", ca_config.label))?;
434                let sk = seal_key.clone();
435                let sc = seal_cert_der.to_vec();
436                crate::produce_bundle::<_, crate::EcdsaSignatureBytes>(
437                    ca,
438                    snapshot,
439                    gen_config,
440                    &mut signing_key,
441                    move |m| crate::create_cms_seal(m, &sk, &sc),
442                    responder_cert_der,
443                )
444            }
445            #[cfg(feature = "pkcs11")]
446            Some(hoike_core::config::SigningKeyConfig::Pkcs11 { .. }) => {
447                let pkcs11_config = resolve_pkcs11_config(ca_config)?;
448                let inner = crate::Pkcs11Signer::new(&pkcs11_config)
449                    .map_err(|e| format!("PKCS#11 init: {e}"))?;
450                let mut bridge = crate::Pkcs11SignerBridge::new(inner);
451                // F07: the same separation proof through the PKCS#11 bridge —
452                // without exporting the HSM private key or assuming public-key
453                // attributes are readable.
454                crate::ensure_distinct_ecdsa_seal_key::<_, crate::Pkcs11EcdsaSignature>(
455                    &bridge,
456                    seal_key,
457                )
458                .map_err(|e| format!("CA '{}': {e}", ca_config.label))?;
459                let sk = seal_key.clone();
460                let sc = seal_cert_der.to_vec();
461                crate::produce_bundle::<_, crate::Pkcs11EcdsaSignature>(
462                    ca,
463                    snapshot,
464                    gen_config,
465                    &mut bridge,
466                    move |m| {
467                        crate::create_cms_seal(m, &sk, &sc)
468                            .map_err(|e| crate::SignError::Seal(e.to_string()))
469                    },
470                    responder_cert_der,
471                )
472            }
473            #[cfg(not(feature = "pkcs11"))]
474            Some(hoike_core::config::SigningKeyConfig::Pkcs11 { .. }) => {
475                return Err(format!(
476                    "CA '{}' requires PKCS#11 but hoike was built without 'pkcs11' feature",
477                    ca_config.label
478                ));
479            }
480            Some(hoike_core::config::SigningKeyConfig::Demo) => {
481                warn!(ca = ca_config.label, "using demo signing key — NOT FOR PRODUCTION");
482                let mut signing_key =
483                    crate::EcdsaP256Signer::new(crate::demo_ecdsa_p256_key());
484                // F07: even the demo OCSP key must stay distinct from an
485                // explicitly configured seal key.
486                crate::ensure_distinct_ecdsa_seal_key::<_, crate::EcdsaSignatureBytes>(
487                    &signing_key,
488                    seal_key,
489                )
490                .map_err(|e| format!("CA '{}': {e}", ca_config.label))?;
491                let sk = seal_key.clone();
492                let sc = seal_cert_der.to_vec();
493                crate::produce_bundle::<_, crate::EcdsaSignatureBytes>(
494                    ca,
495                    snapshot,
496                    gen_config,
497                    &mut signing_key,
498                    move |m| crate::create_cms_seal(m, &sk, &sc),
499                    responder_cert_der,
500                )
501            }
502            None => {
503                return Err(format!("CA '{}': no signing_key configured", ca_config.label));
504            }
505        }
506    }
507    .map_err(|e| format!("bundle production failed for {}: {e}", ca_config.label))?;
508
509    Ok(bundle_bytes)
510}
511
512// ---------------------------------------------------------------------------
513// Config-derived material loading (moved from the CLI so both surfaces share it)
514// ---------------------------------------------------------------------------
515
516fn decode_b64_field(
517    b64: &Option<String>,
518    field_name: &str,
519    ca_label: &str,
520    fallback: &str,
521) -> std::result::Result<Vec<u8>, String> {
522    match b64 {
523        Some(val) => {
524            use base64::Engine;
525            base64::engine::general_purpose::STANDARD
526                .decode(val)
527                .map_err(|e| format!("CA '{}': invalid base64 in {}: {e}", ca_label, field_name))
528        }
529        None => Ok(fallback.as_bytes().to_vec()),
530    }
531}
532
533fn configured_issuer(ca: &CaConfig) -> std::result::Result<Option<x509_cert::Certificate>, String> {
534    if let Some(hoike_core::config::SourceConfig::Crl {
535        issuer_cert: Some(path),
536        ..
537    }) = &ca.source
538    {
539        let bytes = std::fs::read(path).map_err(|e| format!("read issuer certificate: {e}"))?;
540        return crate::rotation::parse_certificate(&bytes)
541            .map(Some)
542            .map_err(|e| e.to_string());
543    }
544    Ok(None)
545}
546
547/// Decode the issuer DN (DER) for a CA, falling back to a synthetic `CN=<label>`.
548pub fn decode_issuer_name(ca: &CaConfig) -> std::result::Result<Vec<u8>, String> {
549    if ca.issuer_name_der_b64.is_none() {
550        if let Some(cert) = configured_issuer(ca)? {
551            use der::Encode;
552            return cert
553                .tbs_certificate
554                .subject
555                .to_der()
556                .map_err(|e| e.to_string());
557        }
558    }
559    decode_b64_field(
560        &ca.issuer_name_der_b64,
561        "issuer_name_der_b64",
562        &ca.label,
563        &format!("CN={}", ca.label),
564    )
565}
566
567/// Decode the issuer public-key bytes for a CA, falling back to a synthetic key.
568pub fn decode_issuer_key(ca: &CaConfig) -> std::result::Result<Vec<u8>, String> {
569    if ca.issuer_key_bytes_b64.is_none() {
570        if let Some(cert) = configured_issuer(ca)? {
571            return cert
572                .tbs_certificate
573                .subject_public_key_info
574                .subject_public_key
575                .as_bytes()
576                .map(|b| b.to_vec())
577                .ok_or_else(|| "issuer public key has unused bits".into());
578        }
579    }
580    decode_b64_field(
581        &ca.issuer_key_bytes_b64,
582        "issuer_key_bytes_b64",
583        &ca.label,
584        &format!("{}-key", ca.label),
585    )
586}
587
588/// Resolve the LDAP bind password from config or environment (no interactive I/O).
589#[cfg(feature = "dogtag-sync")]
590pub fn resolve_ldap_password(
591    password: Option<&str>,
592    env_var: Option<&str>,
593) -> std::result::Result<String, String> {
594    if let Some(pw) = password {
595        return Ok(pw.to_string());
596    }
597    if let Some(var) = env_var {
598        return std::env::var(var).map_err(|_| {
599            format!(
600                "LDAP bind password env var '{var}' not set. \
601                 Set it or use bind_password in config."
602            )
603        });
604    }
605    Err("no LDAP bind password: set bind_password or bind_password_env in config".into())
606}
607
608/// Load and normalize a responder certificate to DER, if configured.
609pub fn load_responder_cert(ca: &CaConfig) -> std::result::Result<Option<Vec<u8>>, String> {
610    match &ca.responder_cert {
611        Some(path) => {
612            let data = std::fs::read(path)
613                .map_err(|e| format!("failed to read responder cert '{}': {e}", path.display()))?;
614            if data.starts_with(b"-----BEGIN") {
615                let pem_str = String::from_utf8(data)
616                    .map_err(|e| format!("responder cert PEM is not valid UTF-8: {e}"))?;
617                // Validate the PEM label — reject non-certificate files.
618                let first_line = pem_str.lines().next().unwrap_or("");
619                if !first_line.contains("CERTIFICATE") {
620                    return Err(format!(
621                        "responder cert '{}' has unexpected PEM label: {} — expected CERTIFICATE",
622                        path.display(),
623                        first_line.trim()
624                    ));
625                }
626                use base64::Engine;
627                let mut b64 = String::new();
628                for line in pem_str.lines() {
629                    if line.starts_with("-----") {
630                        continue;
631                    }
632                    b64.push_str(line.trim());
633                }
634                let der = base64::engine::general_purpose::STANDARD
635                    .decode(&b64)
636                    .map_err(|e| format!("responder cert PEM base64 decode: {e}"))?;
637                Ok(Some(der))
638            } else {
639                Ok(Some(data))
640            }
641        }
642        None => Ok(None),
643    }
644}
645
646/// Load the seal key and certificate for CMS bundle sealing.
647///
648/// F07: delegates the seal-material policy — complete persistent pair,
649/// half-pair error, demo-only distinct ephemeral fallback, and the F08 CMS
650/// pair preflight — to the shared `load_or_generate_seal_material` helper
651/// (the same decision the one-shot CLI sign path uses), prefixing this CA's
652/// label. Implicit OCSP-signing-key reuse and non-demo ephemeral fallback are
653/// removed. The OCSP/seal key-separation proof runs in the loaded-signer
654/// branches that consume this material.
655pub fn load_seal_materials(
656    ca_config: &CaConfig,
657) -> std::result::Result<(SealKey, Vec<u8>), String> {
658    let demo = matches!(
659        &ca_config.signing_key,
660        Some(hoike_core::config::SigningKeyConfig::Demo)
661    );
662    crate::load_or_generate_seal_material(
663        ca_config.seal_key.as_deref(),
664        ca_config.seal_cert.as_deref(),
665        demo,
666    )
667    .map_err(|e| format!("CA '{}': {e}", ca_config.label))
668}
669
670/// Resolve a PKCS#11 config from a CA's signing-key config. PIN resolution is
671/// non-interactive: `pin` → `pin_env` → error. (The CLI's one-shot `sign`
672/// command has its own interactive-prompt variant.)
673#[cfg(feature = "pkcs11")]
674pub fn resolve_pkcs11_config(
675    ca_config: &CaConfig,
676) -> std::result::Result<crate::Pkcs11Config, String> {
677    match &ca_config.signing_key {
678        Some(hoike_core::config::SigningKeyConfig::Pkcs11 {
679            module,
680            token_label,
681            slot_id,
682            pin,
683            pin_env,
684            key_label,
685            key_id,
686        }) => {
687            let resolved_pin = resolve_pkcs11_pin_noninteractive(&ca_config.label, pin, pin_env)?;
688            Ok(crate::Pkcs11Config {
689                module_path: module.clone(),
690                slot_id: *slot_id,
691                token_label: token_label.clone(),
692                pin: resolved_pin,
693                key_label: key_label.clone(),
694                key_id: key_id
695                    .as_ref()
696                    .map(|h| {
697                        hex::decode(h).map_err(|e| {
698                            format!(
699                                "CA '{}': invalid hex in key_id '{}': {e}",
700                                ca_config.label, h
701                            )
702                        })
703                    })
704                    .transpose()?,
705            })
706        }
707        _ => Err(format!(
708            "CA '{}': not a PKCS#11 signing key config",
709            ca_config.label
710        )),
711    }
712}
713
714/// Non-interactive PKCS#11 PIN resolution: config value, then environment.
715#[cfg(feature = "pkcs11")]
716fn resolve_pkcs11_pin_noninteractive(
717    ca_label: &str,
718    pin: &Option<String>,
719    pin_env: &Option<String>,
720) -> std::result::Result<String, String> {
721    if let Some(p) = pin {
722        warn!(
723            ca = ca_label,
724            "PKCS#11 PIN is in config file — use pin_env for production"
725        );
726        return Ok(p.clone());
727    }
728    if let Some(env_var) = pin_env {
729        return std::env::var(env_var).map_err(|_| {
730            format!(
731                "CA '{}': PKCS#11 pin_env '{}' is not set in environment",
732                ca_label, env_var
733            )
734        });
735    }
736    Err(format!(
737        "CA '{}': PKCS#11 PIN required — set pin_env (on-demand signing cannot prompt interactively)",
738        ca_label
739    ))
740}
741
742/// Map an ML-DSA sig-alg string to its PKCS#11 parameter set and OID.
743#[cfg(feature = "pkcs11")]
744pub fn ml_dsa_pkcs11_params(
745    sig_alg: &str,
746) -> std::result::Result<(cryptoki::object::MlDsaParameterSetType, &'static str), String> {
747    match sig_alg {
748        "ml-dsa-44" => Ok((
749            cryptoki::object::MlDsaParameterSetType::ML_DSA_44,
750            crate::ML_DSA_44_OID,
751        )),
752        "ml-dsa-65" => Ok((
753            cryptoki::object::MlDsaParameterSetType::ML_DSA_65,
754            crate::ML_DSA_65_OID,
755        )),
756        "ml-dsa-87" => Ok((
757            cryptoki::object::MlDsaParameterSetType::ML_DSA_87,
758            crate::ML_DSA_87_OID,
759        )),
760        other => Err(format!("unknown ML-DSA variant for PKCS#11: {other}")),
761    }
762}
763
764#[cfg(test)]
765mod publication_tests {
766    use super::*;
767
768    #[test]
769    fn configured_bundle_destination_is_respected_and_failure_preserves_old_file() {
770        let dir = tempfile::tempdir().unwrap();
771        let destination = dir.path().join("custom/active.ahu");
772        let config_path = dir.path().join("hoike.toml");
773        std::fs::write(
774            &config_path,
775            format!(
776                r#"
777[server]
778[storage]
779bundle_dir = "{}/default"
780[[ca]]
781label = "test"
782bundle_file = "{}"
783"#,
784                dir.path().display(),
785                destination.display()
786            ),
787        )
788        .unwrap();
789        let config = Config::from_file(&config_path).unwrap();
790        assert_eq!(write_bundle(&config, "test", b"old").unwrap(), destination);
791        write_bundle(&config, "test", b"complete replacement").unwrap();
792        assert_eq!(
793            std::fs::read(&destination).unwrap(),
794            b"complete replacement"
795        );
796        assert!(!config.storage.bundle_dir.join("test.ahu").exists());
797        // A rename onto a directory fails after the temporary file is written.
798        let blocked = dir.path().join("blocked");
799        std::fs::create_dir(&blocked).unwrap();
800        std::fs::write(blocked.join("previous"), b"old").unwrap();
801        assert!(write_bundle_atomic(&blocked, b"new").is_err());
802        assert_eq!(std::fs::read(blocked.join("previous")).unwrap(), b"old");
803        assert!(
804            !std::fs::read_dir(dir.path()).unwrap().any(|e| e
805                .unwrap()
806                .file_name()
807                .to_string_lossy()
808                .ends_with(".tmp"))
809        );
810    }
811}
812
813#[cfg(test)]
814mod urgent_tests {
815    use super::*;
816    use crate::source::{
817        CaIdentity, CertificateStatus, Epoch, RevocationSource, StatusChange, StatusSnapshot,
818    };
819
820    /// A revocation source with a fixed set of entries, for exercising the
821    /// urgent-revocation detector without a live directory or CRL.
822    struct MockSource(Vec<(Vec<u8>, CertificateStatus)>);
823    impl RevocationSource for MockSource {
824        fn snapshot(&self, _ca: &CaIdentity) -> crate::Result<StatusSnapshot> {
825            let now = crate::source::unix_now()?;
826            Ok(StatusSnapshot {
827                entries: self.0.iter().cloned().collect(),
828                this_update: now,
829                next_update: Some(now + 86400),
830                ..Default::default()
831            })
832        }
833        fn changes_since(
834            &self,
835            _ca: &CaIdentity,
836            _since: Epoch,
837        ) -> crate::Result<Vec<StatusChange>> {
838            Ok(vec![])
839        }
840        fn supports_streaming(&self) -> bool {
841            false
842        }
843        fn is_authoritative_complete(&self) -> bool {
844            false
845        }
846    }
847
848    fn scope_config(dir: &std::path::Path) -> Config {
849        let config_path = dir.join("hoike.toml");
850        std::fs::write(
851            &config_path,
852            format!(
853                r#"
854[server]
855[storage]
856bundle_dir = "{}/bundles"
857state_db = "{}/state"
858[[ca]]
859label = "test"
860issuer_name_der_b64 = "bmFtZQ=="
861issuer_key_bytes_b64 = "a2V5"
862
863[ca.signing_key]
864type = "demo"
865"#,
866                dir.display(),
867                dir.display()
868            ),
869        )
870        .unwrap();
871        Config::from_file(&config_path).unwrap()
872    }
873
874    #[test]
875    fn sign_ca_scope_requires_existing_state() {
876        // Epoch derivation reads persisted state; a missing state file must be
877        // an explicit error, never a silently fresh timeline at epoch 1.
878        let dir = tempfile::tempdir().unwrap();
879        let config = scope_config(dir.path());
880        let source = MockSource(vec![(vec![0x01], CertificateStatus::Good)]);
881        let err = sign_ca_scope(&config, &config.ca[0], &source).unwrap_err();
882        assert!(
883            err.contains("state"),
884            "error must identify the state store: {err}"
885        );
886        assert!(
887            !config.storage.state_db.join("state.json").exists(),
888            "signing must not create state implicitly"
889        );
890    }
891
892    #[test]
893    fn revoked_serials_for_scope_returns_only_revoked() {
894        // issuer_name_der_b64 = base64("name"), issuer_key_bytes_b64 = base64("key")
895        let dir = tempfile::tempdir().unwrap();
896        let toml = format!(
897            r#"
898[server]
899[storage]
900bundle_dir = "{}/bundles"
901[[ca]]
902label = "test"
903issuer_name_der_b64 = "bmFtZQ=="
904issuer_key_bytes_b64 = "a2V5"
905"#,
906            dir.path().display()
907        );
908        let config_path = dir.path().join("hoike.toml");
909        std::fs::write(&config_path, toml).unwrap();
910        let config = Config::from_file(&config_path).unwrap();
911
912        let source = MockSource(vec![
913            (vec![0x01], CertificateStatus::Good),
914            (
915                vec![0x02],
916                CertificateStatus::Revoked {
917                    revocation_time: 1_700_000_000,
918                    reason: None,
919                },
920            ),
921            (
922                vec![0x03],
923                CertificateStatus::Revoked {
924                    revocation_time: 1_700_000_100,
925                    reason: None,
926                },
927            ),
928        ]);
929        let mut sources = PersistentSources::new();
930        sources.insert("test".to_string(), Box::new(source));
931
932        let revoked = revoked_serials_for_scope(&config.ca[0], &sources).unwrap();
933        assert_eq!(revoked.len(), 2);
934        assert!(revoked.contains(&vec![0x02]));
935        assert!(revoked.contains(&vec![0x03]));
936        assert!(!revoked.contains(&vec![0x01]));
937    }
938}