Skip to main content

hoike/
main.rs

1use clap::Parser;
2use std::path::PathBuf;
3use std::str::FromStr;
4use std::sync::Arc;
5use tracing::{error, info, warn};
6
7#[derive(Parser)]
8#[command(
9    name = "hoike",
10    about = "hoike — OCSP responder for pre-signed ahu bundles"
11)]
12struct Cli {
13    #[command(subcommand)]
14    command: Commands,
15}
16
17#[derive(clap::Subcommand)]
18#[allow(clippy::large_enum_variant)]
19enum Commands {
20    /// Start the OCSP responder
21    Serve {
22        /// Config file path
23        #[arg(long, default_value = "hoike.toml")]
24        config: PathBuf,
25    },
26    /// Explicitly initialize a fresh state directory (refuses existing state)
27    InitState {
28        /// Config file path
29        #[arg(long, default_value = "hoike.toml")]
30        config: PathBuf,
31    },
32    /// Check configuration and bundle trust without installing or changing state
33    Check {
34        /// Config file path
35        #[arg(long, default_value = "hoike.toml")]
36        config: PathBuf,
37    },
38    /// Produce a signed ahu bundle from a revocation source
39    Sign {
40        /// CA label
41        #[arg(long)]
42        ca: String,
43        /// CRL file to ingest (DER or PEM)
44        #[arg(long)]
45        crl: PathBuf,
46        /// Output bundle path
47        #[arg(short, long, default_value = "output.ahu")]
48        output: PathBuf,
49        /// Issuer certificate (DER) for CertID computation
50        #[arg(long)]
51        issuer: Option<PathBuf>,
52        /// Epoch number for this generation
53        #[arg(long, default_value = "1")]
54        epoch: u64,
55        /// CertID compatibility mode
56        #[arg(long, default_value = "dual")]
57        certid_compat: String,
58        /// Include known-good serials from a file (one hex serial per line)
59        #[arg(long)]
60        good_serials: Option<PathBuf>,
61        /// Signing algorithm: ecdsa-p256 (default), ml-dsa-44, ml-dsa-65, ml-dsa-87
62        #[arg(long, default_value = "ecdsa-p256")]
63        sig_alg: String,
64        /// Base64-encoded DER issuer name (for correct CertID hashes)
65        #[arg(long)]
66        issuer_name_b64: Option<String>,
67        /// Base64-encoded issuer public key bytes (for correct CertID hashes)
68        #[arg(long)]
69        issuer_key_b64: Option<String>,
70        /// Path to PKCS#8 PEM or DER signing key file
71        #[arg(long, conflicts_with = "demo_key")]
72        signing_key: Option<PathBuf>,
73        /// Path to PKCS#8 PEM or DER P-256 seal key file (required with --seal-cert
74        /// for file/HSM production signing; must be distinct from the signing key)
75        #[arg(long)]
76        seal_key: Option<PathBuf>,
77        /// Path to PEM or DER seal certificate (required with --seal-key for
78        /// file/HSM production signing)
79        #[arg(long)]
80        seal_cert: Option<PathBuf>,
81        /// Produce a dual-algorithm bundle: --sig-alg is the classical algorithm,
82        /// --dual-alg is the post-quantum algorithm (e.g. ml-dsa-87)
83        #[arg(long)]
84        dual_alg: Option<String>,
85        /// Path to PKCS#8 PEM or DER PQ signing key file (for --dual-alg)
86        #[arg(long)]
87        pq_signing_key: Option<PathBuf>,
88        /// Use an ephemeral demo key (NOT FOR PRODUCTION)
89        #[arg(long)]
90        demo_key: bool,
91    },
92    /// Query a running OCSP responder with optional algorithm preference
93    Query {
94        /// Responder URL (e.g. http://localhost:2560)
95        #[arg(long)]
96        url: String,
97        /// Hex-encoded serial number
98        #[arg(long)]
99        serial: String,
100        /// Base64-encoded DER issuer name
101        #[arg(long)]
102        issuer_name_b64: String,
103        /// Base64-encoded issuer public key bytes
104        #[arg(long)]
105        issuer_key_b64: String,
106        /// Preferred signature algorithms (comma-separated, e.g. "ml-dsa-87,ecdsa-p256")
107        #[arg(long)]
108        prefer: Option<String>,
109    },
110    /// Install an authenticated bundle into a configured CA destination
111    /// (offline; enclave/air-gap deployments)
112    Import {
113        /// Path to the .ahu bundle to install
114        #[arg(long)]
115        bundle: PathBuf,
116        /// Configured CA label whose destination to install into
117        #[arg(long)]
118        ca: String,
119        /// Config file (to determine the CA destination and state directory)
120        #[arg(long, default_value = "hoike.toml")]
121        config: PathBuf,
122    },
123}
124
125fn main() {
126    let cli = Cli::parse();
127
128    tracing_subscriber::fmt()
129        .with_env_filter(
130            tracing_subscriber::EnvFilter::try_from_default_env()
131                .unwrap_or_else(|_| "info,tower_http=debug".parse().unwrap()),
132        )
133        .init();
134
135    match cli.command {
136        Commands::Serve { config } => {
137            let rt = tokio::runtime::Runtime::new().expect("failed to create tokio runtime");
138            rt.block_on(run_server(config));
139        }
140        Commands::InitState { config } => {
141            run_init_state(config);
142        }
143        Commands::Check { config } => {
144            run_check(config);
145        }
146        Commands::Sign {
147            ca,
148            crl,
149            output,
150            issuer,
151            epoch,
152            certid_compat,
153            good_serials,
154            sig_alg,
155            issuer_name_b64,
156            issuer_key_b64,
157            signing_key,
158            seal_key,
159            seal_cert,
160            dual_alg,
161            pq_signing_key,
162            demo_key,
163        } => {
164            run_sign(
165                ca,
166                crl,
167                output,
168                issuer,
169                epoch,
170                certid_compat,
171                good_serials,
172                sig_alg,
173                issuer_name_b64,
174                issuer_key_b64,
175                signing_key,
176                seal_key,
177                seal_cert,
178                dual_alg,
179                pq_signing_key,
180                demo_key,
181            );
182        }
183        Commands::Query {
184            url,
185            serial,
186            issuer_name_b64,
187            issuer_key_b64,
188            prefer,
189        } => {
190            run_query(url, serial, issuer_name_b64, issuer_key_b64, prefer);
191        }
192        Commands::Import { bundle, ca, config } => {
193            run_import(bundle, ca, config);
194        }
195    }
196}
197
198async fn run_server(config_path: PathBuf) {
199    let config = hoike_core::Config::from_file(&config_path).unwrap_or_else(|e| {
200        eprintln!("Failed to load config from {}: {e}", config_path.display());
201        std::process::exit(1);
202    });
203
204    if let Err(e) = config.validate_transport(cfg!(feature = "tls")) {
205        eprintln!("Configuration error: {e}");
206        std::process::exit(1);
207    }
208
209    // F04: hold the exclusive writer lock on the state directory for the
210    // entire lifetime of this server — listener, background signer loop, and
211    // admin on-demand writers all retain it through the responder.
212    let writer_guard = std::sync::Arc::new(
213        hoike_core::StateDirectoryLock::acquire(&config.storage.state_db).unwrap_or_else(|e| {
214            eprintln!(
215                "Failed to lock state directory {}: {e}",
216                config.storage.state_db.display()
217            );
218            std::process::exit(1);
219        }),
220    );
221
222    // Validate existing state before any preflight, signing, or source
223    // mutation. State is never initialized implicitly: a missing or incomplete
224    // state directory is an operator error, not a fresh timeline.
225    let state_file = config.storage.state_db.join("state.json");
226    if let Err(e) = hoike_core::StateStore::open(&state_file) {
227        eprintln!("State directory validation failed: {e}");
228        if state_file.exists() {
229            eprintln!(
230                "Recovery means restoring the state directory — marks and committed \
231                 snapshots together — from backup; it is never reset in place."
232            );
233        } else {
234            eprintln!(
235                "Run `hoike init-state --config {path}` once to initialize a new state \
236                 directory.",
237                path = config_path.display()
238            );
239        }
240        std::process::exit(1);
241    }
242
243    let listen = config.server.listen.clone();
244    let needs_signing = config.needs_signing();
245
246    // Recover expired delegated certificates before initial signing or live loading.
247    if needs_signing {
248        for ca in &config.ca {
249            if let Err(e) = prepare_signer_material(ca).await {
250                eprintln!("Signing material preflight failed for {}: {e}", ca.label);
251                std::process::exit(1);
252            }
253        }
254    }
255
256    // Create persistent revocation sources — stateful sources like DogtagSync
257    // must survive across signer loop iterations to retain their in-memory
258    // snapshot and sync cookie. Needed for both combined and signer modes.
259    let persistent_sources = if needs_signing {
260        Some(
261            hoike_sign::create_persistent_sources(&config).unwrap_or_else(|e| {
262                eprintln!("Failed to create revocation sources: {e}");
263                std::process::exit(1);
264            }),
265        )
266    } else {
267        None
268    };
269
270    // In signing modes, run an initial signing pass before loading bundles so
271    // there's something to serve immediately (combined) or a fresh generation
272    // on disk (signer).
273    if let Some(sources) = persistent_sources.as_ref() {
274        info!(
275            mode = config.server.mode,
276            "running initial bundle production"
277        );
278        if let Err(e) = hoike_sign::sign_and_write_all(&config, sources) {
279            eprintln!("Initial signer pass failed: {e}");
280            std::process::exit(1);
281        }
282    }
283
284    // Install the Prometheus recorder (no-op unless built with --features
285    // metrics) before the first bundle load so an initial-load failure is
286    // captured in `hoike_bundle_load_failures_total` too, not just later reloads.
287    if hoike_server::install_metrics() {
288        info!("Prometheus metrics recorder installed");
289    }
290
291    let state = hoike_core::ResponderState::load(config.clone(), writer_guard.clone())
292        .unwrap_or_else(|e| {
293            hoike_server::obs::record_bundle_load_failure(
294                "all",
295                hoike_server::obs::load_failure_reason(&e),
296            );
297            hoike_server::obs::audit!(
298                event = "bundle_load_failed",
299                trigger = "initial_load",
300                reason = hoike_server::obs::load_failure_reason(&e),
301                error = %e,
302                "initial bundle load failed"
303            );
304            eprintln!("Failed to initialize responder: {e}");
305            std::process::exit(1);
306        });
307
308    // F10: per-CA forwarding clients are validated here — an unreadable,
309    // empty, or malformed `forward_ca` bundle (or a root pinned to a
310    // non-HTTPS target) aborts startup instead of degrading the forward
311    // channel at request time.
312    let mut app_state = hoike_server::AppState::new(state, config.clone()).unwrap_or_else(|e| {
313        eprintln!("Failed to build per-CA forwarding clients: {e}");
314        std::process::exit(1);
315    });
316
317    // Attach the shared signing context (holds the persistent sources behind a
318    // mutex) so the admin API and the background loop serialize on one lock.
319    if let Some(sources) = persistent_sources {
320        let ctx = hoike_server::SignerContext {
321            sources: tokio::sync::Mutex::new(sources),
322        };
323        app_state = app_state.with_signer_context(ctx);
324    }
325
326    // A distinct signer is required for every live CA.
327    for ca in config.ca.iter().filter(|ca| ca.nonce_policy == "live") {
328        let live = load_live_signer(ca).unwrap_or_else(|e| {
329            eprintln!("Failed to load live signer for {}: {e}", ca.label);
330            std::process::exit(1);
331        });
332        app_state = app_state.with_live_signer_for(&ca.label, live);
333    }
334
335    // Start gossip BEFORE the signer loop so the loop can announce generations
336    // through the live node. The handle is kept (wrapped in `Arc`, attached to
337    // `AppState`) rather than dropped, so admin fleet endpoints and the signer
338    // path can reach membership, the generation table, and `announce_generation`.
339    if let Some(gossip_cfg) = &config.gossip {
340        if gossip_cfg.enabled {
341            let (msg_tx, mut msg_rx) =
342                tokio::sync::mpsc::channel::<hoike_gossip::GossipMessage>(256);
343
344            // Bridge the core TOML string to the explicit policy (already
345            // validated by Config::validate_for_mode; a mismatch here is still
346            // fatal rather than defaulted).
347            let auth_mode =
348                hoike_gossip::AuthMode::from_str(&gossip_cfg.auth_mode).unwrap_or_else(|e| {
349                    eprintln!("Invalid gossip configuration: {e}");
350                    std::process::exit(1);
351                });
352
353            let gc = hoike_gossip::GossipConfig {
354                enabled: true,
355                bind: gossip_cfg.bind.clone(),
356                seeds: gossip_cfg.seeds.clone(),
357                node_name: gossip_cfg.node_name.clone(),
358                auth_mode,
359                identity_key: gossip_cfg.identity_key.clone(),
360                peer_keys: gossip_cfg.peer_keys.clone(),
361                peer_identities: gossip_cfg.peer_identities.clone(),
362            };
363
364            // F09: an invalid enabled gossip configuration or unreadable key
365            // material is a fatal startup error — never a warning-and-continue
366            // that would silently run unauthenticated gossip. Partitioned or
367            // unreachable peers are NOT startup failures; they only degrade
368            // gossip, never OCSP serving.
369            let gossip_node = match hoike_gossip::GossipNode::start(gc, msg_tx).await {
370                Ok(node) => node,
371                Err(e) => {
372                    eprintln!("gossip startup failed: {e}");
373                    std::process::exit(1);
374                }
375            };
376            info!("gossip node started");
377            let gossip_node = std::sync::Arc::new(gossip_node);
378            app_state = app_state.with_gossip(gossip_node.clone());
379
380            // Consumer: fold received announcements into the generation
381            // table so the fleet view can attribute epochs to nodes and
382            // compute per-node staleness.
383            let consumer_node = gossip_node.clone();
384            tokio::spawn(async move {
385                while let Some(msg) = msg_rx.recv().await {
386                    match &msg {
387                        hoike_gossip::GossipMessage::GenerationAnnouncement {
388                            producer_id,
389                            epoch,
390                            origin_node,
391                            bundle_url,
392                            ..
393                        } => {
394                            info!(
395                                origin = %origin_node,
396                                producer = %producer_id,
397                                epoch,
398                                url = bundle_url.as_deref().unwrap_or("none"),
399                                "received generation announcement"
400                            );
401                            consumer_node.record_generation(&msg).await;
402                            // Bundle pull-on-announce is future work: fetch
403                            // from bundle_url, verify anti-rollback, then
404                            // swap into the router via responder.reload().
405                        }
406                        hoike_gossip::GossipMessage::UrgentRevocation {
407                            producer_id,
408                            epoch,
409                            origin_node,
410                            ..
411                        } => {
412                            info!(
413                                origin = %origin_node,
414                                producer = %producer_id,
415                                epoch,
416                                "received urgent revocation notice — would pull delta"
417                            );
418                        }
419                    }
420                }
421            });
422        }
423    }
424
425    // In signing modes, start the background signer loop. It shares the same
426    // `SignerContext` mutex as the admin API so on-demand and periodic signing
427    // never race on epoch/cookie/write. It also gets the gossip handle so each
428    // successful pass announces the new generation to the mesh.
429    if needs_signing {
430        if let Some(ctx) = app_state.signer.clone() {
431            let signer_state = app_state.clone();
432            let signer_config = config.clone();
433            let signer_gossip = app_state.gossip.clone();
434            tokio::spawn(async move {
435                run_signer_loop(signer_state, signer_config, ctx, signer_gossip).await;
436            });
437        }
438    } else {
439        // Serving-only modes (edge/enclave) never run the signer loop, but
440        // their bundle directory is still live — the signer publishes each
441        // new generation to it (shared transfer volume). Pull-on-announce
442        // over gossip is future work, so poll: hot-reload the router on an
443        // interval. `reload()` re-reads the bundle dir with anti-rollback
444        // checks and is a no-op-safe swap when nothing changed.
445        let edge_state = app_state.responder.clone();
446        tokio::spawn(async move {
447            let interval = std::env::var("HOIKE_RELOAD_INTERVAL_SECS")
448                .ok()
449                .and_then(|v| v.parse::<u64>().ok())
450                .filter(|v| *v > 0)
451                .unwrap_or(15);
452            loop {
453                tokio::time::sleep(std::time::Duration::from_secs(interval)).await;
454                if let Err(e) = edge_state.reload() {
455                    hoike_server::obs::record_bundle_load_failure(
456                        "all",
457                        hoike_server::obs::load_failure_reason(&e),
458                    );
459                    warn!(error = %e, "edge bundle reload failed; serving previous generation");
460                }
461            }
462        });
463    }
464
465    // The recorder was installed earlier (before the initial load). If
466    // configured, expose it on a dedicated private listener — never the public
467    // OCSP port. Optionally TLS-terminated (server.metrics_tls).
468    if let Some(metrics_listen) = config.server.metrics_listen.clone() {
469        let metrics_state = app_state.clone();
470        let metrics_tls = config.server.metrics_tls.clone();
471        tokio::spawn(async move {
472            let router = hoike_server::build_metrics_router(metrics_state);
473            serve_listener("metrics", &metrics_listen, router, metrics_tls).await;
474        });
475    }
476
477    // Dedicated admin/UI listener (NIAP PPCA FTP_TRP.1 trusted path). When
478    // `admin_listen` is set, the management surface moves off the OCSP port and
479    // TLS terminates here, leaving the OCSP data plane plaintext. When unset,
480    // admin/UI stay nested on the OCSP router (legacy single-port layout).
481    if let Some(admin_listen) = config.server.admin_listen.clone() {
482        let admin_state = app_state.clone();
483        let admin_tls = config.server.admin_tls.clone();
484        if admin_tls.is_none() {
485            warn!(
486                listen = %admin_listen,
487                "admin listener configured without admin_tls — management surface is PLAINTEXT"
488            );
489        }
490        tokio::spawn(async move {
491            let router = hoike_server::build_admin_router_standalone(admin_state);
492            serve_listener("admin", &admin_listen, router, admin_tls).await;
493        });
494    }
495
496    let app = hoike_server::build_router(app_state);
497
498    let listener = tokio::net::TcpListener::bind(&listen)
499        .await
500        .unwrap_or_else(|e| {
501            eprintln!("Failed to bind to {listen}: {e}");
502            std::process::exit(1);
503        });
504
505    info!(listen = %listen, mode = config.server.mode, "hoike OCSP responder starting");
506    axum::serve(listener, app).await.unwrap();
507}
508
509/// Serve an axum router on `addr`, using TLS when `tls` is `Some` and the binary
510/// was built with `--features tls`. Falls back to plaintext otherwise (warning
511/// if TLS was requested but unavailable). Used for the metrics and admin
512/// management listeners; the OCSP data plane is always plaintext.
513async fn serve_listener(
514    name: &str,
515    addr: &str,
516    router: axum::Router,
517    tls: Option<hoike_core::config::TlsConfig>,
518) {
519    #[cfg(feature = "tls")]
520    if let Some(tls) = tls.as_ref() {
521        info!(listen = %addr, listener = name, "TLS listener starting");
522        if let Err(e) = hoike_server::tls::serve_router_tls(addr, router, tls).await {
523            warn!(error = %e, listener = name, "TLS listener exited");
524        }
525        return;
526    }
527    #[cfg(not(feature = "tls"))]
528    if tls.is_some() {
529        warn!(
530            listener = name,
531            "TLS configured but binary built without --features tls — listener disabled"
532        );
533        return;
534    }
535
536    match tokio::net::TcpListener::bind(addr).await {
537        Ok(l) => {
538            info!(listen = %addr, listener = name, "listener starting");
539            if let Err(e) = axum::serve(l, router).await {
540                warn!(error = %e, listener = name, "listener exited");
541            }
542        }
543        Err(e) => {
544            warn!(error = %e, listen = %addr, listener = name, "failed to bind listener")
545        }
546    }
547}
548
549/// Renewal runs before startup and every generation; an invalid replacement
550/// must never reach bundle publication. Valid external renewals need no command.
551async fn prepare_signer_material(ca: &hoike_core::config::CaConfig) -> Result<(), String> {
552    if let Some(cert) = hoike_sign::orchestrate::load_responder_cert(ca)? {
553        let renew_before = ca
554            .key_rotation
555            .as_ref()
556            .map(|r| r.renew_before_days.saturating_mul(86400))
557            .unwrap_or(7 * 86400);
558        let status = hoike_sign::check_and_log_rotation(&ca.label, &cert, renew_before)
559            .map_err(|e| e.to_string())?;
560        if matches!(
561            status,
562            hoike_sign::RotationStatus::RenewSoon { .. } | hoike_sign::RotationStatus::Expired
563        ) {
564            if let Some(command) = ca
565                .key_rotation
566                .as_ref()
567                .and_then(|r| r.rotation_command.clone())
568            {
569                let label = ca.label.clone();
570                tokio::task::spawn_blocking(move || {
571                    hoike_sign::run_rotation_command(&label, &command)
572                })
573                .await
574                .map_err(|e| e.to_string())??;
575            }
576        }
577        // Re-read after rotation, including on restart with an expired certificate.
578        let replacement = hoike_sign::orchestrate::load_responder_cert(ca)?
579            .ok_or("responder certificate disappeared")?;
580        let parsed =
581            hoike_sign::rotation::parse_certificate(&replacement).map_err(|e| e.to_string())?;
582        let now = std::time::SystemTime::now()
583            .duration_since(std::time::UNIX_EPOCH)
584            .map_err(|e| e.to_string())?
585            .as_secs();
586        if now
587            < parsed
588                .tbs_certificate
589                .validity
590                .not_before
591                .to_unix_duration()
592                .as_secs()
593            || now
594                >= parsed
595                    .tbs_certificate
596                    .validity
597                    .not_after
598                    .to_unix_duration()
599                    .as_secs()
600        {
601            return Err("responder certificate is not currently valid after renewal check".into());
602        }
603    }
604    if ca.nonce_policy == "live" {
605        load_live_signer(ca)?;
606    }
607    Ok(())
608}
609
610/// Off-cycle urgent-revocation poll cadence (seconds). When any CA enables
611/// `urgent_revocation`, the loop wakes at `min(batch_interval, URGENT_POLL_SECS)`
612/// and, on the wakes between full passes, checks for newly-revoked serials so a
613/// fresh revocation does not wait a whole batch interval to propagate.
614const URGENT_POLL_SECS: u64 = 300;
615
616async fn run_signer_loop(
617    state: hoike_server::AppState,
618    config: hoike_core::Config,
619    ctx: Arc<hoike_server::SignerContext>,
620    gossip: Option<Arc<hoike_gossip::GossipNode>>,
621) {
622    let min_interval = config
623        .ca
624        .iter()
625        .map(|c| c.batch_interval)
626        .min()
627        .unwrap_or(3600);
628
629    let any_urgent = config
630        .ca
631        .iter()
632        .any(|c| c.urgent_revocation && c.source.is_some());
633    let poll_interval = if any_urgent {
634        min_interval.min(URGENT_POLL_SECS)
635    } else {
636        min_interval
637    };
638
639    info!(
640        interval_secs = min_interval,
641        poll_secs = poll_interval,
642        urgent = any_urgent,
643        mode = config.server.mode,
644        "signer loop starting"
645    );
646
647    // Seed the per-CA known-revoked sets so certificates already revoked at
648    // startup do not trigger an off-cycle pass on the first wake.
649    let mut known_revoked: std::collections::HashMap<String, std::collections::BTreeSet<Vec<u8>>> =
650        std::collections::HashMap::new();
651    if any_urgent {
652        let sources = ctx.sources.lock().await;
653        for ca in &config.ca {
654            if ca.urgent_revocation && ca.source.is_some() {
655                match hoike_sign::revoked_serials_for_scope(ca, &sources) {
656                    Ok(set) => {
657                        known_revoked.insert(ca.label.clone(), set);
658                    }
659                    Err(e) => {
660                        warn!(ca = ca.label, error = %e, "urgent-revocation seed snapshot failed")
661                    }
662                }
663            }
664        }
665    }
666
667    let mut elapsed_since_full = 0u64;
668
669    loop {
670        tokio::time::sleep(std::time::Duration::from_secs(poll_interval)).await;
671        elapsed_since_full = elapsed_since_full.saturating_add(poll_interval);
672        let do_full = elapsed_since_full >= min_interval;
673
674        // Off-cycle urgent-revocation check on the wakes between full passes.
675        // A full pass covers new revocations anyway, so it is skipped there.
676        if any_urgent && !do_full {
677            urgent_revocation_pass(&state, &config, &ctx, &gossip, &mut known_revoked).await;
678            continue;
679        }
680        if !do_full {
681            continue;
682        }
683        elapsed_since_full = 0;
684
685        // Serialize key rotation and generation against on-demand management.
686        let sources = ctx.sources.lock().await;
687        let mut material_ready = true;
688        for ca in &config.ca {
689            match prepare_signer_material(ca).await {
690                Ok(()) => {
691                    if let Err(e) = state.reload_live_signer(ca) {
692                        error!(ca = ca.label, error = %e, "live material reload failed");
693                        material_ready = false;
694                    }
695                }
696                Err(e) => {
697                    error!(ca = ca.label, error = %e, "signing material rejected; preserving active generation");
698                    material_ready = false;
699                }
700            }
701        }
702        if !material_ready {
703            continue;
704        }
705
706        info!("signer loop: starting production cycle");
707        let gen_start = std::time::Instant::now();
708        match hoike_sign::sign_and_write_all(&config, &sources) {
709            Ok(signed) => {
710                let gen_secs = gen_start.elapsed().as_secs_f64();
711                for s in &signed {
712                    hoike_server::obs::record_signer_generation(&s.label, gen_secs);
713                    hoike_server::obs::audit!(
714                        event = "signer_generation",
715                        ca = %s.label,
716                        trigger = "scheduled",
717                        epoch = s.epoch,
718                        entry_count = s.entry_count,
719                        "produced bundle on schedule"
720                    );
721                }
722                if let Err(e) = state.responder.reload() {
723                    hoike_server::obs::record_bundle_load_failure(
724                        "all",
725                        hoike_server::obs::load_failure_reason(&e),
726                    );
727                    hoike_server::obs::audit!(
728                        event = "bundle_load_failed",
729                        trigger = "scheduled_reload",
730                        reason = hoike_server::obs::load_failure_reason(&e),
731                        error = %e,
732                        "reload failed after scheduled production"
733                    );
734                    error!(error = %e, "signer loop: reload failed after production");
735                } else {
736                    info!(
737                        scopes = signed.len(),
738                        "signer loop: bundles produced and reloaded"
739                    );
740                    // Announce each new generation to the mesh (best-effort).
741                    if let Some(g) = gossip.as_ref() {
742                        for s in &signed {
743                            hoike_server::announce_bundle_scopes(g, &s.bytes).await;
744                        }
745                    }
746                }
747            }
748            Err(e) => {
749                hoike_server::obs::audit!(
750                    event = "signer_generation_failed",
751                    trigger = "scheduled",
752                    error = %e,
753                    "scheduled production failed"
754                );
755                error!(error = %e, "signer loop: production failed");
756            }
757        }
758
759        // Re-baseline the urgent-revocation sets against the state just produced,
760        // so the next off-cycle check only fires on revocations newer than this
761        // scheduled pass.
762        if any_urgent {
763            for ca in &config.ca {
764                if ca.urgent_revocation && ca.source.is_some() {
765                    if let Ok(set) = hoike_sign::revoked_serials_for_scope(ca, &sources) {
766                        known_revoked.insert(ca.label.clone(), set);
767                    }
768                }
769            }
770        }
771    }
772}
773
774/// One off-cycle urgent-revocation pass: for each opted-in CA, snapshot the
775/// source, diff against the last-known revoked set, and — if new revocations
776/// appeared — produce and reload an off-cycle bundle for just that scope, then
777/// announce it (generation + explicit urgent notice) over gossip.
778async fn urgent_revocation_pass(
779    state: &hoike_server::AppState,
780    config: &hoike_core::Config,
781    ctx: &Arc<hoike_server::SignerContext>,
782    gossip: &Option<Arc<hoike_gossip::GossipNode>>,
783    known_revoked: &mut std::collections::HashMap<String, std::collections::BTreeSet<Vec<u8>>>,
784) {
785    let sources = ctx.sources.lock().await;
786    for ca in &config.ca {
787        if !(ca.urgent_revocation && ca.source.is_some()) {
788            continue;
789        }
790        let current = match hoike_sign::revoked_serials_for_scope(ca, &sources) {
791            Ok(set) => set,
792            Err(e) => {
793                warn!(ca = ca.label, error = %e, "urgent-revocation snapshot failed");
794                continue;
795            }
796        };
797        let previous = known_revoked.entry(ca.label.clone()).or_default();
798        let new_count = current.difference(previous).count();
799        if new_count == 0 {
800            continue;
801        }
802
803        // Newly-revoked serials detected — produce an off-cycle bundle for this
804        // scope. Prepare and reload its signing material first, mirroring the
805        // scheduled path, so a bad key/cert preserves the active generation.
806        if let Err(e) = prepare_signer_material(ca).await {
807            error!(ca = ca.label, error = %e, "urgent: signing material rejected");
808            continue;
809        }
810        if let Err(e) = state.reload_live_signer(ca) {
811            error!(ca = ca.label, error = %e, "urgent: live material reload failed");
812            continue;
813        }
814
815        let gen_start = std::time::Instant::now();
816        match hoike_sign::sign_and_write_scope(config, &sources, ca) {
817            Ok(signed) => {
818                hoike_server::obs::record_signer_generation(
819                    &signed.label,
820                    gen_start.elapsed().as_secs_f64(),
821                );
822                hoike_server::obs::audit!(
823                    event = "signer_generation",
824                    ca = %signed.label,
825                    trigger = "urgent",
826                    epoch = signed.epoch,
827                    entry_count = signed.entry_count,
828                    new_revocations = new_count,
829                    "produced off-cycle bundle on new revocation"
830                );
831                // Commit the new baseline only after a successful production.
832                *previous = current;
833                if let Err(e) = state.responder.reload() {
834                    error!(ca = ca.label, error = %e, "urgent: reload failed after production");
835                } else if let Some(g) = gossip.as_ref() {
836                    hoike_server::announce_bundle_scopes(g, &signed.bytes).await;
837                    match hoike_sign::decode_issuer_key(ca) {
838                        Ok(key_bytes) => {
839                            use sha2::Digest as _;
840                            let ikh = sha2::Sha256::digest(&key_bytes).to_vec();
841                            if let Err(e) = g
842                                .announce_urgent_revocation(
843                                    hoike_sign::COMBINED_PRODUCER_ID.to_string(),
844                                    ikh,
845                                    signed.epoch,
846                                )
847                                .await
848                            {
849                                warn!(ca = ca.label, error = %e, "urgent: gossip broadcast failed");
850                            }
851                        }
852                        Err(e) => {
853                            warn!(ca = ca.label, error = %e, "urgent: issuer key hash unavailable")
854                        }
855                    }
856                }
857            }
858            Err(e) => {
859                hoike_server::obs::audit!(
860                    event = "signer_generation_failed",
861                    ca = %ca.label,
862                    trigger = "urgent",
863                    error = %e,
864                    "off-cycle production failed"
865                );
866                error!(ca = ca.label, error = %e, "urgent: production failed");
867            }
868        }
869    }
870}
871
872fn decode_b64_field(
873    b64: &Option<String>,
874    field_name: &str,
875    ca_label: &str,
876    fallback: &str,
877) -> std::result::Result<Vec<u8>, String> {
878    match b64 {
879        Some(val) => {
880            use base64::Engine;
881            base64::engine::general_purpose::STANDARD
882                .decode(val)
883                .map_err(|e| format!("CA '{}': invalid base64 in {}: {e}", ca_label, field_name))
884        }
885        None => Ok(fallback.as_bytes().to_vec()),
886    }
887}
888
889fn load_live_signer(
890    ca: &hoike_core::config::CaConfig,
891) -> std::result::Result<hoike_server::LiveSignerState, String> {
892    hoike_server::LiveSignerState::from_config(ca)
893}
894
895fn run_query(
896    url: String,
897    serial_hex: String,
898    issuer_name_b64: String,
899    issuer_key_b64: String,
900    prefer: Option<String>,
901) {
902    use base64::Engine;
903    use der::{Decode, Encode, asn1::OctetString};
904    use sha2::{Digest, Sha256};
905
906    let issuer_name_der = base64::engine::general_purpose::STANDARD
907        .decode(&issuer_name_b64)
908        .unwrap_or_else(|e| {
909            eprintln!("Invalid issuer_name_b64: {e}");
910            std::process::exit(1);
911        });
912    let issuer_key_bytes = base64::engine::general_purpose::STANDARD
913        .decode(&issuer_key_b64)
914        .unwrap_or_else(|e| {
915            eprintln!("Invalid issuer_key_b64: {e}");
916            std::process::exit(1);
917        });
918    let serial_bytes = hex::decode(&serial_hex).unwrap_or_else(|e| {
919        eprintln!("Invalid serial hex: {e}");
920        std::process::exit(1);
921    });
922
923    let sha256_oid = const_oid::ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.1");
924    let name_hash = Sha256::digest(&issuer_name_der);
925    let key_hash = Sha256::digest(&issuer_key_bytes);
926
927    let cert_id = x509_ocsp::CertId {
928        hash_algorithm: spki::AlgorithmIdentifierOwned {
929            oid: sha256_oid,
930            parameters: Some(der::asn1::Any::from(der::asn1::Null)),
931        },
932        issuer_name_hash: OctetString::new(name_hash.to_vec()).unwrap(),
933        issuer_key_hash: OctetString::new(key_hash.to_vec()).unwrap(),
934        serial_number: x509_cert::serial_number::SerialNumber::new(&serial_bytes).unwrap_or_else(
935            |e| {
936                eprintln!("Invalid serial: {e}");
937                std::process::exit(1);
938            },
939        ),
940    };
941
942    let request_item = x509_ocsp::Request {
943        req_cert: cert_id,
944        single_request_extensions: None,
945    };
946
947    let mut request_extensions = Vec::new();
948
949    if let Some(prefer_str) = &prefer {
950        let pref_ext_der = build_preferred_sig_algs_extension(prefer_str);
951        let pref_oid = const_oid::ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.48.1.8");
952        request_extensions.push(x509_cert::ext::Extension {
953            extn_id: pref_oid,
954            critical: false,
955            extn_value: OctetString::new(pref_ext_der).unwrap(),
956        });
957    }
958
959    let tbs = x509_ocsp::TbsRequest {
960        version: Default::default(),
961        requestor_name: None,
962        request_list: vec![request_item],
963        request_extensions: if request_extensions.is_empty() {
964            None
965        } else {
966            Some(request_extensions)
967        },
968    };
969    let ocsp_request = x509_ocsp::OcspRequest {
970        tbs_request: tbs,
971        optional_signature: None,
972    };
973
974    let request_der = ocsp_request.to_der().unwrap_or_else(|e| {
975        eprintln!("Failed to encode OcspRequest: {e}");
976        std::process::exit(1);
977    });
978
979    println!("Sending OCSP request to {url}");
980    println!("  Serial:    {serial_hex}");
981    println!("  Request:   {} bytes", request_der.len());
982    if let Some(p) = &prefer {
983        println!("  Prefer:    {p}");
984    }
985
986    let response = ureq::post(&url)
987        .header("Content-Type", "application/ocsp-request")
988        .send(&request_der);
989
990    match response {
991        Ok(resp) => {
992            let status = resp.status();
993            let body = resp.into_body().read_to_vec().unwrap_or_else(|e| {
994                eprintln!("Failed to read response body: {e}");
995                std::process::exit(1);
996            });
997
998            println!("\n── Response ──");
999            println!("  HTTP status: {status}");
1000            println!("  Body size:   {} bytes", body.len());
1001
1002            match x509_ocsp::OcspResponse::from_der(&body) {
1003                Ok(ocsp_resp) => {
1004                    println!("  OCSP status: {:?}", ocsp_resp.response_status);
1005                    if let Some(resp_bytes) = &ocsp_resp.response_bytes {
1006                        match x509_ocsp::BasicOcspResponse::from_der(resp_bytes.response.as_bytes())
1007                        {
1008                            Ok(basic) => {
1009                                let alg_oid = basic.signature_algorithm.oid.to_string();
1010                                let sig_len = basic.signature.raw_bytes().len();
1011                                let alg_name = match alg_oid.as_str() {
1012                                    "1.2.840.10045.4.3.2" => "ecdsa-p256-sha256",
1013                                    "2.16.840.1.101.3.4.3.17" => "ml-dsa-44",
1014                                    "2.16.840.1.101.3.4.3.18" => "ml-dsa-65",
1015                                    "2.16.840.1.101.3.4.3.19" => "ml-dsa-87",
1016                                    other => other,
1017                                };
1018                                println!("  Algorithm:   {alg_name}");
1019                                println!("  Signature:   {sig_len} bytes");
1020                                let resp_count = basic.tbs_response_data.responses.len();
1021                                println!("  Responses:   {resp_count}");
1022
1023                                // Print cert status for each single response
1024                                for (idx, single_resp) in
1025                                    basic.tbs_response_data.responses.iter().enumerate()
1026                                {
1027                                    print!("    [{idx}] ");
1028                                    match &single_resp.cert_status {
1029                                        x509_ocsp::CertStatus::Good(_) => println!("Status: GOOD"),
1030                                        x509_ocsp::CertStatus::Revoked(info) => {
1031                                            println!("Status: REVOKED");
1032                                            if let Some(reason) = &info.revocation_reason {
1033                                                println!("        Reason: {:?}", reason);
1034                                            }
1035                                        }
1036                                        x509_ocsp::CertStatus::Unknown(_) => {
1037                                            println!("Status: UNKNOWN")
1038                                        }
1039                                    }
1040                                }
1041                            }
1042                            Err(e) => {
1043                                eprintln!("  Failed to parse BasicOcspResponse: {e}");
1044                            }
1045                        }
1046                    }
1047                }
1048                Err(e) => {
1049                    eprintln!("  Failed to parse OcspResponse: {e}");
1050                    eprintln!("  Raw (hex): {}", hex::encode(&body));
1051                }
1052            }
1053        }
1054        Err(e) => {
1055            eprintln!("HTTP request failed: {e}");
1056            std::process::exit(1);
1057        }
1058    }
1059}
1060
1061/// Build the DER-encoded PreferredSignatureAlgorithms extension value.
1062///
1063/// Uses the same `#[derive(der::Sequence)]` struct used for parsing in
1064/// hoike-core, ensuring encode/decode symmetry. RFC 6960 §4.4.7.1.
1065fn build_preferred_sig_algs_extension(prefer_str: &str) -> Vec<u8> {
1066    use der::Encode;
1067
1068    #[derive(der::Sequence)]
1069    struct PreferredSignatureAlgorithm {
1070        sig_identifier: spki::AlgorithmIdentifierOwned,
1071    }
1072
1073    let alg_ids: Vec<PreferredSignatureAlgorithm> = prefer_str
1074        .split(',')
1075        .map(|alg| {
1076            let (oid_str, params) = match alg.trim() {
1077                // ECDSA-with-SHA256 requires parameters = NULL per RFC 5754 §3.2
1078                "ecdsa-p256" => (
1079                    "1.2.840.10045.4.3.2",
1080                    Some(der::asn1::Any::from(der::asn1::Null)),
1081                ),
1082                // ML-DSA algorithms: parameters absent per RFC 9881 §9
1083                "ml-dsa-44" => ("2.16.840.1.101.3.4.3.17", None),
1084                "ml-dsa-65" => ("2.16.840.1.101.3.4.3.18", None),
1085                "ml-dsa-87" => ("2.16.840.1.101.3.4.3.19", None),
1086                other => {
1087                    eprintln!("Unknown algorithm for --prefer: {other}");
1088                    std::process::exit(1);
1089                }
1090            };
1091            PreferredSignatureAlgorithm {
1092                sig_identifier: spki::AlgorithmIdentifierOwned {
1093                    oid: const_oid::ObjectIdentifier::new_unwrap(oid_str),
1094                    parameters: params,
1095                },
1096            }
1097        })
1098        .collect();
1099
1100    alg_ids.to_der().unwrap_or_else(|e| {
1101        eprintln!("Failed to encode PreferredSignatureAlgorithms: {e}");
1102        std::process::exit(1);
1103    })
1104}
1105
1106/// Offline, recoverable authenticated installation (design §S5, audit
1107/// remediation F05).
1108///
1109/// The source is read exactly once; everything published comes from those
1110/// checked bytes. The writer guard is acquired (and validated by
1111/// installation) so a running server — which holds the same exclusive lock —
1112/// makes this fail promptly. There is no `--force` escape hatch and no
1113/// SIGHUP suggestion: completion instructs the operator to start the server.
1114fn run_import(bundle_path: PathBuf, ca_label: String, config_path: PathBuf) {
1115    let config = match hoike_core::Config::from_file(&config_path) {
1116        Ok(c) => c,
1117        Err(e) => {
1118            eprintln!("Failed to load config from {}: {e}", config_path.display());
1119            std::process::exit(1);
1120        }
1121    };
1122
1123    println!("Loading bundle: {}", bundle_path.display());
1124    let bytes = match std::fs::read(&bundle_path) {
1125        Ok(b) => b,
1126        Err(e) => {
1127            eprintln!("Failed to read bundle {}: {e}", bundle_path.display());
1128            std::process::exit(1);
1129        }
1130    };
1131
1132    // Offline operation: hold the exclusive writer lock on the state
1133    // directory for the full lifetime of the installation. A running server
1134    // holds the same lock, so import fails promptly instead of racing it.
1135    let guard = match hoike_core::StateDirectoryLock::acquire(&config.storage.state_db) {
1136        Ok(guard) => guard,
1137        Err(e) => {
1138            eprintln!("  Writer lock:  FAIL — {e}");
1139            eprintln!("  Import is offline: stop the writer process holding the state directory.");
1140            std::process::exit(1);
1141        }
1142    };
1143
1144    println!("Authenticating and installing for CA \'{ca_label}\'...");
1145    match hoike_core::install_bundle(&config, &ca_label, &bytes, &guard) {
1146        Ok(result) => {
1147            if let Ok(bundle) = ahu::Bundle::from_bytes(&bytes) {
1148                println!("  Producer:  {}", bundle.manifest.producer_id);
1149                println!("  Entries:   {}", bundle.manifest.entry_count);
1150                for (i, scope) in bundle.manifest.ca_scopes.iter().enumerate() {
1151                    println!("    [{i}] epoch={}", scope.epoch);
1152                }
1153            }
1154            println!("\n  Installed → {}", result.destination.display());
1155            if let Some(warning) = &result.publication_warning {
1156                eprintln!("\n  WARNING: {warning}");
1157            }
1158            println!(
1159                "\n  To serve: hoike serve --config {}",
1160                config_path.display()
1161            );
1162            println!("  Import is offline by design; start the server to serve this generation.");
1163        }
1164        Err(e) => {
1165            eprintln!("Import failed: {e}");
1166            std::process::exit(1);
1167        }
1168    }
1169}
1170
1171/// Explicitly initialize a fresh state directory (F04). Initialization is the
1172/// operator's acknowledgment that the directory is new: an existing state file
1173/// or any recovery material in the directory is refused. There is no `--force`
1174/// reset; recovery means restoring marks and snapshots together.
1175fn run_init_state(config_path: PathBuf) {
1176    let config = hoike_core::Config::from_file(&config_path).unwrap_or_else(|e| {
1177        eprintln!("Failed to load config from {}: {e}", config_path.display());
1178        std::process::exit(1);
1179    });
1180
1181    // Hold the writer lock while initializing so a concurrent writer cannot
1182    // race the emptiness check.
1183    let _guard =
1184        hoike_core::StateDirectoryLock::acquire(&config.storage.state_db).unwrap_or_else(|e| {
1185            eprintln!("Failed to lock state directory: {e}");
1186            std::process::exit(1);
1187        });
1188
1189    let state_path = config.storage.state_db.join("state.json");
1190    match hoike_core::StateStore::initialize(&state_path) {
1191        Ok(_store) => {
1192            println!(
1193                "Initialized empty state directory: {}",
1194                config.storage.state_db.display()
1195            );
1196            println!("  State file: {}", state_path.display());
1197            println!(
1198                "  Existing state is never reset; to recover, restore marks and snapshots together."
1199            );
1200        }
1201        Err(e) => {
1202            eprintln!("Failed to initialize state: {e}");
1203            std::process::exit(1);
1204        }
1205    }
1206}
1207
1208fn run_check(config_path: PathBuf) {
1209    let config = match hoike_core::Config::from_file(&config_path) {
1210        Ok(c) => {
1211            println!("  Config:    OK ({})", config_path.display());
1212            c
1213        }
1214        Err(e) => {
1215            eprintln!("  Config:    FAIL — {e}");
1216            std::process::exit(1);
1217        }
1218    };
1219
1220    println!("  Mode:      {}", config.server.mode);
1221    println!("  Listen:    {}", config.server.listen);
1222    println!("  Bundle:    {}", config.storage.bundle_dir.display());
1223
1224    if let Err(e) = config.validate_transport(cfg!(feature = "tls")) {
1225        eprintln!("  Mode:      FAIL — {e}");
1226        std::process::exit(1);
1227    }
1228
1229    // Check responder certificate expiry for each CA
1230    for ca in &config.ca {
1231        if let Some(cert_path) = &ca.responder_cert {
1232            match std::fs::read(cert_path) {
1233                Ok(cert_der) => match hoike_sign::format_cert_info(&cert_der) {
1234                    Ok(info) => {
1235                        println!("\n  ── Responder Cert ({}) ──", ca.label);
1236                        println!("    Subject:  {}", info.subject);
1237                        println!("    Issuer:   {}", info.issuer);
1238                        println!("    Days remaining: {}", info.days_remaining);
1239                        println!(
1240                            "    OCSP Signing EKU: {}",
1241                            if info.has_ocsp_signing_eku {
1242                                "yes"
1243                            } else {
1244                                "NOT FOUND — clients may reject"
1245                            }
1246                        );
1247                        if info.is_expired {
1248                            eprintln!("    STATUS: EXPIRED");
1249                        } else if info.days_remaining <= 30 {
1250                            eprintln!("    WARNING: expires in {} days", info.days_remaining);
1251                        } else {
1252                            println!("    Status:   OK");
1253                        }
1254                    }
1255                    Err(e) => {
1256                        eprintln!("    Cert parse: FAIL — {e}");
1257                    }
1258                },
1259                Err(e) => {
1260                    eprintln!("    Cert read ({})): FAIL — {e}", cert_path.display());
1261                }
1262            }
1263        }
1264    }
1265
1266    // ── Transport / Trusted Channels (NIAP PPCA v2.1) ──
1267    // Surface cleartext management and inter-component channels. The OCSP data
1268    // plane on `server.listen` is intentionally plaintext (responses are
1269    // CMS/signature-authenticated) and is not flagged here.
1270    check_trusted_channels(&config);
1271
1272    // Resolve bundle selection before checking bundles so configuration and
1273    // selection errors (unscoped legacy config, duplicate destinations, an
1274    // empty bundle directory, invalid nonce policy) are labeled as config
1275    // failures rather than masquerading as bundle verification failures.
1276    let bundle_paths = match hoike_core::router::configured_bundle_paths(&config) {
1277        Ok(paths) => paths,
1278        Err(e) => {
1279            eprintln!("  Bundle selection: FAIL — {e}");
1280            std::process::exit(1);
1281        }
1282    };
1283
1284    if let Err(e) = check_bundles(&config, &bundle_paths) {
1285        eprintln!("  Bundle:    FAIL — {e}");
1286        std::process::exit(1);
1287    }
1288}
1289
1290fn check_bundles(
1291    config: &hoike_core::Config,
1292    paths: &[std::path::PathBuf],
1293) -> hoike_core::error::Result<()> {
1294    use hoike_core::admission::{AdmissionTrust, admit_bundle};
1295    use std::collections::HashSet;
1296
1297    let now = std::time::SystemTime::now()
1298        .duration_since(std::time::UNIX_EPOCH)
1299        .map_err(|e| hoike_core::CoreError::Config(e.to_string()))?
1300        .as_secs();
1301    let mut checked = HashSet::new();
1302    let mut scopes = HashSet::new();
1303    let mut entries = 0;
1304    let mut demo = false;
1305    for path in paths {
1306        if !checked.insert(path.canonicalize().unwrap_or_else(|_| path.clone())) {
1307            continue;
1308        }
1309        let bundle = ahu::Bundle::from_file(path)?;
1310        let trust = admit_bundle(&bundle, &config.storage, now)?;
1311        println!("\n  Bundle:    {}", path.display());
1312        match trust {
1313            AdmissionTrust::Authenticated { signer_sha256 } => {
1314                println!("    Seal: authenticated (signer SHA-256: {signer_sha256})");
1315            }
1316            AdmissionTrust::UnauthenticatedDemo => {
1317                println!("    Unauthenticated demo admission; authenticity not checked.");
1318                demo = true;
1319            }
1320        }
1321        entries += bundle.manifest.entry_count;
1322        for scope in &bundle.manifest.ca_scopes {
1323            scopes.insert((
1324                scope.issuer_name_hash.clone(),
1325                scope.issuer_key_hash.clone(),
1326            ));
1327            println!(
1328                "    Scope: {} epoch={} completeness={:?}",
1329                hex::encode(&scope.issuer_key_hash),
1330                scope.epoch,
1331                scope.completeness,
1332            );
1333        }
1334    }
1335    println!("\n  Bundles:   {}", checked.len());
1336    println!("  Scopes:    {}", scopes.len());
1337    println!("  Entries:   {entries}");
1338    if demo {
1339        println!("\n  Read-only demo checks passed; bundle authenticity not checked.");
1340    } else {
1341        println!("\n  Read-only configuration and bundle authentication checks passed.");
1342    }
1343    println!("  Installation eligibility not checked.");
1344    Ok(())
1345}
1346
1347/// Validate transport-security posture for the management and inter-component
1348/// channels (NIAP PPCA FTP_TRP.1 / FTP_ITC.1). Warnings are advisory; a
1349/// cleartext `forward_to` without the explicit `forward_insecure` escape hatch
1350/// is a hard failure (exit 1), matching how other `hoike check` gates behave.
1351fn check_trusted_channels(config: &hoike_core::Config) {
1352    println!("\n  ── Transport / Trusted Channels (NIAP PPCA) ──");
1353    let mut hard_fail = false;
1354
1355    // Admin trusted path (FTP_TRP.1).
1356    let has_operators = config
1357        .server
1358        .admin
1359        .as_ref()
1360        .is_some_and(|a| !a.operators.is_empty());
1361    match (&config.server.admin_listen, &config.server.admin_tls) {
1362        (None, _) if has_operators => {
1363            eprintln!(
1364                "    WARNING: admin API rides the OCSP port (no admin_listen) — operator \
1365                 credentials and session cookies cross in cleartext. Set server.admin_listen \
1366                 + server.admin_tls for a trusted path (FTP_TRP.1)."
1367            );
1368        }
1369        (Some(addr), None) => {
1370            eprintln!(
1371                "    WARNING: admin_listen ({addr}) has no admin_tls — the management channel \
1372                 is plaintext. Configure server.admin_tls (FCS_TLSS_EXT.1)."
1373            );
1374        }
1375        (Some(addr), Some(_)) => {
1376            println!("    Admin:     TLS on {addr} (FCS_TLSS_EXT.1)");
1377        }
1378        _ => {}
1379    }
1380
1381    // Metrics channel.
1382    match (&config.server.metrics_listen, &config.server.metrics_tls) {
1383        (Some(addr), None) => {
1384            eprintln!(
1385                "    WARNING: metrics_listen ({addr}) has no metrics_tls — Prometheus scrape \
1386                 traffic is plaintext. Bind privately or set server.metrics_tls."
1387            );
1388        }
1389        (Some(addr), Some(_)) => {
1390            println!("    Metrics:   TLS on {addr}");
1391        }
1392        _ => {}
1393    }
1394
1395    // Forward proxy channel (FTP_ITC.1). The clients are built exactly as
1396    // `serve` builds them, so a broken `forward_ca` fails `hoike check` the
1397    // same way startup would — without opening a listener or sending a
1398    // request.
1399    let forward_clients = match hoike_server::build_forward_clients(config) {
1400        Ok(clients) => clients,
1401        Err(e) => {
1402            eprintln!("    FAIL: forwarding client configuration: {e}");
1403            hard_fail = true;
1404            std::collections::HashMap::new()
1405        }
1406    };
1407    for ca in &config.ca {
1408        if let Some(url) = &ca.forward_to {
1409            if url.starts_with("https://") {
1410                println!("    Forward ({}): https (FTP_ITC.1)", ca.label);
1411                if ca.forward_ca.is_some() {
1412                    if forward_clients.contains_key(&ca.label) {
1413                        println!(
1414                            "      forward_ca: pinned private root(s), built-in roots disabled"
1415                        );
1416                    }
1417                } else {
1418                    println!("      trust: bundled WebPKI roots");
1419                }
1420            } else if ca.forward_insecure {
1421                eprintln!(
1422                    "    WARNING: CA '{}' forwards to cleartext {url} (forward_insecure=true) — \
1423                     lab/testing only.",
1424                    ca.label
1425                );
1426            } else {
1427                eprintln!(
1428                    "    FAIL: CA '{}' forward_to is cleartext ({url}). Use https:// or set \
1429                     forward_insecure=true for lab use (FTP_ITC.1).",
1430                    ca.label
1431                );
1432                hard_fail = true;
1433            }
1434        }
1435    }
1436
1437    // 389 DS syncrepl channel (FTP_ITC.1).
1438    for ca in &config.ca {
1439        if let Some(hoike_core::config::SourceConfig::DogtagSync {
1440            ldap_url,
1441            bind_password,
1442            bind_password_env,
1443            tls,
1444            ..
1445        }) = &ca.source
1446        {
1447            let has_bind_pw = bind_password.is_some() || bind_password_env.is_some();
1448            match tls.as_str() {
1449                "ldaps" | "starttls" => {
1450                    println!("    Syncrepl ({}): {tls} (FTP_ITC.1)", ca.label);
1451                }
1452                "none" if has_bind_pw => {
1453                    eprintln!(
1454                        "    WARNING: CA '{}' dogtag-sync uses plaintext {ldap_url} with a bind \
1455                         password — the password crosses in cleartext. Set tls=\"ldaps\" or \
1456                         tls=\"starttls\" (FTP_ITC.1).",
1457                        ca.label
1458                    );
1459                }
1460                "none" => {}
1461                other => {
1462                    eprintln!(
1463                        "    FAIL: CA '{}' dogtag-sync tls={other:?} is invalid (expected \
1464                         ldaps|starttls|none).",
1465                        ca.label
1466                    );
1467                    hard_fail = true;
1468                }
1469            }
1470        }
1471    }
1472
1473    // archive_cutoff_secs is only effective when the source supplies each
1474    // certificate's notAfter — that is 389 DS syncrepl. On a CRL-backed CA it is
1475    // a silent no-op (CRLs carry no per-certificate expiry), so warn rather than
1476    // let an operator believe pruning is happening.
1477    for ca in &config.ca {
1478        if ca.archive_cutoff_secs > 0
1479            && !matches!(
1480                &ca.source,
1481                Some(hoike_core::config::SourceConfig::DogtagSync { .. })
1482            )
1483        {
1484            eprintln!(
1485                "    WARNING: CA '{}' sets archive_cutoff_secs={} but its source provides no \
1486                 per-certificate notAfter (only 389 DS syncrepl does) — pruning has no effect.",
1487                ca.label, ca.archive_cutoff_secs
1488            );
1489        }
1490    }
1491
1492    // Gossip message authentication (FPT_ITT.1, F09). The same auth-loading
1493    // helper GossipNode::start uses decides the effective policy, so check
1494    // reports what serve would actually run — and fails on the same invalid
1495    // configurations that would abort startup.
1496    if let Some(g) = config.gossip.as_ref().filter(|g| g.enabled) {
1497        let auth = hoike_gossip::AuthMode::from_str(&g.auth_mode).and_then(|mode| {
1498            let gc = hoike_gossip::GossipConfig {
1499                enabled: true,
1500                bind: g.bind.clone(),
1501                seeds: g.seeds.clone(),
1502                node_name: g.node_name.clone(),
1503                auth_mode: mode,
1504                identity_key: g.identity_key.clone(),
1505                peer_keys: g.peer_keys.clone(),
1506                peer_identities: g.peer_identities.clone(),
1507            };
1508            hoike_gossip::load_authentication(&gc).map(|(signer, _)| (mode, signer))
1509        });
1510        match auth {
1511            Ok((mode, signer)) => {
1512                let peers = g.peer_identities.len();
1513                let identities = if peers == 1 { "identity" } else { "identities" };
1514                match mode {
1515                    hoike_gossip::AuthMode::Required => println!(
1516                        "    Gossip:    auth_mode=required — signed outbound; unsigned, forged, \
1517                         and unknown-origin broadcasts rejected ({peers} peer {identities} + \
1518                         self) (FPT_ITT.1)"
1519                    ),
1520                    hoike_gossip::AuthMode::Permissive => println!(
1521                        "    Gossip:    auth_mode=permissive — ROLLOUT MODE ({}): unsigned \
1522                         broadcasts are still accepted; signed frames are verified against \
1523                         {peers} provisioned {identities}. Switch to auth_mode=\"required\" \
1524                         once every node signs (FPT_ITT.1).",
1525                        if signer.is_some() {
1526                            "signing outbound"
1527                        } else {
1528                            "not yet signing"
1529                        }
1530                    ),
1531                }
1532            }
1533            Err(e) => {
1534                eprintln!("    FAIL: gossip authentication configuration: {e}");
1535                hard_fail = true;
1536            }
1537        }
1538    }
1539
1540    if hard_fail {
1541        std::process::exit(1);
1542    }
1543}
1544
1545#[allow(clippy::too_many_arguments)]
1546fn run_sign(
1547    ca_label: String,
1548    crl_path: PathBuf,
1549    output: PathBuf,
1550    issuer_path: Option<PathBuf>,
1551    epoch: u64,
1552    certid_compat: String,
1553    good_serials: Option<PathBuf>,
1554    sig_alg: String,
1555    issuer_name_b64: Option<String>,
1556    issuer_key_b64: Option<String>,
1557    signing_key_path: Option<PathBuf>,
1558    seal_key_path: Option<PathBuf>,
1559    seal_cert_path: Option<PathBuf>,
1560    dual_alg: Option<String>,
1561    pq_signing_key_path: Option<PathBuf>,
1562    demo_key: bool,
1563) {
1564    use hoike_sign::{
1565        CaIdentity, CertIdCompat, CertificateStatus, CrlSource, GenerationConfig, RevocationSource,
1566    };
1567
1568    // Resolve signing key — require explicit --signing-key or --demo-key
1569    if signing_key_path.is_none() && !demo_key {
1570        eprintln!(
1571            "Error: no signing key specified.\n\n\
1572             Provide one of:\n  \
1573             --signing-key PATH   PKCS#8 PEM or DER key file\n  \
1574             --demo-key           Ephemeral key for testing only (NOT FOR PRODUCTION)\n"
1575        );
1576        std::process::exit(1);
1577    }
1578
1579    let compat = CertIdCompat::parse(&certid_compat).unwrap_or_else(|e| {
1580        eprintln!("{e}");
1581        std::process::exit(1);
1582    });
1583
1584    let crl_data = std::fs::read(&crl_path).unwrap_or_else(|e| {
1585        eprintln!("Failed to read CRL from {}: {e}", crl_path.display());
1586        std::process::exit(1);
1587    });
1588
1589    let source = if crl_data.starts_with(b"-----BEGIN") {
1590        let pem = String::from_utf8(crl_data).unwrap_or_else(|e| {
1591            eprintln!("CRL file is not valid UTF-8: {e}");
1592            std::process::exit(1);
1593        });
1594        CrlSource::from_pem(&pem).unwrap_or_else(|e| {
1595            eprintln!("Failed to parse PEM CRL: {e}");
1596            std::process::exit(1);
1597        })
1598    } else {
1599        CrlSource::from_der(crl_data).unwrap_or_else(|e| {
1600            eprintln!("Failed to parse DER CRL: {e}");
1601            std::process::exit(1);
1602        })
1603    };
1604
1605    let issuer_bytes = issuer_path
1606        .as_ref()
1607        .and_then(|p| std::fs::read(p).ok())
1608        .unwrap_or_else(|| {
1609            eprintln!(
1610                "--issuer must name a readable authorized CRL issuer certificate (PEM or DER)"
1611            );
1612            std::process::exit(1);
1613        });
1614    let issuer_cert = hoike_sign::rotation::parse_certificate(&issuer_bytes).unwrap_or_else(|e| {
1615        eprintln!("Invalid issuer certificate: {e}");
1616        std::process::exit(1);
1617    });
1618    let source = source
1619        .with_issuer_certificate(&issuer_bytes)
1620        .unwrap_or_else(|e| {
1621            eprintln!("CRL authentication setup failed: {e}");
1622            std::process::exit(1);
1623        });
1624    use base64::Engine as _;
1625    use der::Encode as _;
1626    let issuer_name_b64 = issuer_name_b64.or_else(|| {
1627        Some(
1628            base64::engine::general_purpose::STANDARD.encode(
1629                issuer_cert
1630                    .tbs_certificate
1631                    .subject
1632                    .to_der()
1633                    .expect("valid issuer name"),
1634            ),
1635        )
1636    });
1637    let issuer_key_b64 = issuer_key_b64.or_else(|| {
1638        Some(
1639            base64::engine::general_purpose::STANDARD.encode(
1640                issuer_cert
1641                    .tbs_certificate
1642                    .subject_public_key_info
1643                    .subject_public_key
1644                    .raw_bytes(),
1645            ),
1646        )
1647    });
1648
1649    let issuer_name_der = decode_b64_field(
1650        &issuer_name_b64,
1651        "issuer_name_b64",
1652        &ca_label,
1653        &format!("CN={ca_label}"),
1654    )
1655    .unwrap_or_else(|e| {
1656        eprintln!("{e}");
1657        std::process::exit(1);
1658    });
1659    if issuer_name_b64.is_none() {
1660        warn!(
1661            ca = ca_label,
1662            "no --issuer-name-b64 provided — using synthetic placeholder. \
1663             CertID hashes will not match real client requests."
1664        );
1665    }
1666
1667    let issuer_key_bytes = decode_b64_field(
1668        &issuer_key_b64,
1669        "issuer_key_b64",
1670        &ca_label,
1671        &format!("{ca_label}-key"),
1672    )
1673    .unwrap_or_else(|e| {
1674        eprintln!("{e}");
1675        std::process::exit(1);
1676    });
1677
1678    let ca = CaIdentity {
1679        label: ca_label.clone(),
1680        issuer_name_der,
1681        issuer_key_bytes,
1682    };
1683
1684    let mut snapshot = source.snapshot(&ca).unwrap_or_else(|e| {
1685        eprintln!("Failed to snapshot CRL: {e}");
1686        std::process::exit(1);
1687    });
1688
1689    if let Some(good_path) = good_serials {
1690        let content = std::fs::read_to_string(&good_path).unwrap_or_else(|e| {
1691            eprintln!(
1692                "Failed to read good serials from {}: {e}",
1693                good_path.display()
1694            );
1695            std::process::exit(1);
1696        });
1697        for line in content.lines() {
1698            let line = line.trim();
1699            if line.is_empty() || line.starts_with('#') {
1700                continue;
1701            }
1702            match hex::decode(line) {
1703                Ok(serial) => {
1704                    snapshot
1705                        .entries
1706                        .entry(serial)
1707                        .or_insert(CertificateStatus::Good);
1708                }
1709                Err(e) => {
1710                    eprintln!("Warning: invalid hex serial '{line}': {e}");
1711                }
1712            }
1713        }
1714    }
1715
1716    info!(
1717        ca = ca_label,
1718        revoked = snapshot.entries.values().filter(|s| matches!(s, CertificateStatus::Revoked { .. })).count(),
1719        good = snapshot.entries.values().filter(|s| matches!(s, CertificateStatus::Good)).count(),
1720        sig_alg = %sig_alg,
1721        "snapshot loaded"
1722    );
1723
1724    let config = GenerationConfig {
1725        producer_id: "hoike-cli".into(),
1726        epoch,
1727        certid_compat: compat,
1728        ..Default::default()
1729    };
1730
1731    // F07: seal material resolution. The policy — complete persistent pair,
1732    // half-pair error, demo-only distinct ephemeral fallback, and the F08 CMS
1733    // pair preflight — lives in the shared `load_or_generate_seal_material`
1734    // helper the configured orchestration path also uses. The CLI only adds
1735    // flag-name guidance and exits nonzero on failure.
1736    let seal_inputs_missing = seal_key_path.is_none() && seal_cert_path.is_none();
1737    let (cli_seal_key, cli_seal_cert) =
1738        hoike_sign::load_or_generate_seal_material(
1739            seal_key_path.as_deref(),
1740            seal_cert_path.as_deref(),
1741            demo_key,
1742        )
1743        .unwrap_or_else(|e| {
1744            eprintln!("Error: {e}");
1745            if seal_inputs_missing && !demo_key {
1746                eprintln!(
1747                    "\nProvide a complete persistent pair:\n  \
1748                     --seal-key PATH    PKCS#8 PEM or DER P-256 seal key (distinct from the signing key)\n  \
1749                     --seal-cert PATH   PEM or DER seal certificate\n\n\
1750                     Or use --demo-key, which generates a distinct ephemeral seal \
1751                     pair for testing only (NOT FOR PRODUCTION)."
1752                );
1753            }
1754            std::process::exit(1);
1755        });
1756    // F07: prove the classical ECDSA OCSP signing key is distinct from the
1757    // seal key before producing anything. Runs per loaded signer below; a
1758    // failure exits before any bundle is written.
1759    let separation_preflight = |signer: &p256::ecdsa::SigningKey| {
1760        hoike_sign::ensure_distinct_ecdsa_seal_key::<_, hoike_sign::EcdsaSignatureBytes>(
1761            &hoike_sign::EcdsaP256Signer::new(signer.clone()),
1762            &cli_seal_key,
1763        )
1764        .unwrap_or_else(|e| {
1765            eprintln!("Seal/OCSP key separation preflight failed: {e}");
1766            std::process::exit(1);
1767        });
1768    };
1769    let seal_fn = |m: &[u8]| -> hoike_sign::Result<Vec<u8>> {
1770        hoike_sign::create_cms_seal(m, &cli_seal_key, &cli_seal_cert)
1771    };
1772
1773    let bundle_bytes = if let Some(pq_alg) = &dual_alg {
1774        let disc_pq = match pq_alg.as_str() {
1775            "ml-dsa-44" => ahu::ALG_DISC_ML_DSA_44,
1776            "ml-dsa-65" => ahu::ALG_DISC_ML_DSA_65,
1777            "ml-dsa-87" => ahu::ALG_DISC_ML_DSA_87,
1778            other => {
1779                eprintln!("Unknown --dual-alg: {other}");
1780                std::process::exit(1);
1781            }
1782        };
1783        let mut ecdsa_signer = hoike_sign::EcdsaP256Signer::new(if let Some(key_path) = &signing_key_path {
1784            let key = hoike_sign::load_ecdsa_p256_key(key_path).unwrap_or_else(|e| {
1785                eprintln!("Failed to load classical signing key: {e}");
1786                std::process::exit(1);
1787            });
1788            // F07: the dual-algorithm classical ECDSA signer must stay
1789            // distinct from the seal key before anything is produced.
1790            separation_preflight(&key);
1791            key
1792        } else if demo_key {
1793            warn!("using ephemeral ECDSA demo key — NOT FOR PRODUCTION");
1794            let key = hoike_sign::demo_ecdsa_p256_key();
1795            separation_preflight(&key);
1796            key
1797        } else {
1798            eprintln!("--dual-alg requires --signing-key (classical) or --demo-key");
1799            std::process::exit(1);
1800        });
1801        let mut pq_signer = if let Some(pq_path) = &pq_signing_key_path {
1802            let v = hoike_sign::load_ml_dsa_key(pq_path).unwrap_or_else(|e| {
1803                eprintln!("Failed to load PQ signing key: {e}");
1804                std::process::exit(1);
1805            });
1806            if v.algorithm_name() != pq_alg.as_str() {
1807                eprintln!(
1808                    "PQ key is {} but --dual-alg is {}",
1809                    v.algorithm_name(), pq_alg
1810                );
1811                std::process::exit(1);
1812            }
1813            v
1814        } else if demo_key {
1815            warn!("using ephemeral ML-DSA demo key — NOT FOR PRODUCTION");
1816            hoike_sign::MlDsaSignerVariant::demo(pq_alg).unwrap_or_else(|e| {
1817                eprintln!("{e}");
1818                std::process::exit(1);
1819            })
1820        } else {
1821            eprintln!("--dual-alg requires --pq-signing-key or --demo-key");
1822            std::process::exit(1);
1823        };
1824        match &mut pq_signer {
1825            hoike_sign::MlDsaSignerVariant::MlDsa44(s) => {
1826                hoike_sign::produce_dual_bundle::<_, hoike_sign::EcdsaSignatureBytes, _, hoike_sign::MlDsaSignatureBytes>(
1827                    &ca, &snapshot, &config, &mut ecdsa_signer, s, disc_pq, seal_fn, None, None,
1828                )
1829            }
1830            hoike_sign::MlDsaSignerVariant::MlDsa65(s) => {
1831                hoike_sign::produce_dual_bundle::<_, hoike_sign::EcdsaSignatureBytes, _, hoike_sign::MlDsaSignatureBytes>(
1832                    &ca, &snapshot, &config, &mut ecdsa_signer, s, disc_pq, seal_fn, None, None,
1833                )
1834            }
1835            hoike_sign::MlDsaSignerVariant::MlDsa87(s) => {
1836                hoike_sign::produce_dual_bundle::<_, hoike_sign::EcdsaSignatureBytes, _, hoike_sign::MlDsaSignatureBytes>(
1837                    &ca, &snapshot, &config, &mut ecdsa_signer, s, disc_pq, seal_fn, None, None,
1838                )
1839            }
1840        }
1841    } else { match sig_alg.as_str() {
1842        "ecdsa-p256" => {
1843            let signer = if let Some(key_path) = &signing_key_path {
1844                let key = hoike_sign::load_ecdsa_p256_key(key_path).unwrap_or_else(|e| {
1845                    eprintln!("Failed to load signing key: {e}");
1846                    std::process::exit(1);
1847                });
1848                // F07: prove the OCSP signing key is not the seal key before
1849                // producing anything — the same key under a different file
1850                // name is still rejected.
1851                separation_preflight(&key);
1852                key
1853            } else if demo_key {
1854                warn!("using ephemeral ECDSA demo key — NOT FOR PRODUCTION");
1855                let key = hoike_sign::demo_ecdsa_p256_key();
1856                separation_preflight(&key);
1857                key
1858            } else {
1859                eprintln!("No signing key provided. Use --signing-key <path> for a PKCS#8 key file, or --demo-key for testing.");
1860                std::process::exit(1);
1861            };
1862            hoike_sign::produce_bundle::<_, hoike_sign::EcdsaSignatureBytes>(
1863                &ca,
1864                &snapshot,
1865                &config,
1866                &mut hoike_sign::EcdsaP256Signer::new(signer),
1867                seal_fn,
1868                None,
1869            )
1870        }
1871        "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87" => {
1872            let mut variant = if let Some(key_path) = &signing_key_path {
1873                let v = hoike_sign::load_ml_dsa_key(key_path).unwrap_or_else(|e| {
1874                    eprintln!("Failed to load ML-DSA signing key: {e}");
1875                    std::process::exit(1);
1876                });
1877                if v.algorithm_name() != sig_alg {
1878                    eprintln!(
1879                        "Key algorithm mismatch: key is {} but --sig-alg is {}",
1880                        v.algorithm_name(),
1881                        sig_alg
1882                    );
1883                    std::process::exit(1);
1884                }
1885                info!(
1886                    ca = ca_label,
1887                    key = %key_path.display(),
1888                    alg = v.algorithm_name(),
1889                    "using file-based ML-DSA signing key"
1890                );
1891                v
1892            } else if demo_key {
1893                warn!("using ephemeral ML-DSA demo key — NOT FOR PRODUCTION");
1894                hoike_sign::MlDsaSignerVariant::demo(&sig_alg).unwrap_or_else(|e| {
1895                    eprintln!("{e}");
1896                    std::process::exit(1);
1897                })
1898            } else {
1899                eprintln!(
1900                    "No signing key provided. Use --signing-key <path> for a PKCS#8 key file, \
1901                     or --demo-key for testing."
1902                );
1903                std::process::exit(1);
1904            };
1905            variant.sign_bundle(&ca, &snapshot, &config, seal_fn, None)
1906        }
1907        other => {
1908            eprintln!(
1909                "Unknown sig_alg: {other} (expected: ecdsa-p256, ml-dsa-44, ml-dsa-65, ml-dsa-87)"
1910            );
1911            std::process::exit(1);
1912        }
1913    } }
1914    .unwrap_or_else(|e| {
1915        eprintln!("Failed to produce bundle: {e}");
1916        std::process::exit(1);
1917    });
1918
1919    hoike_sign::orchestrate::write_bundle_atomic(&output, &bundle_bytes).unwrap_or_else(|e| {
1920        eprintln!("Failed to write bundle to {}: {e}", output.display());
1921        std::process::exit(1);
1922    });
1923
1924    let entry_count = ahu::Bundle::from_bytes(&bundle_bytes)
1925        .map(|b| b.manifest.entry_count)
1926        .unwrap_or(0);
1927    let avg_size = if entry_count > 0 {
1928        bundle_bytes.len() / entry_count as usize
1929    } else {
1930        0
1931    };
1932    let sig_overhead = hoike_sign::ml_dsa_signature_size(&sig_alg);
1933
1934    println!("Bundle size: {} bytes", bundle_bytes.len());
1935    println!("  Entries:           {entry_count}");
1936    println!("  Avg response size: {avg_size} bytes");
1937    if sig_overhead > 0 {
1938        println!("  Signature overhead: ~{sig_overhead} bytes ({sig_alg})");
1939    }
1940    println!("  Output:            {}", output.display());
1941}
1942
1943#[cfg(test)]
1944mod rotation_preflight_tests {
1945    use super::*;
1946    use der::{Decode, Encode};
1947    use p256::pkcs8::EncodePrivateKey;
1948
1949    #[tokio::test]
1950    async fn expired_live_certificate_is_renewed_before_startup_and_bad_pair_rejected() {
1951        let dir = tempfile::tempdir().unwrap();
1952        let key = hoike_sign::demo_ecdsa_p256_key();
1953        let valid = hoike_sign::generate_seal_cert(&key).unwrap();
1954        let mut expired = x509_cert::Certificate::from_der(&valid).unwrap();
1955        expired.tbs_certificate.validity.not_after = x509_cert::time::Time::GeneralTime(
1956            der::asn1::GeneralizedTime::from_unix_duration(std::time::Duration::from_secs(
1957                1_700_000_000,
1958            ))
1959            .unwrap(),
1960        );
1961        std::fs::write(
1962            dir.path().join("key.der"),
1963            key.to_pkcs8_der().unwrap().as_bytes(),
1964        )
1965        .unwrap();
1966        std::fs::write(dir.path().join("valid.der"), &valid).unwrap();
1967        std::fs::write(dir.path().join("active.der"), expired.to_der().unwrap()).unwrap();
1968        let config_path = dir.path().join("config.toml");
1969        std::fs::write(
1970            &config_path,
1971            format!(
1972                r#"
1973[server]
1974mode = "combined"
1975[storage]
1976bundle_dir = '{0}'
1977[[ca]]
1978label = "test"
1979nonce_policy = "live"
1980responder_cert = '{0}/active.der'
1981[ca.signing_key]
1982type = "file"
1983path = '{0}/key.der'
1984[ca.key_rotation]
1985renew_before_days = 7
1986rotation_command = "cp '{0}/valid.der' '{0}/active.der'"
1987"#,
1988                dir.path().display()
1989            ),
1990        )
1991        .unwrap();
1992        let config = hoike_core::Config::from_file(&config_path).unwrap();
1993        assert!(load_live_signer(&config.ca[0]).is_err());
1994        prepare_signer_material(&config.ca[0]).await.unwrap();
1995        assert_eq!(std::fs::read(dir.path().join("active.der")).unwrap(), valid);
1996        assert!(load_live_signer(&config.ca[0]).is_ok());
1997        let other = p256::ecdsa::SigningKey::from_bytes((&[13u8; 32]).into()).unwrap();
1998        std::fs::write(
1999            dir.path().join("key.der"),
2000            other.to_pkcs8_der().unwrap().as_bytes(),
2001        )
2002        .unwrap();
2003        assert!(prepare_signer_material(&config.ca[0]).await.is_err());
2004    }
2005}