1use 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
22pub const COMBINED_PRODUCER_ID: &str = "hoike-combined";
28
29pub type PersistentSources = HashMap<String, Box<dyn RevocationSource>>;
33
34#[derive(Debug, Clone)]
36pub struct SignedScope {
37 pub label: String,
38 pub bytes: Vec<u8>,
40 pub entry_count: usize,
41 pub epoch: u64,
43}
44
45#[allow(unused_mut)]
49#[allow(unused_variables)]
50#[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 _ => continue,
99 };
100 sources.insert(ca_config.label.clone(), source);
101 }
102 Ok(sources)
103}
104
105fn 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
163pub 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 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 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
243pub 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
270pub 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
292pub 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
308pub 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
324pub 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#[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 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 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 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
512fn 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
547pub 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
567pub 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#[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
608pub 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 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
646pub 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#[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#[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#[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 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 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 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 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}