Skip to main content

hyprstream_core/cli/
enroll.rs

1//! Shared user-signing-key enrollment routine (#438 wizard + #439 `user create`).
2//!
3//! Enrolling a usable client identity is a register → store → bind sequence
4//! whose silent partial failure leaves the CLI authenticating as `anonymous`
5//! (#438/#439). This module is the single place that sequence lives, so the
6//! bootstrap wizard and the `hyprstream user create` command cannot drift.
7
8use std::path::{Path, PathBuf};
9
10use anyhow::{Context, Result};
11use ed25519_dalek::{SigningKey, VerifyingKey};
12use hyprstream_rpc::crypto::CryptoPolicy;
13
14use crate::auth::identity_store::{self, UserIdentityKeys};
15use crate::auth::{pubkey_fingerprint, KeyAlgorithm, UserStore};
16
17/// Where the client signing key comes from during enrollment.
18#[derive(Debug, Clone)]
19pub enum EnrollKeySource {
20    /// Generate a fresh Ed25519 key, or reuse the existing on-disk
21    /// `user-signing-key` if one is already present (the wizard path).
22    Generate,
23    /// Adopt a raw 32-byte Ed25519 seed, installing it as the client signing key.
24    RawSeed([u8; 32]),
25    /// Adopt an already-decoded Ed25519 signing key, installing it as the
26    /// client signing key (e.g. parsed from an OpenSSH private key).
27    SigningKey(SigningKey),
28}
29
30/// Result of enrolling a user identity.
31#[derive(Debug, Clone)]
32pub struct EnrollOutcome {
33    pub username: String,
34    /// SSH-style `SHA256:` fingerprint of the bound verifying key. Always the
35    /// **Ed25519 anchor's** fingerprint (the kid) — a bound ML-DSA-65 key does
36    /// not change it.
37    pub fingerprint: String,
38    /// Algorithm actually enrolled — [`KeyAlgorithm::HybridEd25519MlDsa65`]
39    /// under a Hybrid policy, [`KeyAlgorithm::Ed25519`] under Classical. Never
40    /// hardcoded; reflects what was really written.
41    pub algorithm: KeyAlgorithm,
42    /// Path of the prior `user-signing-key` backup, if an existing key was
43    /// displaced by an adopt (`--ssh`/`--key`). `None` for `Generate`.
44    pub key_backed_up: Option<PathBuf>,
45    /// Path of the prior `user-signing-key.mldsa` backup, if a PQ sibling was
46    /// displaced by an adopt. `None` otherwise.
47    pub pq_key_backed_up: Option<PathBuf>,
48    /// Human-facing notices the caller should print verbatim (e.g. a classical
49    /// downgrade warning, or that a PQ component was generated for an adopted
50    /// SSH/seed key). Never silent.
51    pub notices: Vec<String>,
52}
53
54/// The one shared enrollment routine.
55///
56/// 1. **Register** the user record if it does not already exist (`register`
57///    overwrites pubkeys on an existing record, so it is only called when the
58///    profile is absent).
59/// 2. **Store** the resolved signing key as the client's actual
60///    `credentials/user-signing-key` (backing up any prior key on the adopt
61///    paths), so the CLI signs with *this* key.
62/// 3. **Bind** the derived public key(s) to the user, idempotently and
63///    collision-safely (see [`bind_user_signing_key_material`]).
64///
65/// Returns the bound fingerprint and algorithm so callers can verify + print
66/// enrollment actually took (`user create` shows it equals
67/// `ssh-keygen -l -E sha256` of the key).
68///
69/// `policy` selects the crypto suite (see [`resolve_and_store_identity`]). Under
70/// [`CryptoPolicy::Hybrid`] (the node default) enrollment mints an Ed25519
71/// anchor **plus** a bound ML-DSA-65 key and writes a hybrid store record; a
72/// missing/unpersistable PQ component is a hard error (fail closed). Under
73/// The test-only [`CryptoPolicy::Classical`] variant writes a classical-only
74/// identity with a loud notice — never a silent downgrade.
75pub async fn enroll_user(
76    store: &dyn UserStore,
77    secrets_dir: &Path,
78    username: &str,
79    source: EnrollKeySource,
80    policy: CryptoPolicy,
81) -> Result<EnrollOutcome> {
82    // 1. Register the user record if absent. Propagate a lookup *failure*
83    //    rather than treating it as "absent" — `register` overwrites an
84    //    existing record's bound pubkeys, so a swallowed error could drop a
85    //    real user's keys.
86    let existing = store
87        .get_profile(username)
88        .await
89        .with_context(|| format!("Failed to look up user identity '{username}'"))?;
90    if existing.is_none() {
91        store
92            .register(username)
93            .await
94            .with_context(|| format!("Failed to register user identity '{username}'"))?;
95    }
96
97    // 2. Resolve the identity key material (per source × policy) and install it
98    //    as the client key(s).
99    let resolved = resolve_and_store_identity(secrets_dir, source, policy)?;
100
101    // 3. Bind the derived public key(s) to the user (hybrid record when a PQ
102    //    component is present).
103    let vk = resolved.keys.ed.verifying_key();
104    let pq_vk = resolved.keys.pq_verifying_key_bytes();
105    bind_user_signing_key_material(store, username, vk, pq_vk).await?;
106
107    Ok(EnrollOutcome {
108        username: username.to_owned(),
109        fingerprint: pubkey_fingerprint(&vk),
110        algorithm: resolved.keys.algorithm(),
111        key_backed_up: resolved.ed_backup,
112        pq_key_backed_up: resolved.pq_backup,
113        notices: resolved.notices,
114    })
115}
116
117/// Identity key material resolved from a source × policy, already installed on
118/// disk as the client key(s).
119struct ResolvedIdentity {
120    keys: UserIdentityKeys,
121    ed_backup: Option<PathBuf>,
122    pq_backup: Option<PathBuf>,
123    notices: Vec<String>,
124}
125
126/// The downgrade notice used by Classical-policy test fixtures.
127fn classical_notice() -> String {
128    "classical-only (policy=Classical): this identity is capped at Classical MAC \
129     assurance. Production enrollment is pinned to Hybrid."
130        .to_owned()
131}
132
133/// Resolve `source` × `policy` into installed identity key material.
134///
135/// - [`EnrollKeySource::Generate`]: load/generate the Ed25519 anchor and (under
136///   Hybrid) the ML-DSA-65 sibling via
137///   [`identity_store::load_or_generate_user_identity`] — this also covers the
138///   in-place upgrade of a legacy Ed25519-only secrets dir.
139/// - [`EnrollKeySource::RawSeed`] / [`EnrollKeySource::SigningKey`] (adopt): the
140///   adopted key is the **classical component only**. Under Hybrid a fresh
141///   ML-DSA-65 key is generated and bound to the same anchor (an SSH/seed key
142///   can never make the identity hybrid by itself); a notice says so.
143fn resolve_and_store_identity(
144    secrets_dir: &Path,
145    source: EnrollKeySource,
146    policy: CryptoPolicy,
147) -> Result<ResolvedIdentity> {
148    match source {
149        EnrollKeySource::Generate => {
150            // load_or_generate persists (or reuses) the on-disk key(s) — no
151            // adopt, no backup. Fails closed under Hybrid if the PQ component
152            // cannot be provisioned.
153            let keys = identity_store::load_or_generate_user_identity(secrets_dir, policy)?;
154            let mut notices = Vec::new();
155            if keys.mldsa.is_none() {
156                notices.push(classical_notice());
157            }
158            Ok(ResolvedIdentity {
159                keys,
160                ed_backup: None,
161                pq_backup: None,
162                notices,
163            })
164        }
165        EnrollKeySource::RawSeed(seed) => adopt_identity(
166            secrets_dir,
167            SigningKey::from_bytes(&seed),
168            policy,
169            &pq_generate,
170        ),
171        EnrollKeySource::SigningKey(sk) => adopt_identity(secrets_dir, sk, policy, &pq_generate),
172    }
173}
174
175/// Generate a fresh ML-DSA-65 signing key (indirection kept small so the adopt
176/// path reads clearly).
177fn pq_generate() -> hyprstream_rpc::crypto::pq::MlDsaSigningKey {
178    hyprstream_rpc::crypto::pq::ml_dsa_generate_keypair().0
179}
180
181/// Install an adopted Ed25519 key as the client anchor, minting + binding a
182/// fresh ML-DSA-65 component under Hybrid.
183fn adopt_identity(
184    secrets_dir: &Path,
185    ed_sk: SigningKey,
186    policy: CryptoPolicy,
187    pq_gen: &dyn Fn() -> hyprstream_rpc::crypto::pq::MlDsaSigningKey,
188) -> Result<ResolvedIdentity> {
189    let mut notices = Vec::new();
190    let mldsa = if policy.uses_pq() {
191        notices.push(
192            "adopted SSH/seed key is classical; a post-quantum ML-DSA-65 component \
193             was generated and bound to the same anchor."
194                .to_owned(),
195        );
196        Some(pq_gen())
197    } else {
198        notices.push(classical_notice());
199        None
200    };
201
202    let backup = identity_store::install_user_identity(secrets_dir, &ed_sk, mldsa.as_ref())?;
203    let keys = UserIdentityKeys { ed: ed_sk, mldsa };
204    Ok(ResolvedIdentity {
205        keys,
206        ed_backup: backup.ed,
207        pq_backup: backup.pq,
208        notices,
209    })
210}
211
212/// Bind a user-signing-key public key to `username`, idempotently and
213/// collision-safely.
214///
215/// `add_pubkey` rejects a fingerprint that is already bound (to the same or a
216/// different user), so the current binding is resolved first:
217/// - already bound to `username` → no-op (the key is already recognized),
218/// - bound to a *different* user (e.g. an `anonymous` record left by a prior
219///   partial run) → re-point it: remove from the old user, add to `username`,
220/// - unbound → add it.
221///
222/// Re-pointing is the least-surprising behavior: there is exactly one local
223/// user-signing-key, so it should map to exactly one identity — the one the
224/// operator is enrolling.
225///
226/// Thin classical (no-PQ) wrapper over [`bind_user_signing_key_material`], used
227/// by the wizard/enroll tests to bind a pre-existing on-disk key; production
228/// enrollment goes through [`bind_user_signing_key_material`] directly.
229#[cfg(test)]
230pub(crate) async fn bind_user_signing_key(
231    store: &dyn UserStore,
232    username: &str,
233    vk: VerifyingKey,
234) -> Result<()> {
235    bind_user_signing_key_material(store, username, vk, None).await
236}
237
238/// Bind a user-signing-key to `username`, carrying an optional bound ML-DSA-65
239/// verifying key (a hybrid record when `pq_vk` is `Some`).
240///
241/// Collision handling is keyed by the **Ed25519 anchor fingerprint** (the PQ vk
242/// never changes the kid), identical to the classical path:
243/// - already bound to `username`: no-op for classical; for hybrid, perform the
244///   in-place Ed25519 → Hybrid upgrade (idempotent) so a legacy classical record
245///   for the same anchor gains its PQ binding;
246/// - bound to a different (stale `anonymous`) user: re-point;
247/// - unbound: add.
248pub(crate) async fn bind_user_signing_key_material(
249    store: &dyn UserStore,
250    username: &str,
251    vk: VerifyingKey,
252    pq_vk: Option<Vec<u8>>,
253) -> Result<()> {
254    let fingerprint = pubkey_fingerprint(&vk);
255
256    match store.get_pubkey_user(&fingerprint).await? {
257        Some(existing) if existing == username => {
258            // Already bound to this user. Classical → nothing to do. Hybrid →
259            // upgrade in place (add_pubkey_hybrid is idempotent and lifts an
260            // existing Ed25519 record to Hybrid for the same anchor).
261            if let Some(pq) = pq_vk {
262                store
263                    .add_pubkey_hybrid(username, vk, pq, Some("enroll".to_owned()))
264                    .await?;
265            }
266            return Ok(());
267        }
268        Some(existing) => {
269            // Bound to a different (likely stale `anonymous`) user — re-point.
270            tracing::info!("Re-pointing user-signing-key from '{existing}' to '{username}'");
271            store.remove_pubkey(&existing, &fingerprint).await?;
272        }
273        None => {}
274    }
275
276    match pq_vk {
277        Some(pq) => {
278            store
279                .add_pubkey_hybrid(username, vk, pq, Some("enroll".to_owned()))
280                .await?;
281        }
282        None => {
283            store
284                .add_pubkey(username, vk, Some("enroll".to_owned()))
285                .await?;
286        }
287    }
288    Ok(())
289}
290
291#[cfg(test)]
292#[allow(clippy::unwrap_used, clippy::expect_used)]
293mod tests {
294    use super::*;
295    use crate::auth::RocksDbUserStore;
296    use tempfile::TempDir;
297
298    fn open(creds: &TempDir) -> RocksDbUserStore {
299        RocksDbUserStore::open(creds.path()).unwrap()
300    }
301
302    #[tokio::test]
303    async fn enroll_generate_registers_binds_and_tags_ed25519() {
304        let creds = TempDir::new().unwrap();
305        let secrets = TempDir::new().unwrap();
306        let store = open(&creds);
307
308        let outcome = enroll_user(
309            &store,
310            secrets.path(),
311            "alice",
312            EnrollKeySource::Generate,
313            CryptoPolicy::Classical,
314        )
315        .await
316        .unwrap();
317
318        assert_eq!(outcome.username, "alice");
319        assert_eq!(outcome.algorithm, KeyAlgorithm::Ed25519);
320        assert!(outcome.fingerprint.starts_with("SHA256:"));
321        assert!(outcome.key_backed_up.is_none(), "generate must not back up");
322
323        // Profile exists and the fingerprint reverse-maps to the user.
324        assert!(store.get_profile("alice").await.unwrap().is_some());
325        assert_eq!(
326            store.get_pubkey_user(&outcome.fingerprint).await.unwrap(),
327            Some("alice".to_owned())
328        );
329
330        // The bound key equals the on-disk user-signing-key the CLI signs with.
331        let (_sk, vk) = identity_store::load_or_generate_user_signing_key(secrets.path()).unwrap();
332        assert_eq!(
333            crate::auth::pubkey_fingerprint(&vk),
334            outcome.fingerprint,
335            "enrolled fingerprint must match the client signing key"
336        );
337    }
338
339    #[tokio::test]
340    async fn enroll_adopt_signing_key_installs_and_backs_up_existing() {
341        let creds = TempDir::new().unwrap();
342        let secrets = TempDir::new().unwrap();
343        let store = open(&creds);
344
345        // Seed the on-disk key first (simulate a prior key), then adopt a new one.
346        let (_prior, _) =
347            identity_store::load_or_generate_user_signing_key(secrets.path()).unwrap();
348        let adopted = SigningKey::generate(&mut rand::rngs::OsRng);
349        let outcome = enroll_user(
350            &store,
351            secrets.path(),
352            "bob",
353            EnrollKeySource::SigningKey(adopted),
354            CryptoPolicy::Classical,
355        )
356        .await
357        .unwrap();
358
359        // A backup of the prior key must exist, and the installed key must be the adopted one.
360        assert!(outcome.key_backed_up.as_ref().unwrap().exists());
361        let (_sk, vk) = identity_store::load_or_generate_user_signing_key(secrets.path()).unwrap();
362        assert_eq!(
363            crate::auth::pubkey_fingerprint(&vk),
364            outcome.fingerprint,
365            "installed signing key must be the adopted key"
366        );
367
368        // Re-running enroll for bob is idempotent.
369        enroll_user(
370            &store,
371            secrets.path(),
372            "bob",
373            EnrollKeySource::Generate,
374            CryptoPolicy::Classical,
375        )
376        .await
377        .unwrap();
378        assert_eq!(store.list_pubkeys("bob").await.unwrap().len(), 1);
379    }
380
381    #[tokio::test]
382    async fn enroll_repoints_from_stale_anonymous_binding() {
383        let creds = TempDir::new().unwrap();
384        let secrets = TempDir::new().unwrap();
385        let store = open(&creds);
386
387        // Generate the on-disk key and bind it to a stale "anonymous" first.
388        let (_sk, vk) = identity_store::load_or_generate_user_signing_key(secrets.path()).unwrap();
389        store.register("anonymous").await.unwrap();
390        bind_user_signing_key(&store, "anonymous", vk)
391            .await
392            .unwrap();
393        let fp = crate::auth::pubkey_fingerprint(&vk);
394        assert_eq!(
395            store.get_pubkey_user(&fp).await.unwrap(),
396            Some("anonymous".to_owned())
397        );
398
399        // Enrolling the real user must re-point the key away from anonymous.
400        let outcome = enroll_user(
401            &store,
402            secrets.path(),
403            "carol",
404            EnrollKeySource::Generate,
405            CryptoPolicy::Classical,
406        )
407        .await
408        .unwrap();
409        assert_eq!(
410            store.get_pubkey_user(&outcome.fingerprint).await.unwrap(),
411            Some("carol".to_owned())
412        );
413    }
414
415    #[tokio::test]
416    async fn enroll_raw_seed_round_trips() {
417        let creds = TempDir::new().unwrap();
418        let secrets = TempDir::new().unwrap();
419        let store = open(&creds);
420
421        let sk = SigningKey::generate(&mut rand::rngs::OsRng);
422        let seed = sk.to_bytes();
423
424        let outcome = enroll_user(
425            &store,
426            secrets.path(),
427            "dan",
428            EnrollKeySource::RawSeed(seed),
429            CryptoPolicy::Classical,
430        )
431        .await
432        .unwrap();
433        assert_eq!(
434            outcome.fingerprint,
435            crate::auth::pubkey_fingerprint(&sk.verifying_key())
436        );
437        // No prior key → no backup.
438        assert!(outcome.key_backed_up.is_none());
439    }
440
441    // ─── Hybrid (post-quantum) enrollment (#439) ─────────────────────────────
442
443    #[tokio::test]
444    async fn enroll_generate_hybrid_writes_pq_record_and_sibling_file() {
445        let creds = TempDir::new().unwrap();
446        let secrets = TempDir::new().unwrap();
447        let store = open(&creds);
448
449        let outcome = enroll_user(
450            &store,
451            secrets.path(),
452            "alice",
453            EnrollKeySource::Generate,
454            CryptoPolicy::Hybrid,
455        )
456        .await
457        .unwrap();
458
459        // The enrolled algorithm reflects reality: hybrid, not a hardcoded tag.
460        assert_eq!(outcome.algorithm, KeyAlgorithm::HybridEd25519MlDsa65);
461        assert!(
462            outcome.notices.is_empty(),
463            "hybrid generate has no downgrade notice"
464        );
465
466        // Both on-disk key files exist, each mode 0600.
467        let ed = secrets.path().join("user-signing-key");
468        let pq = secrets.path().join("user-signing-key.mldsa");
469        assert!(ed.exists() && pq.exists(), "both key files must be written");
470        #[cfg(unix)]
471        {
472            use std::os::unix::fs::PermissionsExt;
473            for p in [&ed, &pq] {
474                let mode = std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
475                assert_eq!(mode, 0o600, "{} must be 0600", p.display());
476            }
477        }
478
479        // The store record is hybrid and carries the bound ML-DSA-65 vk.
480        let keys = store.list_pubkeys("alice").await.unwrap();
481        assert_eq!(keys.len(), 1);
482        assert_eq!(keys[0].algorithm, KeyAlgorithm::HybridEd25519MlDsa65);
483        let pq_bytes = keys[0]
484            .pq_pubkey
485            .as_ref()
486            .expect("hybrid record has pq_pubkey");
487        // Matches the ML-DSA vk derived from the on-disk PQ seed.
488        let loaded =
489            identity_store::load_or_generate_user_identity(secrets.path(), CryptoPolicy::Hybrid)
490                .unwrap();
491        assert_eq!(&loaded.pq_verifying_key_bytes().unwrap(), pq_bytes);
492        // Fingerprint is the Ed25519 anchor's (kid), unchanged by the PQ key.
493        assert_eq!(
494            outcome.fingerprint,
495            crate::auth::pubkey_fingerprint(&loaded.ed.verifying_key())
496        );
497    }
498
499    #[tokio::test]
500    async fn enroll_adopt_ssh_under_hybrid_generates_pq_and_notices() {
501        let creds = TempDir::new().unwrap();
502        let secrets = TempDir::new().unwrap();
503        let store = open(&creds);
504
505        // An adopted (SSH-style) key is the classical component; under Hybrid a
506        // fresh PQ component is generated + bound, with a notice saying so.
507        let adopted = SigningKey::generate(&mut rand::rngs::OsRng);
508        let vk = adopted.verifying_key();
509        let outcome = enroll_user(
510            &store,
511            secrets.path(),
512            "erin",
513            EnrollKeySource::SigningKey(adopted),
514            CryptoPolicy::Hybrid,
515        )
516        .await
517        .unwrap();
518
519        assert_eq!(outcome.algorithm, KeyAlgorithm::HybridEd25519MlDsa65);
520        assert_eq!(
521            outcome.fingerprint,
522            crate::auth::pubkey_fingerprint(&vk),
523            "anchor fingerprint is the adopted Ed25519 key's"
524        );
525        assert!(
526            outcome.notices.iter().any(|n| n.contains("post-quantum")),
527            "must notify that a PQ component was generated for the adopted key"
528        );
529        assert!(secrets.path().join("user-signing-key.mldsa").exists());
530        let keys = store.list_pubkeys("erin").await.unwrap();
531        assert!(keys[0].pq_pubkey.is_some());
532    }
533
534    #[tokio::test]
535    async fn enroll_hybrid_readonly_secrets_fails_closed() {
536        let creds = TempDir::new().unwrap();
537        let secrets = TempDir::new().unwrap();
538        let store = open(&creds);
539
540        // Pre-seed a classical Ed25519 key, then make the dir read-only so the
541        // PQ sibling cannot be generated. Under Hybrid this MUST fail closed —
542        // never mint a classical-only identity.
543        let _ = identity_store::load_or_generate_user_signing_key(secrets.path()).unwrap();
544        #[cfg(unix)]
545        {
546            use std::os::unix::fs::PermissionsExt;
547            std::fs::set_permissions(secrets.path(), std::fs::Permissions::from_mode(0o500))
548                .unwrap();
549
550            let err = enroll_user(
551                &store,
552                secrets.path(),
553                "frank",
554                EnrollKeySource::Generate,
555                CryptoPolicy::Hybrid,
556            )
557            .await
558            .expect_err("hybrid enrollment must fail closed on a read-only secrets dir");
559            assert!(
560                err.to_string().contains("fail closed")
561                    || err.to_string().to_lowercase().contains("hybrid"),
562                "error must name the fail-closed reason: {err}"
563            );
564
565            // Restore perms so TempDir cleanup works.
566            std::fs::set_permissions(secrets.path(), std::fs::Permissions::from_mode(0o700))
567                .unwrap();
568        }
569    }
570
571    #[tokio::test]
572    async fn enroll_legacy_ed25519_dir_upgrades_in_place_same_fingerprint() {
573        let creds = TempDir::new().unwrap();
574        let secrets = TempDir::new().unwrap();
575        let store = open(&creds);
576
577        // Legacy: classical enrollment first (Ed25519 file only, classical record).
578        let classical = enroll_user(
579            &store,
580            secrets.path(),
581            "grace",
582            EnrollKeySource::Generate,
583            CryptoPolicy::Classical,
584        )
585        .await
586        .unwrap();
587        assert_eq!(classical.algorithm, KeyAlgorithm::Ed25519);
588        assert!(!secrets.path().join("user-signing-key.mldsa").exists());
589
590        // Re-enroll under Hybrid: same anchor gains a PQ binding in place; the
591        // fingerprint (kid) is unchanged, and the record becomes hybrid.
592        let hybrid = enroll_user(
593            &store,
594            secrets.path(),
595            "grace",
596            EnrollKeySource::Generate,
597            CryptoPolicy::Hybrid,
598        )
599        .await
600        .unwrap();
601        assert_eq!(
602            hybrid.fingerprint, classical.fingerprint,
603            "in-place upgrade must preserve the anchor fingerprint"
604        );
605        assert_eq!(hybrid.algorithm, KeyAlgorithm::HybridEd25519MlDsa65);
606        let keys = store.list_pubkeys("grace").await.unwrap();
607        assert_eq!(keys.len(), 1, "upgrade is in place, not a second key");
608        assert!(keys[0].pq_pubkey.is_some());
609    }
610}