Skip to main content

hyprstream_core/cli/
bootstrap_manager.rs

1//! BootstrapManager — pre-service bootstrap for first-boot wizard.
2//!
3//! The wizard runs before any hyprstream services exist. BootstrapManager handles
4//! GPU detection, variant installation, directory/key/policy initialization, and
5//! service startup. It implements WizardBackend for the TUI, using bounded channels
6//! with drain-to-latest pattern to bridge async operations to the 30fps render loop.
7
8use std::path::{Path, PathBuf};
9use std::sync::atomic::{AtomicBool, Ordering};
10use std::sync::{mpsc, Arc};
11
12use anyhow::Context;
13use ed25519_dalek::SigningKey;
14use tracing;
15
16use hyprstream_tui::wizard::backend::*;
17
18use crate::auth::identity_store;
19use crate::auth::policy_templates::{get_template, get_templates};
20use crate::auth::{PolicyManager, ProductionUserStore};
21use crate::cli::gpu_detect;
22use crate::cli::policy_handlers::{load_or_generate_signing_key, mint_local_token, parse_duration};
23
24/// Pre-service bootstrap manager for the wizard TUI.
25///
26/// Handles GPU detection, variant download/install, directory/key/policy
27/// initialization, and service startup — everything needed before the
28/// hyprstream service layer exists.
29pub struct BootstrapManager {
30    rt: tokio::runtime::Handle,
31    models_dir: PathBuf,
32    config_services: Vec<String>,
33    signing_key: Option<SigningKey>,
34
35    // Install phase state
36    install_rx: Option<mpsc::Receiver<InstallPoll>>,
37    install_handle: Option<tokio::task::JoinHandle<()>>,
38    install_cancel: Option<Arc<AtomicBool>>,
39
40    // Bootstrap phase state
41    bootstrap_rx: Option<mpsc::Receiver<BootstrapPoll>>,
42    bootstrap_handle: Option<tokio::task::JoinHandle<()>>,
43    bootstrap_cancel: Option<Arc<AtomicBool>>,
44
45    // Service phase state
46    service_rx: Option<mpsc::Receiver<OpStatus>>,
47    service_handle: Option<tokio::task::JoinHandle<()>>,
48
49    /// Test-only dispatch injection for the service-start routing tests.
50    /// Production never consults an override — `new()` stores `None` and the
51    /// real `handle_service_start` path always runs (#1585).
52    #[cfg(test)]
53    start_dispatch: Option<StartDispatchFn>,
54
55    // Cached environment (avoid re-detecting)
56    cached_env: Option<EnvironmentInfo>,
57
58    // Accumulated policy state
59    policy_manager: Option<PolicyManager>,
60}
61
62impl Drop for BootstrapManager {
63    fn drop(&mut self) {
64        if let Some(flag) = self.install_cancel.take() {
65            flag.store(true, Ordering::Relaxed);
66        }
67        if let Some(flag) = self.bootstrap_cancel.take() {
68            flag.store(true, Ordering::Relaxed);
69        }
70        if let Some(handle) = self.install_handle.take() {
71            handle.abort();
72        }
73        if let Some(handle) = self.bootstrap_handle.take() {
74            handle.abort();
75        }
76        if let Some(handle) = self.service_handle.take() {
77            handle.abort();
78        }
79    }
80}
81
82/// Resolve the local OS username exactly as the CLI presents it in `sub`.
83///
84/// Must stay in lockstep with `sign_challenge.rs::load_user_signing_key`
85/// (`$USER` → `$LOGNAME` → `"anonymous"`), so the identity the wizard registers
86/// matches the subject the CLI authenticates as.
87fn os_username() -> String {
88    std::env::var("USER")
89        .or_else(|_| std::env::var("LOGNAME"))
90        .unwrap_or_else(|_| "anonymous".to_owned())
91}
92
93/// Test-only signature of the wizard's service-start dispatch seam: the
94/// resolved service list, explicit-config provenance, direct-launch decision,
95/// and required-native profile. Never named outside `#[cfg(test)]` code —
96/// production always runs the ordinary `dispatch_real_start` path.
97#[cfg(test)]
98type StartDispatchFn = Arc<
99    dyn Fn(
100            Vec<String>,
101            Option<PathBuf>,
102            bool,
103            bool,
104        )
105            -> std::pin::Pin<Box<dyn std::future::Future<Output = anyhow::Result<()>> + Send>>
106        + Send
107        + Sync,
108>;
109
110/// The actual production start: installed systemd units for the default
111/// profile, direct launch when `daemon` is set for explicit-config and
112/// required-native profiles (#1585).
113async fn dispatch_real_start(
114    services: &[String],
115    explicit_config: Option<&Path>,
116    daemon: bool,
117    iroh_required: bool,
118) -> anyhow::Result<()> {
119    crate::cli::handle_service_start(services, None, daemon, explicit_config, iroh_required).await
120}
121
122// The shared enroll routine (#438 wizard + #439 `user create`) lives in
123// `cli::enroll`; the wizard uses it directly. `bind_user_signing_key` is still
124// unit-tested here (see `tests`).
125use crate::cli::enroll::{enroll_user, EnrollKeySource};
126
127/// Returns true if this is the first run (no bootstrap completed yet).
128///
129/// Used by the no-args entry point to decide between wizard and ShellClient.
130/// Checks for the presence of `bootstrap-pubkeys` in the credentials directory,
131/// which is written at the end of a successful bootstrap.
132pub fn is_first_run(_models_dir: &std::path::Path) -> bool {
133    // Check env var first — if signing key is provided externally, not first run
134    if std::env::var("HYPRSTREAM__SIGNING_KEY").is_ok() {
135        return false;
136    }
137
138    // bootstrap-pubkeys is written last during bootstrap — best indicator.
139    // If credentials cannot be resolved, fail closed by treating this as first run.
140    let Ok(credentials_dir) = identity_store::credentials_dir() else {
141        return true;
142    };
143
144    !credentials_dir.join("bootstrap-pubkeys").exists()
145}
146
147impl BootstrapManager {
148    /// Create a new bootstrap manager.
149    pub fn new(
150        rt: tokio::runtime::Handle,
151        models_dir: PathBuf,
152        config_services: Vec<String>,
153    ) -> Self {
154        Self {
155            rt,
156            models_dir,
157            config_services,
158            signing_key: None,
159            install_rx: None,
160            install_handle: None,
161            install_cancel: None,
162            bootstrap_rx: None,
163            bootstrap_handle: None,
164            bootstrap_cancel: None,
165            service_rx: None,
166            service_handle: None,
167            #[cfg(test)]
168            start_dispatch: None,
169            cached_env: None,
170            policy_manager: None,
171        }
172    }
173
174    /// Inject the test-only service-start dispatch. Never called in
175    /// production; exists only so the routing tests can observe which launch
176    /// mode and profile provenance the wizard resolves (#1585).
177    #[cfg(test)]
178    fn set_start_dispatch(&mut self, dispatch: StartDispatchFn) {
179        self.start_dispatch = Some(dispatch);
180    }
181
182    fn data_dir(&self) -> PathBuf {
183        dirs::data_local_dir()
184            .unwrap_or_else(|| self.models_dir.clone())
185            .join("hyprstream")
186    }
187
188    fn policies_dir(&self) -> PathBuf {
189        self.models_dir.join(".registry").join("policies")
190    }
191
192    fn keys_dir(&self) -> PathBuf {
193        self.models_dir.join(".registry").join("keys")
194    }
195
196    /// Register a user identity in UserStore and bind the CLI's user-signing-key
197    /// public key to it.
198    ///
199    /// Delegates to the shared [`enroll_user`] routine (#438 wizard + #439
200    /// `user create`) so the register→store→bind sequence cannot drift. The
201    /// wizard uses the `Generate` source: it adopts the existing/on-disk
202    /// user-signing-key the CLI signs with. Without the binding the server can
203    /// never resolve the CLI's signature back to a subject and falls back to
204    /// `anonymous` (#438).
205    fn register_local_identity(&mut self, username: &str) {
206        let credentials_dir = match identity_store::credentials_dir() {
207            Ok(path) => path,
208            Err(e) => {
209                tracing::warn!(
210                    username,
211                    "Failed to resolve credentials directory during bootstrap — user identity will not be registered: {e}"
212                );
213                return;
214            }
215        };
216        let store = match self
217            .rt
218            .block_on(ProductionUserStore::open(&credentials_dir))
219        {
220            Ok(s) => s,
221            Err(e) => {
222                tracing::warn!(
223                    username, ?credentials_dir,
224                    "Failed to load UserStore during bootstrap — user identity will not be registered: {e}"
225                );
226                return;
227            }
228        };
229
230        // Load the user-signing-key from the SAME secrets dir the CLI uses, so
231        // the bound fingerprint matches the key the CLI signs with.
232        let secrets_dir = match crate::config::HyprConfig::resolve_secrets_dir() {
233            Ok(path) => path,
234            Err(e) => {
235                tracing::warn!(
236                    username,
237                    "Failed to resolve secrets directory — CLI signing key will not be bound to '{username}': {e}"
238                );
239                return;
240            }
241        };
242
243        // Root-of-trust enrollment uses the same mandatory hybrid suite as
244        // envelope traffic.
245        let policy = hyprstream_rpc::envelope::mandatory_envelope_policy();
246        match self.rt.block_on(enroll_user(
247            &*store,
248            &secrets_dir,
249            username,
250            EnrollKeySource::Generate,
251            policy,
252        )) {
253            Ok(outcome) => {
254                // Surface enrollment notices (e.g. the classical-downgrade
255                // warning) — `enroll_user` is fail-loud, not fail-silent.
256                for notice in &outcome.notices {
257                    tracing::warn!(username, "{notice}");
258                }
259            }
260            Err(e) => tracing::warn!(
261                username,
262                "Failed to enroll user identity (register + bind signing key): {e}"
263            ),
264        }
265    }
266
267    /// Ensure the signing key is loaded.
268    fn ensure_signing_key(&mut self) {
269        if self.signing_key.is_none() {
270            let keys_dir = self.keys_dir();
271            if let Ok(key) = self.rt.block_on(load_or_generate_signing_key(&keys_dir)) {
272                self.signing_key = Some(key);
273            }
274        }
275    }
276
277    /// Ensure the policy manager is loaded.
278    fn ensure_policy_manager(&mut self) {
279        if self.policy_manager.is_none() {
280            let policies_dir = self.policies_dir();
281            if let Ok(pm) = self.rt.block_on(PolicyManager::new(&policies_dir)) {
282                self.policy_manager = Some(pm);
283            }
284        }
285    }
286}
287
288impl WizardBackend for BootstrapManager {
289    fn detect_environment(&mut self) -> EnvironmentInfo {
290        let env = gpu_detect::detect_environment(&self.data_dir());
291        self.cached_env = Some(env.clone());
292        env
293    }
294
295    fn recommend_action(&self, env: &EnvironmentInfo) -> InstallAction {
296        if env.run_mode == RunMode::Development {
297            return InstallAction::Skip {
298                reason: "Development mode — LIBTORCH already configured".to_owned(),
299            };
300        }
301        if env.run_mode == RunMode::AppImage {
302            return InstallAction::Skip {
303                reason: "AppImage manages its own backends".to_owned(),
304            };
305        }
306        if env.current_variant == env.recommended_variant {
307            return InstallAction::AlreadyCurrent;
308        }
309        if let Some(ref installed) = env.installed_variant {
310            if *installed == env.recommended_variant {
311                return InstallAction::AlreadyCurrent;
312            }
313        }
314        InstallAction::UpgradeVariant(env.recommended_variant.clone())
315    }
316
317    fn start_install(&mut self, variant: &LibtorchVariant) {
318        let (tx, rx) = mpsc::sync_channel(8);
319        self.install_rx = Some(rx);
320        let cancel = Arc::new(AtomicBool::new(false));
321        self.install_cancel = Some(cancel.clone());
322
323        let variant = variant.clone();
324        let models_dir = self.models_dir.clone();
325        let data_dir = self.data_dir();
326
327        self.install_handle = Some(self.rt.spawn(async move {
328            let result = do_install(&tx, &variant, &models_dir, &data_dir, &cancel).await;
329            if let Err(e) = result {
330                let _ = tx.send(InstallPoll::Failed(e.to_string()));
331            }
332        }));
333    }
334
335    fn poll_install(&mut self) -> InstallPoll {
336        let rx = match &self.install_rx {
337            Some(rx) => rx,
338            None => return InstallPoll::Failed("Install not started".into()),
339        };
340        // Drain-to-latest: consume all pending, stop at terminal state
341        let mut latest = None;
342        while let Ok(msg) = rx.try_recv() {
343            let is_terminal = matches!(msg, InstallPoll::Done { .. } | InstallPoll::Failed(_));
344            latest = Some(msg);
345            if is_terminal {
346                break;
347            }
348        }
349        let result = latest.unwrap_or(InstallPoll::Detecting);
350        // Clear receiver after terminal state to prevent stale fallback on subsequent polls
351        if matches!(result, InstallPoll::Done { .. } | InstallPoll::Failed(_)) {
352            self.install_rx = None;
353        }
354        result
355    }
356
357    fn start_bootstrap(&mut self) {
358        let (tx, rx) = mpsc::sync_channel(8);
359        self.bootstrap_rx = Some(rx);
360        let cancel = Arc::new(AtomicBool::new(false));
361        self.bootstrap_cancel = Some(cancel.clone());
362
363        let models_dir = self.models_dir.clone();
364        let keys_dir = self.keys_dir();
365
366        self.bootstrap_handle = Some(self.rt.spawn(async move {
367            // cancel flag checked via handle.abort() in Drop; no mid-operation
368            // cancellation points in bootstrap (it's a short sequence).
369            let _cancel = cancel; // held to keep Arc alive for Drop
370            let result = do_bootstrap(&tx, &models_dir, &keys_dir).await;
371            if let Err(e) = result {
372                let _ = tx.send(BootstrapPoll::Failed(e.to_string()));
373            }
374        }));
375    }
376
377    fn poll_bootstrap(&mut self) -> BootstrapPoll {
378        let rx = match &self.bootstrap_rx {
379            Some(rx) => rx,
380            None => return BootstrapPoll::InProgress("Not started".to_owned()),
381        };
382        let mut latest = None;
383        while let Ok(msg) = rx.try_recv() {
384            let is_terminal = matches!(msg, BootstrapPoll::Done(_) | BootstrapPoll::Failed(_));
385            latest = Some(msg);
386            if is_terminal {
387                break;
388            }
389        }
390        // If bootstrap is done, load the signing key
391        if let Some(BootstrapPoll::Done(_)) = &latest {
392            self.ensure_signing_key();
393        }
394        let result = latest.unwrap_or_else(|| BootstrapPoll::InProgress("Starting...".to_owned()));
395        if matches!(result, BootstrapPoll::Done(_) | BootstrapPoll::Failed(_)) {
396            self.bootstrap_rx = None;
397        }
398        result
399    }
400
401    fn has_existing_policy(&self) -> bool {
402        let policy_csv = self.policies_dir().join("policy.csv");
403        if let Ok(content) = std::fs::read_to_string(&policy_csv) {
404            content
405                .lines()
406                .any(|l| l.starts_with("p,") || l.starts_with("p "))
407        } else {
408            false
409        }
410    }
411
412    fn apply_template(&mut self, name: &str) {
413        if let Some(template) = get_template(name) {
414            self.ensure_policy_manager();
415            if let Some(ref pm) = self.policy_manager {
416                let _ = self
417                    .rt
418                    .block_on(async { pm.apply_template(template).await });
419            }
420        }
421    }
422
423    fn add_user(&mut self, username: &str, role: &str) {
424        if !VALID_INITIAL_ROLES.contains(&role) {
425            tracing::error!(
426                role,
427                valid = VALID_INITIAL_ROLES.join(", "),
428                "unknown --initial-user-role; aborting bootstrap"
429            );
430            std::process::exit(1);
431        }
432
433        // Register identity first — UserStore is authoritative
434        self.register_local_identity(username);
435
436        self.ensure_policy_manager();
437        if let Some(ref pm) = self.policy_manager {
438            let rules = predefined_role_rules(role);
439            let _ = self.rt.block_on(async {
440                for (resource, action) in rules {
441                    pm.add_policy_with_domain(username, "*", resource, action, "allow")
442                        .await?;
443                }
444                pm.save().await?;
445                Ok::<_, anyhow::Error>(())
446            });
447        }
448    }
449
450    fn add_user_custom(&mut self, username: &str, resource: &str, actions: &[String]) {
451        // Register identity first — UserStore is authoritative
452        self.register_local_identity(username);
453
454        self.ensure_policy_manager();
455        if let Some(ref pm) = self.policy_manager {
456            let _ = self.rt.block_on(async {
457                for action in actions {
458                    pm.add_policy_with_domain(username, "*", resource, action, "allow")
459                        .await?;
460                }
461                pm.save().await?;
462                Ok::<_, anyhow::Error>(())
463            });
464        }
465    }
466
467    fn save_policies(&mut self) {
468        if let Some(ref pm) = self.policy_manager {
469            let _ = self.rt.block_on(pm.save());
470        }
471    }
472
473    fn generate_token(&mut self, username: &str, duration: &str) -> TokenResult {
474        self.ensure_signing_key();
475        let signing_key = match &self.signing_key {
476            Some(k) => k,
477            None => {
478                return TokenResult {
479                    token: "ERROR: No signing key".to_owned(),
480                    expires: "N/A".to_owned(),
481                }
482            }
483        };
484
485        let dur = parse_duration(duration)
486            .unwrap_or_else(|_| Some(chrono::Duration::days(90)))
487            .unwrap_or_else(|| chrono::Duration::days(90));
488
489        let (token, exp) = match mint_local_token(signing_key, username, dur) {
490            Ok(token) => token,
491            Err(error) => {
492                return TokenResult {
493                    token: format!("ERROR: {error}"),
494                    expires: "N/A".to_owned(),
495                };
496            }
497        };
498
499        let expires = if duration == "never" {
500            "never".to_owned()
501        } else {
502            chrono::DateTime::from_timestamp(exp, 0)
503                .map(|dt| dt.format("%Y-%m-%d").to_string())
504                .unwrap_or_else(|| "unknown".to_owned())
505        };
506
507        TokenResult { token, expires }
508    }
509
510    fn start_services(&mut self) {
511        let (tx, rx) = mpsc::sync_channel(8);
512        self.service_rx = Some(rx);
513        let services = self.config_services.clone();
514        // Forward this process's pinned config provenance and native profile
515        // so bootstrap-launched children load what the operator loaded (#1585).
516        let explicit_config = crate::config::explicit_config_path().cloned();
517        // Fail closed: an unloadable configuration is never silently treated
518        // as the default profile (#1585). Installed systemd units cannot carry
519        // this process's explicit --config provenance or the required-native
520        // profile, so those starts take the direct launch path via `daemon`.
521        let (daemon, iroh_required) = match crate::config::HyprConfig::load() {
522            Ok(config) => {
523                let required = config.quic.iroh_required();
524                (explicit_config.is_some() || required, required)
525            }
526            Err(error) => {
527                let message = format!("configuration load failed: {error}");
528                self.service_handle = Some(self.rt.spawn(async move {
529                    let _ = tx.send(OpStatus::InProgress);
530                    let _ = tx.send(OpStatus::Failed(message));
531                }));
532                return;
533            }
534        };
535
536        #[cfg(test)]
537        let start_override = self.start_dispatch.clone();
538
539        self.service_handle = Some(self.rt.spawn(async move {
540            let _ = tx.send(OpStatus::InProgress);
541            #[cfg(test)]
542            let outcome = match start_override {
543                Some(seam) => {
544                    seam(
545                        services.clone(),
546                        explicit_config.clone(),
547                        daemon,
548                        iroh_required,
549                    )
550                    .await
551                }
552                None => {
553                    dispatch_real_start(
554                        &services,
555                        explicit_config.as_deref(),
556                        daemon,
557                        iroh_required,
558                    )
559                    .await
560                }
561            };
562            #[cfg(not(test))]
563            let outcome =
564                dispatch_real_start(&services, explicit_config.as_deref(), daemon, iroh_required)
565                    .await;
566            match outcome {
567                Ok(()) => {
568                    let _ = tx.send(OpStatus::Done);
569                }
570                Err(e) => {
571                    let _ = tx.send(OpStatus::Failed(e.to_string()));
572                }
573            }
574        }));
575    }
576
577    fn poll_pending(&mut self) -> OpStatus {
578        let rx = match &self.service_rx {
579            Some(rx) => rx,
580            None => return OpStatus::Done,
581        };
582        let mut latest = None;
583        while let Ok(msg) = rx.try_recv() {
584            let is_terminal = matches!(msg, OpStatus::Done | OpStatus::Failed(_));
585            latest = Some(msg);
586            if is_terminal {
587                break;
588            }
589        }
590        let result = latest.unwrap_or(OpStatus::InProgress);
591        if matches!(result, OpStatus::Done | OpStatus::Failed(_)) {
592            self.service_rx = None;
593        }
594        result
595    }
596
597    fn local_username(&self) -> String {
598        os_username()
599    }
600
601    fn templates(&self) -> Vec<TemplateInfo> {
602        get_templates()
603            .iter()
604            .map(|t| TemplateInfo {
605                name: t.name.to_owned(),
606                description: t.description.to_owned(),
607            })
608            .collect()
609    }
610}
611
612pub const VALID_INITIAL_ROLES: &[&str] = &["admin", "operator", "viewer", "trainer"];
613
614/// Predefined role rules (mirrors wizard_handlers.rs).
615fn predefined_role_rules(role: &str) -> Vec<(&'static str, &'static str)> {
616    match role {
617        "admin" => vec![("*", "*")],
618        "operator" => vec![
619            ("model:*", "infer"),
620            ("model:*", "query"),
621            ("model:*", "serve"),
622        ],
623        "viewer" => vec![("model:*", "query"), ("registry:*", "query")],
624        "trainer" => vec![
625            ("model:*", "infer"),
626            ("model:*", "query"),
627            ("model:*", "serve"),
628            ("model:*", "train"),
629        ],
630        _ => vec![],
631    }
632}
633
634/// Async install flow.
635///
636/// 1. Parse release manifest (if available)
637/// 2. Clone/fetch release registry
638/// 3. Create pathspec-filtered worktree
639/// 4. Write active-backend + active-version config
640async fn do_install(
641    tx: &mpsc::SyncSender<InstallPoll>,
642    variant: &LibtorchVariant,
643    models_dir: &std::path::Path,
644    data_dir: &std::path::Path,
645    cancel: &AtomicBool,
646) -> anyhow::Result<()> {
647    let _ = tx.send(InstallPoll::Detecting);
648
649    // Check for release registry
650    let releases_dir = models_dir.join("hyprstream-releases.git");
651    let variant_id = variant.id();
652
653    if releases_dir.exists() {
654        // Fetch latest
655        let _ = tx.send(InstallPoll::Downloading {
656            item: "release metadata".to_owned(),
657            pct: 5,
658        });
659        // TODO: git fetch via git2db Registry cloneStream
660    } else {
661        // Clone release registry
662        let _ = tx.send(InstallPoll::Downloading {
663            item: "release registry".to_owned(),
664            pct: 10,
665        });
666        // TODO: Clone via git2db Registry
667    }
668
669    // Simulate download progress (will be replaced with real cloneStream bridge)
670    for pct in (20..=90).step_by(10) {
671        if cancel.load(Ordering::Relaxed) {
672            anyhow::bail!("Cancelled");
673        }
674        let _ = tx.send(InstallPoll::Downloading {
675            item: format!("libtorch {}", variant.label()),
676            pct,
677        });
678        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
679    }
680
681    let _ = tx.send(InstallPoll::Extracting {
682        item: format!("{variant_id} backend"),
683    });
684
685    // Create data directory structure
686    let version = env!("CARGO_PKG_VERSION");
687    let variant_dir = data_dir
688        .join("versions")
689        .join(format!("{version}-{variant_id}"))
690        .join("backends")
691        .join(variant_id);
692    tokio::fs::create_dir_all(&variant_dir)
693        .await
694        .context("Failed to create variant directory")?;
695
696    let _ = tx.send(InstallPoll::Configuring {
697        step: "Writing backend configuration".to_owned(),
698    });
699
700    // TODO: The real binary is placed by pathspec-filtered worktree checkout.
701    // For now this is a stub — the binary won't exist yet.
702    let expected_binary = variant_dir.join("hyprstream");
703
704    // Only write active-backend/active-version AFTER the binary is verified.
705    // This prevents an inconsistent state where config points to a missing binary.
706    if expected_binary.exists() {
707        tokio::fs::write(data_dir.join("active-backend"), variant_id)
708            .await
709            .context("Failed to write active-backend")?;
710        tokio::fs::write(data_dir.join("active-version"), version)
711            .await
712            .context("Failed to write active-version")?;
713
714        let _ = tx.send(InstallPoll::Done {
715            summary: format!("{} backend installed successfully", variant.label()),
716        });
717    } else {
718        // Stub mode: report success but note the binary is not yet placed
719        let _ = tx.send(InstallPoll::Done {
720            summary: format!(
721                "{} backend configured (binary pending real download implementation)",
722                variant.label()
723            ),
724        });
725    }
726
727    Ok(())
728}
729
730/// Async bootstrap flow — silent (no stdout writes; TUI holds the stdout lock).
731async fn do_bootstrap(
732    tx: &mpsc::SyncSender<BootstrapPoll>,
733    models_dir: &std::path::Path,
734    keys_dir: &std::path::Path,
735) -> anyhow::Result<()> {
736    let mut steps = Vec::new();
737
738    // ── 1. Directories ──────────────────────────────────────────────────────
739    let _ = tx.send(BootstrapPoll::InProgress(
740        "Checking directories...".to_owned(),
741    ));
742    let registry_path = models_dir.join(".registry");
743    for dir in &[
744        models_dir,
745        registry_path.as_path(),
746        registry_path.join("policies").as_path(),
747        registry_path.join("keys").as_path(),
748    ] {
749        if !dir.exists() {
750            tokio::fs::create_dir_all(dir)
751                .await
752                .with_context(|| format!("Failed to create {}", dir.display()))?;
753        }
754    }
755    steps.push("Directories OK".to_owned());
756
757    // ── 2. Registry git repo ────────────────────────────────────────────────
758    let _ = tx.send(BootstrapPoll::InProgress(
759        "Verifying registry...".to_owned(),
760    ));
761    let git_dir = registry_path.join(".git");
762    if !git_dir.exists() && git2db::Git2DB::open(models_dir).await.is_err() {
763        git2::Repository::init(&registry_path)
764            .context("Failed to initialize .registry git repo")?;
765    }
766    steps.push("Registry OK".to_owned());
767
768    // ── 3. Default policy files ─────────────────────────────────────────────
769    let policies_dir = registry_path.join("policies");
770    if !policies_dir.join("model.conf").exists() || !policies_dir.join("policy.csv").exists() {
771        PolicyManager::new(&policies_dir)
772            .await
773            .context("Failed to create default policy files")?;
774    }
775
776    // ── 4. Signing key (becomes the CA key for PolicyService) ────────────
777    let _ = tx.send(BootstrapPoll::InProgress(
778        "Loading signing key...".to_owned(),
779    ));
780    let root_key = load_or_generate_signing_key(keys_dir).await?;
781
782    // ── 4b. Per-service independent keys + CA credentials ────────────────
783    let _ = tx.send(BootstrapPoll::InProgress(
784        "Generating service keys...".to_owned(),
785    ));
786    {
787        let credentials_dir = identity_store::credentials_dir()?;
788
789        // Local issuer URL stamped into service JWTs so they verify on the
790        // local IPC/AnySigner plane without tripping the #328 empty-`iss` gate.
791        // Must match the issuer the services' ClusterKeySource trusts
792        // (oauth.issuer_url(), the same value `cluster_key_source()` uses).
793        let local_issuer_url = crate::config::HyprConfig::load()
794            .map(|c| c.oauth.issuer_url())
795            .unwrap_or_default();
796
797        // CA JWT signing key (purpose-derived for JWT signature separation).
798        // Derived BEFORE writing ca-pubkey so we can store the JWT key's verifying key,
799        // not the root key's verifying key. Services verify JWTs with the derived key.
800        let ca_jwt_key =
801            hyprstream_rpc::node_identity::derive_purpose_key(&root_key, "hyprstream-jwt-v1");
802
803        // Write CA signing key only if not already present (idempotent)
804        match identity_store::load_ca_signing_key(&credentials_dir) {
805            Ok(_) => {
806                // CA key exists; preserve it so running services stay valid
807            }
808            Err(_) => {
809                identity_store::write_ca_signing_key(&credentials_dir, &root_key)?;
810                // Write the JWT-derived verifying key as ca-pubkey (not the root key).
811                // PolicyService signs JWTs with ca_jwt_key; services must verify with its pubkey.
812                identity_store::write_ca_verifying_key(
813                    &credentials_dir,
814                    &ca_jwt_key.verifying_key(),
815                )?;
816            }
817        }
818        // Always sync signing-key and verifying keys (derived from root_key, harmless to overwrite).
819        // The ML-DSA-65 verifying key is the post-quantum half of the CA JWT
820        // composite pair: hybrid service JWTs are signed with the exact pair
821        // (derive_mesh_mldsa_key(ca_jwt_key), ca_jwt_key), and verifiers need
822        // this public key on disk to resolve the composite kid.
823        identity_store::write_secret(&credentials_dir, "signing-key", &root_key.to_bytes())?;
824        identity_store::write_ca_verifying_key(&credentials_dir, &ca_jwt_key.verifying_key())?;
825        let ca_pq = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&ca_jwt_key);
826        identity_store::write_ca_ml_dsa_verifying_key(
827            &credentials_dir,
828            &hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk(&ca_pq),
829        )?;
830
831        // Generate independent keypairs for each registered service
832        use hyprstream_service::list_factories;
833
834        let service_names: Vec<&str> = list_factories().map(|f| f.name).collect();
835        let bootstrap_pubkeys = provision_service_identities(
836            &credentials_dir,
837            &root_key,
838            &ca_jwt_key,
839            &local_issuer_url,
840            &service_names,
841            chrono::Utc::now().timestamp(),
842        )?;
843
844        tracing::info!(
845            "Generated service keypairs + JWTs for {} services",
846            bootstrap_pubkeys.len(),
847        );
848    }
849    steps.push("Service keys OK".to_owned());
850
851    // ── 5. Done ─────────────────────────────────────────────────────────────
852    let _ = tx.send(BootstrapPoll::InProgress(
853        "Validating environment...".to_owned(),
854    ));
855    steps.push("Environment OK".to_owned());
856
857    let _ = tx.send(BootstrapPoll::Done(steps));
858    Ok(())
859}
860
861/// Provision one identity per named service: an Ed25519 signing key, a CA-signed
862/// service JWT, and the `bootstrap-pubkeys` entry that publishes the key.
863///
864/// Every entry written here is hybrid (Ed25519 + a derived ML-DSA-65 key). There
865/// is no classical provisioning mode and no flag to request one: the derived
866/// post-quantum key is what the service's own signer signs with, so publishing
867/// it is what makes the service verifiable at all. Re-running is idempotent —
868/// existing per-service keys and JWTs are loaded rather than replaced, so the
869/// entries it rewrites describe the same identities.
870fn provision_service_identities(
871    credentials_dir: &std::path::Path,
872    root_key: &ed25519_dalek::SigningKey,
873    ca_jwt_key: &ed25519_dalek::SigningKey,
874    local_issuer_url: &str,
875    service_names: &[&str],
876    now: i64,
877) -> anyhow::Result<std::collections::HashMap<String, identity_store::BootstrapPubkey>> {
878    let mut bootstrap_pubkeys = std::collections::HashMap::new();
879
880    for service_name in service_names {
881        let service_name = *service_name;
882
883        // PolicyService's identity IS the root/CA key: unlike every other
884        // service it has no independent per-service keypair, so it resolves
885        // to `root_key` rather than `load_or_generate_service_signing_key`
886        // (which would read/generate a divergent `policy/signing-key`).
887        //
888        // But it is NOT skipped: we still mint a CA-signed `service:policy`
889        // JWT — self-signed in the sense that the CA JWT key signs it, with
890        // `cnf` binding the root verifying key — and persist it to
891        // `policy/service-jwt`. That makes PolicyService symmetric with
892        // every other service and keeps the trust store (which records
893        // `root_key.verifying_key()` for "policy") in lockstep with the
894        // on-disk JWT, so a later `service repair`/reinstall can no longer
895        // leave a stale `policy` key/JWT pair that disagrees with the
896        // current CA key (#448). It also enables future per-service
897        // rotation of the policy credential.
898        let service_key = if service_name == "policy" {
899            root_key.clone()
900        } else {
901            identity_store::load_or_generate_service_signing_key(credentials_dir, service_name)?
902        };
903
904        // The hybrid entry: the Ed25519 identity plus the ML-DSA-65 key derived
905        // from it. This is what `seed_bootstrap_pq_bindings` later anchors, and
906        // what turns post-quantum enforcement on for this service.
907        bootstrap_pubkeys.insert(
908            service_name.to_owned(),
909            identity_store::BootstrapPubkey::for_service_key(&service_key)?,
910        );
911
912        // Publish the public sidecars (`signing-key.pub`, `service-pubkey.hybrid`)
913        // next to the key so the bootstrap-enrollment mint can read them without
914        // secret material (#1562 H1). For non-policy services the key loader
915        // already wrote them — an idempotent no-op here; for policy this writes
916        // them flat, alongside the node/CA seed.
917        let sidecar_dir = identity_store::service_signing_key_dir(
918            credentials_dir,
919            service_name,
920            identity_store::SecretsProfile::SharedDirectory,
921        );
922        identity_store::ensure_service_key_sidecars(&sidecar_dir, &service_key)?;
923    }
924
925    identity_store::write_bootstrap_pubkeys_hybrid(credentials_dir, &bootstrap_pubkeys)?;
926
927    // v16 §11: the enrollment manifest is derived BEFORE any credential is
928    // minted, so every bootstrap service JWT is clearance-bearing from first
929    // issue. The manifest is the authority for target clearance; minting
930    // consults it per service. On first provision the manifest is written
931    // with wizard defaults; on re-provision the existing manifest is
932    // authoritative — any drift (missing/extra service, changed Ed25519 or
933    // PQ half) is a hard error until the operator edits the manifest
934    // deliberately (the reviewed rotation).
935    let freshly_written;
936    let enrollment =
937        match crate::auth::service_enrollment::ServiceEnrollmentManifest::load(credentials_dir)? {
938            Some(existing) => {
939                freshly_written = false;
940                existing
941            }
942            None => {
943                let manifest =
944                    crate::auth::service_enrollment::ServiceEnrollmentManifest::from_bootstrap(
945                        &bootstrap_pubkeys,
946                    );
947                manifest.write(credentials_dir)?;
948                freshly_written = true;
949                manifest
950            }
951        };
952    if !freshly_written {
953        enrollment
954            .reconcile_with_bootstrap(&bootstrap_pubkeys)
955            .context("service enrollment manifest disagrees with bootstrap keys")?;
956    }
957
958    for (service_name, entry) in &bootstrap_pubkeys {
959        let jwt = crate::auth::service_jwt::issue_or_load_service_jwt(
960            credentials_dir,
961            service_name,
962            ca_jwt_key,
963            entry,
964            local_issuer_url,
965            now,
966            enrollment.clearance_for_service(service_name).as_ref(),
967        )?;
968        identity_store::write_service_jwt(credentials_dir, service_name, &jwt)?;
969    }
970
971    Ok(bootstrap_pubkeys)
972}
973
974#[cfg(test)]
975mod tests {
976    use super::*;
977    use crate::auth::{RocksDbUserStore, UserStore};
978    use crate::cli::enroll::bind_user_signing_key;
979    use tempfile::TempDir;
980
981    /// What the wizard's service-start dispatch was invoked with.
982    #[derive(Debug)]
983    struct RecordedStart {
984        services: Vec<String>,
985        explicit: Option<PathBuf>,
986        daemon: bool,
987        required: bool,
988    }
989
990    /// Gate marking a re-exec'd child that runs one service-start routing
991    /// scenario in an isolated process (the pinned/explicit config slots are
992    /// process-global and write-once).
993    const ROUTE_CHILD: &str = "HYPRSTREAM_BOOTSTRAP_ROUTE_CHILD";
994
995    /// BootstrapManager service-start routing through the real profile load:
996    /// the default profile stays on installed systemd units (daemon=false);
997    /// explicit-config and required-native route to the direct launch path
998    /// (daemon=true); an unloadable configuration fails closed with a Failed
999    /// status and never reaches the dispatch at all.
1000    #[tokio::test]
1001    async fn bootstrap_start_services_routes_profiles_causally() -> anyhow::Result<()> {
1002        if let Ok(scenario) = std::env::var(ROUTE_CHILD) {
1003            return start_services_child_scenario(&scenario).await;
1004        }
1005        for scenario in ["default", "explicit", "required", "invalid"] {
1006            let status = std::process::Command::new(std::env::current_exe()?)
1007                .args([
1008                    "--exact",
1009                    "cli::bootstrap_manager::tests::bootstrap_start_services_routes_profiles_causally",
1010                    "--nocapture",
1011                ])
1012                .env(ROUTE_CHILD, scenario)
1013                .status()?;
1014            anyhow::ensure!(
1015                status.success(),
1016                "bootstrap service routing scenario '{scenario}' failed"
1017            );
1018        }
1019        Ok(())
1020    }
1021
1022    async fn start_services_child_scenario(scenario: &str) -> anyhow::Result<()> {
1023        let recorded: Arc<parking_lot::Mutex<Vec<RecordedStart>>> = Arc::default();
1024        let sink = recorded.clone();
1025        let models = TempDir::new()?;
1026        let mut manager = BootstrapManager::new(
1027            // The test's own ambient runtime: start_services spawns onto this
1028            // handle and the await-based drain below lets the task run.
1029            tokio::runtime::Handle::current(),
1030            models.path().to_path_buf(),
1031            vec!["policy".to_owned()],
1032        );
1033        manager.set_start_dispatch(Arc::new(
1034            move |services: Vec<String>,
1035                  explicit: Option<PathBuf>,
1036                  daemon: bool,
1037                  required: bool| {
1038                sink.lock().push(RecordedStart {
1039                    services,
1040                    explicit,
1041                    daemon,
1042                    required,
1043                });
1044                Box::pin(async { Ok::<(), anyhow::Error>(()) })
1045                    as std::pin::Pin<
1046                        Box<dyn std::future::Future<Output = anyhow::Result<()>> + Send>,
1047                    >
1048            },
1049        ));
1050
1051        match scenario {
1052            "default" => {
1053                let _ = crate::config::install_pinned_config(crate::config::HyprConfig::default());
1054                manager.start_services();
1055                assert_eq!(drain_to_terminal(&mut manager).await, OpStatus::Done);
1056                let calls = recorded.lock();
1057                assert_eq!(calls.len(), 1, "the dispatch must run exactly once");
1058                let call = &calls[0];
1059                assert_eq!(call.services, vec!["policy".to_owned()]);
1060                assert_eq!(
1061                    call.explicit, None,
1062                    "default profile has no explicit provenance"
1063                );
1064                assert!(
1065                    !call.daemon,
1066                    "default profile must keep the installed systemd unit route"
1067                );
1068                assert!(!call.required, "default profile is not required-native");
1069            }
1070            "explicit" => {
1071                let _ = crate::config::install_pinned_config(crate::config::HyprConfig::default());
1072                let explicit = TempDir::new()?;
1073                let marker = explicit.path().join("operator.toml");
1074                assert!(
1075                    crate::config::install_explicit_config_path(marker.clone()),
1076                    "explicit provenance slot must be installable in a fresh child"
1077                );
1078                manager.start_services();
1079                assert_eq!(drain_to_terminal(&mut manager).await, OpStatus::Done);
1080                let calls = recorded.lock();
1081                assert_eq!(calls.len(), 1, "the dispatch must run exactly once");
1082                let call = &calls[0];
1083                assert_eq!(call.explicit, Some(marker), "provenance must be forwarded");
1084                assert!(
1085                    call.daemon,
1086                    "explicit --config provenance must take the direct launch route"
1087                );
1088                assert!(!call.required);
1089            }
1090            "required" => {
1091                let mut required_config = crate::config::HyprConfig::default();
1092                required_config.quic.enabled = true;
1093                required_config.quic.iroh = true;
1094                required_config.quic.native_network_profile =
1095                    crate::config::NativeNetworkProfile::NetworkIrohRequired;
1096                required_config.validate()?;
1097                let _ = crate::config::install_pinned_config(required_config);
1098                manager.start_services();
1099                assert_eq!(drain_to_terminal(&mut manager).await, OpStatus::Done);
1100                let calls = recorded.lock();
1101                assert_eq!(calls.len(), 1, "the dispatch must run exactly once");
1102                let call = &calls[0];
1103                assert!(
1104                    call.required,
1105                    "the required-native profile must be observed"
1106                );
1107                assert!(
1108                    call.daemon,
1109                    "required-native must take the direct launch route"
1110                );
1111                assert_eq!(call.explicit, None);
1112            }
1113            "invalid" => {
1114                // No pinned snapshot: force the XDG re-derivation onto a
1115                // garbage config file so HyprConfig::load() itself fails.
1116                let root = TempDir::new()?;
1117                let xdg = root.path().join("xdg-config");
1118                std::env::set_var("XDG_CONFIG_HOME", &xdg);
1119                let config_dir = xdg.join("hyprstream");
1120                std::fs::create_dir_all(&config_dir)?;
1121                std::fs::write(config_dir.join("config.toml"), "this is = not [valid toml")?;
1122                manager.start_services();
1123                let terminal = drain_to_terminal(&mut manager).await;
1124                match terminal {
1125                    OpStatus::Failed(message) => assert!(
1126                        message.contains("configuration load failed"),
1127                        "unloadable configuration must fail closed naming the cause, got: {message}"
1128                    ),
1129                    other => panic!("unloadable configuration must surface Failed, got {other:?}"),
1130                }
1131                assert!(
1132                    recorded.lock().is_empty(),
1133                    "an unloadable configuration must never reach the service dispatch"
1134                );
1135            }
1136            other => anyhow::bail!("unknown bootstrap routing scenario '{other}'"),
1137        }
1138        Ok(())
1139    }
1140
1141    /// Drain pending service status until a terminal one arrives (bounded,
1142    /// mirroring the wizard's poll loop without the fixed sleep pacing).
1143    async fn drain_to_terminal(manager: &mut BootstrapManager) -> OpStatus {
1144        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
1145        loop {
1146            match manager.poll_pending() {
1147                OpStatus::InProgress => {
1148                    assert!(
1149                        std::time::Instant::now() < deadline,
1150                        "service start never reached a terminal status"
1151                    );
1152                    tokio::time::sleep(std::time::Duration::from_millis(10)).await;
1153                }
1154                terminal => return terminal,
1155            }
1156        }
1157    }
1158
1159    /// A fresh provisioning run writes a hybrid entry for EVERY service, and
1160    /// those entries anchor into the post-quantum trust store.
1161    ///
1162    /// There is no classical provisioning mode to compare against — this is the
1163    /// only path, so the assertion is that it has no classical output at all.
1164    #[test]
1165    fn provisioning_writes_hybrid_entries_that_anchor_for_every_service() -> anyhow::Result<()> {
1166        use ed25519_dalek::SigningKey;
1167        use hyprstream_rpc::envelope::{KeyedPqTrustStore, PqTrustStore};
1168
1169        let creds = TempDir::new()?;
1170        let root_key = SigningKey::generate(&mut rand::rngs::OsRng);
1171        let ca_jwt_key =
1172            hyprstream_rpc::node_identity::derive_purpose_key(&root_key, "hyprstream-jwt-v1");
1173        let services = ["policy", "discovery", "inference", "storage"];
1174
1175        let provisioned = provision_service_identities(
1176            creds.path(),
1177            &root_key,
1178            &ca_jwt_key,
1179            "https://node.invalid",
1180            &services,
1181            1_700_000_000,
1182        )?;
1183
1184        assert_eq!(provisioned.len(), services.len());
1185        for name in services {
1186            let entry = provisioned
1187                .get(name)
1188                .unwrap_or_else(|| panic!("no bootstrap entry provisioned for '{name}'"));
1189            assert!(
1190                entry.is_hybrid(),
1191                "service '{name}' was provisioned classical"
1192            );
1193        }
1194
1195        // What landed on disk is hybrid too, and passes the strict check.
1196        let on_disk = identity_store::load_bootstrap_pubkeys_hybrid(creds.path())?;
1197        assert_eq!(on_disk.len(), services.len());
1198        identity_store::ensure_bootstrap_pubkeys_hybrid(&on_disk)?;
1199
1200        // Every provisioned service anchors into the PQ trust store.
1201        let mut store = KeyedPqTrustStore::new();
1202        let anchored =
1203            crate::auth::mesh_trust::seed_bootstrap_pq_bindings(&mut store, creds.path());
1204        assert_eq!(anchored, services.len(), "every service must anchor");
1205        for name in services {
1206            let entry = &on_disk[name];
1207            assert!(
1208                store.ml_dsa_key_for(&entry.ed25519.to_bytes()).is_some(),
1209                "service '{name}' is not anchored in the PQ trust store"
1210            );
1211        }
1212
1213        // The anchored ML-DSA key is the one the service's signer signs with.
1214        let policy_pq = store
1215            .ml_dsa_key_for(&root_key.verifying_key().to_bytes())
1216            .ok_or_else(|| anyhow::anyhow!("policy identity not anchored"))?;
1217        let msg = b"anchored-key round trip";
1218        let sig = hyprstream_rpc::crypto::pq::ml_dsa_sign(
1219            &hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&root_key),
1220            msg,
1221        );
1222        hyprstream_rpc::crypto::pq::ml_dsa_verify(&policy_pq, msg, &sig)?;
1223
1224        Ok(())
1225    }
1226
1227    /// Replicates the register + bind sequence performed by
1228    /// `register_local_identity` against a temp store/secrets dir, then asserts
1229    /// the identity↔key binding the CLI relies on actually exists (#438).
1230    #[tokio::test]
1231    async fn register_and_bind_creates_identity_and_reverse_maps_pubkey() -> anyhow::Result<()> {
1232        let creds = TempDir::new()?;
1233        let secrets = TempDir::new()?;
1234        let username = "alice";
1235
1236        // CLI's signing key lives in the secrets dir.
1237        let (_sk, vk) = identity_store::load_or_generate_user_signing_key(secrets.path())?;
1238
1239        let store = RocksDbUserStore::open(creds.path())?;
1240        // Register (user did not exist yet) + bind, exactly like the wizard path.
1241        store.register(username).await?;
1242        bind_user_signing_key(&store, username, vk).await?;
1243
1244        // 1. UserStore has a record for the username.
1245        assert!(
1246            store.get_profile(username).await?.is_some(),
1247            "expected a UserStore record for '{username}'"
1248        );
1249
1250        // 2. The signing key's fingerprint reverse-maps to that username.
1251        let fingerprint = crate::auth::user_store::pubkey_fingerprint(&vk);
1252        assert_eq!(
1253            store.get_pubkey_user(&fingerprint).await?,
1254            Some(username.to_owned()),
1255            "user-signing-key fingerprint must reverse-map to '{username}'"
1256        );
1257
1258        Ok(())
1259    }
1260
1261    /// Binding is idempotent (re-running the wizard) and re-points a key left
1262    /// bound to a stale `anonymous` record from a prior partial run.
1263    #[tokio::test]
1264    async fn bind_is_idempotent_and_repoints_from_anonymous() -> anyhow::Result<()> {
1265        let creds = TempDir::new()?;
1266        let secrets = TempDir::new()?;
1267        let (_sk, vk) = identity_store::load_or_generate_user_signing_key(secrets.path())?;
1268        let fingerprint = crate::auth::user_store::pubkey_fingerprint(&vk);
1269
1270        let store = RocksDbUserStore::open(creds.path())?;
1271
1272        // Simulate a prior partial run: key bound to "anonymous".
1273        store.register("anonymous").await?;
1274        bind_user_signing_key(&store, "anonymous", vk).await?;
1275        assert_eq!(
1276            store.get_pubkey_user(&fingerprint).await?,
1277            Some("anonymous".to_owned())
1278        );
1279
1280        // Wizard now registers the real user and binds — must re-point.
1281        store.register("alice").await?;
1282        bind_user_signing_key(&store, "alice", vk).await?;
1283        assert_eq!(
1284            store.get_pubkey_user(&fingerprint).await?,
1285            Some("alice".to_owned()),
1286            "key should be re-pointed from anonymous to alice"
1287        );
1288
1289        // Re-running for the same user is a no-op (must not error/duplicate).
1290        bind_user_signing_key(&store, "alice", vk).await?;
1291        assert_eq!(
1292            store.get_pubkey_user(&fingerprint).await?,
1293            Some("alice".to_owned())
1294        );
1295        assert_eq!(
1296            store.list_pubkeys("alice").await?.len(),
1297            1,
1298            "idempotent re-bind must not duplicate the pubkey"
1299        );
1300
1301        Ok(())
1302    }
1303
1304    /// `local_username()` (via `os_username`) returns the OS user — not the old
1305    /// hardcoded "anonymous" — matching the `sub` the CLI presents.
1306    #[test]
1307    fn os_username_returns_user_env_not_anonymous() {
1308        // Save/restore env to avoid cross-test contamination.
1309        let prev_user = std::env::var("USER").ok();
1310        let prev_logname = std::env::var("LOGNAME").ok();
1311
1312        std::env::set_var("USER", "alice");
1313        std::env::remove_var("LOGNAME");
1314        assert_eq!(os_username(), "alice");
1315        assert_ne!(os_username(), "anonymous");
1316
1317        // Restore.
1318        match prev_user {
1319            Some(v) => std::env::set_var("USER", v),
1320            None => std::env::remove_var("USER"),
1321        }
1322        if let Some(v) = prev_logname {
1323            std::env::set_var("LOGNAME", v);
1324        }
1325    }
1326}