Skip to main content

hoike_core/
config.rs

1use serde::Deserialize;
2use std::path::PathBuf;
3
4#[derive(Debug, Deserialize, Clone)]
5#[serde(deny_unknown_fields)]
6pub struct Config {
7    pub server: ServerConfig,
8    pub storage: StorageConfig,
9    #[serde(default)]
10    pub ca: Vec<CaConfig>,
11    pub gossip: Option<GossipConfigSection>,
12}
13
14#[derive(Debug, Deserialize, Clone)]
15#[serde(deny_unknown_fields)]
16pub struct GossipConfigSection {
17    #[serde(default)]
18    pub enabled: bool,
19    #[serde(default = "default_gossip_bind")]
20    pub bind: String,
21    #[serde(default)]
22    pub seeds: Vec<String>,
23    #[serde(default = "default_gossip_node_name")]
24    pub node_name: String,
25    /// Explicit inbound authentication policy for gossip broadcasts (FPT_ITT.1,
26    /// F09): "required" (default) or "permissive". Validated against those two
27    /// values here; the CLI bridges the string to hoike-gossip's `AuthMode`.
28    /// `required` drops unsigned/unknown/forged broadcasts and needs an
29    /// `identity_key`; `permissive` is the documented rollout mode that still
30    /// accepts unsigned legacy broadcasts while verifying signed ones.
31    #[serde(default = "default_gossip_auth_mode")]
32    pub auth_mode: String,
33    /// Path to an Ed25519 PKCS#8 private key used to sign outbound gossip
34    /// messages (design §6.3, FPT_ITT.1). Required when gossip is enabled in
35    /// `auth_mode = "required"`; optional while rolling out in permissive mode.
36    pub identity_key: Option<PathBuf>,
37    /// Deprecated unbound key list. Nonempty values fail configuration with
38    /// migration instructions; use peer_identities to authorize each key's
39    /// node identity.
40    #[serde(default)]
41    pub peer_keys: Vec<PathBuf>,
42    #[serde(default)]
43    pub peer_identities: std::collections::BTreeMap<String, PathBuf>,
44}
45
46fn default_gossip_bind() -> String {
47    "0.0.0.0:7946".into()
48}
49fn default_gossip_node_name() -> String {
50    std::env::var("HOSTNAME").unwrap_or_else(|_| "hoike-node".into())
51}
52fn default_gossip_auth_mode() -> String {
53    "required".into()
54}
55
56#[derive(Debug, Deserialize, Clone)]
57#[serde(deny_unknown_fields)]
58pub struct ServerConfig {
59    #[serde(default = "default_mode")]
60    pub mode: String,
61    #[serde(default = "default_listen")]
62    pub listen: String,
63    #[serde(default = "default_max_request")]
64    pub max_request: usize,
65    pub admin: Option<AdminConfig>,
66    pub webui: Option<WebUiConfig>,
67    /// Optional dedicated listener for the Prometheus `/metrics` endpoint, e.g.
68    /// "127.0.0.1:9184". Kept off the public OCSP port. Requires a build with
69    /// the `metrics` feature to expose data; otherwise `/metrics` returns 503.
70    pub metrics_listen: Option<String>,
71    /// Optional dedicated listener for the admin API + web UI, e.g.
72    /// "127.0.0.1:2561". When set, the management surface binds here instead of
73    /// riding the public OCSP port — required to give it a trusted path
74    /// (NIAP PPCA FTP_TRP.1) without wrapping the plaintext OCSP data plane.
75    /// Pair with `admin_tls` to terminate TLS. When unset, admin/UI remain on
76    /// `listen` for backward compatibility.
77    pub admin_listen: Option<String>,
78    /// TLS material for the `admin_listen` listener. Requires a build with the
79    /// `tls` feature; startup fails if TLS support is unavailable.
80    pub admin_tls: Option<TlsConfig>,
81    /// TLS material for the `metrics_listen` listener. Requires the `tls`
82    /// feature. When unset the metrics listener stays plaintext (private-bound).
83    pub metrics_tls: Option<TlsConfig>,
84}
85
86/// PEM certificate/key material for a TLS-terminated listener.
87///
88/// `client_ca`, when set, turns on mutual TLS: clients must present a
89/// certificate chaining to one of these anchors (NIAP PPCA FCS_TLSS_EXT.2).
90/// When absent, the listener does server-auth TLS only (FCS_TLSS_EXT.1) and
91/// authentication falls to the existing bcrypt/RBAC login.
92#[derive(Debug, Deserialize, Clone)]
93#[serde(deny_unknown_fields)]
94pub struct TlsConfig {
95    /// Path to the server certificate chain (PEM, leaf first).
96    pub cert: PathBuf,
97    /// Path to the server private key (PKCS#8 or RSA/SEC1 PEM).
98    pub key: PathBuf,
99    /// Optional PEM bundle of CAs trusted to sign client certificates.
100    /// Presence enables mutual TLS (client-cert required).
101    pub client_ca: Option<PathBuf>,
102}
103
104#[derive(Debug, Deserialize, Clone)]
105#[serde(deny_unknown_fields)]
106pub struct WebUiConfig {
107    pub static_dir: Option<PathBuf>,
108}
109
110#[derive(Debug, Deserialize, Clone)]
111#[serde(deny_unknown_fields)]
112pub struct AdminConfig {
113    #[serde(default = "default_session_ttl")]
114    pub session_ttl_secs: u64,
115    #[serde(default)]
116    pub operators: Vec<OperatorConfig>,
117}
118
119#[derive(Debug, Deserialize, Clone)]
120#[serde(deny_unknown_fields)]
121pub struct OperatorConfig {
122    pub name: String,
123    pub password_hash: String,
124    #[serde(default = "default_operator_role")]
125    pub role: String,
126}
127
128fn default_session_ttl() -> u64 {
129    3600
130}
131fn default_operator_role() -> String {
132    "viewer".into()
133}
134
135#[derive(Debug, Deserialize, Clone)]
136#[serde(deny_unknown_fields)]
137pub struct StorageConfig {
138    pub bundle_dir: PathBuf,
139    #[serde(default = "default_state_db")]
140    pub state_db: PathBuf,
141    /// DER or PEM CA certificates for the bounded direct-issuer seal profile.
142    #[serde(default)]
143    pub seal_trust_anchors: Option<Vec<PathBuf>>,
144    #[serde(default)]
145    pub seal_authorizations: Vec<SealAuthorization>,
146    /// Explicitly trusted signer certificates, distinct from CA trust anchors.
147    #[serde(default)]
148    pub seal_signer_pins: Vec<PathBuf>,
149    /// Permit structure-only demo admission when no seal trust or scope
150    /// authorizations are configured. Never bypasses configured trust checks.
151    #[serde(default)]
152    pub allow_unauthenticated_bundles: bool,
153}
154
155/// Optional restriction of trusted seal certificates to producer and CA scope.
156#[derive(Debug, Deserialize, Clone)]
157#[serde(deny_unknown_fields)]
158pub struct SealAuthorization {
159    pub producer_id: String,
160    pub issuer_key_hash: String,
161    /// SHA-256 of the DER signer certificate, hex encoded.
162    pub signer_sha256: String,
163}
164
165#[derive(Debug, Deserialize, Clone)]
166#[serde(deny_unknown_fields)]
167pub struct CaConfig {
168    pub label: String,
169    pub bundle_file: Option<PathBuf>,
170    #[serde(default = "default_nonce_policy")]
171    pub nonce_policy: String,
172    #[serde(default = "default_completeness")]
173    pub completeness: String,
174    /// Hex-encoded issuerNameHash for explicit routing.
175    /// If absent, extracted from the bundle manifest on load.
176    pub issuer_name_hash: Option<String>,
177    /// Hex-encoded issuerKeyHash for explicit routing.
178    /// If absent, extracted from the bundle manifest on load.
179    pub issuer_key_hash: Option<String>,
180    /// URL to forward nonce-bearing requests to (for nonce_policy = "forward").
181    /// Must be `https://` (trusted channel, FTP_ITC.1) unless `forward_insecure`
182    /// is set.
183    pub forward_to: Option<String>,
184    /// Allow a plaintext `http://` `forward_to` target. Lab/testing only —
185    /// `hoike check` refuses a cleartext forward URL without this escape hatch.
186    #[serde(default)]
187    pub forward_insecure: bool,
188    /// Optional PEM CA bundle for the forward target's server certificate.
189    ///
190    /// When set, the CA's forwarding client trusts only these roots (the
191    /// bundled WebPKI roots are disabled) and the bundle must parse to at
192    /// least one certificate; an unreadable, empty, or malformed file fails
193    /// startup and `hoike check`. A `forward_ca` on a non-HTTPS `forward_to`
194    /// is a configuration error. Without `forward_ca`, the forward channel
195    /// validates against reqwest's bundled WebPKI roots (the `rustls-tls`
196    /// feature) — not the operating system trust store.
197    pub forward_ca: Option<PathBuf>,
198    /// Revocation source (required for combined/signer mode)
199    pub source: Option<SourceConfig>,
200    /// Batch production interval in seconds (combined/signer mode)
201    #[serde(default = "default_batch_interval")]
202    pub batch_interval: u64,
203    /// OCSP response validity in seconds
204    #[serde(default = "default_validity_secs")]
205    pub validity_secs: u64,
206    /// Upper bound (seconds) of randomized jitter added to `nextUpdate` so a
207    /// fleet's responses do not all expire simultaneously (thundering-herd
208    /// avoidance). Bounded by the source's own nextUpdate. Default 7200.
209    #[serde(default = "default_jitter_secs")]
210    pub jitter_secs: u64,
211    /// CertID hash coverage baked into produced bundles:
212    /// `"dual"` (both SHA-256 and SHA-1, default), `"sha256"`, or `"sha1"`.
213    #[serde(default = "default_certid_compat")]
214    pub certid_compat: String,
215    /// Fraction of a response's validity window advertised as HTTP
216    /// `Cache-Control: max-age` at the edge. Must be in `(0, 1]`. Default 0.5.
217    #[serde(default = "default_max_age_fraction")]
218    pub max_age_fraction: f64,
219    /// Drop entries for certificates that expired more than this many seconds
220    /// ago, bounding bundle size. Requires per-certificate `notAfter`, which
221    /// only the 389 DS syncrepl source supplies — a no-op for CRL sources.
222    /// `0` (default) disables pruning.
223    #[serde(default)]
224    pub archive_cutoff_secs: u64,
225    /// When true (default), the signer produces an off-cycle bundle immediately
226    /// upon detecting a newly revoked certificate, instead of waiting for the
227    /// next `batch_interval`.
228    #[serde(default = "default_urgent_revocation")]
229    pub urgent_revocation: bool,
230    /// DER bytes of the issuer DN (for CertID computation in signer mode).
231    /// Base64-encoded in config, decoded on load.
232    pub issuer_name_der_b64: Option<String>,
233    /// Raw issuer public key bytes (for CertID computation in signer mode).
234    /// Base64-encoded in config, decoded on load.
235    pub issuer_key_bytes_b64: Option<String>,
236    /// Signing algorithm: ecdsa-p256 (default), ml-dsa-44, ml-dsa-65, ml-dsa-87
237    #[serde(default = "default_sig_alg")]
238    pub sig_alg: String,
239    /// Signing key configuration (required for signer/combined mode).
240    pub signing_key: Option<SigningKeyConfig>,
241    /// Path to the delegated OCSP signing certificate (DER or PEM).
242    /// Embedded in each OCSPResponse per RFC 9919 §3.2.2 so clients
243    /// can validate the response without pre-caching the responder cert.
244    pub responder_cert: Option<PathBuf>,
245    /// Key rotation monitoring configuration.
246    pub key_rotation: Option<KeyRotationConfigToml>,
247    /// Path to PKCS#8 PEM/DER key for bundle seal signing.
248    /// Required together with `seal_cert` for production signing keys
249    /// (file/PKCS#11); must hold a key distinct from the OCSP signing key.
250    /// Demo signing may omit both (a distinct ephemeral pair is generated),
251    /// but configuring exactly one of the two is always an error.
252    pub seal_key: Option<PathBuf>,
253    /// Path to the DER/PEM certificate for the seal signer.
254    /// Required together with `seal_key` for production signing keys;
255    /// a half-configured pair is always an error.
256    pub seal_cert: Option<PathBuf>,
257}
258
259impl CaConfig {
260    /// Returns true if the configured sig_alg is an ML-DSA variant.
261    pub fn is_ml_dsa(&self) -> bool {
262        matches!(
263            self.sig_alg.as_str(),
264            "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87"
265        )
266    }
267}
268
269/// TOML-level key rotation configuration.
270#[derive(Debug, Deserialize, Clone)]
271#[serde(deny_unknown_fields)]
272pub struct KeyRotationConfigToml {
273    /// Days before cert expiry to trigger rotation warning/action (default: 7).
274    #[serde(default = "default_renew_before_days")]
275    pub renew_before_days: u64,
276    /// Hours between rotation checks (default: 1).
277    #[serde(default = "default_check_interval_hours")]
278    pub check_interval_hours: u64,
279    /// Shell command to execute when rotation is needed.
280    /// The command receives CA label and cert path as arguments.
281    pub rotation_command: Option<String>,
282}
283
284fn default_renew_before_days() -> u64 {
285    7
286}
287fn default_check_interval_hours() -> u64 {
288    1
289}
290
291/// How to obtain the signing key for OCSP response production.
292#[derive(Debug, Deserialize, Clone)]
293#[serde(tag = "type")]
294pub enum SigningKeyConfig {
295    /// Load from a PKCS#8 PEM or DER file on disk.
296    #[serde(rename = "file")]
297    File { path: PathBuf },
298
299    /// Sign via a PKCS#11 hardware security module.
300    ///
301    /// Supported HSMs: Thales Luna, Entrust nShield, Utimaco CryptoServer,
302    /// FutureX Vectera Plus, SoftHSM2 (testing).
303    #[serde(rename = "pkcs11")]
304    Pkcs11 {
305        /// Path to the vendor's PKCS#11 shared library.
306        module: String,
307        /// Find slot by token label (e.g., Luna partition name).
308        token_label: Option<String>,
309        /// Explicit slot ID (alternative to token_label).
310        slot_id: Option<u64>,
311        /// Login PIN (plaintext — prefer pin_env for production).
312        pin: Option<String>,
313        /// Environment variable containing the login PIN.
314        pin_env: Option<String>,
315        /// Find key by CKA_LABEL.
316        key_label: Option<String>,
317        /// Find key by CKA_ID (hex-encoded).
318        key_id: Option<String>,
319    },
320
321    /// Ephemeral demo key for testing only. Produces a warning on every use.
322    #[serde(rename = "demo")]
323    Demo,
324}
325
326#[derive(Debug, Deserialize, Clone)]
327#[serde(tag = "type")]
328pub enum SourceConfig {
329    #[serde(rename = "crl")]
330    Crl {
331        path: PathBuf,
332        issuer_cert: Option<PathBuf>,
333    },
334
335    /// RFC 4533 syncrepl against a Dogtag 389 DS certificate repository.
336    ///
337    /// Initial refresh loads the full cert population; subsequent refreshes
338    /// send the stored sync cookie so 389 DS returns only changes.
339    /// Produces both `Good` and `Revoked` entries — enables
340    /// `authoritative-complete` bundles.
341    #[serde(rename = "dogtag-sync")]
342    DogtagSync {
343        /// LDAP URL, e.g. `ldap://ds-iot.cert-lab.local:3389`
344        ldap_url: String,
345        /// Search base DN, e.g. `ou=certificateRepository,ou=ca,o=pki-iot-ca-CA`
346        base_dn: String,
347        /// Bind DN (e.g. `cn=Directory Manager`)
348        #[serde(default = "default_bind_dn")]
349        bind_dn: String,
350        /// Bind password (plaintext — prefer `bind_password_env`)
351        bind_password: Option<String>,
352        /// Environment variable holding the bind password
353        bind_password_env: Option<String>,
354        /// Path to checkpoint the sync cookie (default: state_db/sync-cookie.dat)
355        cookie_path: Option<PathBuf>,
356        /// LDAP filter (default: `(objectClass=certificateRecord)`)
357        #[serde(default = "default_sync_filter")]
358        filter: Option<String>,
359        /// Transport security for the LDAP connection (FTP_ITC.1):
360        /// `"ldaps"` (implicit TLS), `"starttls"` (upgrade before bind), or
361        /// `"none"` (plaintext — the default, for backward compatibility).
362        /// With `starttls` the upgrade completes *before* the bind, so the bind
363        /// password is never sent in cleartext.
364        #[serde(default = "default_ldap_tls")]
365        tls: String,
366        /// Optional PEM CA bundle to validate the directory server's TLS
367        /// certificate against (instead of the system roots).
368        ca_cert: Option<PathBuf>,
369    },
370}
371
372fn default_ldap_tls() -> String {
373    "none".into()
374}
375
376fn default_bind_dn() -> String {
377    "cn=Directory Manager".into()
378}
379
380fn default_sync_filter() -> Option<String> {
381    Some("(objectClass=certificateRecord)".into())
382}
383
384fn default_mode() -> String {
385    "edge".into()
386}
387fn default_listen() -> String {
388    "0.0.0.0:2560".into()
389}
390fn default_max_request() -> usize {
391    8192
392}
393fn default_state_db() -> PathBuf {
394    PathBuf::from("/var/lib/hoike/state")
395}
396fn default_sig_alg() -> String {
397    "ecdsa-p256".into()
398}
399fn default_nonce_policy() -> String {
400    "ignore".into()
401}
402fn default_completeness() -> String {
403    "partial".into()
404}
405fn default_batch_interval() -> u64 {
406    3600
407}
408fn default_validity_secs() -> u64 {
409    86400
410}
411fn default_jitter_secs() -> u64 {
412    7200
413}
414fn default_certid_compat() -> String {
415    "dual".into()
416}
417fn default_max_age_fraction() -> f64 {
418    0.5
419}
420fn default_urgent_revocation() -> bool {
421    true
422}
423
424impl Config {
425    pub fn from_file(path: &std::path::Path) -> crate::error::Result<Self> {
426        let contents = std::fs::read_to_string(path)?;
427        toml::from_str(&contents).map_err(|e| crate::error::CoreError::Config(e.to_string()))
428    }
429
430    pub fn is_combined(&self) -> bool {
431        self.server.mode == "combined"
432    }
433
434    /// Resolve the configured bundle destination for a CA label (design
435    /// §S5). The selected `bundle_file` wins; otherwise use
436    /// `bundle_dir/<label>.ahu`. Never infer a destination from an uploaded
437    /// filename.
438    ///
439    /// Rejects unknown labels, legacy unscoped configuration (no `[[ca]]`
440    /// entries — there is no per-CA destination to select), unsafe label
441    /// file-name components, and a destination shared with another
442    /// configured CA label: replacing it would ambiguously serve multiple
443    /// labels from one file.
444    pub fn bundle_destination(&self, label: &str) -> crate::error::Result<std::path::PathBuf> {
445        if self.ca.is_empty() {
446            return Err(crate::error::CoreError::Config(
447                "no [[ca]] entries are configured — legacy unscoped configuration has no \
448                 per-CA bundle destination; configure a labeled CA before producing or \
449                 importing bundles"
450                    .into(),
451            ));
452        }
453        if label.is_empty() || label == "." || label == ".." || label.contains(['/', '\\']) {
454            return Err(crate::error::CoreError::Config(format!(
455                "CA label '{label}' is not a safe bundle file name"
456            )));
457        }
458        let selected = self.ca.iter().find(|ca| ca.label == label).ok_or_else(|| {
459            crate::error::CoreError::Config(format!(
460                "unknown CA label '{label}' — configured labels: {}",
461                self.ca
462                    .iter()
463                    .map(|ca| ca.label.as_str())
464                    .collect::<Vec<_>>()
465                    .join(", ")
466            ))
467        })?;
468        let destination = selected
469            .bundle_file
470            .clone()
471            .unwrap_or_else(|| self.storage.bundle_dir.join(format!("{label}.ahu")));
472        let canonical = |p: &std::path::Path| p.canonicalize().unwrap_or_else(|_| p.to_path_buf());
473        let mine = canonical(&destination);
474        for ca in &self.ca {
475            if ca.label == label {
476                continue;
477            }
478            let other = ca
479                .bundle_file
480                .clone()
481                .unwrap_or_else(|| self.storage.bundle_dir.join(format!("{}.ahu", ca.label)));
482            if canonical(&other) == mine {
483                return Err(crate::error::CoreError::Config(format!(
484                    "CA label '{label}' destination {} is also configured for CA '{}' — give \
485                     each label a distinct destination",
486                    destination.display(),
487                    ca.label
488                )));
489            }
490        }
491        Ok(destination)
492    }
493
494    pub fn is_signer(&self) -> bool {
495        self.server.mode == "signer"
496    }
497
498    pub fn needs_signing(&self) -> bool {
499        self.is_combined() || self.is_signer()
500    }
501
502    /// Validate the actual build before binding listeners or producing bundles.
503    pub fn validate_transport(&self, tls_supported: bool) -> crate::error::Result<()> {
504        let fail = |s: &str| crate::error::CoreError::Config(s.into());
505        if (self.server.admin_tls.is_some() || self.server.metrics_tls.is_some()) && !tls_supported
506        {
507            return Err(fail(
508                "TLS configured but this binary was built without the tls feature",
509            ));
510        }
511        if self.server.admin_tls.is_some() && self.server.admin_listen.is_none() {
512            return Err(fail(
513                "admin_tls requires admin_listen; refusing plaintext management fallback",
514            ));
515        }
516        if self.server.metrics_tls.is_some() && self.server.metrics_listen.is_none() {
517            return Err(fail("metrics_tls requires metrics_listen"));
518        }
519        self.validate_for_mode()
520    }
521
522    pub fn validate_for_mode(&self) -> crate::error::Result<()> {
523        if let Some(g) = self.gossip.as_ref() {
524            if !g.peer_keys.is_empty() {
525                return Err(crate::error::CoreError::Config("replace gossip.peer_keys with peer_identities mapping node names to public-key files".into()));
526            }
527            if !matches!(g.auth_mode.as_str(), "required" | "permissive") {
528                return Err(crate::error::CoreError::Config(format!(
529                    "gossip.auth_mode must be \"required\" or \"permissive\" (got '{}')",
530                    g.auth_mode
531                )));
532            }
533        }
534        let mut labels = std::collections::HashSet::new();
535        for ca in &self.ca {
536            if ca.label.is_empty()
537                || ca.label == "."
538                || ca.label == ".."
539                || ca.label.contains(['/', '\\'])
540                || !labels.insert(&ca.label)
541            {
542                return Err(crate::error::CoreError::Config(
543                    "CA labels must be unique nonempty file names".into(),
544                ));
545            }
546            if let Some(url) = &ca.forward_to {
547                if !url.starts_with("https://")
548                    && !(ca.forward_insecure && url.starts_with("http://"))
549                {
550                    return Err(crate::error::CoreError::Config(format!(
551                        "CA '{}': forward_to requires https:// (or explicit forward_insecure for http://)",
552                        ca.label
553                    )));
554                }
555            }
556        }
557        let valid_sig_algs = ["ecdsa-p256", "ml-dsa-44", "ml-dsa-65", "ml-dsa-87"];
558        for ca in &self.ca {
559            if !valid_sig_algs.contains(&ca.sig_alg.as_str()) {
560                return Err(crate::error::CoreError::Config(format!(
561                    "CA '{}' has invalid sig_alg '{}' — expected one of: {}",
562                    ca.label,
563                    ca.sig_alg,
564                    valid_sig_algs.join(", ")
565                )));
566            }
567            if ca.is_ml_dsa() && ca.nonce_policy == "live" {
568                return Err(crate::error::CoreError::Config(format!(
569                    "CA '{}': nonce_policy=live is not yet supported with {} signing",
570                    ca.label, ca.sig_alg
571                )));
572            }
573            let valid_certid_compat = ["dual", "sha256", "sha1"];
574            if !valid_certid_compat.contains(&ca.certid_compat.as_str()) {
575                return Err(crate::error::CoreError::Config(format!(
576                    "CA '{}' has invalid certid_compat '{}' — expected one of: {}",
577                    ca.label,
578                    ca.certid_compat,
579                    valid_certid_compat.join(", ")
580                )));
581            }
582            if !(ca.max_age_fraction > 0.0 && ca.max_age_fraction <= 1.0) {
583                return Err(crate::error::CoreError::Config(format!(
584                    "CA '{}' has invalid max_age_fraction {} — must be in the range (0, 1]",
585                    ca.label, ca.max_age_fraction
586                )));
587            }
588        }
589        if self.needs_signing() {
590            for ca in &self.ca {
591                if ca.source.is_none() {
592                    return Err(crate::error::CoreError::Config(format!(
593                        "CA '{}' has no source configured, required for {} mode",
594                        ca.label, self.server.mode
595                    )));
596                }
597                if ca.signing_key.is_none() {
598                    return Err(crate::error::CoreError::Config(format!(
599                        "CA '{}' has no signing_key configured, required for {} mode. \
600                         Use type='file' with a PKCS#8 key, type='pkcs11' for HSM, \
601                         or type='demo' for testing only.",
602                        ca.label, self.server.mode
603                    )));
604                }
605                // F07: production signing requires a complete persistent seal
606                // pair. Demo signing may generate a distinct ephemeral seal
607                // pair only when neither seal input is supplied; a
608                // half-configured pair is always an error.
609                match (&ca.seal_key, &ca.seal_cert) {
610                    (None, None) => {
611                        if !matches!(&ca.signing_key, Some(SigningKeyConfig::Demo)) {
612                            return Err(crate::error::CoreError::Config(format!(
613                                "CA '{}': production signing requires a persistent seal_key \
614                                 and seal_cert pair — configure both, or use the demo signing \
615                                 key for testing",
616                                ca.label
617                            )));
618                        }
619                    }
620                    (Some(_), None) | (None, Some(_)) => {
621                        return Err(crate::error::CoreError::Config(format!(
622                            "CA '{}': seal_key and seal_cert must be configured together — a \
623                             half-configured seal pair is always an error",
624                            ca.label
625                        )));
626                    }
627                    (Some(_), Some(_)) => {}
628                }
629            }
630            if self.ca.is_empty() {
631                return Err(crate::error::CoreError::Config(format!(
632                    "{} mode requires at least one [[ca]] with a source",
633                    self.server.mode
634                )));
635            }
636        }
637        Ok(())
638    }
639}