Skip to main content

hyprstream_core/auth/
identity_store.rs

1//! Persistent file-based credential storage.
2//!
3//! This module provides atomic read/write of secret key material to a
4//! configurable directory (`secrets.path` in config, or the systemd
5//! credentials directory when running under systemd).
6//!
7//! # Design
8//!
9//! - **Centralized directory resolution** — callers use `credentials_dir()` so
10//!   all secret-bearing paths fail closed consistently.
11//! - **Atomic writes** — secrets are written via tempfile + rename so partial
12//!   writes are never visible.
13//! - **Mode 0600 / 0700** — secret files and their parent directory are created
14//!   with restrictive permissions on Unix.
15//! - **Read-only detection** — when the secrets directory is not writable (e.g.
16//!   the systemd credentials ramfs), missing secrets are a hard error rather than
17//!   triggering key generation.
18
19use anyhow::{anyhow, ensure, Context, Result};
20use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
21use ed25519_dalek::{SigningKey, VerifyingKey};
22use zeroize::{Zeroize, Zeroizing};
23
24use crate::server::tls::TlsMaterials;
25
26// ─── Low-level primitives ───────────────────────────────────────────────────
27
28/// Resolve the credentials/secrets directory via the unified config resolver.
29///
30/// Precedence is `HYPRSTREAM__SECRETS__PATH`, config `[secrets].path`, XDG
31/// `<config_dir>/credentials`, then error. Fails closed — NEVER falls back to a
32/// world-writable `/tmp` path or implicit `/etc` path for a secret-bearing dir.
33pub fn credentials_dir() -> anyhow::Result<std::path::PathBuf> {
34    crate::config::HyprConfig::resolve_secrets_dir()
35}
36
37/// Resolve credentials from an already-loaded config handle.
38///
39/// This is the same resolver family as `credentials_dir()`, but lets CLI paths
40/// that loaded config from `--config` avoid reloading default locations.
41pub fn credentials_dir_for_config(
42    config: Option<&crate::config::HyprConfig>,
43) -> anyhow::Result<std::path::PathBuf> {
44    crate::config::HyprConfig::resolve_secrets_dir_for(config)
45}
46
47/// Read a named secret from `dir`.  Returns `None` if the file does not exist.
48pub fn read_secret(dir: &std::path::Path, name: &str) -> Result<Option<Vec<u8>>> {
49    let path = dir.join(name);
50    match std::fs::read(&path) {
51        Ok(bytes) => Ok(Some(bytes)),
52        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
53        Err(e) => Err(anyhow!("failed to read secret '{}': {}", path.display(), e)),
54    }
55}
56
57/// Write a named secret to `dir` atomically (tempfile + rename).
58///
59/// Creates `dir` with mode 0700 if it does not exist.  The resulting file has
60/// mode 0600.  Returns an error if the directory is not writable.
61///
62/// Uses `NamedTempFile` so the temporary file is automatically removed on any
63/// failure path — no stale `.{name}.tmp` files are left on disk.
64pub fn write_secret(dir: &std::path::Path, name: &str, value: &[u8]) -> Result<()> {
65    write_secret_with_durability(dir, name, value, false)
66}
67
68/// Atomically publish a file and synchronize its data and directory entry.
69///
70/// A returned success is the ordering barrier used before publishing a
71/// composite authority's commit marker. Synchronization errors propagate;
72/// this never treats an atomic rename as evidence of power-loss durability.
73pub(crate) fn write_secret_durable(dir: &std::path::Path, name: &str, value: &[u8]) -> Result<()> {
74    write_secret_with_durability(dir, name, value, true)
75}
76
77/// Re-establish durability for a previously published file before trusting it.
78///
79/// A rename may have succeeded before an earlier directory sync failed. A
80/// retry must synchronize the selected file and directory instead of treating
81/// existence as proof that the earlier publication completed durably.
82pub(crate) fn sync_secret_durable(dir: &std::path::Path, name: &str) -> Result<()> {
83    let file = std::fs::File::open(dir.join(name))
84        .with_context(|| format!("failed to open published secret in '{}'", dir.display()))?;
85    #[cfg(test)]
86    durable_write_test::before(name, durable_write_test::Stage::FileSync)?;
87    file.sync_all().with_context(|| {
88        format!(
89            "failed to synchronize published secret in '{}'",
90            dir.display()
91        )
92    })?;
93    sync_secret_directory(dir, name)
94}
95
96fn sync_secret_directory(dir: &std::path::Path, _name: &str) -> Result<()> {
97    #[cfg(test)]
98    durable_write_test::before(_name, durable_write_test::Stage::DirectorySync)?;
99    std::fs::File::open(dir)
100        .and_then(|directory| directory.sync_all())
101        .with_context(|| format!("failed to synchronize secret directory '{}'", dir.display()))
102}
103
104fn write_secret_with_durability(
105    dir: &std::path::Path,
106    name: &str,
107    value: &[u8],
108    durable: bool,
109) -> Result<()> {
110    use std::io::Write as _;
111    ensure_secrets_dir(dir)?;
112    let path = dir.join(name);
113
114    let mut tmp = tempfile::NamedTempFile::new_in(dir)
115        .with_context(|| format!("failed to create temp file in '{}'", dir.display()))?;
116
117    tmp.write_all(value)
118        .with_context(|| format!("failed to write secret in '{}'", dir.display()))?;
119
120    #[cfg(unix)]
121    {
122        use std::os::unix::fs::PermissionsExt;
123        std::fs::set_permissions(tmp.path(), std::fs::Permissions::from_mode(0o600))
124            .with_context(|| format!("failed to chmod secret in '{}'", dir.display()))?;
125    }
126
127    if durable {
128        #[cfg(test)]
129        durable_write_test::before(name, durable_write_test::Stage::FileSync)?;
130        tmp.as_file().sync_all().with_context(|| {
131            format!("failed to synchronize staged secret in '{}'", dir.display())
132        })?;
133    }
134
135    tmp.persist(&path)
136        .with_context(|| format!("failed to persist secret to '{}'", path.display()))?;
137
138    if durable {
139        sync_secret_directory(dir, name)?;
140    }
141
142    tracing::debug!("wrote secret '{}'", path.display());
143    Ok(())
144}
145
146#[cfg(test)]
147#[allow(clippy::expect_used)]
148pub(crate) mod durable_write_test {
149    use std::cell::RefCell;
150
151    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
152    pub(crate) enum Stage {
153        FileSync,
154        DirectorySync,
155    }
156
157    #[derive(Default)]
158    struct State {
159        fail: Option<(String, Stage)>,
160        events: Vec<(String, Stage)>,
161    }
162
163    thread_local! {
164        static STATE: RefCell<Option<State>> = const { RefCell::new(None) };
165    }
166
167    pub(crate) struct Scope;
168
169    pub(crate) fn install(fail: Option<(String, Stage)>) -> Scope {
170        STATE.with(|state| {
171            assert!(
172                state.borrow().is_none(),
173                "durability fault scope already active"
174            );
175            *state.borrow_mut() = Some(State {
176                fail,
177                events: Vec::new(),
178            });
179        });
180        Scope
181    }
182
183    impl Drop for Scope {
184        fn drop(&mut self) {
185            STATE.with(|state| *state.borrow_mut() = None);
186        }
187    }
188
189    pub(crate) fn before(name: &str, stage: Stage) -> std::io::Result<()> {
190        STATE.with(|state| {
191            if let Some(state) = state.borrow_mut().as_mut() {
192                state.events.push((name.to_owned(), stage));
193                if state
194                    .fail
195                    .as_ref()
196                    .is_some_and(|(file, step)| file == name && *step == stage)
197                {
198                    return Err(std::io::Error::other(
199                        "injected durability synchronization failure",
200                    ));
201                }
202            }
203            Ok(())
204        })
205    }
206
207    pub(crate) fn events() -> Vec<(String, Stage)> {
208        STATE.with(|state| {
209            state
210                .borrow()
211                .as_ref()
212                .expect("active fault scope")
213                .events
214                .clone()
215        })
216    }
217}
218
219/// Write a secret only if the file does not already exist (atomic O_EXCL).
220///
221/// Returns `Ok(true)` if the file was created, `Ok(false)` if it already
222/// existed (another process won the race). This eliminates the TOCTOU race
223/// between checking if a key exists and generating a new one.
224pub fn write_secret_exclusive(dir: &std::path::Path, name: &str, value: &[u8]) -> Result<bool> {
225    use std::io::Write as _;
226    ensure_secrets_dir(dir)?;
227    let path = dir.join(name);
228
229    match std::fs::OpenOptions::new()
230        .write(true)
231        .create_new(true) // O_EXCL — atomic check-and-create
232        .open(&path)
233    {
234        Ok(mut f) => {
235            #[cfg(unix)]
236            {
237                use std::os::unix::fs::PermissionsExt;
238                std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))
239                    .with_context(|| format!("failed to chmod '{}'", path.display()))?;
240            }
241            f.write_all(value)
242                .with_context(|| format!("failed to write secret to '{}'", path.display()))?;
243            tracing::debug!("exclusively wrote secret '{}'", path.display());
244            Ok(true)
245        }
246        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(false),
247        Err(e) => Err(e).with_context(|| format!("failed to create '{}'", path.display())),
248    }
249}
250
251/// Write a named **public** trust artifact to `dir` atomically (tempfile +
252/// rename).
253///
254/// Same atomic-write contract as [`write_secret`], but for non-secret material
255/// (public keys, attestations): the resulting file has mode 0644 so other
256/// local readers (e.g. a credential-mint unit mounting the directory) can
257/// consume it. NEVER pass secret material here.
258pub fn write_public(dir: &std::path::Path, name: &str, value: &[u8]) -> Result<()> {
259    use std::io::Write as _;
260    ensure_secrets_dir(dir)?;
261    let path = dir.join(name);
262
263    let mut tmp = tempfile::NamedTempFile::new_in(dir)
264        .with_context(|| format!("failed to create temp file in '{}'", dir.display()))?;
265
266    tmp.write_all(value)
267        .with_context(|| format!("failed to write public file in '{}'", dir.display()))?;
268
269    #[cfg(unix)]
270    {
271        use std::os::unix::fs::PermissionsExt;
272        std::fs::set_permissions(tmp.path(), std::fs::Permissions::from_mode(0o644))
273            .with_context(|| format!("failed to chmod public file in '{}'", dir.display()))?;
274    }
275
276    tmp.persist(&path)
277        .with_context(|| format!("failed to persist public file to '{}'", path.display()))?;
278
279    tracing::debug!("wrote public file '{}'", path.display());
280    Ok(())
281}
282
283/// Write a public artifact only when it is missing or its content differs.
284///
285/// Keeps re-provisioning and service restarts idempotent: an up-to-date
286/// sidecar is left untouched (no mtime churn, no rewrite).
287fn write_public_if_changed(dir: &std::path::Path, name: &str, value: &[u8]) -> Result<()> {
288    if let Some(existing) = read_secret(dir, name)? {
289        if existing == value {
290            return Ok(());
291        }
292    }
293    write_public(dir, name, value)
294}
295
296/// Returns `true` if `dir` exists and is writable (or can be created).
297///
298/// Uses `tempfile::tempfile_in` so no named probe file is left on disk,
299/// even if the process is killed during the check.
300pub fn is_writable(dir: &std::path::Path) -> bool {
301    if !dir.exists() {
302        return dir.parent().map(is_writable).unwrap_or(false);
303    }
304    tempfile::tempfile_in(dir).is_ok()
305}
306
307/// Ensure the secrets directory exists with mode 0700.
308fn ensure_secrets_dir(dir: &std::path::Path) -> Result<()> {
309    if dir.exists() {
310        return Ok(());
311    }
312    std::fs::create_dir_all(dir)
313        .with_context(|| format!("failed to create secrets directory '{}'", dir.display()))?;
314
315    #[cfg(unix)]
316    {
317        use std::os::unix::fs::PermissionsExt;
318        std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
319            .with_context(|| format!("failed to chmod secrets directory '{}'", dir.display()))?;
320    }
321
322    Ok(())
323}
324
325/// Return a hard error indicating that a required secret is missing from a
326/// read-only credentials directory (e.g. the systemd credentials ramfs).
327fn missing_in_readonly(secrets_dir: &std::path::Path, name: &str) -> anyhow::Error {
328    anyhow!(
329        "Secret '{}' not found in credentials directory '{}'.\n\
330         The directory is not writable, so automatic key generation is not possible.\n\
331         Re-run 'hyprstream service install' to provision credentials.",
332        name,
333        secrets_dir.display()
334    )
335}
336
337// ─── High-level key loaders ─────────────────────────────────────────────────
338
339// ─── Per-service key management ──────────────────────────────────────────────
340
341/// Per-service credential directory layout:
342///
343/// ```text
344/// credentials/
345///   ca-key            # CA private key (policy service only)
346///   ca-pubkey         # CA verifying key (public, all services)
347///   ca-mldsa-pubkey   # CA derived ML-DSA-65 verifying key (public, all services)
348///   {service}/
349///     signing-key     # service's own Ed25519 private key
350///     signing-key.pub # service's Ed25519 verifying key (public sidecar, 0644)
351///     service-pubkey.hybrid  # hybrid bootstrap entry (public sidecar, 0644)
352///     service-jwt     # CA-signed JWT certificate
353///   bootstrap-pubkeys # JSON: { "policy": "base64...", "discovery": "base64..." }
354/// ```
355///
356/// Load or generate an independent Ed25519 signing key for a specific service.
357///
358/// Each service gets its own randomly-generated keypair stored in
359/// `credentials/{service_name}/signing-key`. This is NOT derived from the root
360/// key — it's an independent key that the CA (PolicyService) certifies via a
361/// service JWT.
362///
363/// # Arguments
364///
365/// * `credentials_dir` — Base credentials directory (e.g., `~/.config/hyprstream/credentials`)
366/// * `service_name` — Service name (e.g., "model", "discovery")
367///
368/// Validate a service name for use in filesystem paths.
369///
370/// Rejects names containing path separators, `..`, or characters
371/// outside `[a-z0-9-]`. Prevents directory traversal when service
372/// names are used in path construction.
373pub fn validate_service_name(name: &str) -> Result<()> {
374    if name.is_empty() {
375        anyhow::bail!("service name cannot be empty");
376    }
377    if name.len() > 64 {
378        anyhow::bail!("service name too long (max 64 chars): '{name}'");
379    }
380    if !name
381        .chars()
382        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
383    {
384        anyhow::bail!(
385            "service name '{name}' contains invalid characters; \
386             only lowercase ASCII, digits, and hyphens are allowed"
387        );
388    }
389    if name.starts_with('-') {
390        anyhow::bail!("service name cannot start with a hyphen: '{name}'");
391    }
392    Ok(())
393}
394
395/// File name of the public Ed25519 sidecar written alongside a service's
396/// `signing-key` seed: the raw 32-byte verifying key.
397pub const SIGNING_KEY_PUB_NAME: &str = "signing-key.pub";
398
399/// File name of the public hybrid (Ed25519 ‖ ML-DSA-65) sidecar written
400/// alongside a service's `signing-key` seed.
401///
402/// Contents are exactly the service's 1984-byte `bootstrap-pubkeys` entry
403/// value (see `docs/bootstrap-pubkeys-format.md`), so a bootstrap-enrollment
404/// mint can consume it without ever touching secret material — the ML-DSA-65
405/// half is derived from the Ed25519 seed and cannot be recomputed from a
406/// public key alone.
407pub const SERVICE_PUBKEY_HYBRID_NAME: &str = "service-pubkey.hybrid";
408
409/// The directory holding `service_name`'s signing key under `secrets_dir` for
410/// the given profile.
411///
412/// Mirrors [`resolve_service_signing_key`]'s file layout: "policy" and any
413/// per-service-scoped directory use the flat layout, everything else gets a
414/// `{service_name}/` subdirectory.
415pub fn service_signing_key_dir(
416    secrets_dir: &std::path::Path,
417    service_name: &str,
418    profile: SecretsProfile,
419) -> std::path::PathBuf {
420    match (profile, service_name) {
421        (_, "policy") | (SecretsProfile::PerServiceScoped, _) => secrets_dir.to_path_buf(),
422        (SecretsProfile::SharedDirectory, _) => secrets_dir.join(service_name),
423    }
424}
425
426/// Write the public sidecars for a service signing key next to its seed:
427///
428/// - [`SIGNING_KEY_PUB_NAME`] — the 32-byte Ed25519 verifying key.
429/// - [`SERVICE_PUBKEY_HYBRID_NAME`] — the 1984-byte hybrid `bootstrap-pubkeys`
430///   entry (Ed25519 ‖ derived ML-DSA-65) for bootstrap enrollment.
431///
432/// Both are public trust material (mode 0644) derived from the key's public
433/// half only; the seed never appears in either. Idempotent: a sidecar whose
434/// content already matches is left untouched.
435pub fn ensure_service_key_sidecars(
436    service_dir: &std::path::Path,
437    service_key: &SigningKey,
438) -> Result<()> {
439    write_public_if_changed(
440        service_dir,
441        SIGNING_KEY_PUB_NAME,
442        service_key.verifying_key().as_bytes(),
443    )?;
444    let hybrid = BootstrapPubkey::for_service_key(service_key)?.to_key_bytes();
445    write_public_if_changed(service_dir, SERVICE_PUBKEY_HYBRID_NAME, &hybrid)?;
446    Ok(())
447}
448
449/// Best-effort sidecar write from the key loader.
450///
451/// Never fails key loading over a public sidecar (e.g. on a read-only
452/// credentials mount): the sidecar is backfilled on every writable load and
453/// by `hyprstream service ensure-key`.
454fn backfill_service_key_sidecars(
455    service_dir: &std::path::Path,
456    service_name: &str,
457    service_key: &SigningKey,
458) {
459    if let Err(e) = ensure_service_key_sidecars(service_dir, service_key) {
460        tracing::warn!("could not write public key sidecars for service '{service_name}': {e:#}");
461    }
462}
463
464pub fn load_or_generate_service_signing_key(
465    credentials_dir: &std::path::Path,
466    service_name: &str,
467) -> Result<SigningKey> {
468    validate_service_name(service_name)?;
469    let service_dir = credentials_dir.join(service_name);
470    const NAME: &str = "signing-key";
471
472    if let Some(mut bytes) = read_secret(&service_dir, NAME)? {
473        let mut arr: [u8; 32] = bytes.as_slice().try_into().map_err(|_| {
474            anyhow!("service '{service_name}' signing-key must be 32 bytes (Ed25519 seed)")
475        })?;
476        let sk = SigningKey::from_bytes(&arr);
477        bytes.zeroize();
478        arr.zeroize();
479        // Backfill the public sidecars for pre-existing seeds (written on
480        // generate below, but a seed written by an older version has none).
481        backfill_service_key_sidecars(&service_dir, service_name, &sk);
482        tracing::info!("Loaded Ed25519 signing key for service '{service_name}'");
483        return Ok(sk);
484    }
485
486    if !is_writable(&service_dir) && !is_writable(credentials_dir) {
487        return Err(missing_in_readonly(&service_dir, NAME));
488    }
489
490    let key = SigningKey::generate(&mut rand::rngs::OsRng);
491    let mut raw = key.to_bytes();
492    match write_secret_exclusive(&service_dir, NAME, &raw) {
493        Ok(true) => {
494            raw.zeroize();
495            backfill_service_key_sidecars(&service_dir, service_name, &key);
496            tracing::info!("Generated new Ed25519 signing key for service '{service_name}'");
497            Ok(key)
498        }
499        Ok(false) => {
500            // Another process won the race — reload their key
501            raw.zeroize();
502            tracing::info!("Key for '{service_name}' created by another process — reloading");
503            // Re-read (not recursive — file now exists)
504            let mut bytes = read_secret(&service_dir, NAME)?
505                .ok_or_else(|| anyhow!("race loser: key file disappeared"))?;
506            let mut arr: [u8; 32] = bytes
507                .as_slice()
508                .try_into()
509                .map_err(|_| anyhow!("service '{service_name}' signing-key must be 32 bytes"))?;
510            let sk = SigningKey::from_bytes(&arr);
511            bytes.zeroize();
512            arr.zeroize();
513            backfill_service_key_sidecars(&service_dir, service_name, &sk);
514            Ok(sk)
515        }
516        Err(e) => {
517            raw.zeroize();
518            Err(e)
519        }
520    }
521}
522
523/// Load the CA signing key (PolicyService only).
524///
525/// The CA key is the PolicyService's own signing key — it signs service JWTs
526/// that bind service names to their Ed25519 pubkeys.
527pub fn load_ca_signing_key(credentials_dir: &std::path::Path) -> Result<SigningKey> {
528    const NAME: &str = "ca-key";
529    if let Some(mut bytes) = read_secret(credentials_dir, NAME)? {
530        let mut arr: [u8; 32] = bytes
531            .as_slice()
532            .try_into()
533            .map_err(|_| anyhow!("ca-key must be 32 bytes (Ed25519 seed)"))?;
534        let sk = SigningKey::from_bytes(&arr);
535        bytes.zeroize();
536        arr.zeroize();
537        tracing::info!("Loaded CA signing key");
538        return Ok(sk);
539    }
540    Err(missing_in_readonly(credentials_dir, NAME))
541}
542
543/// Write the CA signing key to the credentials directory.
544///
545/// Used during wizard bootstrap to persist the generated CA key.
546pub fn write_ca_signing_key(credentials_dir: &std::path::Path, key: &SigningKey) -> Result<()> {
547    write_secret(credentials_dir, "ca-key", &key.to_bytes())
548}
549
550/// Load the CA verifying key (public, distributed to all services).
551///
552/// This is the trust anchor for verifying service JWTs.
553pub fn load_ca_verifying_key(credentials_dir: &std::path::Path) -> Result<VerifyingKey> {
554    const NAME: &str = "ca-pubkey";
555    if let Some(bytes) = read_secret(credentials_dir, NAME)? {
556        let arr: [u8; 32] = bytes
557            .as_slice()
558            .try_into()
559            .map_err(|_| anyhow!("ca-pubkey must be 32 bytes (Ed25519 pubkey)"))?;
560        VerifyingKey::from_bytes(&arr).map_err(|e| anyhow!("invalid ca-pubkey: {e}"))
561    } else {
562        Err(missing_in_readonly(credentials_dir, NAME))
563    }
564}
565
566/// Write the CA verifying key to the credentials directory.
567pub fn write_ca_verifying_key(credentials_dir: &std::path::Path, key: &VerifyingKey) -> Result<()> {
568    write_secret(credentials_dir, "ca-pubkey", key.as_bytes())
569}
570
571/// Load the CA's derived ML-DSA-65 verifying key (public, distributed to all
572/// services).
573///
574/// This is the post-quantum half of the CA JWT composite pair: the CA signs
575/// hybrid service WITs with `(derive_mesh_mldsa_key(ca_jwt_key), ca_jwt_key)`,
576/// and verifiers resolve the composite kid to this key plus `ca-pubkey`.
577pub fn load_ca_ml_dsa_verifying_key(
578    credentials_dir: &std::path::Path,
579) -> Result<hyprstream_rpc::crypto::pq::MlDsaVerifyingKey> {
580    const NAME: &str = "ca-mldsa-pubkey";
581    if let Some(bytes) = read_secret(credentials_dir, NAME)? {
582        hyprstream_rpc::crypto::pq::ml_dsa_vk_from_bytes(&bytes)
583            .map_err(|e| anyhow!("invalid ca-mldsa-pubkey: {e}"))
584    } else {
585        Err(missing_in_readonly(credentials_dir, NAME))
586    }
587}
588
589/// Write the CA's derived ML-DSA-65 verifying key to the credentials directory.
590pub fn write_ca_ml_dsa_verifying_key(
591    credentials_dir: &std::path::Path,
592    key: &hyprstream_rpc::crypto::pq::MlDsaVerifyingKey,
593) -> Result<()> {
594    write_secret(
595        credentials_dir,
596        "ca-mldsa-pubkey",
597        &hyprstream_rpc::crypto::pq::ml_dsa_vk_bytes(key),
598    )
599}
600
601fn provisioned_service_jwt_dir(
602    credentials_dir: &std::path::Path,
603    service_name: &str,
604    profile: SecretsProfile,
605) -> std::path::PathBuf {
606    match profile {
607        SecretsProfile::SharedDirectory => credentials_dir.join(service_name),
608        SecretsProfile::PerServiceScoped => credentials_dir.to_path_buf(),
609    }
610}
611
612fn writable_service_jwt_dir(
613    credentials_dir: &std::path::Path,
614    service_name: &str,
615    profile: SecretsProfile,
616) -> std::path::PathBuf {
617    let state_dir = super::key_rotation::rotation_state_dir(credentials_dir);
618    if profile == SecretsProfile::PerServiceScoped && state_dir == credentials_dir {
619        state_dir
620    } else {
621        // `$STATE_DIRECTORY` is shared by the generated service units, so the
622        // writable fallback must retain a service-name component even when the
623        // read-only systemd credential directory was already service-scoped.
624        state_dir.join(service_name)
625    }
626}
627
628/// Load a service JWT using the active credential layout.
629///
630/// Renewed state is preferred. When a read-only credential provider caused
631/// writes to fall back to `$STATE_DIRECTORY`/XDG state, the originally
632/// provisioned credential remains the first-boot fallback.
633pub fn load_service_jwt_for_profile(
634    credentials_dir: &std::path::Path,
635    service_name: &str,
636    profile: SecretsProfile,
637) -> Result<Option<String>> {
638    validate_service_name(service_name)?;
639    let state_dir = writable_service_jwt_dir(credentials_dir, service_name, profile);
640    let provisioned_dir = provisioned_service_jwt_dir(credentials_dir, service_name, profile);
641    let bytes = match read_secret(&state_dir, "service-jwt")? {
642        Some(bytes) => Some(bytes),
643        None if state_dir != provisioned_dir => read_secret(&provisioned_dir, "service-jwt")?,
644        None => None,
645    };
646    match bytes {
647        Some(bytes) => {
648            let jwt = String::from_utf8(bytes).context("service-jwt is not valid UTF-8")?;
649            Ok(Some(jwt))
650        }
651        None => Ok(None),
652    }
653}
654
655/// Seed a provisioned service JWT under the key selected by startup.
656///
657/// Service factories first consult the process trust store. Keeping this
658/// bridge beside the profile-aware loader lets a caller that already resolved
659/// a custom config path carry the authoritative JWT into a factory that has no
660/// config handle of its own.
661pub fn seed_service_jwt_into_trust_store(
662    service_name: &str,
663    signing_key: &SigningKey,
664    credentials_dir: &std::path::Path,
665    profile: SecretsProfile,
666) {
667    if let Ok(Some(jwt_str)) = load_service_jwt_for_profile(credentials_dir, service_name, profile)
668    {
669        let expires_at = decode_jwt_exp_raw(&jwt_str).unwrap_or(0);
670        hyprstream_service::global_trust_store().insert(
671            signing_key.verifying_key(),
672            hyprstream_service::Attestation {
673                scopes: std::iter::once(service_name.to_owned()).collect(),
674                subject: None,
675                jwt: Some(jwt_str),
676                expires_at,
677                attested_by: None,
678            },
679        );
680        tracing::info!(service = %service_name, "Seeded trust store with own service-jwt from credential dir");
681    }
682}
683
684/// Persist a service JWT using the same profile-aware path startup reads.
685pub fn write_service_jwt_for_profile(
686    credentials_dir: &std::path::Path,
687    service_name: &str,
688    profile: SecretsProfile,
689    jwt: &str,
690) -> Result<()> {
691    validate_service_name(service_name)?;
692    let state_dir = writable_service_jwt_dir(credentials_dir, service_name, profile);
693    write_secret(&state_dir, "service-jwt", jwt.as_bytes())
694}
695
696/// Load a service JWT from the shared-directory credential layout.
697pub fn load_service_jwt(
698    credentials_dir: &std::path::Path,
699    service_name: &str,
700) -> Result<Option<String>> {
701    load_service_jwt_for_profile(
702        credentials_dir,
703        service_name,
704        SecretsProfile::SharedDirectory,
705    )
706}
707
708/// Write a service JWT to the shared-directory credential layout.
709pub fn write_service_jwt(
710    credentials_dir: &std::path::Path,
711    service_name: &str,
712    jwt: &str,
713) -> Result<()> {
714    write_service_jwt_for_profile(
715        credentials_dir,
716        service_name,
717        SecretsProfile::SharedDirectory,
718        jwt,
719    )
720}
721
722/// Bootstrap pubkeys — the pubkeys of services needed before discovery is available.
723///
724/// Contains the pubkeys of PolicyService and DiscoveryService, which must be
725/// known to all services so they can verify RPC responses from these bootstrap
726/// services without querying discovery (chicken-and-egg).
727///
728/// Wire format (see `docs/bootstrap-pubkeys-format.md`): a flat JSON object
729/// `{ "<service>": "<base64>" }`, base64 using the URL-safe-no-pad alphabet
730/// (RFC 4648 §5, no `+`/`/`/`=`). Each value decodes either to 32 raw Ed25519
731/// bytes (classical entry) or to 1984 bytes — 32 Ed25519 followed by 1952
732/// ML-DSA-65 — for a hybrid entry, the same concatenation the deployment CA
733/// root uses.
734///
735/// This projection returns only the Ed25519 anchor of each entry, so callers
736/// that predate hybrid entries keep working unchanged. Callers that need the
737/// bound post-quantum key use [`load_bootstrap_pubkeys_hybrid`].
738pub fn load_bootstrap_pubkeys(
739    credentials_dir: &std::path::Path,
740) -> Result<std::collections::HashMap<String, VerifyingKey>> {
741    Ok(load_bootstrap_pubkeys_hybrid(credentials_dir)?
742        .into_iter()
743        .map(|(name, entry)| (name, entry.ed25519))
744        .collect())
745}
746
747/// Write bootstrap pubkeys to the credentials directory.
748///
749/// Every entry is written in the classical 32-byte form. Use
750/// [`write_bootstrap_pubkeys_hybrid`] to persist entries that carry a bound
751/// ML-DSA-65 key.
752pub fn write_bootstrap_pubkeys(
753    credentials_dir: &std::path::Path,
754    pubkeys: &std::collections::HashMap<String, VerifyingKey>,
755) -> Result<()> {
756    let hybrid: std::collections::HashMap<String, BootstrapPubkey> = pubkeys
757        .iter()
758        .map(|(name, vk)| (name.clone(), BootstrapPubkey::classical(*vk)))
759        .collect();
760    write_bootstrap_pubkeys_hybrid(credentials_dir, &hybrid)
761}
762
763// ─── Hybrid bootstrap entries ────────────────────────────────────────────────
764
765/// Length of a raw Ed25519 verifying key.
766const BOOTSTRAP_ED25519_BYTES: usize = 32;
767/// Length of a raw ML-DSA-65 verifying key.
768const BOOTSTRAP_ML_DSA_65_BYTES: usize = 1952;
769/// Length of the concatenated hybrid form (Ed25519 ‖ ML-DSA-65).
770const BOOTSTRAP_HYBRID_BYTES: usize = BOOTSTRAP_ED25519_BYTES + BOOTSTRAP_ML_DSA_65_BYTES;
771
772/// The on-disk file name of the bootstrap pubkeys seed.
773const BOOTSTRAP_PUBKEYS_NAME: &str = "bootstrap-pubkeys";
774
775/// One `bootstrap-pubkeys` entry: the Ed25519 anchor plus an optional bound
776/// ML-DSA-65 verifying key.
777///
778/// The Ed25519 key is always the identity of the entry — the post-quantum key
779/// is bound *to* it, mirroring the user identity and deployment-CA layouts.
780/// Verification is per-identity: an entry that carries no PQ key verifies
781/// classically, an entry that carries one requires both signatures.
782#[derive(Clone, Debug)]
783pub struct BootstrapPubkey {
784    pub ed25519: VerifyingKey,
785    pub ml_dsa_65: Option<hyprstream_rpc::crypto::pq::MlDsaVerifyingKey>,
786}
787
788impl BootstrapPubkey {
789    /// A classical (Ed25519-only) entry.
790    pub fn classical(ed25519: VerifyingKey) -> Self {
791        Self {
792            ed25519,
793            ml_dsa_65: None,
794        }
795    }
796
797    /// A hybrid entry binding an ML-DSA-65 key to an Ed25519 anchor.
798    pub fn hybrid(
799        ed25519: VerifyingKey,
800        ml_dsa_65: hyprstream_rpc::crypto::pq::MlDsaVerifyingKey,
801    ) -> Self {
802        Self {
803            ed25519,
804            ml_dsa_65: Some(ml_dsa_65),
805        }
806    }
807
808    /// The hybrid entry for a service that signs with `service_key`.
809    ///
810    /// The ML-DSA-65 half is DERIVED from the service's Ed25519 key with
811    /// [`hyprstream_rpc::node_identity::derive_mesh_mldsa_key`] rather than
812    /// generated independently. That is not merely convenient — it is required
813    /// for the entry to be usable: every signer in the tree (the local signer,
814    /// the service dispatch default, the published `#mesh-pq` verification
815    /// method) produces its post-quantum signature from exactly that
816    /// derivation, so an independently generated key would anchor a public key
817    /// nothing ever signs with. It also keeps the service's secret material a
818    /// single Ed25519 seed — nothing new to persist, protect, back up or
819    /// rotate.
820    pub fn for_service_key(service_key: &SigningKey) -> Result<Self> {
821        let pq_sk = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(service_key);
822        let pq_vk_bytes = hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk_bytes(&pq_sk);
823        let pq_vk = hyprstream_rpc::crypto::pq::ml_dsa_vk_from_bytes(&pq_vk_bytes)
824            .context("derived mesh ML-DSA-65 verifying key is malformed")?;
825        Ok(Self::hybrid(service_key.verifying_key(), pq_vk))
826    }
827
828    /// Whether this entry carries a bound post-quantum key.
829    pub fn is_hybrid(&self) -> bool {
830        self.ml_dsa_65.is_some()
831    }
832
833    /// The canonical byte encoding: the 32 raw Ed25519 bytes, followed by the
834    /// 1952 raw ML-DSA-65 bytes when the entry is hybrid.
835    pub fn to_key_bytes(&self) -> Vec<u8> {
836        let mut out = Vec::with_capacity(if self.is_hybrid() {
837            BOOTSTRAP_HYBRID_BYTES
838        } else {
839            BOOTSTRAP_ED25519_BYTES
840        });
841        out.extend_from_slice(self.ed25519.as_bytes());
842        if let Some(pq) = &self.ml_dsa_65 {
843            out.extend_from_slice(&hyprstream_rpc::crypto::pq::ml_dsa_vk_bytes(pq));
844        }
845        out
846    }
847
848    /// Decode the canonical byte encoding, discriminating on length.
849    ///
850    /// `service` names the entry only so the error text is actionable.
851    pub fn from_key_bytes(service: &str, bytes: &[u8]) -> Result<Self> {
852        let (ed_bytes, pq_bytes) = match bytes.len() {
853            BOOTSTRAP_ED25519_BYTES => (bytes, None),
854            BOOTSTRAP_HYBRID_BYTES => {
855                let (ed, pq) = bytes.split_at(BOOTSTRAP_ED25519_BYTES);
856                (ed, Some(pq))
857            }
858            other => {
859                return Err(anyhow!(
860                    "bootstrap-pubkey for '{service}' must decode to either \
861                     {BOOTSTRAP_ED25519_BYTES} bytes (raw Ed25519 verifying key) or \
862                     {BOOTSTRAP_HYBRID_BYTES} bytes (32-byte Ed25519 followed by \
863                     {BOOTSTRAP_ML_DSA_65_BYTES}-byte ML-DSA-65 verifying key); \
864                     got {other} bytes"
865                ))
866            }
867        };
868
869        let arr: [u8; BOOTSTRAP_ED25519_BYTES] = ed_bytes.try_into().map_err(|_| {
870            anyhow!("bootstrap-pubkey for '{service}' has a malformed Ed25519 part")
871        })?;
872        let ed25519 = VerifyingKey::from_bytes(&arr)
873            .map_err(|e| anyhow!("invalid bootstrap-pubkey for '{service}': {e}"))?;
874
875        let ml_dsa_65 = match pq_bytes {
876            Some(pq) => Some(
877                hyprstream_rpc::crypto::pq::ml_dsa_vk_from_bytes(pq).map_err(|e| {
878                    anyhow!("bootstrap-pubkey for '{service}' has a malformed ML-DSA-65 part: {e}")
879                })?,
880            ),
881            None => None,
882        };
883
884        Ok(Self { ed25519, ml_dsa_65 })
885    }
886
887    /// Verify a signature over `message` under this entry's per-identity policy.
888    ///
889    /// - Classical entry: the Ed25519 signature must verify. A post-quantum
890    ///   signature cannot be checked against an entry with no bound PQ key, so
891    ///   supplying one is an error rather than a silently ignored input.
892    /// - Hybrid entry: **both** the Ed25519 and the ML-DSA-65 signature must be
893    ///   present and verify.
894    ///
895    /// Post-quantum verification is never demanded of an entry that does not
896    /// carry a post-quantum key — a classical entry keeps its classical floor.
897    pub fn verify(
898        &self,
899        message: &[u8],
900        ed25519_sig: &ed25519_dalek::Signature,
901        ml_dsa_65_sig: Option<&[u8]>,
902    ) -> Result<()> {
903        use ed25519_dalek::Verifier;
904
905        self.ed25519
906            .verify(message, ed25519_sig)
907            .map_err(|e| anyhow!("Ed25519 signature verification failed: {e}"))?;
908
909        match (&self.ml_dsa_65, ml_dsa_65_sig) {
910            (Some(pq_key), Some(sig)) => {
911                hyprstream_rpc::crypto::pq::ml_dsa_verify(pq_key, message, sig)
912            }
913            (Some(_), None) => Err(anyhow!(
914                "this bootstrap key is hybrid (Ed25519 + ML-DSA-65) but no ML-DSA-65 \
915                 signature was supplied; both signatures are required"
916            )),
917            (None, Some(_)) => Err(anyhow!(
918                "an ML-DSA-65 signature was supplied but this bootstrap key is \
919                 Ed25519-only, so the signature cannot be verified; re-provision the \
920                 entry in its 1984-byte hybrid form to enable post-quantum verification"
921            )),
922            (None, None) => Ok(()),
923        }
924    }
925}
926
927/// Load bootstrap pubkeys, preserving any bound post-quantum key material.
928///
929/// Accepts both the classical (32-byte value) and the hybrid (1984-byte value)
930/// form in the same file; the two are distinguished by decoded length. Files
931/// written before hybrid entries existed load unchanged.
932pub fn load_bootstrap_pubkeys_hybrid(
933    credentials_dir: &std::path::Path,
934) -> Result<std::collections::HashMap<String, BootstrapPubkey>> {
935    let Some(bytes) = read_secret(credentials_dir, BOOTSTRAP_PUBKEYS_NAME)? else {
936        return Ok(std::collections::HashMap::new());
937    };
938
939    let json: std::collections::HashMap<String, String> = serde_json::from_slice(&bytes).context(
940        "bootstrap-pubkeys is not valid JSON: expected a flat object \
941         `{ \"<service>\": \"<base64>\" }` (see docs/bootstrap-pubkeys-format.md)",
942    )?;
943
944    let mut map = std::collections::HashMap::new();
945    let mut classical_only = Vec::new();
946    for (name, b64) in json {
947        let key_bytes: Vec<u8> = URL_SAFE_NO_PAD.decode(&b64).with_context(|| {
948            format!(
949                "invalid base64 in bootstrap-pubkeys for '{name}': expected \
950                 URL-safe-no-pad alphabet (RFC 4648 §5, no '+'/'/'/'='), got {b64:?}"
951            )
952        })?;
953        let entry = BootstrapPubkey::from_key_bytes(&name, &key_bytes)?;
954        if !entry.is_hybrid() {
955            classical_only.push(name.clone());
956        }
957        map.insert(name, entry);
958    }
959
960    if !classical_only.is_empty() {
961        classical_only.sort();
962        tracing::debug!(
963            services = %classical_only.join(", "),
964            "bootstrap-pubkeys entries are Ed25519-only; they verify classically \
965             until re-provisioned with a bound ML-DSA-65 key"
966        );
967    }
968
969    Ok(map)
970}
971
972/// Reject a `bootstrap-pubkeys` map that still carries Ed25519-only service
973/// entries.
974///
975/// Every service this node provisions gets a bound ML-DSA-65 key: there is no
976/// classical-only install path, so a classical entry here is stale material
977/// from a pre-hybrid provisioning run, not a supported configuration. Left
978/// alone it does not degrade gracefully — the service is simply never anchored
979/// in the post-quantum trust store, and its RPC is later refused with an
980/// opaque "no anchored ML-DSA-65 signer key" at verification time. Failing
981/// here converts that into an actionable provisioning error.
982///
983/// Deliberately NOT enforced inside [`load_bootstrap_pubkeys_hybrid`]: the
984/// low-level loader must stay able to read a legacy file so tooling — and this
985/// error itself — can report precisely which entries are stale.
986pub fn ensure_bootstrap_pubkeys_hybrid(
987    entries: &std::collections::HashMap<String, BootstrapPubkey>,
988) -> Result<()> {
989    let mut classical: Vec<&str> = entries
990        .iter()
991        .filter(|(_, entry)| !entry.is_hybrid())
992        .map(|(name, _)| name.as_str())
993        .collect();
994    if classical.is_empty() {
995        return Ok(());
996    }
997    classical.sort_unstable();
998    Err(anyhow!(
999        "bootstrap-pubkeys has Ed25519-only entries for service(s): {}. Service \
1000         identities must be hybrid (Ed25519 + ML-DSA-65); these were written by a \
1001         pre-hybrid provisioning run and cannot be anchored for post-quantum \
1002         verification. Re-provision this node by running 'hyprstream wizard' — \
1003         it re-provisions in place, preserving existing keys while binding the \
1004         ML-DSA-65 half for every service — to rewrite {BOOTSTRAP_PUBKEYS_NAME}.",
1005        classical.join(", ")
1006    ))
1007}
1008
1009/// Write bootstrap pubkeys, encoding hybrid entries in their concatenated form.
1010///
1011/// Classical entries are written exactly as the pre-hybrid writer wrote them, so
1012/// a file round-trips byte-for-byte when no entry carries a PQ key.
1013pub fn write_bootstrap_pubkeys_hybrid(
1014    credentials_dir: &std::path::Path,
1015    pubkeys: &std::collections::HashMap<String, BootstrapPubkey>,
1016) -> Result<()> {
1017    let json: std::collections::HashMap<String, String> = pubkeys
1018        .iter()
1019        .map(|(name, entry)| (name.clone(), URL_SAFE_NO_PAD.encode(entry.to_key_bytes())))
1020        .collect();
1021    let data = serde_json::to_vec(&json).context("failed to serialize bootstrap-pubkeys")?;
1022    write_secret(credentials_dir, BOOTSTRAP_PUBKEYS_NAME, &data)
1023}
1024
1025/// Directory sibling to `bootstrap-pubkeys` holding the per-service chain-signed
1026/// enrollment attestations (hyprstream#1562 H3): `{service}.json` per
1027/// allowlisted service.
1028pub const BOOTSTRAP_PUBKEYS_ENROLLMENT_DIR: &str = "bootstrap-pubkeys.enrollment";
1029
1030/// Fail-closed enrollment check for OS-owned deployments (hyprstream#1562 H3).
1031///
1032/// Every bootstrap entry for a service in the fixed enrollment allowlist
1033/// (`hyprstream_discovery::SERVICE_KEY_ENROLLMENT_ALLOWED_SERVICES`) must be
1034/// backed by an attestation in
1035/// `{credentials_dir}/bootstrap-pubkeys.enrollment/{service}.json` that
1036/// verifies against the node's OS-owned deployment trust chain and names
1037/// exactly this entry's hybrid key — the unsigned-TOFU posture is refused.
1038/// Missing, malformed, expired, or mismatched attestations are fatal. Entries
1039/// outside the allowlist cannot be enrolled by design and keep their existing
1040/// local posture. Wizard/dev (non-OsOwnedFiles) deployments never call this.
1041pub fn ensure_bootstrap_pubkeys_enrolled(
1042    credentials_dir: &std::path::Path,
1043    entries: &std::collections::HashMap<String, BootstrapPubkey>,
1044) -> Result<()> {
1045    let mut names: Vec<&str> = entries.keys().map(String::as_str).collect();
1046    names.sort_unstable();
1047    for name in names {
1048        if !hyprstream_discovery::SERVICE_KEY_ENROLLMENT_ALLOWED_SERVICES.contains(&name) {
1049            continue;
1050        }
1051        let path = credentials_dir
1052            .join(BOOTSTRAP_PUBKEYS_ENROLLMENT_DIR)
1053            .join(format!("{name}.json"));
1054        let bytes = std::fs::read(&path).map_err(|error| {
1055            anyhow!(
1056                "OS-owned deployment requires a chain-signed enrollment attestation for \
1057                 service '{name}' at {}: {error} (re-run the service-key enrollment \
1058                 provisioning step)",
1059                path.display()
1060            )
1061        })?;
1062        let verified = hyprstream_discovery::verify_os_owned_service_key_enrollment(&bytes)
1063            .with_context(|| format!("enrollment attestation for service '{name}' rejected"))?;
1064        ensure!(
1065            verified.service == name,
1066            "enrollment attestation at {} is for service '{}', not '{name}'",
1067            path.display(),
1068            verified.service
1069        );
1070        let entry = &entries[name];
1071        ensure!(
1072            entry.is_hybrid() && verified.hybrid_public_key == entry.to_key_bytes(),
1073            "enrollment attestation for service '{name}' does not match its \
1074             bootstrap-pubkeys entry"
1075        );
1076    }
1077    Ok(())
1078}
1079
1080// ─── Node-level key loaders ──────────────────────────────────────────────────
1081
1082/// Load or generate the Ed25519 **node** signing key (the root-of-trust key
1083/// that identifies this Hyprstream instance).
1084///
1085/// Callers **must** check `HyprConfig::node_signing_key_bypass()` before
1086/// calling this. This function is pure file I/O with no config awareness.
1087///
1088/// 1. Read `secrets_dir/signing-key` → return if present.
1089/// 2. If writable: generate new key, write, return.
1090/// 3. If read-only and missing: hard error.
1091pub fn load_or_generate_node_signing_key(secrets_dir: &std::path::Path) -> Result<SigningKey> {
1092    const NAME: &str = "signing-key";
1093
1094    if let Some(mut bytes) = read_secret(secrets_dir, NAME)? {
1095        let mut arr: [u8; 32] = bytes
1096            .as_slice()
1097            .try_into()
1098            .map_err(|_| anyhow!("secret '{}' must be 32 bytes (Ed25519 seed)", NAME))?;
1099        let sk = SigningKey::from_bytes(&arr);
1100        bytes.zeroize();
1101        arr.zeroize();
1102        tracing::info!(
1103            "Loaded Ed25519 signing key from '{}'",
1104            secrets_dir.display()
1105        );
1106        return Ok(sk);
1107    }
1108
1109    if !is_writable(secrets_dir) {
1110        return Err(missing_in_readonly(secrets_dir, NAME));
1111    }
1112
1113    let key = SigningKey::generate(&mut rand::rngs::OsRng);
1114    let mut raw = key.to_bytes();
1115    let result = write_secret(secrets_dir, NAME, &raw);
1116    raw.zeroize();
1117    result?;
1118    tracing::info!(
1119        "Generated new Ed25519 signing key → '{}/{}'",
1120        secrets_dir.display(),
1121        NAME
1122    );
1123    Ok(key)
1124}
1125
1126/// Describes how a service's credentials directory is scoped.
1127///
1128/// This is deliberately about directory layout rather than a particular
1129/// process manager. Both systemd `LoadCredential` directories and projected
1130/// Kubernetes Secret/CSI volumes can present a directory already scoped to a
1131/// single service, while standalone multi-process deployments share one
1132/// writable directory among services.
1133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1134pub enum SecretsProfile {
1135    /// One base directory is shared by all services; non-policy credentials
1136    /// live under a `{service_name}/` subdirectory.
1137    SharedDirectory,
1138    /// The provider has already scoped the directory to one service, so its
1139    /// credentials use flat names such as `signing-key`.
1140    PerServiceScoped,
1141}
1142
1143/// Explicit deployment signal for credential-directory layout.
1144///
1145/// The path override is deliberately separate: setting
1146/// `HYPRSTREAM__SECRETS__PATH` alone does not prove that a provider has already
1147/// scoped the directory to one service.
1148pub const SECRETS_PROFILE_ENV: &str = "HYPRSTREAM_SECRETS_PROFILE";
1149
1150impl SecretsProfile {
1151    pub fn from_env() -> Result<Self> {
1152        match std::env::var(SECRETS_PROFILE_ENV) {
1153            Err(std::env::VarError::NotPresent) => Ok(Self::SharedDirectory),
1154            Ok(value) if value == "shared-directory" => Ok(Self::SharedDirectory),
1155            Ok(value) if value == "per-service-scoped" => Ok(Self::PerServiceScoped),
1156            Ok(value) => Err(anyhow!(
1157                "{SECRETS_PROFILE_ENV} must be 'shared-directory' or \
1158                 'per-service-scoped', got {value:?}"
1159            )),
1160            Err(error) => Err(anyhow!(
1161                "{SECRETS_PROFILE_ENV} is not valid Unicode: {error}"
1162            )),
1163        }
1164    }
1165}
1166
1167/// Resolve the Ed25519 signing key a service process should use to sign its
1168/// own RPC responses in `--ipc` (multi-process) deployment.
1169///
1170/// # PolicyService is special
1171///
1172/// PolicyService's identity IS the root/CA key, not an independent
1173/// per-service key: `bootstrap_manager::do_bootstrap` registers
1174/// `bootstrap_pubkeys["policy"] = root_key.verifying_key()` (the same value
1175/// persisted flat at `secrets_dir/signing-key`), rather than generating a
1176/// `secrets_dir/policy/signing-key` like every other service gets.
1177///
1178/// Resolving "policy" via the generic per-service path
1179/// (`load_or_generate_service_signing_key`) reads/generates a *different*
1180/// file (`{secrets_dir}/policy/signing-key`) that bootstrap never populated —
1181/// so on first `--ipc` startup it silently mints a fresh, unrelated key. Every
1182/// peer that resolves "policy" from the trust store (seeded from
1183/// `bootstrap-pubkeys`) still expects `root_key.verifying_key()`, so
1184/// PolicyService's actual responses fail verification with "Response signed
1185/// by unexpected key" (#759) — a sibling gap to the CA-derivation fallback
1186/// #441 already removed from `resolve_service_key`.
1187///
1188/// - [`SecretsProfile::PerServiceScoped`]: the credential provider already
1189///   scopes `secrets_dir` to that one service, so the flat top-level file is
1190///   correct for every service, policy included.
1191/// - [`SecretsProfile::SharedDirectory`]: `secrets_dir` is shared across every
1192///   spawned service process, so non-policy services use a `{service_name}/`
1193///   subdirectory to avoid collisions — but policy must still resolve to the
1194///   flat root/CA key, matching what bootstrap registered.
1195pub fn resolve_service_signing_key(
1196    secrets_dir: &std::path::Path,
1197    service_name: &str,
1198    profile: SecretsProfile,
1199) -> Result<SigningKey> {
1200    match (profile, service_name) {
1201        (_, "policy") | (SecretsProfile::PerServiceScoped, _) => {
1202            load_or_generate_node_signing_key(secrets_dir)
1203        }
1204        (SecretsProfile::SharedDirectory, _) => {
1205            load_or_generate_service_signing_key(secrets_dir, service_name)
1206        }
1207    }
1208}
1209
1210/// Load a provisioned service identity without ever generating a replacement.
1211pub fn load_existing_service_signing_key(
1212    secrets_dir: &std::path::Path,
1213    service_name: &str,
1214    profile: SecretsProfile,
1215) -> Result<SigningKey> {
1216    validate_service_name(service_name)?;
1217    let directory = match (profile, service_name) {
1218        (_, "policy") | (SecretsProfile::PerServiceScoped, _) => secrets_dir.to_owned(),
1219        (SecretsProfile::SharedDirectory, _) => secrets_dir.join(service_name),
1220    };
1221    let bytes =
1222        Zeroizing::new(read_secret(&directory, "signing-key")?.ok_or_else(|| {
1223            anyhow!("provisioned signing key is missing for service {service_name}")
1224        })?);
1225    let seed = Zeroizing::new(
1226        <[u8; 32]>::try_from(bytes.as_slice())
1227            .map_err(|_| anyhow!("service {service_name} signing-key must be 32 bytes"))?,
1228    );
1229    Ok(SigningKey::from_bytes(&seed))
1230}
1231
1232// The `#atproto` commit-signing key is NOT loaded here. It is the *active* key
1233// of the shared `Es256SigningKeyStore` (`auth::key_rotation`), the same P-256
1234// key `oauth::did_document` publishes as the `#atproto` verification method —
1235// one source of truth for signer and published key. The PDS writer
1236// (`services::discovery::PdsPublisher`) sources it from that store; there is no
1237// separate `atproto-signing-key` secret and no duplicate loader (#910a).
1238
1239/// Decode the `exp` claim from a JWT without signature verification.
1240/// Returns `None` on any parse error (invalid base64, not JSON, missing exp).
1241pub fn decode_jwt_exp_raw(jwt: &str) -> Option<i64> {
1242    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
1243    use base64::Engine as _;
1244    let payload_b64 = jwt.split('.').nth(1)?;
1245    let payload = URL_SAFE_NO_PAD.decode(payload_b64).ok()?;
1246    let value: serde_json::Value = serde_json::from_slice(&payload).ok()?;
1247    value["exp"].as_i64()
1248}
1249
1250/// Return the Unix mtime of `secrets_dir/signing-key`, or `now` if missing.
1251/// Used to populate the `nbf` field in JWKS entries (key was valid since written).
1252pub fn node_signing_key_mtime(secrets_dir: &std::path::Path) -> i64 {
1253    let path = secrets_dir.join("signing-key");
1254    path.metadata()
1255        .and_then(|m| m.modified())
1256        .ok()
1257        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1258        .map(|d| d.as_secs() as i64)
1259        .unwrap_or_else(|| chrono::Utc::now().timestamp())
1260}
1261
1262/// Load or generate the user signing key (Ed25519).
1263///
1264/// Callers **must** check the `config.oauth.user_signing_key` bypass before
1265/// calling this.
1266///
1267/// 1. Read `secrets_dir/user-signing-key` → return if present.
1268/// 2. If writable: generate, write, return.
1269/// 3. If read-only and missing: hard error.
1270pub fn load_or_generate_user_signing_key(
1271    secrets_dir: &std::path::Path,
1272) -> Result<(SigningKey, VerifyingKey)> {
1273    const NAME: &str = "user-signing-key";
1274
1275    if let Some(mut bytes) = read_secret(secrets_dir, NAME)? {
1276        let mut arr: [u8; 32] = bytes
1277            .as_slice()
1278            .try_into()
1279            .map_err(|_| anyhow!("secret '{}' must be 32 bytes (Ed25519 seed)", NAME))?;
1280        let sk = SigningKey::from_bytes(&arr);
1281        bytes.zeroize();
1282        arr.zeroize();
1283        let vk = sk.verifying_key();
1284        tracing::info!("Loaded user signing key from '{}'", secrets_dir.display());
1285        return Ok((sk, vk));
1286    }
1287
1288    if !is_writable(secrets_dir) {
1289        return Err(missing_in_readonly(secrets_dir, NAME));
1290    }
1291
1292    let sk = SigningKey::generate(&mut rand::rngs::OsRng);
1293    let mut raw = sk.to_bytes();
1294    let result = write_secret(secrets_dir, NAME, &raw);
1295    raw.zeroize();
1296    result?;
1297    let vk = sk.verifying_key();
1298    tracing::info!(
1299        "Generated new user signing key → '{}/{}'",
1300        secrets_dir.display(),
1301        NAME
1302    );
1303    Ok((sk, vk))
1304}
1305
1306/// Install `sk` as the client's user-signing-key (the file
1307/// `load_or_generate_user_signing_key` reads), backing up any existing key
1308/// first.
1309///
1310/// Used by `hyprstream user create --ssh`/`--key` (#439) to adopt an external
1311/// key as the *actual* signing key the CLI signs with — without this, an
1312/// imported-but-not-installed key leaves the client authenticating as
1313/// `anonymous`. The previous key, if any, is copied to `user-signing-key.bak`
1314/// (mode 0600) so the adopt is reversible; `None` is returned when no prior
1315/// key existed.
1316pub fn install_user_signing_key(
1317    secrets_dir: &std::path::Path,
1318    sk: &SigningKey,
1319) -> Result<Option<std::path::PathBuf>> {
1320    const NAME: &str = "user-signing-key";
1321    const BAK: &str = "user-signing-key.bak";
1322
1323    if !is_writable(secrets_dir) {
1324        return Err(missing_in_readonly(secrets_dir, NAME));
1325    }
1326
1327    let path = secrets_dir.join(NAME);
1328    let backup = if path.exists() {
1329        let bak = secrets_dir.join(BAK);
1330        // Back up via `write_secret` (atomic temp-file write with mode 0600 set
1331        // *before* persist) so the raw seed is never briefly world-readable, and
1332        // zeroize the in-memory copy before dropping it.
1333        let mut existing = std::fs::read(&path)
1334            .with_context(|| format!("failed to read existing {NAME} for backup"))?;
1335        let result = write_secret(secrets_dir, BAK, &existing);
1336        existing.zeroize();
1337        result
1338            .with_context(|| format!("failed to back up existing {NAME} to '{}'", bak.display()))?;
1339        tracing::info!("Backed up prior user signing key → '{}'", bak.display());
1340        Some(bak)
1341    } else {
1342        None
1343    };
1344
1345    let mut raw = sk.to_bytes();
1346    let result = write_secret(secrets_dir, NAME, &raw);
1347    raw.zeroize();
1348    result?;
1349    tracing::info!(
1350        "Installed adopted user signing key → '{}/{}'",
1351        secrets_dir.display(),
1352        NAME
1353    );
1354    Ok(backup)
1355}
1356
1357// ─── Post-quantum hybrid user identity (#439) ────────────────────────────────
1358
1359/// The on-disk name of the ML-DSA-65 sibling of `user-signing-key`.
1360const USER_PQ_NAME: &str = "user-signing-key.mldsa";
1361const USER_PQ_BAK: &str = "user-signing-key.mldsa.bak";
1362
1363/// A user's client identity key material: the Ed25519 anchor plus an optional
1364/// bound ML-DSA-65 key (present under [`CryptoPolicy::Hybrid`], absent under
1365/// `Classical`). The fingerprint / kid is always the Ed25519 anchor's — the PQ
1366/// key is bound *to* it, never fingerprinted itself.
1367pub struct UserIdentityKeys {
1368    pub ed: SigningKey,
1369    pub mldsa: Option<hyprstream_rpc::crypto::pq::MlDsaSigningKey>,
1370}
1371
1372impl UserIdentityKeys {
1373    /// The store algorithm tag this key material corresponds to.
1374    pub fn algorithm(&self) -> crate::auth::KeyAlgorithm {
1375        if self.mldsa.is_some() {
1376            crate::auth::KeyAlgorithm::HybridEd25519MlDsa65
1377        } else {
1378            crate::auth::KeyAlgorithm::Ed25519
1379        }
1380    }
1381
1382    /// The bound ML-DSA-65 verifying key bytes (~1952B), if hybrid.
1383    pub fn pq_verifying_key_bytes(&self) -> Option<Vec<u8>> {
1384        self.mldsa
1385            .as_ref()
1386            .map(hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk_bytes)
1387    }
1388}
1389
1390/// Load (or, under `Hybrid`, generate) the user's identity key material for the
1391/// given [`CryptoPolicy`].
1392///
1393/// - The Ed25519 anchor is loaded/generated exactly as before
1394///   ([`load_or_generate_user_signing_key`]) — the on-disk `user-signing-key`
1395///   file is unchanged, so existing loaders keep working.
1396/// - Under [`CryptoPolicy::Hybrid`] an ML-DSA-65 sibling
1397///   (`user-signing-key.mldsa`, a 32-byte FIPS 204 seed) is loaded if present,
1398///   or generated when absent. This covers the **in-place upgrade** case: a
1399///   legacy secrets dir that has only the Ed25519 key gains a bound PQ key for
1400///   the *same anchor* (same fingerprint) — no re-enrollment. If the PQ
1401///   component is missing and the directory is not writable, or if generating /
1402///   persisting it fails, this is a **hard error — never a classical fallback**
1403///   (fail closed, matching the node's default Hybrid policy).
1404/// - Under [`CryptoPolicy::Classical`] no PQ key is loaded or generated.
1405pub fn load_or_generate_user_identity(
1406    secrets_dir: &std::path::Path,
1407    policy: hyprstream_rpc::crypto::CryptoPolicy,
1408) -> Result<UserIdentityKeys> {
1409    use hyprstream_rpc::crypto::pq;
1410
1411    let (ed, _vk) = load_or_generate_user_signing_key(secrets_dir)?;
1412
1413    if !policy.uses_pq() {
1414        return Ok(UserIdentityKeys { ed, mldsa: None });
1415    }
1416
1417    // Hybrid: load the PQ sibling if present, else generate (fail closed).
1418    if let Some(mut seed_bytes) = read_secret(secrets_dir, USER_PQ_NAME)? {
1419        let mut seed: [u8; 32] = seed_bytes.as_slice().try_into().map_err(|_| {
1420            anyhow!(
1421                "secret '{}' must be 32 bytes (ML-DSA-65 seed)",
1422                USER_PQ_NAME
1423            )
1424        })?;
1425        let mldsa = pq::ml_dsa_sk_from_seed(&seed);
1426        seed_bytes.zeroize();
1427        seed.zeroize();
1428        tracing::info!(
1429            "Loaded hybrid PQ (ML-DSA-65) user key from '{}'",
1430            secrets_dir.display()
1431        );
1432        return Ok(UserIdentityKeys {
1433            ed,
1434            mldsa: Some(mldsa),
1435        });
1436    }
1437
1438    // Missing PQ component. Under Hybrid this must be generated; if we cannot
1439    // write, fail closed rather than mint a classical-only identity.
1440    if !is_writable(secrets_dir) {
1441        return Err(anyhow!(
1442            "CryptoPolicy is Hybrid but the post-quantum component '{}' is missing \
1443             and '{}' is not writable — refusing to fall back to a classical-only \
1444             identity (fail closed). Provision the ML-DSA-65 key or set the policy \
1445             to Classical explicitly.",
1446            USER_PQ_NAME,
1447            secrets_dir.display()
1448        ));
1449    }
1450
1451    let (mldsa, _mldsa_vk) = pq::ml_dsa_generate_keypair();
1452    let mut seed = pq::ml_dsa_sk_to_seed(&mldsa);
1453    let result = write_secret(secrets_dir, USER_PQ_NAME, &seed);
1454    seed.zeroize();
1455    result.with_context(|| {
1456        format!(
1457            "CryptoPolicy is Hybrid but persisting the ML-DSA-65 component '{}' failed \
1458             — refusing a classical-only fallback (fail closed)",
1459            USER_PQ_NAME
1460        )
1461    })?;
1462    tracing::info!(
1463        "Generated new hybrid PQ (ML-DSA-65) user key → '{}/{}'",
1464        secrets_dir.display(),
1465        USER_PQ_NAME
1466    );
1467    Ok(UserIdentityKeys {
1468        ed,
1469        mldsa: Some(mldsa),
1470    })
1471}
1472
1473/// Paths of any prior key files displaced by an adopt, so the caller can report
1474/// the backup(s).
1475#[derive(Debug, Default)]
1476pub struct InstalledIdentityBackup {
1477    pub ed: Option<std::path::PathBuf>,
1478    pub pq: Option<std::path::PathBuf>,
1479}
1480
1481/// Install adopted identity key material (the `--ssh`/`--key` path), backing up
1482/// any displaced key files first.
1483///
1484/// The adopted Ed25519 key becomes the client's `user-signing-key` (via
1485/// [`install_user_signing_key`]). Under `Hybrid`, a **freshly generated**
1486/// ML-DSA-65 key is installed as its sibling — an adopted SSH/seed key can never
1487/// make the identity hybrid by itself, so a new PQ component is minted and bound
1488/// to the same anchor. Under `Classical`, no PQ sibling is written, and any
1489/// pre-existing sibling is backed up and removed so the on-disk pair stays
1490/// consistent (the file layout never claims hybrid without a matching PQ key).
1491pub fn install_user_identity(
1492    secrets_dir: &std::path::Path,
1493    ed_sk: &SigningKey,
1494    mldsa_sk: Option<&hyprstream_rpc::crypto::pq::MlDsaSigningKey>,
1495) -> Result<InstalledIdentityBackup> {
1496    use hyprstream_rpc::crypto::pq;
1497
1498    let ed_backup = install_user_signing_key(secrets_dir, ed_sk)?;
1499
1500    let pq_backup = match mldsa_sk {
1501        Some(mldsa) => {
1502            // Back up any existing PQ sibling, then install the fresh one.
1503            let bak = backup_secret_if_present(secrets_dir, USER_PQ_NAME, USER_PQ_BAK)?;
1504            let mut seed = pq::ml_dsa_sk_to_seed(mldsa);
1505            let result = write_secret(secrets_dir, USER_PQ_NAME, &seed);
1506            seed.zeroize();
1507            result?;
1508            tracing::info!(
1509                "Installed adopted hybrid PQ (ML-DSA-65) user key → '{}/{}'",
1510                secrets_dir.display(),
1511                USER_PQ_NAME
1512            );
1513            bak
1514        }
1515        None => {
1516            // Classical adopt: retire any stale PQ sibling so the pair is
1517            // consistent (never leave a PQ seed bound to a displaced anchor).
1518            let bak = backup_secret_if_present(secrets_dir, USER_PQ_NAME, USER_PQ_BAK)?;
1519            if bak.is_some() {
1520                let live = secrets_dir.join(USER_PQ_NAME);
1521                std::fs::remove_file(&live).with_context(|| {
1522                    format!("failed to retire stale PQ key '{}'", live.display())
1523                })?;
1524                tracing::info!("Retired stale PQ user key (classical adopt) → backup kept");
1525            }
1526            bak
1527        }
1528    };
1529
1530    Ok(InstalledIdentityBackup {
1531        ed: ed_backup,
1532        pq: pq_backup,
1533    })
1534}
1535
1536/// Back up `name` → `bak_name` (via [`write_secret`], mode 0600 before persist)
1537/// if `name` exists, zeroizing the read buffer. Returns the backup path if made.
1538fn backup_secret_if_present(
1539    secrets_dir: &std::path::Path,
1540    name: &str,
1541    bak_name: &str,
1542) -> Result<Option<std::path::PathBuf>> {
1543    let path = secrets_dir.join(name);
1544    if !path.exists() {
1545        return Ok(None);
1546    }
1547    let mut existing = std::fs::read(&path)
1548        .with_context(|| format!("failed to read existing {name} for backup"))?;
1549    let result = write_secret(secrets_dir, bak_name, &existing);
1550    existing.zeroize();
1551    result.with_context(|| format!("failed to back up existing {name}"))?;
1552    Ok(Some(secrets_dir.join(bak_name)))
1553}
1554
1555/// Load or generate an RSA 2048 keypair for RS256 JWT signing.
1556///
1557/// Stored as PKCS#8 DER in `secrets_dir/rsa-key`. If the file doesn't exist
1558/// and the directory is writable, a new keypair is generated using `openssl`.
1559///
1560/// Returns the DER-encoded PKCS#8 private key bytes (suitable for
1561/// `jsonwebtoken::EncodingKey::from_rsa_der`).
1562pub fn load_or_generate_rsa_key(secrets_dir: &std::path::Path) -> Result<Vec<u8>> {
1563    const NAME: &str = "rsa-key";
1564
1565    if let Some(bytes) = read_secret(secrets_dir, NAME)? {
1566        tracing::info!("Loaded RSA key from '{}'", secrets_dir.display());
1567        return Ok(bytes);
1568    }
1569
1570    if !is_writable(secrets_dir) {
1571        return Err(missing_in_readonly(secrets_dir, NAME));
1572    }
1573
1574    // Generate RSA 2048 keypair via openssl (avoids adding rsa crate dependency).
1575    // Output is PKCS#8 DER, compatible with jsonwebtoken::EncodingKey::from_rsa_der.
1576    let output = std::process::Command::new("openssl")
1577        .args([
1578            "genpkey",
1579            "-algorithm",
1580            "RSA",
1581            "-pkeyopt",
1582            "rsa_keygen_bits:2048",
1583            "-outform",
1584            "DER",
1585        ])
1586        .stdout(std::process::Stdio::piped())
1587        .stderr(std::process::Stdio::piped())
1588        .output()
1589        .context("Failed to run openssl for RSA key generation")?;
1590
1591    if !output.status.success() {
1592        let stderr = String::from_utf8_lossy(&output.stderr);
1593        return Err(anyhow!("openssl RSA key generation failed: {stderr}"));
1594    }
1595
1596    let der_bytes = output.stdout;
1597    if der_bytes.len() < 100 {
1598        return Err(anyhow!(
1599            "openssl produced unexpectedly small RSA key ({} bytes)",
1600            der_bytes.len()
1601        ));
1602    }
1603
1604    write_secret(secrets_dir, NAME, &der_bytes)?;
1605    tracing::info!(
1606        "Generated new RSA 2048 key → '{}/{}'",
1607        secrets_dir.display(),
1608        NAME
1609    );
1610    Ok(der_bytes)
1611}
1612
1613/// Load or generate TLS materials using the default secret names (`tls-key`, `tls-cert`).
1614///
1615/// See [`load_or_generate_tls_materials_named`] for details.
1616pub fn load_or_generate_tls_materials(
1617    secrets_dir: &std::path::Path,
1618    server_name: &str,
1619    max_validity_days: u32,
1620) -> Result<TlsMaterials> {
1621    load_or_generate_tls_materials_named(
1622        secrets_dir,
1623        server_name,
1624        max_validity_days,
1625        "tls-key",
1626        "tls-cert",
1627    )
1628}
1629
1630/// Load or generate TLS materials (ECDSA P-256 key + self-signed cert) using
1631/// caller-specified secret names.
1632///
1633/// - If `secrets_dir` contains both `key_name` and `cert_name`, load them.
1634/// - If the cert is nearing expiry, exceeds the WebTransport lifetime limit,
1635///   or its SAN no longer covers `server_name`,
1636///   regenerate the cert using the same key.
1637/// - If writable and files are missing, generate key + cert and write both.
1638/// - If read-only and files are missing, hard error.
1639///
1640/// `max_validity_days` should be 365 for HTTP services and 14 for QUIC/WebTransport.
1641///
1642/// Returns a [`TlsMaterials`] with DER-encoded cert and key.
1643pub fn load_or_generate_tls_materials_named(
1644    secrets_dir: &std::path::Path,
1645    server_name: &str,
1646    max_validity_days: u32,
1647    key_name: &str,
1648    cert_name: &str,
1649) -> Result<TlsMaterials> {
1650    let key_bytes = read_secret(secrets_dir, key_name)?;
1651    let cert_bytes = read_secret(secrets_dir, cert_name)?;
1652
1653    match (key_bytes, cert_bytes) {
1654        (Some(key_der), Some(cert_der)) => {
1655            // A configured public QUIC name can change independently of the
1656            // persisted key. Never keep serving a fresh but wrong-name leaf.
1657            let name_mismatch = !certificate_covers_name(&cert_der, server_name);
1658            // Older QUIC leaves could span slightly more than 14 days because
1659            // their endpoints were calculated with separate clock reads.
1660            // Browsers reject that leaf even when it is otherwise fresh.
1661            let excessive_validity = max_validity_days <= 14
1662                && certificate_validity_exceeds_limit(&cert_der, max_validity_days);
1663            let needs_renewal = name_mismatch
1664                || excessive_validity
1665                || cert_renewal_needed(secrets_dir, cert_name, max_validity_days);
1666
1667            if needs_renewal && is_writable(secrets_dir) {
1668                tracing::info!(
1669                    "TLS cert '{}' requires renewal; regenerating (reusing existing key)",
1670                    cert_name
1671                );
1672                let new_cert_der =
1673                    generate_cert_from_key_der(&key_der, server_name, max_validity_days)?;
1674                write_secret(secrets_dir, cert_name, &new_cert_der)?;
1675                return Ok(TlsMaterials {
1676                    cert_der: new_cert_der,
1677                    key_der: Zeroizing::new(key_der),
1678                });
1679            }
1680
1681            if needs_renewal {
1682                anyhow::ensure!(
1683                    !name_mismatch,
1684                    "TLS cert '{cert_name}' does not cover configured server name '{server_name}' and credentials are read-only"
1685                );
1686                anyhow::ensure!(
1687                    !excessive_validity,
1688                    "TLS cert '{cert_name}' exceeds the WebTransport validity limit and credentials are read-only"
1689                );
1690                // Read-only credentials dir (e.g. systemd $CREDENTIALS_DIRECTORY):
1691                // the imported cert ages past validity with no on-disk remedy from
1692                // inside the service. Fail loud so operators re-provision (#808).
1693                tracing::error!(
1694                    "TLS cert '{}' in '{}' is past its renewal threshold but the \
1695                     credentials directory is read-only; renewal was SKIPPED and the \
1696                     cert will expire. Re-run 'hyprstream service install' to \
1697                     re-provision a fresh certificate.",
1698                    cert_name,
1699                    secrets_dir.display()
1700                );
1701            }
1702
1703            tracing::info!(
1704                "Loaded persisted TLS materials from '{}'",
1705                secrets_dir.display()
1706            );
1707            Ok(TlsMaterials {
1708                cert_der,
1709                key_der: Zeroizing::new(key_der),
1710            })
1711        }
1712
1713        (Some(key_der), None) => {
1714            // Key exists but cert is missing — regenerate cert from existing key.
1715            if !is_writable(secrets_dir) {
1716                return Err(missing_in_readonly(secrets_dir, cert_name));
1717            }
1718            let cert_der = generate_cert_from_key_der(&key_der, server_name, max_validity_days)?;
1719            write_secret(secrets_dir, cert_name, &cert_der)?;
1720            tracing::info!("Regenerated TLS cert '{}' from persisted key", cert_name);
1721            Ok(TlsMaterials {
1722                cert_der,
1723                key_der: Zeroizing::new(key_der),
1724            })
1725        }
1726
1727        (None, _) => {
1728            // No key — generate from scratch.
1729            if !is_writable(secrets_dir) {
1730                return Err(missing_in_readonly(secrets_dir, key_name));
1731            }
1732            let key_pair = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256)?;
1733            let key_der = key_pair.serialize_der();
1734            let cert_der =
1735                generate_cert_from_rcgen_keypair(&key_pair, server_name, max_validity_days)?;
1736            write_secret(secrets_dir, key_name, &key_der)?;
1737            write_secret(secrets_dir, cert_name, &cert_der)?;
1738            tracing::info!(
1739                "Generated new TLS key '{}' + cert '{}' ({max_validity_days}d) → '{}'",
1740                key_name,
1741                cert_name,
1742                secrets_dir.display()
1743            );
1744            Ok(TlsMaterials {
1745                cert_der,
1746                key_der: Zeroizing::new(key_der),
1747            })
1748        }
1749    }
1750}
1751
1752fn certificate_covers_name(cert_der: &[u8], server_name: &str) -> bool {
1753    let server_ip = server_name.parse::<std::net::IpAddr>().ok();
1754    x509_parser::parse_x509_certificate(cert_der)
1755        .ok()
1756        .is_some_and(|(_, certificate)| {
1757            certificate.extensions().iter().any(|extension| {
1758                matches!(
1759                    extension.parsed_extension(),
1760                    x509_parser::extensions::ParsedExtension::SubjectAlternativeName(names)
1761                        if names.general_names.iter().any(|name| match (server_ip, name) {
1762                            (Some(std::net::IpAddr::V4(ip)), x509_parser::extensions::GeneralName::IPAddress(bytes)) => bytes == &ip.octets(),
1763                            (Some(std::net::IpAddr::V6(ip)), x509_parser::extensions::GeneralName::IPAddress(bytes)) => bytes == &ip.octets(),
1764                            (None, x509_parser::extensions::GeneralName::DNSName(dns)) => dns.eq_ignore_ascii_case(server_name),
1765                            _ => false,
1766                        })
1767                )
1768            })
1769        })
1770}
1771
1772fn certificate_validity_exceeds_limit(cert_der: &[u8], max_validity_days: u32) -> bool {
1773    x509_parser::parse_x509_certificate(cert_der)
1774        .ok()
1775        .is_none_or(|(_, certificate)| {
1776            certificate.validity().not_after.timestamp()
1777                - certificate.validity().not_before.timestamp()
1778                > i64::from(max_validity_days) * 86_400
1779        })
1780}
1781
1782// ─── TLS helpers ────────────────────────────────────────────────────────────
1783
1784/// Check whether the persisted cert needs renewal.
1785///
1786/// Returns `true` if the cert file's mtime is older than `(max_validity_days - 1)` days.
1787///
1788/// # Note on mtime-as-proxy
1789///
1790/// We use the cert file's mtime as a proxy for its `notBefore` date to avoid
1791/// parsing DER. This is a heuristic: over-renewing is safe (one extra I/O on
1792/// startup), while under-renewing could cause expired-cert errors in clients.
1793/// Clock skew (mtime in the future) is handled conservatively — we trigger
1794/// renewal rather than silently skipping it.
1795fn cert_renewal_needed(
1796    secrets_dir: &std::path::Path,
1797    cert_name: &str,
1798    max_validity_days: u32,
1799) -> bool {
1800    let cert_path = secrets_dir.join(cert_name);
1801    let renewal_threshold =
1802        std::time::Duration::from_secs(u64::from(max_validity_days.saturating_sub(1)) * 86_400);
1803    match std::fs::metadata(&cert_path).and_then(|m| m.modified()) {
1804        Ok(mtime) => match mtime.elapsed() {
1805            Ok(age) => age >= renewal_threshold,
1806            Err(_) => {
1807                tracing::warn!(
1808                    "cert '{}': mtime is in the future (clock skew?); triggering renewal",
1809                    cert_path.display()
1810                );
1811                true
1812            }
1813        },
1814        Err(_) => true,
1815    }
1816}
1817
1818/// Generate a self-signed cert DER from a raw DER-encoded ECDSA P-256 key.
1819fn generate_cert_from_key_der(
1820    key_der: &[u8],
1821    server_name: &str,
1822    max_validity_days: u32,
1823) -> Result<Vec<u8>> {
1824    let pki_key = rustls::pki_types::PrivateKeyDer::try_from(key_der)
1825        .map_err(|e| anyhow!("invalid TLS key DER: {}", e))?;
1826    let key_pair = rcgen::KeyPair::from_der_and_sign_algo(&pki_key, &rcgen::PKCS_ECDSA_P256_SHA256)
1827        .context("failed to parse persisted TLS key DER")?;
1828    generate_cert_from_rcgen_keypair(&key_pair, server_name, max_validity_days)
1829}
1830
1831/// Generate a self-signed cert DER from an rcgen KeyPair.
1832fn generate_cert_from_rcgen_keypair(
1833    key_pair: &rcgen::KeyPair,
1834    server_name: &str,
1835    max_validity_days: u32,
1836) -> Result<Vec<u8>> {
1837    let mut params = rcgen::CertificateParams::new(vec![server_name.to_owned()])?;
1838    let now = time::OffsetDateTime::now_utc();
1839    // A small clock-skew allowance and a sub-limit lifetime keep WebTransport
1840    // self-signed leaves strictly below its two-week maximum.
1841    params.not_before = now - time::Duration::minutes(5);
1842    params.not_after =
1843        now + time::Duration::days(i64::from(max_validity_days)) - time::Duration::hours(1);
1844    let cert = params.self_signed(key_pair)?;
1845    Ok(cert.der().to_vec())
1846}
1847
1848// ─── Tests ───────────────────────────────────────────────────────────────────
1849
1850#[cfg(test)]
1851#[allow(clippy::unwrap_used, clippy::expect_used)]
1852mod tests {
1853    use super::*;
1854    use tempfile::TempDir;
1855
1856    static SECRETS_ENV_LOCK: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
1857
1858    // ── Helpers ──────────────────────────────────────────────────────────────
1859
1860    /// Back-date a file's mtime by `days` days using nix utimes.
1861    #[cfg(unix)]
1862    fn backdate_mtime(path: &std::path::Path, days: i64) {
1863        use nix::sys::time::TimeVal;
1864        let past_secs = std::time::SystemTime::now()
1865            .duration_since(std::time::UNIX_EPOCH)
1866            .unwrap()
1867            .as_secs() as i64
1868            - days * 86_400;
1869        let tv = TimeVal::new(past_secs, 0);
1870        nix::sys::stat::utimes(path, &tv, &tv).unwrap();
1871    }
1872
1873    /// RAII guard to set/unset a process env var for the duration of a test and
1874    /// restore the previous value, keeping env-mutating tests from leaking state.
1875    struct EnvVarGuard {
1876        key: String,
1877        prev: Option<String>,
1878    }
1879    impl EnvVarGuard {
1880        fn set(key: &str, val: &str) -> Self {
1881            let prev = std::env::var(key).ok();
1882            std::env::set_var(key, val);
1883            Self {
1884                key: key.to_owned(),
1885                prev,
1886            }
1887        }
1888        fn unset(key: &str) -> Self {
1889            let prev = std::env::var(key).ok();
1890            std::env::remove_var(key);
1891            Self {
1892                key: key.to_owned(),
1893                prev,
1894            }
1895        }
1896    }
1897    impl Drop for EnvVarGuard {
1898        fn drop(&mut self) {
1899            match &self.prev {
1900                Some(v) => std::env::set_var(&self.key, v),
1901                None => std::env::remove_var(&self.key),
1902            }
1903        }
1904    }
1905
1906    /// `credentials_dir()` precedence: `HYPRSTREAM__SECRETS__PATH` wins when set;
1907    /// otherwise resolution falls back to a `<config_dir>/credentials` path.
1908    /// Both cases in one test — the env var is process-global and tests run in
1909    /// parallel, so splitting them would race.
1910    #[test]
1911    fn test_credentials_dir_precedence() {
1912        let _serial = SECRETS_ENV_LOCK.lock();
1913        const VAR: &str = "HYPRSTREAM__SECRETS__PATH";
1914
1915        // (a) env var set → returns exactly that path.
1916        {
1917            let _g = EnvVarGuard::set(VAR, "/run/credentials/hyprstream");
1918            let dir = credentials_dir().unwrap();
1919            assert_eq!(dir, std::path::PathBuf::from("/run/credentials/hyprstream"));
1920        }
1921
1922        // (b) env var unset → default resolution yields a path ending in
1923        // `credentials` (via config load or the XDG fallback).
1924        {
1925            let _g = EnvVarGuard::unset(VAR);
1926            let dir = credentials_dir().unwrap();
1927            assert_eq!(
1928                dir.file_name().and_then(|n| n.to_str()),
1929                Some("credentials"),
1930                "default resolution should end in 'credentials': {}",
1931                dir.display()
1932            );
1933        }
1934    }
1935
1936    #[test]
1937    fn test_path_override_alone_keeps_shared_profile_and_service_key_isolation() {
1938        let _serial = SECRETS_ENV_LOCK.lock();
1939        let dir = TempDir::new().unwrap();
1940        let _path = EnvVarGuard::set("HYPRSTREAM__SECRETS__PATH", dir.path().to_str().unwrap());
1941        let _profile = EnvVarGuard::unset(SECRETS_PROFILE_ENV);
1942
1943        let profile = SecretsProfile::from_env().unwrap();
1944        assert_eq!(
1945            profile,
1946            SecretsProfile::SharedDirectory,
1947            "a general path override is not proof of per-service scoping"
1948        );
1949        let model = resolve_service_signing_key(dir.path(), "model", profile).unwrap();
1950        let worker = resolve_service_signing_key(dir.path(), "worker", profile).unwrap();
1951        assert_ne!(
1952            model.to_bytes(),
1953            worker.to_bytes(),
1954            "services sharing an overridden directory must retain independent keys"
1955        );
1956        assert!(dir.path().join("model").join("signing-key").exists());
1957        assert!(dir.path().join("worker").join("signing-key").exists());
1958        assert!(!dir.path().join("signing-key").exists());
1959    }
1960
1961    #[test]
1962    fn test_service_jwt_write_round_trips_through_startup_read_layouts() {
1963        let dir = TempDir::new().unwrap();
1964
1965        write_service_jwt_for_profile(
1966            dir.path(),
1967            "model",
1968            SecretsProfile::SharedDirectory,
1969            "shared.jwt",
1970        )
1971        .unwrap();
1972        assert_eq!(
1973            load_service_jwt_for_profile(dir.path(), "model", SecretsProfile::SharedDirectory,)
1974                .unwrap()
1975                .as_deref(),
1976            Some("shared.jwt")
1977        );
1978        assert!(dir.path().join("model").join("service-jwt").exists());
1979
1980        let scoped = dir.path().join("scoped");
1981        write_service_jwt_for_profile(
1982            &scoped,
1983            "model",
1984            SecretsProfile::PerServiceScoped,
1985            "scoped.jwt",
1986        )
1987        .unwrap();
1988        assert_eq!(
1989            load_service_jwt_for_profile(&scoped, "model", SecretsProfile::PerServiceScoped,)
1990                .unwrap()
1991                .as_deref(),
1992            Some("scoped.jwt")
1993        );
1994        assert!(scoped.join("service-jwt").exists());
1995        assert!(!scoped.join("model").exists());
1996    }
1997
1998    #[cfg(unix)]
1999    #[test]
2000    fn test_scoped_service_jwt_renewal_survives_read_only_credentials_restart() {
2001        use std::os::unix::fs::PermissionsExt as _;
2002
2003        let _serial = SECRETS_ENV_LOCK.lock();
2004        let dir = TempDir::new().unwrap();
2005        let credentials = dir.path().join("credentials");
2006        let state = dir.path().join("state");
2007        std::fs::create_dir_all(&credentials).unwrap();
2008        std::fs::create_dir_all(&state).unwrap();
2009        write_secret(&credentials, "service-jwt", b"provisioned.jwt").unwrap();
2010
2011        std::fs::set_permissions(&credentials, std::fs::Permissions::from_mode(0o500)).unwrap();
2012        let _state = EnvVarGuard::set("STATE_DIRECTORY", state.to_str().unwrap());
2013        let _instance = EnvVarGuard::unset("HYPRSTREAM_INSTANCE");
2014
2015        write_service_jwt_for_profile(
2016            &credentials,
2017            "model",
2018            SecretsProfile::PerServiceScoped,
2019            "renewed.jwt",
2020        )
2021        .unwrap();
2022        assert_eq!(
2023            load_service_jwt_for_profile(&credentials, "model", SecretsProfile::PerServiceScoped,)
2024                .unwrap()
2025                .as_deref(),
2026            Some("renewed.jwt"),
2027            "startup must prefer the renewed JWT written to writable state"
2028        );
2029        assert_eq!(
2030            std::fs::read_to_string(state.join("credentials").join("model").join("service-jwt"))
2031                .unwrap(),
2032            "renewed.jwt"
2033        );
2034    }
2035
2036    #[test]
2037    fn test_is_writable_leaves_no_probe_file() {
2038        let dir = TempDir::new().unwrap();
2039        assert!(is_writable(dir.path()));
2040        let count = std::fs::read_dir(dir.path()).unwrap().count();
2041        assert_eq!(count, 0, "is_writable should not leave any files behind");
2042    }
2043
2044    #[test]
2045    fn test_write_secret_no_tmp_remnant() {
2046        let dir = TempDir::new().unwrap();
2047        write_secret(dir.path(), "mykey", b"value").unwrap();
2048        let names: Vec<String> = std::fs::read_dir(dir.path())
2049            .unwrap()
2050            .map(|e| e.unwrap().file_name().to_string_lossy().to_string())
2051            .collect();
2052        assert_eq!(names, vec!["mykey"], "only the final file should exist");
2053    }
2054
2055    #[test]
2056    fn test_read_write_roundtrip() {
2057        let dir = TempDir::new().unwrap();
2058        let data = b"hello world";
2059        write_secret(dir.path(), "test-key", data).unwrap();
2060        let loaded = read_secret(dir.path(), "test-key").unwrap().unwrap();
2061        assert_eq!(loaded, data);
2062    }
2063
2064    #[test]
2065    fn test_read_missing_returns_none() {
2066        let dir = TempDir::new().unwrap();
2067        let result = read_secret(dir.path(), "nonexistent").unwrap();
2068        assert!(result.is_none());
2069    }
2070
2071    #[test]
2072    #[cfg(unix)]
2073    fn test_write_sets_mode_0600() {
2074        use std::os::unix::fs::PermissionsExt;
2075        let dir = TempDir::new().unwrap();
2076        write_secret(dir.path(), "test-key", b"secret").unwrap();
2077        let meta = std::fs::metadata(dir.path().join("test-key")).unwrap();
2078        let mode = meta.permissions().mode();
2079        assert_eq!(
2080            mode & 0o777,
2081            0o600,
2082            "expected mode 0600, got {:o}",
2083            mode & 0o777
2084        );
2085    }
2086
2087    #[test]
2088    fn test_generate_on_first_run_writes_file() {
2089        let dir = TempDir::new().unwrap();
2090        let key = load_or_generate_node_signing_key(dir.path()).unwrap();
2091        assert_eq!(key.to_bytes().len(), 32);
2092        // File should now exist
2093        let raw = read_secret(dir.path(), "signing-key").unwrap().unwrap();
2094        assert_eq!(raw, key.to_bytes().to_vec());
2095    }
2096
2097    #[test]
2098    fn test_load_persisted_signing_key() {
2099        let dir = TempDir::new().unwrap();
2100        // Write a known key
2101        let known = SigningKey::generate(&mut rand::rngs::OsRng);
2102        write_secret(dir.path(), "signing-key", &known.to_bytes()).unwrap();
2103        let loaded = load_or_generate_node_signing_key(dir.path()).unwrap();
2104        assert_eq!(loaded.to_bytes(), known.to_bytes());
2105    }
2106
2107    #[test]
2108    #[cfg(unix)]
2109    fn test_signing_key_readonly_dir_fails() {
2110        use std::os::unix::fs::PermissionsExt;
2111        // 0o500 = r-x------ (owner read+traverse, no write, no group/other access).
2112        // Mirrors a systemd credentials directory.  TempDir::drop uses rmdir which
2113        // only needs write on the *parent* dir, so cleanup succeeds without restoring.
2114        let parent = TempDir::new().unwrap();
2115        let secrets_dir = parent.path().join("secrets");
2116        std::fs::create_dir(&secrets_dir).unwrap();
2117        std::fs::set_permissions(&secrets_dir, std::fs::Permissions::from_mode(0o500)).unwrap();
2118        let result = load_or_generate_node_signing_key(&secrets_dir);
2119        assert!(result.is_err());
2120    }
2121
2122    #[test]
2123    fn test_user_signing_key_roundtrip() {
2124        let dir = TempDir::new().unwrap();
2125        let (sk1, vk1) = load_or_generate_user_signing_key(dir.path()).unwrap();
2126        let (sk2, vk2) = load_or_generate_user_signing_key(dir.path()).unwrap();
2127        assert_eq!(sk1.to_bytes(), sk2.to_bytes());
2128        assert_eq!(vk1.as_bytes(), vk2.as_bytes());
2129    }
2130
2131    #[test]
2132    fn test_tls_materials_cert_hash_stable() {
2133        let dir = TempDir::new().unwrap();
2134        let m1 = load_or_generate_tls_materials(dir.path(), "localhost", 365).unwrap();
2135        let m2 = load_or_generate_tls_materials(dir.path(), "localhost", 365).unwrap();
2136        // Same cert bytes → same hash
2137        assert_eq!(m1.cert_der, m2.cert_der);
2138        assert_eq!(*m1.key_der, *m2.key_der);
2139    }
2140
2141    #[test]
2142    fn test_tls_materials_cert_regenerated_from_same_key() {
2143        use sha2::{Digest, Sha256};
2144        let dir = TempDir::new().unwrap();
2145        let m1 = load_or_generate_tls_materials(dir.path(), "localhost", 365).unwrap();
2146        // Remove only the cert file to force regeneration
2147        std::fs::remove_file(dir.path().join("tls-cert")).unwrap();
2148        let m2 = load_or_generate_tls_materials(dir.path(), "localhost", 365).unwrap();
2149        // Key must be identical (stable identity)
2150        assert_eq!(*m1.key_der, *m2.key_der);
2151        // New cert is a different DER (different not_before/not_after)
2152        // but has the same public key embedded
2153        let h1 = Sha256::digest(&m1.cert_der);
2154        let h2 = Sha256::digest(&m2.cert_der);
2155        // Hashes differ because cert timestamps differ
2156        assert_ne!(h1, h2);
2157    }
2158
2159    // ── Directory mode 0700 ──────────────────────────────────────────────────
2160
2161    #[test]
2162    #[cfg(unix)]
2163    fn test_ensure_dir_mode_0700() {
2164        use std::os::unix::fs::PermissionsExt;
2165        let parent = TempDir::new().unwrap();
2166        let secrets_dir = parent.path().join("new-secrets");
2167        // Dir does not exist yet; write_secret should create it with mode 0700.
2168        write_secret(&secrets_dir, "k", b"v").unwrap();
2169        let meta = std::fs::metadata(&secrets_dir).unwrap();
2170        assert_eq!(
2171            meta.permissions().mode() & 0o777,
2172            0o700,
2173            "secrets dir should be 0700, got {:o}",
2174            meta.permissions().mode() & 0o777
2175        );
2176    }
2177
2178    // ── Binary data roundtrip ────────────────────────────────────────────────
2179
2180    #[test]
2181    fn test_read_write_binary_roundtrip() {
2182        let dir = TempDir::new().unwrap();
2183        // Include null bytes and high-bit bytes to verify binary fidelity.
2184        let data: Vec<u8> = (0u8..=255).collect();
2185        write_secret(dir.path(), "binary-key", &data).unwrap();
2186        let loaded = read_secret(dir.path(), "binary-key").unwrap().unwrap();
2187        assert_eq!(loaded, data);
2188    }
2189
2190    // ── Invalid signing key length ───────────────────────────────────────────
2191
2192    #[test]
2193    fn test_load_signing_key_wrong_length_errors() {
2194        let dir = TempDir::new().unwrap();
2195        // Write 16 bytes instead of 32 — should produce a clear error.
2196        write_secret(dir.path(), "signing-key", &[0u8; 16]).unwrap();
2197        let result = load_or_generate_node_signing_key(dir.path());
2198        assert!(result.is_err());
2199        assert!(
2200            result.unwrap_err().to_string().contains("32 bytes"),
2201            "error should mention expected 32-byte length"
2202        );
2203    }
2204
2205    #[test]
2206    fn test_load_user_signing_key_wrong_length_errors() {
2207        let dir = TempDir::new().unwrap();
2208        write_secret(dir.path(), "user-signing-key", &[0u8; 64]).unwrap();
2209        let result = load_or_generate_user_signing_key(dir.path());
2210        assert!(result.is_err());
2211        assert!(result.unwrap_err().to_string().contains("32 bytes"));
2212    }
2213
2214    // ── User signing key: generate + readonly paths ──────────────────────────
2215
2216    #[test]
2217    fn test_user_signing_key_generates_on_first_run() {
2218        let dir = TempDir::new().unwrap();
2219        let (sk, vk) = load_or_generate_user_signing_key(dir.path()).unwrap();
2220        assert_eq!(sk.to_bytes().len(), 32);
2221        assert_eq!(vk.as_bytes().len(), 32);
2222        // Key file should now exist.
2223        let raw = read_secret(dir.path(), "user-signing-key")
2224            .unwrap()
2225            .unwrap();
2226        assert_eq!(raw, sk.to_bytes().as_slice());
2227    }
2228
2229    #[test]
2230    #[cfg(unix)]
2231    fn test_user_signing_key_readonly_dir_fails() {
2232        use std::os::unix::fs::PermissionsExt;
2233        let parent = TempDir::new().unwrap();
2234        let secrets_dir = parent.path().join("secrets");
2235        std::fs::create_dir(&secrets_dir).unwrap();
2236        std::fs::set_permissions(&secrets_dir, std::fs::Permissions::from_mode(0o500)).unwrap();
2237        let result = load_or_generate_user_signing_key(&secrets_dir);
2238        assert!(result.is_err());
2239    }
2240
2241    // ── TLS: initial key+cert generation (the (None, _) branch) ────────────
2242
2243    #[test]
2244    fn test_tls_materials_initial_generation() {
2245        let dir = TempDir::new().unwrap();
2246        // No pre-existing key or cert.
2247        let m = load_or_generate_tls_materials(dir.path(), "localhost", 365).unwrap();
2248        assert!(!m.cert_der.is_empty(), "cert_der should be non-empty");
2249        assert!(!m.key_der.is_empty(), "key_der should be non-empty");
2250        // Both files should have been written.
2251        assert!(
2252            dir.path().join("tls-key").exists(),
2253            "tls-key file should exist"
2254        );
2255        assert!(
2256            dir.path().join("tls-cert").exists(),
2257            "tls-cert file should exist"
2258        );
2259    }
2260
2261    #[test]
2262    fn test_tls_materials_name_change_renews_leaf_without_rotating_key() {
2263        let dir = TempDir::new().unwrap();
2264        let old = load_or_generate_tls_materials_named(
2265            dir.path(),
2266            "localhost",
2267            14,
2268            "quic-key",
2269            "quic-cert",
2270        )
2271        .unwrap();
2272        let renewed = load_or_generate_tls_materials_named(
2273            dir.path(),
2274            "discovery.example.test",
2275            14,
2276            "quic-key",
2277            "quic-cert",
2278        )
2279        .unwrap();
2280        assert_eq!(*old.key_der, *renewed.key_der);
2281        assert!(certificate_covers_name(
2282            &renewed.cert_der,
2283            "discovery.example.test"
2284        ));
2285        assert!(!certificate_covers_name(&renewed.cert_der, "localhost"));
2286        let (_, certificate) = x509_parser::parse_x509_certificate(&renewed.cert_der).unwrap();
2287        assert!(
2288            certificate.validity().not_after.timestamp()
2289                - certificate.validity().not_before.timestamp()
2290                < 14 * 86_400
2291        );
2292    }
2293
2294    #[test]
2295    fn test_legacy_overlimit_quic_cert_renews_without_rotating_key() {
2296        let dir = TempDir::new().unwrap();
2297        let key_pair = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap();
2298        let key_der = key_pair.serialize_der();
2299        let mut params =
2300            rcgen::CertificateParams::new(vec!["discovery.example.test".into()]).unwrap();
2301        let now = time::OffsetDateTime::now_utc();
2302        params.not_before = now;
2303        params.not_after = now + time::Duration::days(14) + time::Duration::seconds(1);
2304        let legacy_der = params.self_signed(&key_pair).unwrap().der().to_vec();
2305        assert!(certificate_validity_exceeds_limit(&legacy_der, 14));
2306        write_secret(dir.path(), "quic-key", &key_der).unwrap();
2307        write_secret(dir.path(), "quic-cert", &legacy_der).unwrap();
2308
2309        let renewed = load_or_generate_tls_materials_named(
2310            dir.path(),
2311            "discovery.example.test",
2312            14,
2313            "quic-key",
2314            "quic-cert",
2315        )
2316        .unwrap();
2317        assert_eq!(*renewed.key_der, key_der);
2318        assert_ne!(renewed.cert_der, legacy_der);
2319        assert!(!certificate_validity_exceeds_limit(&renewed.cert_der, 14));
2320    }
2321
2322    #[test]
2323    #[cfg(unix)]
2324    fn test_legacy_overlimit_quic_cert_fails_closed_when_readonly() {
2325        use std::os::unix::fs::PermissionsExt;
2326        let dir = TempDir::new().unwrap();
2327        let key_pair = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap();
2328        let mut params =
2329            rcgen::CertificateParams::new(vec!["discovery.example.test".into()]).unwrap();
2330        let now = time::OffsetDateTime::now_utc();
2331        params.not_before = now;
2332        params.not_after = now + time::Duration::days(14) + time::Duration::seconds(1);
2333        let legacy_der = params.self_signed(&key_pair).unwrap().der().to_vec();
2334        write_secret(dir.path(), "quic-key", &key_pair.serialize_der()).unwrap();
2335        write_secret(dir.path(), "quic-cert", &legacy_der).unwrap();
2336        std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o500)).unwrap();
2337
2338        let error = load_or_generate_tls_materials_named(
2339            dir.path(),
2340            "discovery.example.test",
2341            14,
2342            "quic-key",
2343            "quic-cert",
2344        )
2345        .err()
2346        .unwrap();
2347        assert!(error.to_string().contains("WebTransport validity limit"));
2348        assert_eq!(
2349            std::fs::read(dir.path().join("quic-cert")).unwrap(),
2350            legacy_der
2351        );
2352    }
2353
2354    #[test]
2355    #[cfg(unix)]
2356    fn test_exact_limit_quic_cert_remains_usable_when_readonly() {
2357        use std::os::unix::fs::PermissionsExt;
2358        let dir = TempDir::new().unwrap();
2359        let key_pair = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap();
2360        let mut params =
2361            rcgen::CertificateParams::new(vec!["discovery.example.test".into()]).unwrap();
2362        let now = time::OffsetDateTime::now_utc();
2363        params.not_before = now;
2364        params.not_after = now + time::Duration::days(14);
2365        let cert_der = params.self_signed(&key_pair).unwrap().der().to_vec();
2366        assert!(!certificate_validity_exceeds_limit(&cert_der, 14));
2367        write_secret(dir.path(), "quic-key", &key_pair.serialize_der()).unwrap();
2368        write_secret(dir.path(), "quic-cert", &cert_der).unwrap();
2369        std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o500)).unwrap();
2370
2371        let loaded = load_or_generate_tls_materials_named(
2372            dir.path(),
2373            "discovery.example.test",
2374            14,
2375            "quic-key",
2376            "quic-cert",
2377        )
2378        .unwrap();
2379        assert_eq!(loaded.cert_der, cert_der);
2380    }
2381
2382    #[test]
2383    fn test_tls_materials_ip_address_sans_survive_restart() {
2384        for server_name in ["127.0.0.1", "::1"] {
2385            let dir = TempDir::new().unwrap();
2386            let first = load_or_generate_tls_materials_named(
2387                dir.path(),
2388                server_name,
2389                14,
2390                "quic-key",
2391                "quic-cert",
2392            )
2393            .unwrap();
2394            assert!(certificate_covers_name(&first.cert_der, server_name));
2395            let restarted = load_or_generate_tls_materials_named(
2396                dir.path(),
2397                server_name,
2398                14,
2399                "quic-key",
2400                "quic-cert",
2401            )
2402            .unwrap();
2403            assert_eq!(first.cert_der, restarted.cert_der);
2404        }
2405    }
2406
2407    #[test]
2408    #[cfg(unix)]
2409    fn test_tls_materials_readonly_no_key_fails() {
2410        use std::os::unix::fs::PermissionsExt;
2411        let parent = TempDir::new().unwrap();
2412        let secrets_dir = parent.path().join("secrets");
2413        std::fs::create_dir(&secrets_dir).unwrap();
2414        std::fs::set_permissions(&secrets_dir, std::fs::Permissions::from_mode(0o500)).unwrap();
2415        let result = load_or_generate_tls_materials(&secrets_dir, "localhost", 365);
2416        assert!(result.is_err(), "expected error for unwritable dir");
2417    }
2418
2419    // ── cert_renewal_needed: mtime-based logic ───────────────────────────────
2420
2421    #[test]
2422    #[cfg(unix)]
2423    fn test_cert_renewal_not_needed_for_fresh_cert() {
2424        let dir = TempDir::new().unwrap();
2425        write_secret(dir.path(), "tls-cert", b"fake-cert-data").unwrap();
2426        // A freshly created file should not need renewal under a 365-day window.
2427        assert!(!cert_renewal_needed(dir.path(), "tls-cert", 365));
2428    }
2429
2430    #[test]
2431    #[cfg(unix)]
2432    fn test_cert_renewal_needed_for_old_cert() {
2433        let dir = TempDir::new().unwrap();
2434        write_secret(dir.path(), "tls-cert", b"fake-cert-data").unwrap();
2435        let cert_path = dir.path().join("tls-cert");
2436        // Backdate the cert file mtime by 365 days.
2437        backdate_mtime(&cert_path, 365);
2438        // Now renewal should be triggered (elapsed >= 364 days = threshold for 365d validity).
2439        assert!(cert_renewal_needed(dir.path(), "tls-cert", 365));
2440    }
2441
2442    #[test]
2443    #[cfg(unix)]
2444    fn test_cert_renewal_triggers_regen_with_same_key() {
2445        use sha2::{Digest, Sha256};
2446        let dir = TempDir::new().unwrap();
2447        let m1 = load_or_generate_tls_materials(dir.path(), "localhost", 365).unwrap();
2448        // Backdate the cert file to trigger mtime-based renewal.
2449        backdate_mtime(&dir.path().join("tls-cert"), 365);
2450        let m2 = load_or_generate_tls_materials(dir.path(), "localhost", 365).unwrap();
2451        // Key bytes must be unchanged (stable key = stable cert hash lineage).
2452        assert_eq!(
2453            *m1.key_der, *m2.key_der,
2454            "key must be reused on cert renewal"
2455        );
2456        // Cert is a different DER (different timestamps).
2457        let h1 = Sha256::digest(&m1.cert_der);
2458        let h2 = Sha256::digest(&m2.cert_der);
2459        assert_ne!(
2460            h1, h2,
2461            "renewed cert should have different DER due to new timestamps"
2462        );
2463    }
2464
2465    // ── resolve_service_signing_key (#759 regression) ────────────────────────
2466
2467    #[test]
2468    fn test_resolve_service_signing_key_policy_matches_bootstrap_root_key() {
2469        // Reproduces the bootstrap flow in `bootstrap_manager::do_bootstrap`:
2470        // the root key is written flat as "signing-key" and its verifying key
2471        // is what gets registered as `bootstrap_pubkeys["policy"]` — PolicyService
2472        // never gets an independent `policy/signing-key` file.
2473        let dir = TempDir::new().unwrap();
2474        let root_key = load_or_generate_node_signing_key(dir.path()).unwrap();
2475
2476        // Standalone (non-systemd) `--ipc` startup, resolving policy's own key —
2477        // this must equal the root key bootstrap registered, not a freshly
2478        // minted independent key.
2479        let resolved =
2480            resolve_service_signing_key(dir.path(), "policy", SecretsProfile::SharedDirectory)
2481                .unwrap();
2482        assert_eq!(
2483            resolved.to_bytes(),
2484            root_key.to_bytes(),
2485            "policy must resolve to the flat root/CA key, matching bootstrap_pubkeys[\"policy\"]"
2486        );
2487
2488        // No independent `policy/signing-key` file should have been created.
2489        assert!(
2490            read_secret(&dir.path().join("policy"), "signing-key")
2491                .unwrap()
2492                .is_none(),
2493            "resolving policy's key must not mint an independent per-service key file"
2494        );
2495    }
2496
2497    #[test]
2498    fn test_resolve_service_signing_key_policy_matches_root_key_when_scoped() {
2499        let dir = TempDir::new().unwrap();
2500        let root_key = load_or_generate_node_signing_key(dir.path()).unwrap();
2501        let resolved =
2502            resolve_service_signing_key(dir.path(), "policy", SecretsProfile::PerServiceScoped)
2503                .unwrap();
2504        assert_eq!(resolved.to_bytes(), root_key.to_bytes());
2505    }
2506
2507    #[test]
2508    fn test_resolve_service_signing_key_non_policy_uses_flat_key_when_scoped() {
2509        let dir = TempDir::new().unwrap();
2510        let flat_key = load_or_generate_node_signing_key(dir.path()).unwrap();
2511        let resolved =
2512            resolve_service_signing_key(dir.path(), "model", SecretsProfile::PerServiceScoped)
2513                .unwrap();
2514
2515        assert_eq!(resolved.to_bytes(), flat_key.to_bytes());
2516        assert!(!dir.path().join("model").exists());
2517    }
2518
2519    #[test]
2520    fn test_resolve_service_signing_key_non_policy_uses_independent_subdir_key() {
2521        let dir = TempDir::new().unwrap();
2522        let root_key = load_or_generate_node_signing_key(dir.path()).unwrap();
2523
2524        let model_key =
2525            resolve_service_signing_key(dir.path(), "model", SecretsProfile::SharedDirectory)
2526                .unwrap();
2527        assert_ne!(
2528            model_key.to_bytes(), root_key.to_bytes(),
2529            "non-policy services must keep their own independent key, distinct from the root/CA key"
2530        );
2531
2532        // Independent key file lives under the service subdirectory.
2533        let from_disk = read_secret(&dir.path().join("model"), "signing-key")
2534            .unwrap()
2535            .unwrap();
2536        assert_eq!(from_disk, model_key.to_bytes().to_vec());
2537    }
2538
2539    #[test]
2540    fn test_resolve_service_signing_key_is_stable_across_calls() {
2541        // Simulates repeated resolution (e.g. across a restart) — the same
2542        // key must come back every time, for both policy and non-policy.
2543        let dir = TempDir::new().unwrap();
2544        let _root_key = load_or_generate_node_signing_key(dir.path()).unwrap();
2545
2546        let policy_1 =
2547            resolve_service_signing_key(dir.path(), "policy", SecretsProfile::SharedDirectory)
2548                .unwrap();
2549        let policy_2 =
2550            resolve_service_signing_key(dir.path(), "policy", SecretsProfile::SharedDirectory)
2551                .unwrap();
2552        assert_eq!(policy_1.to_bytes(), policy_2.to_bytes());
2553
2554        let model_1 =
2555            resolve_service_signing_key(dir.path(), "model", SecretsProfile::SharedDirectory)
2556                .unwrap();
2557        let model_2 =
2558            resolve_service_signing_key(dir.path(), "model", SecretsProfile::SharedDirectory)
2559                .unwrap();
2560        assert_eq!(model_1.to_bytes(), model_2.to_bytes());
2561    }
2562
2563    // ── service key public sidecars (#1562 H1) ──────────────────────────────
2564
2565    #[cfg(unix)]
2566    fn file_mode(path: &std::path::Path) -> u32 {
2567        use std::os::unix::fs::PermissionsExt;
2568        std::fs::metadata(path).unwrap().permissions().mode() & 0o777
2569    }
2570
2571    #[test]
2572    fn test_service_key_sidecars_written_on_generate() {
2573        let dir = TempDir::new().unwrap();
2574        let key = load_or_generate_service_signing_key(dir.path(), "discovery").unwrap();
2575        let svc = dir.path().join("discovery");
2576
2577        let pub_bytes = std::fs::read(svc.join(SIGNING_KEY_PUB_NAME)).unwrap();
2578        assert_eq!(pub_bytes, key.verifying_key().as_bytes());
2579
2580        let hybrid_bytes = std::fs::read(svc.join(SERVICE_PUBKEY_HYBRID_NAME)).unwrap();
2581        let expected = BootstrapPubkey::for_service_key(&key)
2582            .unwrap()
2583            .to_key_bytes();
2584        assert_eq!(hybrid_bytes, expected);
2585        assert_eq!(hybrid_bytes.len(), 1984);
2586
2587        #[cfg(unix)]
2588        {
2589            assert_eq!(file_mode(&svc.join("signing-key")), 0o600);
2590            assert_eq!(file_mode(&svc.join(SIGNING_KEY_PUB_NAME)), 0o644);
2591            assert_eq!(file_mode(&svc.join(SERVICE_PUBKEY_HYBRID_NAME)), 0o644);
2592        }
2593    }
2594
2595    #[test]
2596    fn test_service_key_sidecars_backfilled_on_load_of_preexisting_seed() {
2597        let dir = TempDir::new().unwrap();
2598        // Simulate a pre-H1 install: only the seed exists, no sidecars.
2599        let seed = SigningKey::generate(&mut rand::rngs::OsRng);
2600        write_secret(
2601            &dir.path().join("discovery"),
2602            "signing-key",
2603            &seed.to_bytes(),
2604        )
2605        .unwrap();
2606        let svc = dir.path().join("discovery");
2607        assert!(!svc.join(SIGNING_KEY_PUB_NAME).exists());
2608        assert!(!svc.join(SERVICE_PUBKEY_HYBRID_NAME).exists());
2609
2610        let loaded = load_or_generate_service_signing_key(dir.path(), "discovery").unwrap();
2611        assert_eq!(
2612            loaded.to_bytes(),
2613            seed.to_bytes(),
2614            "load must adopt the existing seed, not rotate it"
2615        );
2616
2617        let pub_bytes = std::fs::read(svc.join(SIGNING_KEY_PUB_NAME)).unwrap();
2618        assert_eq!(pub_bytes, seed.verifying_key().as_bytes());
2619        let hybrid_bytes = std::fs::read(svc.join(SERVICE_PUBKEY_HYBRID_NAME)).unwrap();
2620        assert_eq!(
2621            hybrid_bytes,
2622            BootstrapPubkey::for_service_key(&seed)
2623                .unwrap()
2624                .to_key_bytes()
2625        );
2626        #[cfg(unix)]
2627        {
2628            assert_eq!(file_mode(&svc.join(SIGNING_KEY_PUB_NAME)), 0o644);
2629            assert_eq!(file_mode(&svc.join(SERVICE_PUBKEY_HYBRID_NAME)), 0o644);
2630        }
2631    }
2632
2633    #[test]
2634    fn test_service_key_sidecars_idempotent() {
2635        let dir = TempDir::new().unwrap();
2636        let first = load_or_generate_service_signing_key(dir.path(), "registry").unwrap();
2637        let svc = dir.path().join("registry");
2638        let pub1 = std::fs::read(svc.join(SIGNING_KEY_PUB_NAME)).unwrap();
2639        let hyb1 = std::fs::read(svc.join(SERVICE_PUBKEY_HYBRID_NAME)).unwrap();
2640
2641        let second = load_or_generate_service_signing_key(dir.path(), "registry").unwrap();
2642        assert_eq!(
2643            first.to_bytes(),
2644            second.to_bytes(),
2645            "re-running must not rotate the key"
2646        );
2647        assert_eq!(std::fs::read(svc.join(SIGNING_KEY_PUB_NAME)).unwrap(), pub1);
2648        assert_eq!(
2649            std::fs::read(svc.join(SERVICE_PUBKEY_HYBRID_NAME)).unwrap(),
2650            hyb1
2651        );
2652        #[cfg(unix)]
2653        {
2654            assert_eq!(file_mode(&svc.join(SIGNING_KEY_PUB_NAME)), 0o644);
2655            assert_eq!(file_mode(&svc.join(SERVICE_PUBKEY_HYBRID_NAME)), 0o644);
2656        }
2657    }
2658
2659    #[test]
2660    fn test_service_key_sidecars_contain_no_secret_material() {
2661        let dir = TempDir::new().unwrap();
2662        let key = load_or_generate_service_signing_key(dir.path(), "model").unwrap();
2663        let seed = key.to_bytes();
2664        let svc = dir.path().join("model");
2665
2666        for name in [SIGNING_KEY_PUB_NAME, SERVICE_PUBKEY_HYBRID_NAME] {
2667            let bytes = std::fs::read(svc.join(name)).unwrap();
2668            assert_ne!(bytes, seed.as_slice());
2669            assert!(
2670                !bytes.windows(seed.len()).any(|w| w == seed.as_slice()),
2671                "{name} must not embed the seed anywhere"
2672            );
2673        }
2674
2675        // Positive control: the sidecar bytes are exactly the public derivation
2676        // of the seed — Ed25519 verifying key, then the derived ML-DSA-65
2677        // verifying key.
2678        let pub_bytes = std::fs::read(svc.join(SIGNING_KEY_PUB_NAME)).unwrap();
2679        assert_eq!(pub_bytes, key.verifying_key().as_bytes());
2680        let pq_sk = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&key);
2681        let pq_vk = hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk_bytes(&pq_sk);
2682        let hybrid_bytes = std::fs::read(svc.join(SERVICE_PUBKEY_HYBRID_NAME)).unwrap();
2683        assert_eq!(&hybrid_bytes[..32], key.verifying_key().as_bytes());
2684        assert_eq!(&hybrid_bytes[32..], pq_vk.as_slice());
2685    }
2686
2687    #[test]
2688    fn test_service_signing_key_dir_matches_resolve_layout() {
2689        let base = std::path::Path::new("/credentials");
2690        assert_eq!(
2691            service_signing_key_dir(base, "policy", SecretsProfile::SharedDirectory),
2692            base
2693        );
2694        assert_eq!(
2695            service_signing_key_dir(base, "policy", SecretsProfile::PerServiceScoped),
2696            base
2697        );
2698        assert_eq!(
2699            service_signing_key_dir(base, "model", SecretsProfile::PerServiceScoped),
2700            base
2701        );
2702        assert_eq!(
2703            service_signing_key_dir(base, "model", SecretsProfile::SharedDirectory),
2704            base.join("model")
2705        );
2706    }
2707
2708    // ── bootstrap-pubkeys wire format ────────────────────────────────────────
2709
2710    fn bootstrap_ed_key(seed: u8) -> SigningKey {
2711        SigningKey::from_bytes(&[seed; 32])
2712    }
2713
2714    /// Write a `bootstrap-pubkeys` file verbatim, as an external provisioner
2715    /// (or an older release of this code) would have left it on disk.
2716    fn write_raw_bootstrap_pubkeys(dir: &std::path::Path, entries: &[(&str, &str)]) {
2717        let json: std::collections::BTreeMap<&str, &str> = entries.iter().copied().collect();
2718        write_secret(
2719            dir,
2720            "bootstrap-pubkeys",
2721            &serde_json::to_vec(&json).unwrap(),
2722        )
2723        .unwrap();
2724    }
2725
2726    // ── mandatory hybrid service entries ─────────────────────────────────────
2727
2728    /// A classical service entry is a hard, actionable error — never a silent
2729    /// downgrade to the classical floor.
2730    #[test]
2731    fn classical_service_entry_is_a_hard_actionable_error() {
2732        let dir = TempDir::new().unwrap();
2733        let mut map = std::collections::HashMap::new();
2734        map.insert(
2735            "discovery".to_owned(),
2736            BootstrapPubkey::classical(bootstrap_ed_key(11).verifying_key()),
2737        );
2738        map.insert(
2739            "policy".to_owned(),
2740            BootstrapPubkey::for_service_key(&bootstrap_ed_key(12)).unwrap(),
2741        );
2742        write_bootstrap_pubkeys_hybrid(dir.path(), &map).unwrap();
2743
2744        // The low-level loader still reads the file, so the error can name the
2745        // offending entries precisely.
2746        let loaded = load_bootstrap_pubkeys_hybrid(dir.path()).unwrap();
2747        assert_eq!(loaded.len(), 2);
2748
2749        let err = format!(
2750            "{:#}",
2751            ensure_bootstrap_pubkeys_hybrid(&loaded).unwrap_err()
2752        );
2753        assert!(
2754            err.contains("discovery"),
2755            "error names the classical service: {err}"
2756        );
2757        assert!(
2758            !err.contains("policy"),
2759            "error must not implicate the hybrid service: {err}"
2760        );
2761        assert!(
2762            err.contains("wizard"),
2763            "error names the working recovery: {err}"
2764        );
2765        assert!(
2766            !err.contains("service repair"),
2767            "error must not name the dead-end 'service repair' command: {err}"
2768        );
2769        assert!(
2770            err.contains("ML-DSA-65"),
2771            "error names what is missing: {err}"
2772        );
2773    }
2774
2775    /// An all-hybrid file passes, and an unprovisioned (empty) node is not an
2776    /// error — there are no service identities to be wrong about yet.
2777    #[test]
2778    fn hybrid_service_entries_and_empty_file_both_pass() {
2779        let mut map = std::collections::HashMap::new();
2780        for (name, seed) in [("policy", 21u8), ("discovery", 22), ("inference", 23)] {
2781            map.insert(
2782                name.to_owned(),
2783                BootstrapPubkey::for_service_key(&bootstrap_ed_key(seed)).unwrap(),
2784            );
2785        }
2786        ensure_bootstrap_pubkeys_hybrid(&map).unwrap();
2787        ensure_bootstrap_pubkeys_hybrid(&std::collections::HashMap::new()).unwrap();
2788    }
2789
2790    /// H3: in an OS-owned deployment an allowlisted service without a
2791    /// chain-signed enrollment attestation fails closed — the missing-file
2792    /// check fires before any chain access, so no trust dir is needed here.
2793    #[test]
2794    fn enrollment_attestation_missing_fails_closed() {
2795        let dir = TempDir::new().unwrap();
2796        let mut map = std::collections::HashMap::new();
2797        map.insert(
2798            "discovery".to_owned(),
2799            BootstrapPubkey::for_service_key(&bootstrap_ed_key(41)).unwrap(),
2800        );
2801        let err = ensure_bootstrap_pubkeys_enrolled(dir.path(), &map)
2802            .unwrap_err()
2803            .to_string();
2804        assert!(
2805            err.contains(BOOTSTRAP_PUBKEYS_ENROLLMENT_DIR),
2806            "error names the enrollment directory: {err}"
2807        );
2808        assert!(err.contains("discovery"), "error names the service: {err}");
2809    }
2810
2811    /// H3: services outside the fixed enrollment allowlist cannot be enrolled
2812    /// by design, so they require no attestation — and an empty (unprovisioned)
2813    /// node passes, matching the hybrid check's posture.
2814    #[test]
2815    fn unallowlisted_bootstrap_entries_need_no_attestation() {
2816        let dir = TempDir::new().unwrap();
2817        let mut map = std::collections::HashMap::new();
2818        map.insert(
2819            "inference".to_owned(),
2820            BootstrapPubkey::for_service_key(&bootstrap_ed_key(42)).unwrap(),
2821        );
2822        ensure_bootstrap_pubkeys_enrolled(dir.path(), &map).unwrap();
2823        ensure_bootstrap_pubkeys_enrolled(dir.path(), &std::collections::HashMap::new()).unwrap();
2824    }
2825
2826    /// A provisioned service entry round-trips through the file and then
2827    /// verifies a real hybrid signature made with the keys the service actually
2828    /// signs with — the Ed25519 key plus the ML-DSA-65 key derived from it.
2829    #[test]
2830    fn provisioned_service_entry_verifies_a_hybrid_signature_end_to_end() {
2831        use ed25519_dalek::Signer;
2832
2833        let dir = TempDir::new().unwrap();
2834        let service_key = bootstrap_ed_key(31);
2835
2836        let mut map = std::collections::HashMap::new();
2837        map.insert(
2838            "discovery".to_owned(),
2839            BootstrapPubkey::for_service_key(&service_key).unwrap(),
2840        );
2841        write_bootstrap_pubkeys_hybrid(dir.path(), &map).unwrap();
2842
2843        let loaded = load_bootstrap_pubkeys_hybrid(dir.path()).unwrap();
2844        let entry = &loaded["discovery"];
2845        assert!(entry.is_hybrid());
2846        ensure_bootstrap_pubkeys_hybrid(&loaded).unwrap();
2847
2848        // Sign exactly as the service's own signer does.
2849        let msg = b"service response payload";
2850        let ed_sig = service_key.sign(msg);
2851        let pq_sk = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&service_key);
2852        let pq_sig = hyprstream_rpc::crypto::pq::ml_dsa_sign(&pq_sk, msg);
2853
2854        entry.verify(msg, &ed_sig, Some(&pq_sig)).unwrap();
2855
2856        // And the Ed25519 signature alone is not enough for a provisioned service.
2857        assert!(
2858            entry.verify(msg, &ed_sig, None).is_err(),
2859            "a provisioned service entry must require both signatures"
2860        );
2861    }
2862
2863    #[test]
2864    fn bootstrap_pubkeys_classical_round_trip() {
2865        let dir = TempDir::new().unwrap();
2866        let vk = bootstrap_ed_key(7).verifying_key();
2867
2868        let mut map = std::collections::HashMap::new();
2869        map.insert("discovery".to_owned(), vk);
2870        write_bootstrap_pubkeys(dir.path(), &map).unwrap();
2871
2872        let loaded = load_bootstrap_pubkeys(dir.path()).unwrap();
2873        assert_eq!(loaded.get("discovery"), Some(&vk));
2874
2875        let hybrid = load_bootstrap_pubkeys_hybrid(dir.path()).unwrap();
2876        let entry = &hybrid["discovery"];
2877        assert!(
2878            !entry.is_hybrid(),
2879            "an entry written from a bare Ed25519 key is classical"
2880        );
2881        assert_eq!(entry.to_key_bytes().len(), 32);
2882    }
2883
2884    #[test]
2885    fn bootstrap_pubkeys_hybrid_round_trip() {
2886        let dir = TempDir::new().unwrap();
2887        let ed = bootstrap_ed_key(9).verifying_key();
2888        let (_pq_sk, pq_vk) = hyprstream_rpc::crypto::pq::ml_dsa_generate_keypair();
2889
2890        let mut map = std::collections::HashMap::new();
2891        map.insert(
2892            "discovery".to_owned(),
2893            BootstrapPubkey::hybrid(ed, pq_vk.clone()),
2894        );
2895        write_bootstrap_pubkeys_hybrid(dir.path(), &map).unwrap();
2896
2897        let loaded = load_bootstrap_pubkeys_hybrid(dir.path()).unwrap();
2898        let entry = &loaded["discovery"];
2899        assert!(entry.is_hybrid());
2900        assert_eq!(entry.ed25519, ed);
2901        assert_eq!(
2902            hyprstream_rpc::crypto::pq::ml_dsa_vk_bytes(entry.ml_dsa_65.as_ref().unwrap()),
2903            hyprstream_rpc::crypto::pq::ml_dsa_vk_bytes(&pq_vk)
2904        );
2905        assert_eq!(entry.to_key_bytes().len(), 1984);
2906
2907        // The Ed25519-only projection still sees the anchor, so callers that
2908        // predate hybrid entries keep resolving the same key.
2909        assert_eq!(
2910            load_bootstrap_pubkeys(dir.path()).unwrap().get("discovery"),
2911            Some(&ed)
2912        );
2913    }
2914
2915    #[test]
2916    fn bootstrap_pubkeys_legacy_file_loads_unchanged() {
2917        let dir = TempDir::new().unwrap();
2918        let discovery = bootstrap_ed_key(0x11).verifying_key();
2919        let policy = bootstrap_ed_key(0x22).verifying_key();
2920
2921        // Exactly the shape deployed nodes and external provisioning emit:
2922        // a flat map of URL-safe-no-pad base64 over 32 raw Ed25519 bytes.
2923        write_raw_bootstrap_pubkeys(
2924            dir.path(),
2925            &[
2926                ("discovery", &URL_SAFE_NO_PAD.encode(discovery.as_bytes())),
2927                ("policy", &URL_SAFE_NO_PAD.encode(policy.as_bytes())),
2928            ],
2929        );
2930
2931        let loaded = load_bootstrap_pubkeys(dir.path()).unwrap();
2932        assert_eq!(loaded.len(), 2);
2933        assert_eq!(loaded.get("discovery"), Some(&discovery));
2934        assert_eq!(loaded.get("policy"), Some(&policy));
2935
2936        let hybrid = load_bootstrap_pubkeys_hybrid(dir.path()).unwrap();
2937        assert!(hybrid.values().all(|e| !e.is_hybrid()));
2938    }
2939
2940    #[test]
2941    fn bootstrap_pubkeys_mixed_file_verifies_per_identity() {
2942        let dir = TempDir::new().unwrap();
2943        let legacy_sk = bootstrap_ed_key(0x33);
2944        let hybrid_ed_sk = bootstrap_ed_key(0x44);
2945        let (pq_sk, pq_vk) = hyprstream_rpc::crypto::pq::ml_dsa_generate_keypair();
2946
2947        let hybrid_entry = BootstrapPubkey::hybrid(hybrid_ed_sk.verifying_key(), pq_vk);
2948        write_raw_bootstrap_pubkeys(
2949            dir.path(),
2950            &[
2951                (
2952                    "policy",
2953                    &URL_SAFE_NO_PAD.encode(legacy_sk.verifying_key().as_bytes()),
2954                ),
2955                (
2956                    "discovery",
2957                    &URL_SAFE_NO_PAD.encode(hybrid_entry.to_key_bytes()),
2958                ),
2959            ],
2960        );
2961
2962        let loaded = load_bootstrap_pubkeys_hybrid(dir.path()).unwrap();
2963        assert_eq!(loaded.len(), 2);
2964
2965        let msg = b"bootstrap trust seed";
2966
2967        // Classical entry: an Ed25519 signature alone is sufficient, and no
2968        // post-quantum material is demanded of it.
2969        let legacy = &loaded["policy"];
2970        assert!(!legacy.is_hybrid());
2971        let legacy_sig = {
2972            use ed25519_dalek::Signer;
2973            legacy_sk.sign(msg)
2974        };
2975        legacy.verify(msg, &legacy_sig, None).unwrap();
2976
2977        // Hybrid entry: both signatures are required, and the classical half
2978        // alone is rejected.
2979        let hybrid = &loaded["discovery"];
2980        assert!(hybrid.is_hybrid());
2981        let hybrid_ed_sig = {
2982            use ed25519_dalek::Signer;
2983            hybrid_ed_sk.sign(msg)
2984        };
2985        let pq_sig = hyprstream_rpc::crypto::pq::ml_dsa_sign(&pq_sk, msg);
2986        hybrid.verify(msg, &hybrid_ed_sig, Some(&pq_sig)).unwrap();
2987        assert!(
2988            hybrid.verify(msg, &hybrid_ed_sig, None).is_err(),
2989            "a hybrid entry must not verify on the Ed25519 signature alone"
2990        );
2991
2992        // A post-quantum signature has nothing to check against on a classical
2993        // entry, so it is rejected rather than silently ignored.
2994        assert!(legacy.verify(msg, &legacy_sig, Some(&pq_sig)).is_err());
2995    }
2996
2997    #[test]
2998    fn bootstrap_pubkeys_reject_wrong_length_values() {
2999        let dir = TempDir::new().unwrap();
3000        // 33 bytes: neither the classical nor the hybrid length.
3001        write_raw_bootstrap_pubkeys(
3002            dir.path(),
3003            &[("discovery", &URL_SAFE_NO_PAD.encode([0u8; 33]))],
3004        );
3005
3006        let err = load_bootstrap_pubkeys(dir.path()).unwrap_err().to_string();
3007        assert!(
3008            err.contains("'discovery'"),
3009            "error names the offending service: {err}"
3010        );
3011        assert!(
3012            err.contains("32 bytes"),
3013            "error states the classical shape: {err}"
3014        );
3015        assert!(
3016            err.contains("1984 bytes"),
3017            "error states the hybrid shape: {err}"
3018        );
3019        assert!(
3020            err.contains("got 33 bytes"),
3021            "error states what was found: {err}"
3022        );
3023    }
3024
3025    #[test]
3026    fn bootstrap_pubkeys_reject_standard_alphabet_base64() {
3027        let dir = TempDir::new().unwrap();
3028        // Standard-alphabet base64 with padding is not the documented alphabet.
3029        write_raw_bootstrap_pubkeys(
3030            dir.path(),
3031            &[("discovery", "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=")],
3032        );
3033
3034        let err = format!("{:#}", load_bootstrap_pubkeys(dir.path()).unwrap_err());
3035        assert!(
3036            err.contains("URL-safe-no-pad"),
3037            "error states the expected alphabet: {err}"
3038        );
3039    }
3040
3041    #[test]
3042    fn bootstrap_pubkeys_reject_malformed_pq_length() {
3043        let dir = TempDir::new().unwrap();
3044        // Correct Ed25519 prefix, truncated ML-DSA-65 tail.
3045        let mut bytes = bootstrap_ed_key(0x55).verifying_key().as_bytes().to_vec();
3046        bytes.extend_from_slice(&[0u8; 1951]);
3047        write_raw_bootstrap_pubkeys(
3048            dir.path(),
3049            &[("discovery", &URL_SAFE_NO_PAD.encode(&bytes))],
3050        );
3051
3052        let err = load_bootstrap_pubkeys_hybrid(dir.path())
3053            .unwrap_err()
3054            .to_string();
3055        assert!(
3056            err.contains("1984 bytes"),
3057            "error states the hybrid shape: {err}"
3058        );
3059    }
3060
3061    /// The hybrid `discovery` value published as the worked example in
3062    /// `docs/bootstrap-pubkeys-format.md`. Kept verbatim so the documented
3063    /// example cannot drift away from what the parser actually accepts.
3064    const DOC_EXAMPLE_HYBRID_VALUE: &str = "JIrL26-eBQGW3nBL6i1odw5RkVDRA7WH2uLZytU92TAXHtJkdXNEM19SNj1GPxnt-7mImdVPdRRENw5lnPLIVkDc3BiWsqDvmLI2x9roidQrSRArrQ-itYpEyQaLf-y6ckpa1NdkeN9ibwNu393M3E8PD2N3Vh9vx_sD2mbn532l0QXGV3i-9lQppfKcFwzinBkQN7eLLWRrInMfbE3IY_7FnC9Q0scH7bUMBvNY7k5jEDNtz1ZpEWgR-1u2M-iF221WgzT9AnQX5X88dd9gYs0SsIHLjx5o8-nnHk0XRxPq1JtegEupUKLf5a7e3IEm62VSXRJhH_V2IA9PAJMlSL8rJGYHdMwjscP1DyKCpCquSgYIH8zJDQCPqVUFBujtdq3x-eMFd0CxpVssPuLeoNb_4YZbtSwdk6iMMPupiDYIKOgknxymsnYGxR1PiA_7b1lZVaD62pCZHSCi9nJEDVoWuQ0_cSMB589zaDSTcI7r5Ks6l0MUPtVsa_yWQ4jwS8GnDMikXXmLvKegE5V6rZpG6AXx707kEvpxyESIzwnMU9UO2h4MGI1uWp36SXzHxF5RSZrY3Wr1ei1MwnJj7kgve4w1skjtZ32EE4A8r7R8mIl8L6LkXsD6n4FXFWQWocLdBerVvVBSDTDca8mQ3Lqr-3Q8wasUx-Ifqk6AAOZTmPseQ50uoiZnr0MCzxVkbAmvB5o_I5J_BqxKqQUimv0xiq69n9Vr__7FS8HTd9139LUPBkBDduZeH4qqJyIkDshEPJeXqOwBQZDIupnjc-PvDNKRM6o8Kg1OtaBjYwWWL6pVFRXYw3NeGb52N77-T9dEOCR659RHFrI-741xIaJ_gTJb6G43C7Go-EMI0aMkzakh-LSyTrv4C2s-KYksgVap-EsREaKmX1FAinmWsn0222V-tzJ-9dvPKKwCnTyTXpYRK3ltR-3LnP-onbg4ysP_tpVMg8K7jAeCzYsEEZCIjoJr5qpTkwGncfytwVvT6sHsoD988S10in7Dz9TNcNnFmb_foYqELht6jhAv_X6nf8IJEZgaLNaz9eV-_L87TdgQDF4iKrgHcuUZjPlfi-az1B6uV1Z7pqUsqJBT5XQkCqr3j4chZ2gNEw8SpconZVuXsT1tEtSWyo9GmvNntsiCvGM30faWGj-_cIsrCveMeMfLLsfNP3X7jG7Jgb7uYbj50Mwf7b-VqrdAmIJ0CMmCSygBaWV7YDx_qTEEuE7oL-R6_fXkhmXeZYyhFPF-As70CrVW-KwAJVp0mYasmPwu9YZ-Mlerg-QgHiAXnNpVjXE-wvnqP6JKbrbgaUZiLC4gXn0VTnB70y4e97Efl8ztGqE7AazPxwRMDyfher5oGpVm2lh9StBZYqaoAO7XQTUKvczld7imzqDugagVpWRW7ffE5qKp0ezq5PUwws4GB7UfTrmBm2gQ2HmT8aouV15b5zJaI1x9sOsNUjFrL1yL3V-Fi8adOXfRc5MR1JzdsaAki5YZhyjjYEHzdZfD8mwvN8jxN5U03tq495bR87ER_tHZNNd875gYZNYQ-pkD8zBlLWq54mDj5AKCwdTce3gOVTx9CtNYm3LFxsaB9VL_B93X81IR_Czaf_cHNQPsTpd8wWCWTZbc9zBhHUYtlrTrxhzXV68yBDcjnVF3LkbOcqapBCsUTrQ6XgloOp-fkUYd1LWTQN7ofcCXvR7x30BXXsM_qZnlUR4zminj2lWlJacV90Uqf7SL4HAEefqH8btyoVepUG_5JYQ7bp7NsUWUlw-Jc0hkumvNcaNX5uNFCLIIVTGgA9dG8ELuC3g-bhVjokIr4wSHVCyjFJs2qo93VdHy-abKdwpjeRwo6r66uaideZKEBxKUlZ_XHiZmT_FksJZIOHrq-8gQVPyjwo0oyI9Dq8xF-5aVN8NpHaJU7x4VcsndfHqsY5CGQUV0ZfuDpA94Srx-vvnvAJeM8ql63Ng2-0dNDra6fr8fgdEZeyJaIhdVBU8wBlshyeX32N2dbiJR7qWY5VqLbaKjePvqLa1LnnMtWdS2PqMX2UE_Q44Oa_FUdOB2sFdvKpxEbHDS74w5sd6C5AZzYPNUL1ICrV1F-c0Mxm9Z2j8PFEuYDz6fpR4Z1iDzLH9QKFUwus9fPzCU7b-ptTU3T3vnFTN4NLgxR6Ih78B-Mp3QrrCOxW3NtBNpnImuqHgRYBBPkg_dM659hgNtgCMYefiQuWJlpS22GG3kwPVuHoG8eqa-NDtxgMgFOPy30IKJcLh9ooG-QD9reZht_TBkLWbDW1JfeINAeJ86oZ5g3qtTdVAftVHaRCHLQN0ClLXPquM-v1GJm2F_tIXFJF-utsp0SgCDKo2VUymmMSgXQL3iP29lHQcp6Jzgisk6ZAEs6MqzrGV-T0cl0sQ4pKECzGHUL-8B8CKmMtshHZLCX4hvc3ALGd8ls72e6sh2JkFcU84I_8GLPgJu66dN5eZtOPR9CkmTKa2Ph1MgXqBGwmcYcvlg5GVZvzZC-UlhTrF7WAbObzDrGQbIGHBKG09dobSuSXpiSmZljJUh-88qsTXEVW12C4ZoWyDQ4OzH09JofMByTzb-k5Hn8cKIawcJBqCaAXElF5Z6MLrxxwagcL9XuMMdKG3UtEWY9HrsGY6qsA";
3065
3066    #[test]
3067    fn documented_hybrid_example_loads_as_a_hybrid_entry() {
3068        let dir = TempDir::new().unwrap();
3069        write_raw_bootstrap_pubkeys(dir.path(), &[("discovery", DOC_EXAMPLE_HYBRID_VALUE)]);
3070
3071        let loaded = load_bootstrap_pubkeys_hybrid(dir.path()).unwrap();
3072        let entry = &loaded["discovery"];
3073        assert!(
3074            entry.is_hybrid(),
3075            "the documented example must be a hybrid entry"
3076        );
3077        assert_eq!(entry.to_key_bytes().len(), 1984);
3078        // The documented Ed25519 anchor is the leading 43 base64 characters.
3079        assert!(
3080            DOC_EXAMPLE_HYBRID_VALUE.starts_with(&URL_SAFE_NO_PAD.encode(entry.ed25519.as_bytes())),
3081            "the documented anchor prefix must be the entry's Ed25519 key"
3082        );
3083    }
3084}