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 #[serde(default = "default_gossip_auth_mode")]
32 pub auth_mode: String,
33 pub identity_key: Option<PathBuf>,
37 #[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 pub metrics_listen: Option<String>,
71 pub admin_listen: Option<String>,
78 pub admin_tls: Option<TlsConfig>,
81 pub metrics_tls: Option<TlsConfig>,
84}
85
86#[derive(Debug, Deserialize, Clone)]
93#[serde(deny_unknown_fields)]
94pub struct TlsConfig {
95 pub cert: PathBuf,
97 pub key: PathBuf,
99 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 #[serde(default)]
143 pub seal_trust_anchors: Option<Vec<PathBuf>>,
144 #[serde(default)]
145 pub seal_authorizations: Vec<SealAuthorization>,
146 #[serde(default)]
148 pub seal_signer_pins: Vec<PathBuf>,
149 #[serde(default)]
152 pub allow_unauthenticated_bundles: bool,
153}
154
155#[derive(Debug, Deserialize, Clone)]
157#[serde(deny_unknown_fields)]
158pub struct SealAuthorization {
159 pub producer_id: String,
160 pub issuer_key_hash: String,
161 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 pub issuer_name_hash: Option<String>,
177 pub issuer_key_hash: Option<String>,
180 pub forward_to: Option<String>,
184 #[serde(default)]
187 pub forward_insecure: bool,
188 pub forward_ca: Option<PathBuf>,
198 pub source: Option<SourceConfig>,
200 #[serde(default = "default_batch_interval")]
202 pub batch_interval: u64,
203 #[serde(default = "default_validity_secs")]
205 pub validity_secs: u64,
206 #[serde(default = "default_jitter_secs")]
210 pub jitter_secs: u64,
211 #[serde(default = "default_certid_compat")]
214 pub certid_compat: String,
215 #[serde(default = "default_max_age_fraction")]
218 pub max_age_fraction: f64,
219 #[serde(default)]
224 pub archive_cutoff_secs: u64,
225 #[serde(default = "default_urgent_revocation")]
229 pub urgent_revocation: bool,
230 pub issuer_name_der_b64: Option<String>,
233 pub issuer_key_bytes_b64: Option<String>,
236 #[serde(default = "default_sig_alg")]
238 pub sig_alg: String,
239 pub signing_key: Option<SigningKeyConfig>,
241 pub responder_cert: Option<PathBuf>,
245 pub key_rotation: Option<KeyRotationConfigToml>,
247 pub seal_key: Option<PathBuf>,
253 pub seal_cert: Option<PathBuf>,
257}
258
259impl CaConfig {
260 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#[derive(Debug, Deserialize, Clone)]
271#[serde(deny_unknown_fields)]
272pub struct KeyRotationConfigToml {
273 #[serde(default = "default_renew_before_days")]
275 pub renew_before_days: u64,
276 #[serde(default = "default_check_interval_hours")]
278 pub check_interval_hours: u64,
279 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#[derive(Debug, Deserialize, Clone)]
293#[serde(tag = "type")]
294pub enum SigningKeyConfig {
295 #[serde(rename = "file")]
297 File { path: PathBuf },
298
299 #[serde(rename = "pkcs11")]
304 Pkcs11 {
305 module: String,
307 token_label: Option<String>,
309 slot_id: Option<u64>,
311 pin: Option<String>,
313 pin_env: Option<String>,
315 key_label: Option<String>,
317 key_id: Option<String>,
319 },
320
321 #[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 #[serde(rename = "dogtag-sync")]
342 DogtagSync {
343 ldap_url: String,
345 base_dn: String,
347 #[serde(default = "default_bind_dn")]
349 bind_dn: String,
350 bind_password: Option<String>,
352 bind_password_env: Option<String>,
354 cookie_path: Option<PathBuf>,
356 #[serde(default = "default_sync_filter")]
358 filter: Option<String>,
359 #[serde(default = "default_ldap_tls")]
365 tls: String,
366 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 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 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 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}