Skip to main content

reddb_server/
service_cli.rs

1use std::net::{SocketAddr, TcpListener, TcpStream, ToSocketAddrs};
2use std::path::PathBuf;
3use std::process::Command;
4use std::sync::Arc;
5use std::thread;
6use std::time::Duration;
7
8use crate::auth::store::AuthStore;
9use crate::replication::ReplicationConfig;
10use crate::runtime::RedDBRuntime;
11use crate::service_router::{serve_tcp_router, InProcessRouterConfig};
12use crate::storage::StorageProfileSelection;
13pub use crate::transport::{TransportListenerFailure, TransportListenerState, TransportReadiness};
14use crate::{
15    GrpcServerOptions, RedDBGrpcServer, RedDBOptions, RedDBServer, ServerOptions, StorageMode,
16};
17
18mod server_bootstrap;
19pub use server_bootstrap::{bootstrap_server, run_server, transport_set, BootedNode};
20
21pub const DEFAULT_ROUTER_BIND_ADDR: &str = "127.0.0.1:5050";
22
23fn suggested_worker_count(cpus: usize) -> usize {
24    match cpus {
25        0 | 1 => 1,
26        2 => 2,
27        _ => cpus - 1,
28    }
29}
30
31/// Detect available CPU cores and suggest worker thread count.
32pub fn detect_runtime_config() -> RuntimeConfig {
33    let cpus = thread::available_parallelism()
34        .map(|n| n.get())
35        .unwrap_or(1);
36
37    // Two-core instances need both workers to avoid a single blocked query
38    // serialising all engine work. Larger hosts still reserve one core.
39    let suggested_workers = suggested_worker_count(cpus);
40
41    RuntimeConfig {
42        available_cpus: cpus,
43        suggested_workers,
44        stack_size: 8 * 1024 * 1024, // 16MB default
45    }
46}
47
48#[derive(Debug, Clone)]
49pub struct RuntimeConfig {
50    pub available_cpus: usize,
51    pub suggested_workers: usize,
52    pub stack_size: usize,
53}
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum ServerTransport {
57    Grpc,
58    Http,
59    Wire,
60}
61
62impl ServerTransport {
63    pub const fn as_str(self) -> &'static str {
64        match self {
65            Self::Grpc => "gRPC",
66            Self::Http => "HTTP",
67            Self::Wire => "wire",
68        }
69    }
70
71    pub const fn default_bind_addr(self) -> &'static str {
72        match self {
73            Self::Grpc => "127.0.0.1:55055",
74            Self::Http => "127.0.0.1:5000",
75            Self::Wire => "127.0.0.1:5050",
76        }
77    }
78}
79
80#[derive(Debug, Clone)]
81pub struct ServerCommandConfig {
82    pub path: Option<PathBuf>,
83    pub router_bind_addr: Option<String>,
84    pub router_bind_explicit: bool,
85    pub grpc_bind_addr: Option<String>,
86    pub grpc_bind_explicit: bool,
87    /// TLS-encrypted gRPC bind address. Can run side-by-side with
88    /// `grpc_bind_addr` (e.g. `:55055` plain + `:55555` TLS) or
89    /// stand alone for TLS-only deploys. Defaults to `None`.
90    pub grpc_tls_bind_addr: Option<String>,
91    /// Path to PEM-encoded gRPC server certificate. Resolved through
92    /// `REDDB_GRPC_TLS_CERT` (with `_FILE` companion for k8s secret
93    /// mounts). When `None` and dev-mode is enabled
94    /// (`RED_GRPC_TLS_DEV=1`) the server auto-generates a self-signed
95    /// cert and prints its SHA-256 fingerprint to stderr.
96    pub grpc_tls_cert: Option<PathBuf>,
97    /// Path to PEM-encoded gRPC server private key. Same env-var
98    /// pattern as `grpc_tls_cert`.
99    pub grpc_tls_key: Option<PathBuf>,
100    /// Optional path to a PEM bundle of trust anchors used to verify
101    /// client certificates. When set, the gRPC listener requires
102    /// every client to present a cert that chains to this CA — i.e.
103    /// mutual TLS. When unset, one-way TLS only.
104    pub grpc_tls_client_ca: Option<PathBuf>,
105    pub http_bind_addr: Option<String>,
106    pub http_bind_explicit: bool,
107    /// HTTPS bind address. When set, the HTTP server also serves a
108    /// TLS-terminated listener on this addr. Plain HTTP and HTTPS can
109    /// run side by side (e.g. 5000 plain + 55555 TLS).
110    pub http_tls_bind_addr: Option<String>,
111    /// PEM cert for HTTPS. Reads `REDDB_HTTP_TLS_CERT` / its `_FILE`
112    /// companion when not set explicitly.
113    pub http_tls_cert: Option<PathBuf>,
114    /// PEM key for HTTPS. Reads `REDDB_HTTP_TLS_KEY` / its `_FILE`
115    /// companion when not set explicitly.
116    pub http_tls_key: Option<PathBuf>,
117    /// Optional PEM CA bundle. When set, the HTTPS listener requires
118    /// every client to present a cert that chains to a CA in this
119    /// bundle (mTLS). When unset, plain server-side TLS only.
120    pub http_tls_client_ca: Option<PathBuf>,
121    pub wire_bind_addr: Option<String>,
122    pub wire_bind_explicit: bool,
123    /// TLS-encrypted wire protocol bind address
124    pub wire_tls_bind_addr: Option<String>,
125    /// Path to TLS cert PEM (if None + wire_tls_bind, auto-generate)
126    pub wire_tls_cert: Option<PathBuf>,
127    /// Path to TLS key PEM
128    pub wire_tls_key: Option<PathBuf>,
129    /// PostgreSQL wire protocol bind address (Phase 3.1 PG parity).
130    /// When set the server accepts psql / JDBC / DBeaver clients on
131    /// this port via the v3 protocol. Defaults to None (disabled).
132    pub pg_bind_addr: Option<String>,
133    pub create_if_missing: bool,
134    pub bounded_disk_residency: bool,
135    pub read_only: bool,
136    pub role: String,
137    pub primary_addr: Option<String>,
138    pub storage_profile: StorageProfileSelection,
139    /// Explicit auth enable switch from CLI/env. `--no-auth` remains
140    /// the final override and forces this off at option resolution time.
141    pub auth: bool,
142    /// Require authenticated requests. Implies `auth = true` when set.
143    pub require_auth: bool,
144    pub vault: bool,
145    /// Issue #663 — explicit `--no-auth` / `--dev` flag for local
146    /// no-password mode. When `true`, the boot pipeline force-disables
147    /// auth (`auth.enabled = false`, `auth.require_auth = false`,
148    /// `auth.vault_enabled = false`) and skips
149    /// `AuthStore::bootstrap_from_env`, so an explicit
150    /// `REDDB_USERNAME` + `REDDB_PASSWORD` pair cannot accidentally
151    /// turn anonymous access into a logged-in admin. An unmissable
152    /// warning is emitted at startup. Default `false` — the existing
153    /// implicit no-auth behaviour (just don't set the envs) is
154    /// unchanged.
155    pub no_auth: bool,
156    /// Override worker thread count (None = auto-detect from CPUs)
157    pub workers: Option<usize>,
158    /// Telemetry config (Phase 6 logging). `None` falls back to the
159    /// built-in default derived from `path` + stderr-only.
160    pub telemetry: Option<crate::telemetry::TelemetryConfig>,
161    /// HTTP handler-pool knobs from the CLI layer (issue #574 slice 5).
162    /// Carries flag and env values; red_config and built-in defaults
163    /// are applied later by [`crate::server::http_limits::resolve_http_limits`]
164    /// once the runtime is open.
165    pub http_limits_cli: crate::server::HttpLimitsCliInput,
166    /// `red server --ui` (issue #1047, ADR 0051). When `true`, the HTTP
167    /// listener also serves the pinned red-ui bundle as static assets.
168    /// The bundle directory is resolved at boot from the local cache
169    /// (downloading on first use, ADR 0050) unless `ui_dir` overrides it.
170    pub ui: bool,
171    /// Explicit bundle directory for `--ui` (`--ui-dir <DIR>`). When set,
172    /// it is served as-is with no download — the seam tests and an
173    /// air-gapped deploy use this. `None` resolves the pinned bundle.
174    pub ui_dir: Option<PathBuf>,
175    /// First-boot bootstrap settings resolved from CLI flags and, when
176    /// unset here, from environment variables by the bootstrap layer.
177    pub bootstrap: BootstrapConfig,
178}
179
180#[derive(Debug, Clone, Default)]
181pub struct BootstrapConfig {
182    pub preset: Option<String>,
183    pub manifest: Option<PathBuf>,
184    pub admin_username: Option<String>,
185    pub admin_password: Option<String>,
186    pub cloud_head_admin: Option<String>,
187    pub cloud_head_admin_password: Option<String>,
188    pub customer_admin: Option<String>,
189    pub customer_admin_password: Option<String>,
190    /// `--bootstrap-cert-out <path>` (issue #1589). When set and the
191    /// first-boot self-bootstrap mints an unseal certificate, that
192    /// certificate hex is written to this file (in addition to the
193    /// stdout/stderr emission) so a distroless single-machine init can
194    /// read it back for the subsequent unseal via `REDDB_CERTIFICATE_FILE`
195    /// without scraping machine logs. Written only on the
196    /// bootstrap-creating boot; a re-boot against an existing vault does
197    /// not rewrite it.
198    pub cert_out: Option<PathBuf>,
199}
200
201#[derive(Debug, Clone)]
202pub struct SystemdServiceConfig {
203    pub service_name: String,
204    pub binary_path: PathBuf,
205    pub run_user: String,
206    pub run_group: String,
207    pub data_path: PathBuf,
208    pub router_bind_addr: Option<String>,
209    pub grpc_bind_addr: Option<String>,
210    pub http_bind_addr: Option<String>,
211}
212
213impl SystemdServiceConfig {
214    pub fn data_dir(&self) -> PathBuf {
215        self.data_path
216            .parent()
217            .map(PathBuf::from)
218            .unwrap_or_else(|| PathBuf::from("."))
219    }
220
221    pub fn unit_path(&self) -> PathBuf {
222        PathBuf::from(format!("/etc/systemd/system/{}.service", self.service_name))
223    }
224}
225
226/// Build a sane default `TelemetryConfig` from a server path when the
227/// caller didn't set one explicitly. Writes rotating logs into the
228/// parent directory of the DB file (or `./logs` for in-memory /
229/// pathless runs). Level defaults to `info`, pretty stderr format.
230pub fn default_telemetry_for_path(
231    path: Option<&std::path::Path>,
232) -> crate::telemetry::TelemetryConfig {
233    let log_dir = match path {
234        Some(p) => p
235            .parent()
236            .map(|parent| parent.join("logs"))
237            .or_else(|| Some(std::path::PathBuf::from("./logs"))),
238        None => None, // in-memory — no file, stderr-only
239    };
240    crate::telemetry::TelemetryConfig {
241        log_dir,
242        file_prefix: "reddb.log".to_string(),
243        level_filter: std::env::var("RUST_LOG").unwrap_or_else(|_| "info".to_string()),
244        format: if std::io::IsTerminal::is_terminal(&std::io::stderr()) {
245            crate::telemetry::LogFormat::Pretty
246        } else {
247            crate::telemetry::LogFormat::Json
248        },
249        rotation_keep_days: 14,
250        service_name: "reddb",
251        // Implicit defaults — no CLI flag has claimed these values yet.
252        level_explicit: false,
253        format_explicit: false,
254        rotation_keep_days_explicit: false,
255        file_prefix_explicit: false,
256        log_dir_explicit: false,
257        log_file_disabled: false,
258    }
259}
260
261/// Metadata key used to thread the parsed backup config from
262/// `to_db_options` down to runner threads. The runner reads it back
263/// (via `runner_backup_intervals`) to spawn the periodic checkpointer
264/// and WAL-flush tasks. Threading through `metadata` avoids extending
265/// `RedDBOptions` with a public field that has no meaning for
266/// library consumers.
267const BACKUP_INTERVAL_META_CHECKPOINT: &str = "red.boot.backup.checkpoint_interval_secs";
268const BACKUP_INTERVAL_META_WAL_FLUSH: &str = "red.boot.backup.wal_flush_interval_secs";
269const BACKUP_KIND_META: &str = "red.boot.backup.backend_kind";
270/// Issue #519 — threaded through `metadata` like the existing interval
271/// values. `0` (default) means "feature disabled" and the runner skips
272/// the lag-monitor wiring entirely.
273const BACKUP_PAUSE_ON_LAG_META: &str = "red.boot.backup.pause_on_lag_secs";
274
275/// Issue #663 — metadata key set by `to_db_options` when the operator
276/// passes `--no-auth` / `--dev`. Read in `build_runtime_with_telemetry`
277/// to (a) skip `AuthStore::bootstrap_from_env` (so a stray
278/// `REDDB_USERNAME`/`REDDB_PASSWORD` cannot auto-create an admin) and
279/// (b) emit the loud "auth disabled" warning. Threaded via `metadata`
280/// — rather than a public `RedDBOptions` field — to keep the flag a
281/// CLI/boot concern with no meaning for library consumers.
282pub(crate) const NO_AUTH_META: &str = "red.boot.no_auth";
283
284/// Returns `true` when `--no-auth` / `--dev` was active for this boot,
285/// i.e. when `to_db_options` stamped [`NO_AUTH_META`] on `options.metadata`.
286pub(crate) fn no_auth_active(options: &RedDBOptions) -> bool {
287    options
288        .metadata
289        .get(NO_AUTH_META)
290        .map(|v| v == "true")
291        .unwrap_or(false)
292}
293
294/// Loud, unmissable warning printed when the operator opts into
295/// anonymous access via `--no-auth` / `--dev`. Goes to stderr (always
296/// visible at startup) **and** the tracing layer (captured by file
297/// logs once telemetry is wired).
298const NO_AUTH_WARNING: &str =
299    "⚠ auth disabled (--no-auth) — anonymous access, do NOT use in production";
300
301impl ServerCommandConfig {
302    fn to_db_options(&self) -> Result<RedDBOptions, String> {
303        let mut options = match &self.path {
304            Some(path) => RedDBOptions::persistent(path),
305            None => RedDBOptions::in_memory(),
306        };
307
308        options.mode = StorageMode::Persistent;
309        options.create_if_missing = self.create_if_missing;
310        options.bounded_disk_residency = self.bounded_disk_residency;
311        // PLAN.md Phase 4.3 — read_only resolution priority:
312        //   1. CLI flag (`--readonly`) — explicit operator intent.
313        //   2. `RED_READONLY=true` env — orchestrator override.
314        //   3. Persisted `<data>/.runtime-state.json` from a prior
315        //      `POST /admin/readonly` — survives restart.
316        //   4. Default `false`.
317        options.read_only = self.read_only
318            || env_nonempty("RED_READONLY")
319                .or_else(|| env_nonempty("REDDB_READONLY"))
320                .map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"))
321                .unwrap_or(false)
322            || self.path.as_ref().is_some_and(|data_path| {
323                crate::server::handlers_admin::load_runtime_readonly(std::path::Path::new(
324                    data_path,
325                ))
326                .unwrap_or(false)
327            });
328
329        options.replication = match self.role.as_str() {
330            "primary" => ReplicationConfig::primary(),
331            "replica" => {
332                let primary_addr = self
333                    .primary_addr
334                    .clone()
335                    .unwrap_or_else(|| "http://127.0.0.1:55055".to_string());
336                // Public-mutation rejection on replicas is enforced by
337                // `WriteGate` at the runtime/RPC boundary (PLAN.md W1).
338                // Leaving `options.read_only = false` keeps the pager
339                // writable so the internal logical-WAL apply path can
340                // ingest records from the primary; WriteGate ensures no
341                // client request reaches storage.
342                ReplicationConfig::replica(primary_addr)
343            }
344            _ => ReplicationConfig::standalone(),
345        };
346        options.storage_profile = self.storage_profile.validate()?;
347
348        let no_auth = self.no_auth || env_truthy("REDDB_NO_AUTH") || env_truthy("REDDB_DEV");
349        let preset = self.bootstrap.resolved_preset_for_options()?;
350        let preset_requires_auth = matches!(preset.as_str(), PRESET_PRODUCTION | PRESET_CLOUD);
351
352        if self.auth || env_truthy("REDDB_AUTH") || preset_requires_auth {
353            options.auth.enabled = true;
354        }
355        if self.require_auth || env_truthy("REDDB_REQUIRE_AUTH") || preset_requires_auth {
356            options.auth.enabled = true;
357            options.auth.require_auth = true;
358        }
359        if self.vault || env_truthy("REDDB_VAULT") || preset_requires_auth {
360            options.auth.vault_enabled = true;
361        }
362
363        // Issue #663 — `--no-auth` / `--dev` is the last word on auth
364        // for this boot: force every auth knob off, regardless of any
365        // env-derived config (`--vault`, `REDDB_USERNAME`/`PASSWORD`,
366        // OAuth, cert) the operator may also have
367        // set. We *also* stamp [`NO_AUTH_META`] so the auth-store
368        // builder downstream knows to skip `bootstrap_from_env`
369        // (which would otherwise auto-create an admin from
370        // `REDDB_USERNAME`/`REDDB_PASSWORD` even with auth disabled,
371        // a footgun for the local-dev workflow this flag exists to
372        // support).
373        if no_auth {
374            options.auth.enabled = false;
375            options.auth.require_auth = false;
376            options.auth.vault_enabled = false;
377            options
378                .metadata
379                .insert(NO_AUTH_META.to_string(), "true".to_string());
380        }
381
382        // Issue #1587 — first-boot self-bootstrap. A single distroless
383        // `red server` must be able to create the paged vault in place and
384        // serve in one process. The default embedded single-file packaging
385        // routes storage through `UnifiedStore::with_config`, which exposes no
386        // pager, so the vault gate in `build_runtime_with_bootstrap` aborts
387        // with "vault requires a paged database (persistent mode)". The
388        // separate `red bootstrap` subcommand escapes this by opening with the
389        // operational-directory packaging; compose the same storage selection
390        // here so the fresh database is paged, the vault pages exist, and the
391        // existing preset machinery (`ProceedLocal` → `apply_preset_from_config`)
392        // can mint the admins + certificate before listeners come up.
393        //
394        // Gated on (path absent AND a bootstrap intent is present AND the vault
395        // is enabled): an existing database keeps whatever packaging is already
396        // on disk (so a re-boot just serves — no re-bootstrap, no cert churn),
397        // and a fresh path with no intent keeps today's behaviour (a clear
398        // "vault requires a paged database" error rather than a silently
399        // created empty vault). `--no-auth` / `--dev` cleared `vault_enabled`
400        // above, so the development carveout never triggers first-boot either.
401        let bootstrap_intent_present = !matches!(
402            self.bootstrap.auth_bootstrap_input(),
403            crate::cluster::AuthBootstrapInput::None
404        );
405        let path_absent = self.path.as_ref().is_some_and(|path| !path.exists());
406        // Mirrors `embedded_single_file_selected`: only this profile lacks a
407        // pager, so it is the only one that needs promotion to create a vault.
408        let embedded_single_file = options.storage_profile.deploy_profile
409            == crate::storage::DeployProfile::Embedded
410            && options.storage_profile.packaging == crate::storage::StoragePackaging::SingleFile;
411        if options.auth.vault_enabled
412            && bootstrap_intent_present
413            && path_absent
414            && embedded_single_file
415        {
416            // Explicit disk residency already creates a native pager. Keep its
417            // single-file selection instead of routing it through the legacy
418            // snapshot factory's operational-directory bootstrap workaround.
419            if !options.bounded_disk_residency {
420                options.storage_profile.packaging =
421                    crate::storage::StoragePackaging::OperationalDirectory;
422            }
423            options.create_if_missing = true;
424            tracing::info!(
425                target: "reddb::bootstrap",
426                "first-boot self-bootstrap: creating paged vault in place for a fresh database with a bootstrap intent"
427            );
428        }
429
430        // Issue #652 — Control Event Ledger Compliance Mode.
431        // `REDDB_COMPLIANCE_MODE=true|1|yes|on` makes the producer
432        // slices (652b/c/d) fail-closed on ledger persistence
433        // failures. Default `false` — log-and-continue on emit error.
434        if let Some(raw) = env_nonempty("REDDB_COMPLIANCE_MODE") {
435            options.control_events.compliance_mode = matches!(
436                raw.to_ascii_lowercase().as_str(),
437                "1" | "true" | "yes" | "on"
438            );
439        }
440        if preset == PRESET_REGULATED {
441            options.control_events.compliance_mode = true;
442            options.query_audit = crate::runtime::query_audit::QueryAuditConfig::regulated();
443        }
444
445        // Issue #517 — canonical `REDDB_BACKUP_*` contract takes
446        // precedence. On Err, surface the partial-config message so
447        // boot exits non-zero with a clear operator message. On
448        // Ok(None), fall through to the legacy backend-from-env path.
449        match crate::backup_bootstrap::from_env(|k| std::env::var(k).ok()) {
450            Err(msg) => {
451                return Err(format!("backup bootstrap: {msg}"));
452            }
453            Ok(Some(cfg)) => {
454                apply_backup_config(&mut options, &cfg);
455            }
456            Ok(None) => {
457                configure_remote_backend_from_env(&mut options);
458            }
459        }
460
461        if options.remote_backend.is_some()
462            || options
463                .metadata
464                .contains_key(BACKUP_INTERVAL_META_CHECKPOINT)
465        {
466            let mut selection = options.storage_profile;
467            selection.managed_backup = true;
468            options.storage_profile = selection.validate()?;
469        }
470
471        Ok(options)
472    }
473
474    pub fn enabled_transports(&self) -> Vec<ServerTransport> {
475        let mut transports = Vec::with_capacity(3);
476        if self.router_bind_addr.is_some() || self.grpc_bind_addr.is_some() {
477            transports.push(ServerTransport::Grpc);
478        }
479        if self.router_bind_addr.is_some() || self.http_bind_addr.is_some() {
480            transports.push(ServerTransport::Http);
481        }
482        if self.router_bind_addr.is_some() || self.wire_bind_addr.is_some() {
483            transports.push(ServerTransport::Wire);
484        }
485        transports
486    }
487}
488
489/// Read an env var, treating empty / whitespace-only as `None`.
490/// Honors the `<NAME>_FILE` convention. Re-exports the shared
491/// `crate::utils::env_with_file_fallback` helper so call sites in
492/// this module can keep their short local name.
493/// A non-empty env value, also honouring the `<NAME>_FILE` companion for
494/// mounted secrets. Reads the file on demand instead of copying its
495/// contents into the process environment, so the secret never appears in
496/// `/proc/<pid>/environ` or in a child's inherited env.
497fn env_nonempty(name: &str) -> Option<String> {
498    if let Some(value) = crate::utils::env_with_file_fallback(name) {
499        let trimmed = value.trim();
500        if !trimmed.is_empty() {
501            return Some(trimmed.to_string());
502        }
503        return None;
504    }
505    env_nonempty_plain(name)
506}
507
508fn env_nonempty_plain(name: &str) -> Option<String> {
509    crate::utils::env_with_file_fallback(name)
510}
511
512fn env_truthy(name: &str) -> bool {
513    env_nonempty(name)
514        .map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"))
515        .unwrap_or(false)
516}
517
518impl BootstrapConfig {
519    fn resolved_preset(&self) -> String {
520        self.preset
521            .as_deref()
522            .map(str::trim)
523            .filter(|s| !s.is_empty())
524            .map(str::to_string)
525            .or_else(|| env_nonempty(BOOTSTRAP_PRESET_ENV).or_else(|| env_nonempty(PRESET_ENV)))
526            .unwrap_or_else(|| PRESET_SIMPLE.to_string())
527    }
528
529    fn resolved_preset_for_options(&self) -> Result<String, String> {
530        if let Some(path) = self.selected_manifest() {
531            if let Some(manifest_bootstrap) =
532                crate::cli::bootstrap_manifest::bootstrap_config_from_manifest_file(&path)?
533            {
534                return Ok(manifest_bootstrap.resolved_preset());
535            }
536        }
537        Ok(self.resolved_preset())
538    }
539
540    fn selected_manifest(&self) -> Option<PathBuf> {
541        self.manifest.clone().or_else(|| {
542            env_nonempty(crate::cli::bootstrap_manifest::MANIFEST_ENV).map(PathBuf::from)
543        })
544    }
545
546    /// Resolve the `--bootstrap-cert-out` target (issue #1589): the CLI
547    /// flag wins, else the `REDDB_BOOTSTRAP_CERT_OUT` env (with its
548    /// `_FILE` companion) — matching the flag/env pattern used by the
549    /// other bootstrap inputs.
550    fn selected_cert_out(&self) -> Option<PathBuf> {
551        self.cert_out
552            .clone()
553            .or_else(|| env_nonempty(BOOTSTRAP_CERT_OUT_ENV).map(PathBuf::from))
554    }
555
556    /// Classify the auth bootstrap this config would perform, for the
557    /// cluster bootstrap authority seam (ADR 0058). A manifest wins over
558    /// preset/credential env because it is the broadest authority input.
559    fn auth_bootstrap_input(&self) -> crate::cluster::AuthBootstrapInput {
560        use crate::cluster::AuthBootstrapInput;
561        if self.selected_manifest().is_some() {
562            return AuthBootstrapInput::Manifest;
563        }
564        let preset = self.resolved_preset();
565        let preset_creates_auth = matches!(
566            preset.as_str(),
567            PRESET_PRODUCTION | PRESET_CLOUD | PRESET_REGULATED
568        );
569        // Even the `simple` preset auto-creates an admin when
570        // `REDDB_USERNAME` + `REDDB_PASSWORD` are present (see
571        // `AuthStore::bootstrap_from_env`), so treat credential env as
572        // auth bootstrap input too.
573        let credentials_present =
574            self.production_username().is_some() && self.production_password().is_some();
575        if preset_creates_auth || credentials_present {
576            AuthBootstrapInput::Env
577        } else {
578            AuthBootstrapInput::None
579        }
580    }
581
582    fn explicit_value(value: &Option<String>) -> Option<String> {
583        value
584            .as_deref()
585            .map(str::trim)
586            .filter(|s| !s.is_empty())
587            .map(str::to_string)
588    }
589
590    fn value_or_env(value: &Option<String>, env: &str) -> Option<String> {
591        Self::explicit_value(value).or_else(|| env_nonempty(env))
592    }
593
594    fn production_username(&self) -> Option<String> {
595        Self::value_or_env(&self.admin_username, "REDDB_USERNAME")
596    }
597
598    fn production_password(&self) -> Option<String> {
599        Self::value_or_env(&self.admin_password, "REDDB_PASSWORD")
600    }
601
602    fn cloud_head_username(&self) -> Option<String> {
603        Self::explicit_value(&self.cloud_head_admin)
604            .or_else(|| Self::explicit_value(&self.admin_username))
605            .or_else(|| env_nonempty("REDDB_CLOUD_HEAD_ADMIN"))
606            .or_else(|| env_nonempty("REDDB_USERNAME"))
607    }
608
609    fn cloud_head_password(&self) -> Option<String> {
610        Self::explicit_value(&self.cloud_head_admin_password)
611            .or_else(|| Self::explicit_value(&self.admin_password))
612            .or_else(|| env_nonempty("REDDB_CLOUD_HEAD_ADMIN_PASSWORD"))
613            .or_else(|| env_nonempty("REDDB_PASSWORD"))
614    }
615
616    fn customer_username(&self) -> Option<String> {
617        Self::value_or_env(&self.customer_admin, "REDDB_CUSTOMER_ADMIN")
618    }
619
620    fn customer_password(&self) -> Option<String> {
621        Self::value_or_env(
622            &self.customer_admin_password,
623            "REDDB_CUSTOMER_ADMIN_PASSWORD",
624        )
625    }
626}
627
628/// Apply a parsed [`BackupConfig`] to `options`. Wires the S3
629/// backend via `with_remote_backend` + `with_atomic_remote_backend`
630/// when the `backend-s3` feature is on, stashes intervals + backend
631/// kind in `metadata` so the runner can spawn the periodic tasks,
632/// and emits the startup INFO log required by #517.
633fn apply_backup_config(options: &mut RedDBOptions, cfg: &crate::backup_bootstrap::BackupConfig) {
634    let endpoint_host = endpoint_host(&cfg.endpoint);
635
636    options.metadata.insert(
637        BACKUP_INTERVAL_META_CHECKPOINT.to_string(),
638        cfg.checkpoint_interval_secs.to_string(),
639    );
640    options.metadata.insert(
641        BACKUP_INTERVAL_META_WAL_FLUSH.to_string(),
642        cfg.wal_flush_interval_secs.to_string(),
643    );
644    options
645        .metadata
646        .insert(BACKUP_KIND_META.to_string(), "s3".to_string());
647    options.metadata.insert(
648        BACKUP_PAUSE_ON_LAG_META.to_string(),
649        cfg.pause_on_lag_secs.to_string(),
650    );
651
652    #[cfg(feature = "backend-s3")]
653    {
654        let s3_cfg = crate::storage::backend::S3Config {
655            endpoint: cfg.endpoint.clone(),
656            bucket: cfg.bucket.clone(),
657            key_prefix: cfg.prefix.clone(),
658            access_key: cfg.access_key_id.clone(),
659            secret_key: cfg.secret_access_key.clone(),
660            region: cfg.region.clone(),
661            path_style: true,
662        };
663        let mut backend = crate::storage::backend::S3Backend::new(s3_cfg);
664        if let Some(path) = &cfg.credentials_file {
665            backend = backend.with_credentials_file(path);
666        }
667        let backend = Arc::new(backend);
668        options.remote_backend = Some(backend.clone());
669        options.remote_backend_atomic = Some(backend);
670        // Use the operator-supplied prefix as the snapshot key root.
671        // The existing helpers (`default_snapshot_prefix`,
672        // `default_wal_archive_prefix`) derive sub-prefixes from the
673        // parent of `remote_key`.
674        let trimmed = cfg.prefix.trim_end_matches('/');
675        options.remote_key = Some(reddb_file::remote_database_key(trimmed));
676
677        tracing::info!(
678            backend = "s3",
679            endpoint = %endpoint_host,
680            bucket = %cfg.bucket,
681            prefix = %cfg.prefix,
682            checkpoint_interval_secs = cfg.checkpoint_interval_secs,
683            wal_flush_interval_secs = cfg.wal_flush_interval_secs,
684            "backup backend configured from REDDB_BACKUP_* env"
685        );
686    }
687
688    #[cfg(not(feature = "backend-s3"))]
689    {
690        tracing::warn!(
691            backend = "s3",
692            endpoint = %endpoint_host,
693            bucket = %cfg.bucket,
694            prefix = %cfg.prefix,
695            "REDDB_BACKUP_S3_* configured but binary built without `backend-s3` feature; \
696             backend wiring skipped (archiver/checkpointer also disabled)"
697        );
698    }
699}
700
701fn endpoint_host(endpoint: &str) -> &str {
702    let after_scheme = endpoint
703        .split_once("://")
704        .map(|(_, r)| r)
705        .unwrap_or(endpoint);
706    after_scheme.split('/').next().unwrap_or(after_scheme)
707}
708
709/// If `options` carry backup-task intervals threaded in via
710/// [`apply_backup_config`], spawn periodic checkpointer + WAL-flush
711/// tasks against `runtime`. Returns a `BackupTasksHandle` that
712/// stops the tasks when dropped; runners keep it alive for the
713/// server lifetime.
714fn spawn_backup_tasks_if_configured(
715    options: &RedDBOptions,
716    runtime: &RedDBRuntime,
717) -> Option<BackupTasksHandle> {
718    let checkpoint_secs: u64 = options
719        .metadata
720        .get(BACKUP_INTERVAL_META_CHECKPOINT)?
721        .parse()
722        .ok()?;
723    let wal_secs: u64 = options
724        .metadata
725        .get(BACKUP_INTERVAL_META_WAL_FLUSH)?
726        .parse()
727        .ok()?;
728    // Issue #519 — opt-in graceful read-only when remote archive lag
729    // exceeds the threshold. `0` (default) keeps legacy behaviour.
730    let pause_on_lag_secs: u64 = options
731        .metadata
732        .get(BACKUP_PAUSE_ON_LAG_META)
733        .and_then(|raw| raw.parse().ok())
734        .unwrap_or(0);
735    options.remote_backend.as_ref()?;
736
737    let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
738
739    // Stamp the gate with the threshold + a "now" baseline so the
740    // first auto-pause can only fire after `pause_on_lag_secs` of
741    // archive silence. The poller below re-evaluates on the same
742    // clock the archive-task wrapper uses.
743    if pause_on_lag_secs > 0 {
744        let now_ms = std::time::SystemTime::now()
745            .duration_since(std::time::UNIX_EPOCH)
746            .map(|d| d.as_millis() as u64)
747            .unwrap_or(0);
748        runtime
749            .write_gate()
750            .configure_archive_lag_pause(pause_on_lag_secs, now_ms);
751        tracing::info!(
752            pause_on_lag_secs,
753            "archive-lag pause enabled — engine will transition to read-only after threshold seconds of archiver silence"
754        );
755    }
756
757    let checkpoint_handle = {
758        let stop = Arc::clone(&stop);
759        let runtime = runtime.clone();
760        let interval = Duration::from_secs(checkpoint_secs);
761        thread::Builder::new()
762            .name("red-checkpointer".into())
763            .spawn(move || {
764                periodic_loop(stop, interval, move || {
765                    if let Err(err) = runtime.checkpoint() {
766                        tracing::warn!(error = %err, "periodic checkpoint failed");
767                    }
768                })
769            })
770            .ok()
771    };
772
773    let archiver_handle = {
774        let stop = Arc::clone(&stop);
775        let runtime = runtime.clone();
776        let interval = Duration::from_secs(wal_secs);
777        let lag_enabled = pause_on_lag_secs > 0;
778        thread::Builder::new()
779            .name("red-wal-archiver".into())
780            .spawn(move || {
781                periodic_loop(stop, interval, move || match runtime.trigger_backup() {
782                    Ok(_) if lag_enabled => {
783                        let now_ms = std::time::SystemTime::now()
784                            .duration_since(std::time::UNIX_EPOCH)
785                            .map(|d| d.as_millis() as u64)
786                            .unwrap_or(0);
787                        runtime.write_gate().record_archive_success(now_ms);
788                        // Same-tick re-evaluation: catching up while
789                        // already auto-paused must auto-resume without
790                        // waiting for the poller's cadence.
791                        runtime.write_gate().evaluate_archive_lag(now_ms);
792                    }
793                    Ok(_) => {}
794                    Err(err) => {
795                        tracing::warn!(error = %err, "periodic WAL archive/backup failed");
796                    }
797                })
798            })
799            .ok()
800    };
801
802    // Issue #519 — lag poller. Wakes on a short cadence so a frozen
803    // archiver (the worst case) still flips the gate within ~5s of
804    // crossing the threshold, instead of waiting up to a full
805    // `wal_secs` for the next archive attempt that may never come.
806    let lag_monitor_handle = if pause_on_lag_secs > 0 {
807        let stop = Arc::clone(&stop);
808        let runtime = runtime.clone();
809        // 5s is short enough that the threshold is honoured tightly
810        // and long enough that the atomic loads stay invisible at the
811        // process level.
812        let interval = Duration::from_secs(5);
813        thread::Builder::new()
814            .name("red-archive-lag-monitor".into())
815            .spawn(move || {
816                periodic_loop(stop, interval, move || {
817                    let now_ms = std::time::SystemTime::now()
818                        .duration_since(std::time::UNIX_EPOCH)
819                        .map(|d| d.as_millis() as u64)
820                        .unwrap_or(0);
821                    let was_paused = runtime.write_gate().is_auto_paused();
822                    let now_paused = runtime.write_gate().evaluate_archive_lag(now_ms);
823                    if now_paused && !was_paused {
824                        tracing::warn!(
825                            pause_on_lag_secs,
826                            last_archive_at_ms = runtime.write_gate().last_archive_at_ms(),
827                            "WAL archive lag exceeded threshold — entering graceful read-only mode (issue #519)"
828                        );
829                    } else if !now_paused && was_paused {
830                        tracing::info!(
831                            "WAL archive caught up — exiting graceful read-only mode (issue #519)"
832                        );
833                    }
834                })
835            })
836            .ok()
837    } else {
838        None
839    };
840
841    tracing::info!(
842        checkpoint_interval_secs = checkpoint_secs,
843        wal_flush_interval_secs = wal_secs,
844        "backup tasks spawned (checkpointer + WAL archiver)"
845    );
846
847    Some(BackupTasksHandle {
848        stop,
849        _checkpoint_handle: checkpoint_handle,
850        _archiver_handle: archiver_handle,
851        _lag_monitor_handle: lag_monitor_handle,
852    })
853}
854
855/// Shutdown handle for the periodic checkpointer + archiver tasks.
856/// Drop signals both loops to exit on their next wake.
857pub struct BackupTasksHandle {
858    stop: Arc<std::sync::atomic::AtomicBool>,
859    _checkpoint_handle: Option<thread::JoinHandle<()>>,
860    _archiver_handle: Option<thread::JoinHandle<()>>,
861    /// Issue #519 — periodic archive-lag poller, only spawned when
862    /// `REDDB_BACKUP_PAUSE_ON_LAG_SECS > 0`.
863    _lag_monitor_handle: Option<thread::JoinHandle<()>>,
864}
865
866impl Drop for BackupTasksHandle {
867    fn drop(&mut self) {
868        self.stop.store(true, std::sync::atomic::Ordering::Release);
869    }
870}
871
872fn periodic_loop<F: FnMut()>(
873    stop: Arc<std::sync::atomic::AtomicBool>,
874    interval: Duration,
875    mut tick: F,
876) {
877    // Wake on a short cadence so shutdown is responsive even when the
878    // operator-configured interval is large (e.g. 1h checkpoint).
879    let wake = Duration::from_secs(1);
880    let mut elapsed = Duration::ZERO;
881    while !stop.load(std::sync::atomic::Ordering::Acquire) {
882        thread::sleep(wake);
883        elapsed += wake;
884        if elapsed >= interval {
885            tick();
886            elapsed = Duration::ZERO;
887        }
888    }
889}
890
891fn configure_remote_backend_from_env(options: &mut RedDBOptions) {
892    // PLAN.md (cloud-agnostic) — prefer the new spelling
893    // `RED_BACKEND`; accept the legacy `REDDB_REMOTE_BACKEND` for
894    // existing dev installs. `none` (default) means standalone — no
895    // remote backend, valid for development and on-prem without
896    // remote.
897    let backend = env_nonempty("RED_BACKEND")
898        .or_else(|| env_nonempty("REDDB_REMOTE_BACKEND"))
899        .unwrap_or_else(|| "none".to_string())
900        .to_ascii_lowercase();
901
902    match backend.as_str() {
903        // Universal S3-compatible — covers AWS, R2, MinIO, Ceph,
904        // GCS-interop, B2, DO Spaces, Wasabi, Garage, SeaweedFS,
905        // IDrive, Storj. The `path_style` toggle in S3Config picks
906        // the right addressing for self-hosted vs hosted.
907        "s3" | "minio" | "r2" => {
908            #[cfg(feature = "backend-s3")]
909            {
910                if let Some(config) = s3_config_from_env() {
911                    let remote_key = env_nonempty("RED_REMOTE_KEY")
912                        .or_else(|| env_nonempty("REDDB_REMOTE_KEY"))
913                        .unwrap_or_else(|| reddb_file::remote_database_key("clusters/dev"));
914                    let backend = Arc::new(crate::storage::backend::S3Backend::new(config));
915                    options.remote_backend = Some(backend.clone());
916                    options.remote_backend_atomic = Some(backend);
917                    options.remote_key = Some(remote_key);
918                }
919            }
920            #[cfg(not(feature = "backend-s3"))]
921            {
922                tracing::warn!(
923                    backend = %backend,
924                    "RED_BACKEND={backend} requested but binary was built without `backend-s3` feature"
925                );
926            }
927        }
928        // Filesystem backend (NFS/EFS/SMB/local-disk). PLAN.md spec
929        // calls it `fs`; legacy code shipped it as `local`. Both
930        // names map to LocalBackend, with the remote_key derived
931        // from `RED_FS_PATH` + a per-database suffix when provided.
932        "fs" | "local" => {
933            let base_path = env_nonempty("RED_FS_PATH").or_else(|| env_nonempty("REDDB_FS_PATH"));
934            let remote_key = match (
935                base_path,
936                env_nonempty("RED_REMOTE_KEY").or_else(|| env_nonempty("REDDB_REMOTE_KEY")),
937            ) {
938                (Some(base), Some(rel)) => Some(format!(
939                    "{}/{}",
940                    base.trim_end_matches('/'),
941                    rel.trim_start_matches('/')
942                )),
943                (Some(base), None) => Some(reddb_file::remote_database_key(&format!(
944                    "{}/clusters/dev",
945                    base.trim_end_matches('/')
946                ))),
947                (None, Some(rel)) => Some(rel),
948                (None, None) => None,
949            };
950            if let Some(key) = remote_key {
951                let backend = Arc::new(crate::storage::backend::LocalBackend);
952                options.remote_backend = Some(backend.clone());
953                options.remote_backend_atomic = Some(backend);
954                options.remote_key = Some(key);
955            }
956        }
957        // Generic HTTP backend (PLAN.md Phase 2.3). Maximum
958        // portability: any service exposing PUT/GET/DELETE serves
959        // as a backup target. Optional auth via *_FILE secret
960        // path keeps the token out of the env.
961        "http" => {
962            let base_url = match env_nonempty("RED_HTTP_BACKEND_URL")
963                .or_else(|| env_nonempty("REDDB_HTTP_BACKEND_URL"))
964            {
965                Some(u) => u,
966                None => {
967                    tracing::warn!(
968                        "RED_BACKEND=http requires RED_HTTP_BACKEND_URL — backend disabled"
969                    );
970                    return;
971                }
972            };
973            let prefix = env_nonempty("RED_HTTP_BACKEND_PREFIX")
974                .or_else(|| env_nonempty("REDDB_HTTP_BACKEND_PREFIX"))
975                .unwrap_or_default();
976            let auth_header = if let Some(path) = env_nonempty("RED_HTTP_BACKEND_AUTH_HEADER_FILE")
977                .or_else(|| env_nonempty("REDDB_HTTP_BACKEND_AUTH_HEADER_FILE"))
978            {
979                std::fs::read_to_string(&path)
980                    .ok()
981                    .map(|s| s.trim().to_string())
982                    .filter(|s| !s.is_empty())
983            } else {
984                env_nonempty("RED_HTTP_BACKEND_AUTH_HEADER")
985                    .or_else(|| env_nonempty("REDDB_HTTP_BACKEND_AUTH_HEADER"))
986            };
987
988            let mut config =
989                crate::storage::backend::HttpBackendConfig::new(base_url).with_prefix(prefix);
990            if let Some(auth) = auth_header {
991                config = config.with_auth_header(auth);
992            }
993            let conditional_writes = env_truthy("RED_HTTP_CONDITIONAL_WRITES")
994                || env_truthy("RED_HTTP_BACKEND_CONDITIONAL_WRITES")
995                || env_truthy("REDDB_HTTP_BACKEND_CONDITIONAL_WRITES");
996            config = config.with_conditional_writes(conditional_writes);
997            // Always populate the snapshot-transport handle. When the
998            // operator confirmed CAS support, also populate the atomic
999            // handle via AtomicHttpBackend — without that flag,
1000            // LeaseStore must remain unreachable on this backend.
1001            if conditional_writes {
1002                match crate::storage::backend::AtomicHttpBackend::try_new(config.clone()) {
1003                    Ok(atomic) => {
1004                        let atomic_arc = Arc::new(atomic);
1005                        options.remote_backend = Some(atomic_arc.clone());
1006                        options.remote_backend_atomic = Some(atomic_arc);
1007                    }
1008                    Err(err) => {
1009                        tracing::warn!(error = %err, "AtomicHttpBackend init failed; falling back to plain HTTP (no CAS)");
1010                        options.remote_backend =
1011                            Some(Arc::new(crate::storage::backend::HttpBackend::new(config)));
1012                    }
1013                }
1014            } else {
1015                options.remote_backend =
1016                    Some(Arc::new(crate::storage::backend::HttpBackend::new(config)));
1017            }
1018            options.remote_key = env_nonempty("RED_REMOTE_KEY")
1019                .or_else(|| env_nonempty("REDDB_REMOTE_KEY"))
1020                .or_else(|| Some(reddb_file::remote_database_key("clusters/dev")));
1021        }
1022        // `none` is the explicit standalone — no remote, no backup
1023        // pipeline. Boot never blocks on network reachability.
1024        "none" | "" => {}
1025        other => {
1026            tracing::warn!(
1027                backend = %other,
1028                "unknown RED_BACKEND value — supported: s3 | fs | http | none"
1029            );
1030        }
1031    }
1032}
1033
1034/// Resolve a value from env, accepting both the cloud-agnostic
1035/// `RED_S3_*` family (PLAN.md spec) and the legacy `REDDB_S3_*` form
1036/// kept for existing dev installs. The new spelling wins; the
1037/// legacy spelling is read with a warning hint in callers' logs.
1038#[cfg(feature = "backend-s3")]
1039fn env_s3(suffix: &str) -> Option<String> {
1040    env_nonempty(&format!("RED_S3_{suffix}"))
1041        .or_else(|| env_nonempty(&format!("REDDB_S3_{suffix}")))
1042}
1043
1044/// Read a secret value from either the literal env var or a file
1045/// path supplied via `*_FILE` (PLAN.md spec — compatible with
1046/// Kubernetes / Docker Secrets, HashiCorp Vault Agent, sealed-
1047/// secrets). The `_FILE` variant wins so an operator can set it to
1048/// override the inline value without touching the inline env.
1049#[cfg(feature = "backend-s3")]
1050fn env_s3_secret(suffix: &str) -> Option<String> {
1051    let file_key_red = format!("RED_S3_{suffix}_FILE");
1052    let file_key_legacy = format!("REDDB_S3_{suffix}_FILE");
1053    if let Some(path) = env_nonempty(&file_key_red).or_else(|| env_nonempty(&file_key_legacy)) {
1054        return std::fs::read_to_string(&path)
1055            .ok()
1056            .map(|s| s.trim().to_string())
1057            .filter(|s| !s.is_empty());
1058    }
1059    env_s3(suffix)
1060}
1061
1062#[cfg(feature = "backend-s3")]
1063fn s3_config_from_env() -> Option<crate::storage::backend::S3Config> {
1064    let endpoint = env_s3("ENDPOINT")?;
1065    let bucket = env_s3("BUCKET")?;
1066    let access_key = env_s3_secret("ACCESS_KEY")?;
1067    let secret_key = env_s3_secret("SECRET_KEY")?;
1068    let region = env_s3("REGION").unwrap_or_else(|| "us-east-1".to_string());
1069    let key_prefix = env_s3("KEY_PREFIX")
1070        .or_else(|| env_s3("PREFIX"))
1071        .unwrap_or_default();
1072    let path_style = env_s3("PATH_STYLE")
1073        .map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"))
1074        .unwrap_or(true);
1075    Some(crate::storage::backend::S3Config {
1076        endpoint,
1077        bucket,
1078        key_prefix,
1079        access_key,
1080        secret_key,
1081        region,
1082        path_style,
1083    })
1084}
1085
1086pub fn render_systemd_unit(config: &SystemdServiceConfig) -> String {
1087    let data_dir = config.data_dir();
1088    let exec_start = render_systemd_exec_start(config);
1089    format!(
1090        "[Unit]\n\
1091Description=RedDB unified database service\n\
1092After=network-online.target\n\
1093Wants=network-online.target\n\
1094\n\
1095[Service]\n\
1096Type=simple\n\
1097User={user}\n\
1098Group={group}\n\
1099WorkingDirectory={workdir}\n\
1100ExecStart={exec_start}\n\
1101Restart=always\n\
1102RestartSec=2\n\
1103LimitSTACK=16M\n\
1104NoNewPrivileges=true\n\
1105PrivateTmp=true\n\
1106ProtectSystem=strict\n\
1107ProtectHome=true\n\
1108ProtectControlGroups=true\n\
1109ProtectKernelTunables=true\n\
1110ProtectKernelModules=true\n\
1111RestrictNamespaces=true\n\
1112LockPersonality=true\n\
1113MemoryDenyWriteExecute=true\n\
1114ReadWritePaths={workdir}\n\
1115\n\
1116[Install]\n\
1117WantedBy=multi-user.target\n",
1118        user = config.run_user,
1119        group = config.run_group,
1120        workdir = data_dir.display(),
1121        exec_start = exec_start,
1122    )
1123}
1124
1125/// Install a systemd unit + start the service.
1126///
1127/// Linux-only. The helper shells out to `systemctl`, `useradd`,
1128/// `groupadd`, `install`, `getent`, and `id` — none of which exist on
1129/// Windows or macOS. The Windows/macOS branch returns a hard error so
1130/// callers (the CLI) surface a clear message instead of a confusing
1131/// syscall failure. A proper Windows-service equivalent (sc.exe /
1132/// NSSM) is a Phase 3.6 follow-up.
1133#[cfg(target_os = "linux")]
1134pub fn install_systemd_service(config: &SystemdServiceConfig) -> Result<(), String> {
1135    ensure_root()?;
1136    ensure_command_available("systemctl")?;
1137    ensure_command_available("getent")?;
1138    ensure_command_available("groupadd")?;
1139    ensure_command_available("useradd")?;
1140    ensure_command_available("install")?;
1141    ensure_executable(&config.binary_path)?;
1142
1143    if !command_success("getent", ["group", config.run_group.as_str()])? {
1144        run_command("groupadd", ["--system", config.run_group.as_str()])?;
1145    }
1146
1147    if !command_success("id", ["-u", config.run_user.as_str()])? {
1148        let data_dir = config.data_dir();
1149        run_command(
1150            "useradd",
1151            [
1152                "--system",
1153                "--gid",
1154                config.run_group.as_str(),
1155                "--home-dir",
1156                data_dir.to_string_lossy().as_ref(),
1157                "--shell",
1158                "/usr/sbin/nologin",
1159                config.run_user.as_str(),
1160            ],
1161        )?;
1162    }
1163
1164    let data_dir = config.data_dir();
1165    run_command(
1166        "install",
1167        [
1168            "-d",
1169            "-o",
1170            config.run_user.as_str(),
1171            "-g",
1172            config.run_group.as_str(),
1173            "-m",
1174            "0750",
1175            data_dir.to_string_lossy().as_ref(),
1176        ],
1177    )?;
1178
1179    std::fs::write(config.unit_path(), render_systemd_unit(config))
1180        .map_err(|err| format!("failed to write systemd unit: {err}"))?;
1181
1182    run_command("systemctl", ["daemon-reload"])?;
1183    run_command(
1184        "systemctl",
1185        [
1186            "enable",
1187            "--now",
1188            format!("{}.service", config.service_name).as_str(),
1189        ],
1190    )?;
1191
1192    Ok(())
1193}
1194
1195/// Non-Linux fallback — systemd is Linux-specific. Keep the signature
1196/// identical so callers compile on every platform; surface a clear
1197/// error at runtime. Windows/macOS service-manager integration is a
1198/// Phase 3.6 follow-up (sc.exe + NSSM on Windows, launchd on macOS).
1199#[cfg(not(target_os = "linux"))]
1200pub fn install_systemd_service(_config: &SystemdServiceConfig) -> Result<(), String> {
1201    Err("systemd install is Linux-only — use sc.exe (Windows) or \
1202         launchd (macOS) to install the service manually using the \
1203         unit printed by `red service print-unit`"
1204        .to_string())
1205}
1206
1207#[cfg(target_os = "linux")]
1208fn ensure_root() -> Result<(), String> {
1209    let output = Command::new("id")
1210        .arg("-u")
1211        .output()
1212        .map_err(|err| format!("failed to determine current uid: {err}"))?;
1213    if !output.status.success() {
1214        return Err("failed to determine current uid".to_string());
1215    }
1216    let uid = String::from_utf8_lossy(&output.stdout);
1217    if uid.trim() != "0" {
1218        return Err("run this command as root (sudo)".to_string());
1219    }
1220    Ok(())
1221}
1222
1223#[cfg(target_os = "linux")]
1224fn ensure_command_available(command: &str) -> Result<(), String> {
1225    let status = Command::new("sh")
1226        .args(["-lc", &format!("command -v {command} >/dev/null 2>&1")])
1227        .status()
1228        .map_err(|err| format!("failed to check command '{command}': {err}"))?;
1229    if status.success() {
1230        Ok(())
1231    } else {
1232        Err(format!("required command not found: {command}"))
1233    }
1234}
1235
1236#[cfg(target_os = "linux")]
1237fn ensure_executable(path: &std::path::Path) -> Result<(), String> {
1238    let metadata = std::fs::metadata(path)
1239        .map_err(|err| format!("binary not found '{}': {err}", path.display()))?;
1240    #[cfg(unix)]
1241    {
1242        use std::os::unix::fs::PermissionsExt;
1243        if metadata.permissions().mode() & 0o111 == 0 {
1244            return Err(format!("binary is not executable: {}", path.display()));
1245        }
1246    }
1247    #[cfg(not(unix))]
1248    {
1249        if !metadata.is_file() {
1250            return Err(format!("binary is not a file: {}", path.display()));
1251        }
1252    }
1253    Ok(())
1254}
1255
1256#[cfg(target_os = "linux")]
1257fn command_success<const N: usize>(program: &str, args: [&str; N]) -> Result<bool, String> {
1258    Command::new(program)
1259        .args(args)
1260        .status()
1261        .map(|status| status.success())
1262        .map_err(|err| format!("failed to run {program}: {err}"))
1263}
1264
1265#[cfg(target_os = "linux")]
1266fn run_command<const N: usize>(program: &str, args: [&str; N]) -> Result<(), String> {
1267    let output = Command::new(program)
1268        .args(args)
1269        .output()
1270        .map_err(|err| format!("failed to run {program}: {err}"))?;
1271    if output.status.success() {
1272        return Ok(());
1273    }
1274
1275    let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
1276    let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
1277    let detail = if !stderr.is_empty() {
1278        stderr
1279    } else if !stdout.is_empty() {
1280        stdout
1281    } else {
1282        format!("exit status {}", output.status)
1283    };
1284    Err(format!("{program} failed: {detail}"))
1285}
1286
1287fn render_systemd_exec_start(config: &SystemdServiceConfig) -> String {
1288    let mut parts = vec![
1289        config.binary_path.display().to_string(),
1290        "server".to_string(),
1291        "--path".to_string(),
1292        config.data_path.display().to_string(),
1293    ];
1294
1295    if let Some(bind_addr) = &config.router_bind_addr {
1296        parts.push("--bind".to_string());
1297        parts.push(bind_addr.clone());
1298    } else if let Some(bind_addr) = &config.grpc_bind_addr {
1299        parts.push("--grpc-bind".to_string());
1300        parts.push(bind_addr.clone());
1301    }
1302    if let Some(bind_addr) = &config.http_bind_addr {
1303        parts.push("--http-bind".to_string());
1304        parts.push(bind_addr.clone());
1305    }
1306
1307    parts.join(" ")
1308}
1309
1310pub fn probe_listener(target: &str, timeout: Duration) -> bool {
1311    let addresses: Vec<SocketAddr> = match target.to_socket_addrs() {
1312        Ok(addresses) => addresses.collect(),
1313        Err(_) => return false,
1314    };
1315
1316    addresses
1317        .into_iter()
1318        .any(|address| TcpStream::connect_timeout(&address, timeout).is_ok())
1319}
1320
1321/// Bind a TCP listener for a transport at startup and record the
1322/// outcome in the shared [`TransportReadiness`] state.
1323///
1324/// The split between *explicit* and *implicit/default* binds is the
1325/// contract from issue #545:
1326///
1327/// * `explicit == true` — the operator named this transport on the
1328///   CLI / env / config. A failed bind is fatal: this returns `Err`
1329///   and the boot path must propagate the error so the process exits
1330///   non-zero with the recorded `reason`.
1331/// * `explicit == false` — this is a default listener the server
1332///   would have spun up regardless. A failed bind degrades: this
1333///   returns `Ok(None)` (no listener) but the failure is still
1334///   recorded in `readiness.failed`, so the server keeps running and
1335///   the next `/health` probe enumerates the degraded listener.
1336///
1337/// On success the bound listener lands in `readiness.active`.
1338pub fn bind_listener_for_startup(
1339    readiness: &mut TransportReadiness,
1340    transport: &str,
1341    bind_addr: &str,
1342    explicit: bool,
1343) -> Result<Option<TcpListener>, String> {
1344    match TcpListener::bind(bind_addr) {
1345        Ok(listener) => {
1346            readiness.active(transport, bind_addr, explicit);
1347            Ok(Some(listener))
1348        }
1349        Err(err) => {
1350            let reason = format!("{transport} listener bind {bind_addr}: {err}");
1351            readiness.failed(transport, bind_addr, explicit, reason.clone());
1352            if explicit {
1353                tracing::error!(
1354                    transport,
1355                    bind = %bind_addr,
1356                    error = %err,
1357                    "fatal explicit bind failure"
1358                );
1359                Err(format!("explicit {reason}"))
1360            } else {
1361                tracing::warn!(
1362                    transport,
1363                    bind = %bind_addr,
1364                    error = %err,
1365                    "non-fatal implicit bind failure; listener degraded"
1366                );
1367                Ok(None)
1368            }
1369        }
1370    }
1371}
1372
1373/// Wire SIGTERM and SIGINT to `RedDBRuntime::graceful_shutdown`.
1374///
1375/// PLAN.md Phase 1.1 — orchestrators (K8s preStop, Fly autostop, ECS
1376/// drain, systemd, plain `docker stop`) all rely on SIGTERM with a
1377/// grace window. SIGKILL after that grace window is the OS's
1378/// fallback; we are responsible for finishing in time.
1379///
1380/// Spawns a tokio task on the caller's runtime that:
1381///   1. Awaits the first of SIGTERM / SIGINT.
1382///   2. Calls `runtime.graceful_shutdown(backup_on_shutdown)`. The
1383///      runtime moves to `Stopped` on its own; this just runs the
1384///      flush + checkpoint pipeline and (optionally) a final backup.
1385///   3. Calls `std::process::exit(0)` so the orchestrator sees a
1386///      clean exit code.
1387///
1388/// `RED_BACKUP_ON_SHUTDOWN` (default `true` if a remote backend is
1389/// configured) toggles step 3's backup branch. The flush + checkpoint
1390/// always run.
1391///
1392/// Idempotent across signal storms — `graceful_shutdown` returns the
1393/// cached report on second call, but we exit on the first one
1394/// regardless, so the second SIGTERM never reaches the handler.
1395async fn spawn_lifecycle_signal_handler(runtime: RedDBRuntime) {
1396    let backup_on_shutdown = std::env::var("RED_BACKUP_ON_SHUTDOWN")
1397        .ok()
1398        .map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"))
1399        .unwrap_or(true);
1400
1401    #[cfg(unix)]
1402    {
1403        use tokio::signal::unix::{signal, SignalKind};
1404
1405        let mut sigterm = match signal(SignalKind::terminate()) {
1406            Ok(s) => s,
1407            Err(err) => {
1408                tracing::warn!(
1409                    error = %err,
1410                    "could not install SIGTERM handler; orchestrator graceful shutdown will fall back to SIGKILL"
1411                );
1412                return;
1413            }
1414        };
1415        let mut sigint = match signal(SignalKind::interrupt()) {
1416            Ok(s) => s,
1417            Err(err) => {
1418                tracing::warn!(error = %err, "could not install SIGINT handler");
1419                return;
1420            }
1421        };
1422        // PLAN.md Phase 6.4 — SIGHUP triggers a reload of secrets from
1423        // their `_FILE` companions without restarting the process.
1424        // Useful for credential rotation pipelines (kubectl create
1425        // secret + kubectl rollout restart, but for systemd / Nomad /
1426        // bare-metal where rolling the process is heavier).
1427        let mut sighup = match signal(SignalKind::hangup()) {
1428            Ok(s) => Some(s),
1429            Err(err) => {
1430                tracing::warn!(error = %err, "could not install SIGHUP handler; secret reload via signal disabled");
1431                None
1432            }
1433        };
1434
1435        let reload_runtime = runtime.clone();
1436        tokio::spawn(async move {
1437            loop {
1438                let signal_name = match &mut sighup {
1439                    Some(hup) => tokio::select! {
1440                        _ = sigterm.recv() => "SIGTERM",
1441                        _ = sigint.recv() => "SIGINT",
1442                        _ = hup.recv() => "SIGHUP",
1443                    },
1444                    None => tokio::select! {
1445                        _ = sigterm.recv() => "SIGTERM",
1446                        _ = sigint.recv() => "SIGINT",
1447                    },
1448                };
1449
1450                if signal_name == "SIGHUP" {
1451                    handle_sighup_reload(&reload_runtime);
1452                    continue; // stay alive; SIGHUP isn't a shutdown
1453                }
1454
1455                tracing::info!(
1456                    signal = signal_name,
1457                    "lifecycle signal received; shutting down"
1458                );
1459                match runtime.graceful_shutdown(backup_on_shutdown) {
1460                    Ok(report) => {
1461                        tracing::info!(
1462                            duration_ms = report.duration_ms,
1463                            flushed_wal = report.flushed_wal,
1464                            final_checkpoint = report.final_checkpoint,
1465                            backup_uploaded = report.backup_uploaded,
1466                            "graceful shutdown complete"
1467                        );
1468                    }
1469                    Err(err) => {
1470                        tracing::error!(error = %err, "graceful shutdown failed");
1471                        // Issue #205 — graceful shutdown returning Err
1472                        // means the runtime is exiting without a clean
1473                        // flush/checkpoint. Operator-grade event so the
1474                        // operator notices the dirty exit even when the
1475                        // process restarts before they read tracing logs.
1476                        crate::telemetry::operator_event::OperatorEvent::ShutdownForced {
1477                            reason: format!("graceful shutdown failed: {err}"),
1478                        }
1479                        .emit_global();
1480                    }
1481                }
1482                std::process::exit(0);
1483            }
1484        });
1485    }
1486
1487    #[cfg(not(unix))]
1488    {
1489        tokio::spawn(async move {
1490            let interrupted = tokio::signal::ctrl_c().await;
1491            if let Err(err) = interrupted {
1492                tracing::warn!(error = %err, "could not install Ctrl+C handler");
1493                return;
1494            }
1495
1496            tracing::info!(
1497                signal = "Ctrl+C",
1498                "lifecycle signal received; shutting down"
1499            );
1500            match runtime.graceful_shutdown(backup_on_shutdown) {
1501                Ok(report) => {
1502                    tracing::info!(
1503                        duration_ms = report.duration_ms,
1504                        flushed_wal = report.flushed_wal,
1505                        final_checkpoint = report.final_checkpoint,
1506                        backup_uploaded = report.backup_uploaded,
1507                        "graceful shutdown complete"
1508                    );
1509                }
1510                Err(err) => {
1511                    tracing::error!(error = %err, "graceful shutdown failed");
1512                }
1513            }
1514            std::process::exit(0);
1515        });
1516    }
1517}
1518
1519/// PLAN.md Phase 6.4 — re-read secrets from `*_FILE` companion env
1520/// vars. Today this only refreshes the audit log + records the
1521/// reload event; the runtime modules that hold cached secret
1522/// material (S3 backend credentials, admin token, JWT keys) read
1523/// the env on each request so the next call after SIGHUP picks up
1524/// the new file contents automatically. A future extension can
1525/// punch through to the LeaseStore / AuthStore for in-memory
1526/// caches that don't re-read on each call.
1527fn handle_sighup_reload(runtime: &RedDBRuntime) {
1528    let now_ms = std::time::SystemTime::now()
1529        .duration_since(std::time::UNIX_EPOCH)
1530        .map(|d| d.as_millis() as u64)
1531        .unwrap_or(0);
1532    tracing::info!(
1533        target: "reddb::secrets",
1534        ts_unix_ms = now_ms,
1535        "SIGHUP received; secrets will be re-read from *_FILE on next access"
1536    );
1537    // Routed through AuditFieldEscaper (ADR 0010 / issue #177) so
1538    // every emission goes through the typed-field guard. The
1539    // arguments here are static, but using the typed entry point
1540    // keeps the discipline uniform across call sites.
1541    use crate::runtime::audit_log::{AuditAuthSource, AuditEvent, AuditFieldEscaper, Outcome};
1542    runtime.audit_log().record_event(
1543        AuditEvent::builder("config/sighup_reload")
1544            .source(AuditAuthSource::System)
1545            .resource("secrets")
1546            .outcome(Outcome::Success)
1547            .field(AuditFieldEscaper::field("ts_unix_ms", now_ms))
1548            .build(),
1549    );
1550}
1551
1552/// Resolve the TLS material the PG-Wire listener shares with the native
1553/// wire transport, if any.
1554///
1555/// Policy: when the operator has enabled wire TLS — an explicit cert/key
1556/// pair or a `--wire-tls-bind` that auto-generates a self-signed dev cert
1557/// — the PG-Wire listener answers `SSLRequest` with `'S'` over the *same*
1558/// cert config (`resolve_wire_tls_config`) rather than inventing a
1559/// parallel surface. With no wire TLS configured the listener stays
1560/// plaintext and declines `SSLRequest` with `'N'`. A config error degrades
1561/// to plaintext rather than killing the listener.
1562fn resolve_pg_wire_tls(config: &ServerCommandConfig) -> Option<crate::wire::WireTlsConfig> {
1563    let tls_configured = config.wire_tls_bind_addr.is_some()
1564        || (config.wire_tls_cert.is_some() && config.wire_tls_key.is_some());
1565    if !tls_configured {
1566        return None;
1567    }
1568    match resolve_wire_tls_config(config) {
1569        Ok(cfg) => Some(cfg),
1570        Err(e) => {
1571            tracing::error!(
1572                err = %e,
1573                "pg wire TLS config error; listener will run plaintext"
1574            );
1575            None
1576        }
1577    }
1578}
1579
1580/// Resolve gRPC TLS material into PEM bytes.
1581///
1582/// Lookup order, in priority:
1583///   1. Explicit `config.grpc_tls_cert` / `config.grpc_tls_key` (paths
1584///      passed via CLI/env). Both must be present together.
1585///   2. `RED_GRPC_TLS_DEV=1` — auto-generate a self-signed cert next
1586///      to the data dir. Refuses to run without the env flag so an
1587///      operator can't accidentally ship a dev cert in prod.
1588///
1589/// `client_ca` is loaded when `config.grpc_tls_client_ca` is set,
1590/// turning the listener into a mutual-TLS endpoint that requires
1591/// every client to present a chain that anchors at one of the CAs
1592/// in the bundle.
1593fn resolve_grpc_tls_options(config: &ServerCommandConfig) -> Result<crate::GrpcTlsOptions, String> {
1594    let (cert_pem, key_pem) = match (&config.grpc_tls_cert, &config.grpc_tls_key) {
1595        (Some(cert), Some(key)) => {
1596            let cert_pem = std::fs::read(cert)
1597                .map_err(|e| format!("read grpc cert {}: {e}", cert.display()))?;
1598            let key_pem =
1599                std::fs::read(key).map_err(|e| format!("read grpc key {}: {e}", key.display()))?;
1600            (cert_pem, key_pem)
1601        }
1602        _ => {
1603            // No explicit material → only proceed when dev-mode is on.
1604            let dev = std::env::var("RED_GRPC_TLS_DEV")
1605                .ok()
1606                .map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"))
1607                .unwrap_or(false);
1608            if !dev {
1609                return Err("gRPC TLS configured but no cert/key supplied — set \
1610                     REDDB_GRPC_TLS_CERT / REDDB_GRPC_TLS_KEY (or \
1611                     RED_GRPC_TLS_DEV=1 to auto-generate a self-signed cert)"
1612                    .to_string());
1613            }
1614            let dir = config
1615                .path
1616                .as_ref()
1617                .and_then(|p| p.parent())
1618                .map(PathBuf::from)
1619                .unwrap_or_else(|| PathBuf::from("."));
1620            let (cert_pem_str, key_pem_str) =
1621                crate::wire::tls::generate_self_signed_cert("localhost")
1622                    .map_err(|e| format!("auto-generate dev grpc cert: {e}"))?;
1623
1624            // Constant-time-friendly fingerprint to stderr so the
1625            // operator can pin a client trust store. We log via
1626            // `tracing::warn!` so it stands out next to ordinary
1627            // listener-online events.
1628            let fp = sha256_pem_fingerprint(cert_pem_str.as_bytes());
1629            tracing::warn!(
1630                target: "reddb::security",
1631                transport = "grpc",
1632                cert_sha256 = %fp,
1633                "RED_GRPC_TLS_DEV=1: using auto-generated self-signed cert; \
1634                 DO NOT use in production"
1635            );
1636            // Persist so that restarts reuse the same identity.
1637            let cert_path = dir.join("grpc-tls-cert.pem");
1638            let key_path = dir.join("grpc-tls-key.pem");
1639            if !cert_path.exists() || !key_path.exists() {
1640                let _ = std::fs::create_dir_all(&dir);
1641                std::fs::write(&cert_path, cert_pem_str.as_bytes())
1642                    .map_err(|e| format!("write grpc dev cert: {e}"))?;
1643                std::fs::write(&key_path, key_pem_str.as_bytes())
1644                    .map_err(|e| format!("write grpc dev key: {e}"))?;
1645                #[cfg(unix)]
1646                {
1647                    use std::os::unix::fs::PermissionsExt;
1648                    let _ =
1649                        std::fs::set_permissions(&key_path, std::fs::Permissions::from_mode(0o600));
1650                }
1651            }
1652            (cert_pem_str.into_bytes(), key_pem_str.into_bytes())
1653        }
1654    };
1655
1656    let client_ca_pem = match &config.grpc_tls_client_ca {
1657        Some(path) => Some(
1658            std::fs::read(path)
1659                .map_err(|e| format!("read grpc client CA {}: {e}", path.display()))?,
1660        ),
1661        None => None,
1662    };
1663
1664    Ok(crate::GrpcTlsOptions {
1665        cert_pem,
1666        key_pem,
1667        client_ca_pem,
1668    })
1669}
1670
1671/// Hex-encoded SHA-256 of a PEM blob, used for cert-pin operator log
1672/// lines. Constant-time hash; no token contents leave this fn.
1673fn sha256_pem_fingerprint(pem: &[u8]) -> String {
1674    use sha2::{Digest, Sha256};
1675    let mut h = Sha256::new();
1676    h.update(pem);
1677    let d = h.finalize();
1678    let mut buf = String::with_capacity(64);
1679    for b in d.iter() {
1680        buf.push_str(&format!("{b:02x}"));
1681    }
1682    buf
1683}
1684
1685/// Resolve TLS config: use provided cert/key or auto-generate.
1686fn resolve_wire_tls_config(
1687    config: &ServerCommandConfig,
1688) -> Result<crate::wire::WireTlsConfig, String> {
1689    match (&config.wire_tls_cert, &config.wire_tls_key) {
1690        (Some(cert), Some(key)) => Ok(crate::wire::WireTlsConfig {
1691            cert_path: cert.clone(),
1692            key_path: key.clone(),
1693        }),
1694        _ => {
1695            // Auto-generate self-signed cert
1696            let dir = config
1697                .path
1698                .as_ref()
1699                .and_then(|p| p.parent())
1700                .map(PathBuf::from)
1701                .unwrap_or_else(|| PathBuf::from("."));
1702            crate::wire::tls::auto_generate_cert(&dir).map_err(|e| e.to_string())
1703        }
1704    }
1705}
1706
1707#[inline(never)]
1708fn build_runtime_and_auth_store(
1709    config: &ServerCommandConfig,
1710    db_options: RedDBOptions,
1711) -> Result<
1712    (
1713        RedDBRuntime,
1714        Arc<AuthStore>,
1715        Option<crate::telemetry::TelemetryGuard>,
1716    ),
1717    String,
1718> {
1719    // Return the TelemetryGuard so server runners can bind it for
1720    // their full lifetime. Dropping the guard tears down the
1721    // non-blocking log writer thread and, because that writer is
1722    // built with `.lossy(true)`, any subsequent log event routed to
1723    // the file sink is silently dropped — so callers MUST keep the
1724    // returned `Option<TelemetryGuard>` alive until shutdown.
1725    build_runtime_with_bootstrap(db_options, config.telemetry.clone(), &config.bootstrap)
1726}
1727
1728/// Open the runtime, initialise structured logging from merged CLI +
1729/// `red_config` settings, and return a guard the caller must keep
1730/// alive for the server lifetime (drop flushes pending log writes).
1731///
1732/// Merge priority: CLI flag (explicit `Some`) beats `red.logging.*`
1733/// in red_config, beats the built-in default. A CLI-flag value of
1734/// `None` / empty means "inherit from config or default" — never
1735/// "disable". The one exception is `--no-log-file` which forces
1736/// `log_dir = None` regardless of config.
1737pub(crate) fn build_runtime_with_telemetry(
1738    db_options: RedDBOptions,
1739    cli_telemetry: Option<crate::telemetry::TelemetryConfig>,
1740) -> Result<
1741    (
1742        RedDBRuntime,
1743        Arc<AuthStore>,
1744        Option<crate::telemetry::TelemetryGuard>,
1745    ),
1746    String,
1747> {
1748    let bootstrap = BootstrapConfig::default();
1749    build_runtime_with_bootstrap(db_options, cli_telemetry, &bootstrap)
1750}
1751
1752fn build_runtime_with_bootstrap(
1753    db_options: RedDBOptions,
1754    cli_telemetry: Option<crate::telemetry::TelemetryConfig>,
1755    bootstrap: &BootstrapConfig,
1756) -> Result<
1757    (
1758        RedDBRuntime,
1759        Arc<AuthStore>,
1760        Option<crate::telemetry::TelemetryGuard>,
1761    ),
1762    String,
1763> {
1764    let runtime = RedDBRuntime::with_options(db_options.clone()).map_err(|err| {
1765        // Issue #205 — runtime construction failure is the canonical
1766        // StartupFailed phase. The audit sink isn't installed yet
1767        // (it would have been registered inside `with_options`), so
1768        // the emit falls through to tracing+eprintln only — operator
1769        // still sees it on stderr.
1770        let msg = err.to_string();
1771        crate::telemetry::operator_event::OperatorEvent::StartupFailed {
1772            phase: "runtime_construction".to_string(),
1773            error: msg.clone(),
1774        }
1775        .emit_global();
1776        msg
1777    })?;
1778
1779    // PLAN.md Phase 5 / W6 — opt into serverless writer-lease fencing
1780    // when `RED_LEASE_REQUIRED=true`. Failure here aborts boot: the
1781    // operator asked for a fence; running unfenced would silently
1782    // expose split-brain risk.
1783    crate::runtime::lease_loop::start_lease_loop_if_required(&runtime).map_err(|err| {
1784        let msg = err.to_string();
1785        crate::telemetry::operator_event::OperatorEvent::StartupFailed {
1786            phase: "lease_loop".to_string(),
1787            error: msg.clone(),
1788        }
1789        .emit_global();
1790        msg
1791    })?;
1792
1793    // #213 — edge-triggered disk-space watchdog. Watches the data
1794    // directory; falls back to polling when fanotify is unavailable
1795    // (non-Linux or unprivileged container).
1796    if let Some(data_path) = db_options.data_path.as_deref() {
1797        let watch_dir = data_path.parent().unwrap_or(data_path);
1798        crate::runtime::disk_space_monitor::DiskSpaceMonitor::new(watch_dir, 90).spawn();
1799    }
1800
1801    // #214 — inotify config hot-reload watcher. Watches the config file
1802    // (REDDB_CONFIG_FILE or /etc/reddb/config.json) for changes and
1803    // applies hot-reloadable keys without restart.
1804    {
1805        let config_path = crate::runtime::config_overlay::config_file_path();
1806        let store = runtime.db().store();
1807        crate::runtime::config_watcher::ConfigWatcher::new(config_path, store).spawn();
1808    }
1809
1810    // Phase 6 logging: merge red_config overrides onto the CLI-built
1811    // telemetry config, then install the global subscriber.
1812    let merged = merge_telemetry_with_config(
1813        cli_telemetry
1814            .unwrap_or_else(|| default_telemetry_for_path(db_options.data_path.as_deref())),
1815        &runtime,
1816    );
1817    let telemetry_guard = crate::telemetry::init(merged);
1818    if db_options.bounded_disk_residency {
1819        tracing::info!(
1820            target: "reddb::storage::residency",
1821            resident_memory_bytes_max = runtime.db().store().config().resident_memory_bytes_max,
1822            "bounded disk residency enabled"
1823        );
1824    }
1825
1826    let no_auth = no_auth_active(&db_options);
1827    let auth_store =
1828        if db_options.auth.vault_enabled {
1829            let pager =
1830                runtime.db().store().pager().cloned().ok_or_else(|| {
1831                    "vault requires a paged database (persistent mode)".to_string()
1832                })?;
1833            let store = AuthStore::with_vault(db_options.auth.clone(), pager)
1834                .map_err(|err| err.to_string())?;
1835            Arc::new(store)
1836        } else {
1837            Arc::new(AuthStore::new(db_options.auth.clone()))
1838        };
1839    auth_store.configure_control_events(
1840        runtime.control_event_ledger(),
1841        runtime.control_event_config(),
1842    );
1843    // ADR 0058 — cluster bootstrap authority fail-closed seam. A
1844    // cluster-shaped boot may only run auth bootstrap when a concrete
1845    // reserved-range owner can be proven; none is implemented yet, so the
1846    // seam rejects credentialled cluster boots and allows only the explicit
1847    // `--no-auth` / `--dev` development carveout. Issue #663 — when
1848    // `--no-auth` is active, deliberately skip the preset machinery so a
1849    // stray `REDDB_USERNAME`+`REDDB_PASSWORD` pair cannot silently create an
1850    // admin, defeating the point of anonymous mode.
1851    //
1852    // Issue #1230 — the durable bootstrap completion marker
1853    // (`system.bootstrap.completed`) is the authority path's record that
1854    // first boot already produced global auth state. Observing it makes a
1855    // restart or duplicate bootstrap attempt idempotent: the seam returns
1856    // `AlreadyComplete` and the caller rehydrates read-only state only,
1857    // recreating no users, reissuing no vault certificate, and reapplying no
1858    // mutable config over operator changes.
1859    let bootstrap_already_completed = runtime
1860        .db()
1861        .store()
1862        .try_get_config(BOOTSTRAP_COMPLETED_KEY)
1863        .map_err(|error| error.to_string())?
1864        .is_some();
1865    let disposition = crate::cluster::authorize_cluster_bootstrap(
1866        db_options.storage_profile.deploy_profile,
1867        no_auth,
1868        bootstrap.auth_bootstrap_input(),
1869        bootstrap_already_completed,
1870    )?;
1871    // Issue #1231 — wire cluster vault first boot through the bootstrap
1872    // authority. The authorized disposition selects the vault plan: the owner
1873    // path (`ProceedLocal`) opens the vault against the real cluster-global
1874    // auth store (`auth_store`, backed by the runtime pager) and consumes the
1875    // env/`_FILE` secret inputs to mint the certificate; a restart after
1876    // completion (`AlreadyComplete`) reopens and unseals that same store
1877    // without consuming secret inputs. A non-owner cluster boot already failed
1878    // closed above, so no scratch or per-member vault is minted.
1879    let vault_plan = crate::cluster::plan_vault_bootstrap(disposition);
1880    match disposition {
1881        crate::cluster::BootstrapDisposition::SkipDevBypass => {
1882            debug_assert_eq!(vault_plan, crate::cluster::VaultBootstrapPlan::SkipNoVault);
1883            eprintln!("{NO_AUTH_WARNING}");
1884            tracing::warn!("{NO_AUTH_WARNING}");
1885        }
1886        crate::cluster::BootstrapDisposition::AlreadyComplete => {
1887            // First boot is over. Rehydrate the read-only manifest registry
1888            // so config-derived state is observable, but create no users,
1889            // reissue no vault material, and reapply no mutable config
1890            // (issue #1230). `apply_preset_from_config` does exactly this
1891            // when the completion marker is present — matching the unseal-only
1892            // vault plan (no secret inputs consumed).
1893            debug_assert_eq!(
1894                vault_plan,
1895                crate::cluster::VaultBootstrapPlan::OpenClusterGlobalStore {
1896                    consume_secret_inputs: false,
1897                }
1898            );
1899            apply_preset_from_config(&runtime, &auth_store, bootstrap)?;
1900            tracing::info!("bootstrap already completed, unsealing existing cluster auth store");
1901        }
1902        crate::cluster::BootstrapDisposition::ProceedLocal => {
1903            // Owner first boot: open the vault against the real cluster-global
1904            // auth store and consume the secret inputs to mint the certificate.
1905            debug_assert_eq!(
1906                vault_plan,
1907                crate::cluster::VaultBootstrapPlan::OpenClusterGlobalStore {
1908                    consume_secret_inputs: true,
1909                }
1910            );
1911            apply_preset_from_config(&runtime, &auth_store, bootstrap)?;
1912            maybe_apply_policy_break_glass(&auth_store);
1913        }
1914    }
1915
1916    // Background session purge (every 5 minutes)
1917    {
1918        let store = Arc::clone(&auth_store);
1919        std::thread::Builder::new()
1920            .name("reddb-session-purge".into())
1921            .spawn(move || loop {
1922                std::thread::sleep(std::time::Duration::from_secs(300));
1923                store.purge_expired_sessions();
1924            })
1925            .ok();
1926    }
1927
1928    Ok((runtime, auth_store, telemetry_guard))
1929}
1930
1931/// Honour `REDDB_POLICY_BREAK_GLASS=1` at boot — see issue #713 and
1932/// the [`crate::auth::self_lock_guard`] module. Anything other than
1933/// `1`/`true`/`yes` (case-insensitive) is treated as not set.
1934fn maybe_apply_policy_break_glass(auth_store: &Arc<AuthStore>) {
1935    use crate::auth::self_lock_guard::BREAK_GLASS_ENV;
1936
1937    let enabled = std::env::var(BREAK_GLASS_ENV)
1938        .ok()
1939        .map(|v| {
1940            let trimmed = v.trim().to_ascii_lowercase();
1941            matches!(trimmed.as_str(), "1" | "true" | "yes")
1942        })
1943        .unwrap_or(false);
1944    if !enabled {
1945        return;
1946    }
1947    let now = crate::utils::now_unix_millis() as u128;
1948    match auth_store.apply_policy_break_glass(now) {
1949        Ok(()) => {
1950            tracing::warn!(env = BREAK_GLASS_ENV, "policy break-glass recovery applied");
1951        }
1952        Err(err) => {
1953            tracing::error!(env = BREAK_GLASS_ENV, %err, "policy break-glass recovery failed");
1954        }
1955    }
1956}
1957
1958/// Reserved config keys describing first-boot bootstrap state (issue #650).
1959/// Presence of [`BOOTSTRAP_COMPLETED_KEY`] is the idempotency hinge: when
1960/// it is set, [`apply_preset`] silently no-ops on subsequent boots so a
1961/// container restart with the same env is a no-op.
1962pub(crate) const BOOTSTRAP_COMPLETED_KEY: &str = "system.bootstrap.completed";
1963pub(crate) const BOOTSTRAP_PRESET_KEY: &str = "system.bootstrap.preset";
1964pub(crate) const BOOTSTRAP_FIRST_ADMIN_KEY: &str = "system.bootstrap.first_admin_id";
1965
1966/// Env vars selecting the bootstrap preset. `REDDB_BOOTSTRAP_PRESET`
1967/// is canonical; `REDDB_PRESET` remains accepted for compatibility.
1968pub(crate) const BOOTSTRAP_PRESET_ENV: &str = "REDDB_BOOTSTRAP_PRESET";
1969pub(crate) const PRESET_ENV: &str = "REDDB_PRESET";
1970/// Env equivalent of `--bootstrap-cert-out` (issue #1589). Honours the
1971/// `_FILE` companion via [`env_nonempty`].
1972pub(crate) const BOOTSTRAP_CERT_OUT_ENV: &str = "REDDB_BOOTSTRAP_CERT_OUT";
1973pub(crate) const PRESET_SIMPLE: &str = "simple";
1974pub(crate) const PRESET_PRODUCTION: &str = "production";
1975pub(crate) const PRESET_REGULATED: &str = "regulated";
1976pub(crate) const PRESET_CLOUD: &str = "cloud";
1977
1978/// Policy id installed by the `production` preset and attached to the
1979/// first admin. Grants `"*"` on `"*"` so the admin has policy-derived
1980/// broad authority (acceptance #3) — not an authorization bypass.
1981pub(crate) const FIRST_ADMIN_ALLOW_ALL_POLICY: &str = "system.bootstrap.first-admin-allow-all";
1982pub(crate) const REGULATED_PROTECT_MANAGED_POLICY: &str = "system.regulated.protect-managed";
1983pub(crate) const CLOUD_PROTECT_MANAGED_POLICY: &str = "system.cloud.protect-managed";
1984pub(crate) const CLOUD_CONFIG_NAMESPACE: &str = "red.config.cloud";
1985pub(crate) const REGULATED_AUDIT_CONFIG_NAMESPACE: &str = "red.config.audit";
1986pub(crate) const REGULATED_EVIDENCE_CONFIG_NAMESPACE: &str = "red.config.evidence";
1987pub(crate) const REGULATED_QUERY_AUDIT_CONFIG_NAMESPACE: &str = "red.config.query_audit";
1988
1989/// Apply the bootstrap preset selected by `REDDB_BOOTSTRAP_PRESET` (or
1990/// legacy `REDDB_PRESET`; default `simple`). Idempotent — if
1991/// `system.bootstrap.completed` is already set, this is a one-line
1992/// `tracing::info!` no-op and the server proceeds (issue #650
1993/// acceptance #5).
1994///
1995/// Caller must have already short-circuited the `--no-auth` / `--dev`
1996/// path (issue #663): when that flag is set, the preset must be skipped
1997/// entirely — no admin created, no bootstrap state written.
1998pub(crate) fn apply_preset(
1999    runtime: &RedDBRuntime,
2000    auth_store: &Arc<AuthStore>,
2001) -> Result<(), String> {
2002    let bootstrap = BootstrapConfig::default();
2003    apply_preset_from_config(runtime, auth_store, &bootstrap)
2004}
2005
2006fn apply_preset_from_config(
2007    runtime: &RedDBRuntime,
2008    auth_store: &Arc<AuthStore>,
2009    bootstrap: &BootstrapConfig,
2010) -> Result<(), String> {
2011    let store = runtime.db().store();
2012
2013    if store
2014        .try_get_config(BOOTSTRAP_COMPLETED_KEY)
2015        .map_err(|error| error.to_string())?
2016        .is_some()
2017    {
2018        crate::cli::bootstrap_manifest::rehydrate_manifest_registry(
2019            runtime,
2020            &runtime.config_registry(),
2021        )?;
2022        tracing::info!("bootstrap state present, skipping preset application");
2023        return Ok(());
2024    }
2025
2026    let preset = bootstrap.resolved_preset();
2027
2028    if let Some(path) = bootstrap.selected_manifest() {
2029        if let Some(manifest_bootstrap) =
2030            crate::cli::bootstrap_manifest::bootstrap_config_from_manifest_file(&path)?
2031        {
2032            apply_preset_from_config(runtime, auth_store, &manifest_bootstrap)?;
2033            return Ok(());
2034        }
2035        let first_admin_id = crate::cli::bootstrap_manifest::apply_manifest_file(
2036            runtime,
2037            auth_store,
2038            &runtime.config_registry(),
2039            &path,
2040        )?;
2041        persist_bootstrap_state(runtime, "manifest", Some(&first_admin_id))?;
2042        tracing::info!("bootstrap manifest applied");
2043        return Ok(());
2044    }
2045
2046    let (first_admin_id, certificate) = match preset.as_str() {
2047        PRESET_SIMPLE => {
2048            // `simple` is the default low-friction preset. Auth knobs
2049            // remain whatever the CLI/env set; we only persist the
2050            // bootstrap state so subsequent boots are idempotent.
2051            (None, None)
2052        }
2053        PRESET_PRODUCTION => {
2054            let (id, cert) = apply_production_preset_from_config(auth_store, bootstrap)?;
2055            (Some(id), cert)
2056        }
2057        PRESET_CLOUD => {
2058            let (id, cert) = apply_cloud_preset(runtime, auth_store, bootstrap)?;
2059            (Some(id), cert)
2060        }
2061        PRESET_REGULATED => {
2062            apply_regulated_preset(runtime, auth_store)?;
2063            (None, None)
2064        }
2065        other => {
2066            return Err(format!(
2067                "bootstrap preset {other:?} is not recognised (expected `simple`, `production`, `regulated`, or `cloud`)"
2068            ));
2069        }
2070    };
2071
2072    // Issue #1589 — write the freshly minted unseal certificate to the
2073    // caller-specified file so a distroless single-machine init can read
2074    // it back for the next boot's `REDDB_CERTIFICATE_FILE` unseal. This
2075    // path runs only on the bootstrap-creating boot (the completion
2076    // marker short-circuits above before any cert is minted), so the file
2077    // is written exactly once and a re-boot never churns it.
2078    if let Some(cert) = certificate.as_deref() {
2079        write_bootstrap_certificate(bootstrap, cert)?;
2080    }
2081
2082    persist_bootstrap_state(runtime, &preset, first_admin_id.as_deref())?;
2083    tracing::info!(preset = %preset, "bootstrap preset applied");
2084    Ok(())
2085}
2086
2087/// Write the unseal certificate to `--bootstrap-cert-out` when that
2088/// target is set (issue #1589). No-op when the flag/env is absent, so
2089/// the certificate is still emitted on stderr by the preset as before.
2090fn write_bootstrap_certificate(
2091    bootstrap: &BootstrapConfig,
2092    certificate_hex: &str,
2093) -> Result<(), String> {
2094    let Some(path) = bootstrap.selected_cert_out() else {
2095        return Ok(());
2096    };
2097    std::fs::write(&path, certificate_hex)
2098        .map_err(|err| format!("write --bootstrap-cert-out {}: {err}", path.display()))?;
2099    tracing::info!(
2100        target: "reddb::bootstrap",
2101        path = %path.display(),
2102        "first-boot self-bootstrap: wrote unseal certificate to --bootstrap-cert-out (consume via REDDB_CERTIFICATE_FILE on the next boot)"
2103    );
2104    Ok(())
2105}
2106
2107fn apply_production_preset_from_config(
2108    auth_store: &Arc<AuthStore>,
2109    bootstrap: &BootstrapConfig,
2110) -> Result<(String, Option<String>), String> {
2111    use crate::auth::store::PrincipalRef;
2112    use crate::auth::UserId;
2113
2114    let username = bootstrap.production_username().ok_or_else(|| {
2115        "production preset requires --bootstrap-admin or REDDB_USERNAME (or REDDB_USERNAME_FILE)"
2116            .to_string()
2117    })?;
2118    let password = bootstrap.production_password().ok_or_else(|| {
2119        "production preset requires --bootstrap-admin-password or REDDB_PASSWORD (or REDDB_PASSWORD_FILE)"
2120            .to_string()
2121    })?;
2122
2123    // (1) Create the first admin as an ordinary platform-scoped user.
2124    // Managed guardrails are policy-derived; bootstrap does not stamp a
2125    // parallel ownership flag.
2126    let result = auth_store
2127        .bootstrap(&username, &password)
2128        .map_err(|err| format!("bootstrap first admin: {err}"))?;
2129    let certificate = result.certificate.clone();
2130    if let Some(cert) = certificate.as_deref() {
2131        eprintln!("[reddb] CERTIFICATE: {}", cert);
2132        tracing::warn!(
2133            "vault certificate issued by REDDB_PRESET=production -- save it and update the runtime secret before restart"
2134        );
2135    }
2136    let first_admin = UserId::platform(result.user.username.clone());
2137
2138    // (2) Install the allow-all policy as an ordinary policy row.
2139    install_allow_all_policy(auth_store)?;
2140
2141    // (3) Attach the policy to the first admin.
2142    auth_store
2143        .attach_policy(
2144            PrincipalRef::User(first_admin.clone()),
2145            FIRST_ADMIN_ALLOW_ALL_POLICY,
2146        )
2147        .map_err(|err| format!("attach allow-all policy: {err}"))?;
2148
2149    Ok((first_admin.to_string(), certificate))
2150}
2151
2152fn apply_cloud_preset(
2153    runtime: &RedDBRuntime,
2154    auth_store: &Arc<AuthStore>,
2155    bootstrap: &BootstrapConfig,
2156) -> Result<(String, Option<String>), String> {
2157    use crate::auth::store::PrincipalRef;
2158    use crate::auth::{Role, UserId};
2159
2160    let head_username = bootstrap.cloud_head_username().ok_or_else(|| {
2161        "cloud preset requires --cloud-head-admin or REDDB_CLOUD_HEAD_ADMIN (or REDDB_USERNAME)"
2162            .to_string()
2163    })?;
2164    let head_password = bootstrap.cloud_head_password().ok_or_else(|| {
2165        "cloud preset requires --cloud-head-admin-password or REDDB_CLOUD_HEAD_ADMIN_PASSWORD (or REDDB_PASSWORD)"
2166            .to_string()
2167    })?;
2168    let customer_username = bootstrap.customer_username().ok_or_else(|| {
2169        "cloud preset requires --customer-admin or REDDB_CUSTOMER_ADMIN".to_string()
2170    })?;
2171    let customer_password = bootstrap.customer_password().ok_or_else(|| {
2172        "cloud preset requires --customer-admin-password or REDDB_CUSTOMER_ADMIN_PASSWORD"
2173            .to_string()
2174    })?;
2175    if head_username == customer_username {
2176        return Err("cloud preset requires distinct head and customer admin usernames".to_string());
2177    }
2178
2179    let head = auth_store
2180        .bootstrap_system_admin(&head_username, &head_password)
2181        .map_err(|err| format!("bootstrap cloud head admin: {err}"))?;
2182    let certificate = head.certificate.clone();
2183    let head_id = UserId::platform(head.user.username.clone());
2184
2185    auth_store
2186        .create_user(&customer_username, &customer_password, Role::Admin)
2187        .map_err(|err| format!("create cloud customer admin: {err}"))?;
2188    let customer_id = UserId::platform(customer_username.clone());
2189
2190    install_allow_all_policy(auth_store)?;
2191    for user_id in [&head_id, &customer_id] {
2192        auth_store
2193            .attach_policy(
2194                PrincipalRef::User(user_id.clone()),
2195                FIRST_ADMIN_ALLOW_ALL_POLICY,
2196            )
2197            .map_err(|err| format!("attach allow-all policy: {err}"))?;
2198    }
2199    install_cloud_guardrails(runtime, auth_store, &head_id)?;
2200    auth_store
2201        .attach_policy(
2202            PrincipalRef::User(customer_id),
2203            CLOUD_PROTECT_MANAGED_POLICY,
2204        )
2205        .map_err(|err| format!("attach cloud guardrail policy: {err}"))?;
2206
2207    Ok((head_id.to_string(), certificate))
2208}
2209
2210pub(crate) fn install_allow_all_policy(auth_store: &AuthStore) -> Result<(), String> {
2211    use crate::auth::policies::Policy;
2212
2213    let policy = Policy::from_json_str(&format!(
2214        r#"{{
2215            "id": "{id}",
2216            "version": 1,
2217            "statements": [{{
2218                "effect": "allow",
2219                "actions": ["*"],
2220                "resources": ["*"]
2221            }}]
2222        }}"#,
2223        id = FIRST_ADMIN_ALLOW_ALL_POLICY
2224    ))
2225    .map_err(|err| format!("compile allow-all policy: {err}"))?;
2226    auth_store
2227        .put_policy(policy)
2228        .map_err(|err| format!("install allow-all policy: {err}"))
2229}
2230
2231fn install_cloud_guardrails(
2232    runtime: &RedDBRuntime,
2233    auth_store: &Arc<AuthStore>,
2234    head_admin: &crate::auth::UserId,
2235) -> Result<(), String> {
2236    use crate::auth::policies::Policy;
2237    use crate::auth::registry::EvidenceRequirement;
2238
2239    let policy = Policy::from_json_str(&format!(
2240        r#"{{
2241            "id": "{id}",
2242            "version": 1,
2243            "statements": [
2244                {{
2245                    "effect": "deny",
2246                    "actions": ["policy:put", "policy:drop", "policy:attach", "policy:detach"],
2247                    "resources": ["policy:{id}"]
2248                }},
2249                {{
2250                    "effect": "deny",
2251                    "actions": [
2252                        "user:delete",
2253                        "user:disable",
2254                        "user:password:change",
2255                        "user:role:update"
2256                    ],
2257                    "resources": ["user:{head_admin}"]
2258                }},
2259                {{
2260                    "effect": "deny",
2261                    "actions": ["config:write"],
2262                    "resources": ["config:{cloud}.*"]
2263                }}
2264            ]
2265        }}"#,
2266        id = CLOUD_PROTECT_MANAGED_POLICY,
2267        head_admin = head_admin,
2268        cloud = CLOUD_CONFIG_NAMESPACE,
2269    ))
2270    .map_err(|err| format!("compile cloud guardrail policy: {err}"))?;
2271    auth_store
2272        .put_policy(policy)
2273        .map_err(|err| format!("install cloud guardrail policy: {err}"))?;
2274
2275    let now_ms = crate::utils::now_unix_millis() as u128;
2276    let entries = vec![
2277        regulated_registry_entry(
2278            CLOUD_PROTECT_MANAGED_POLICY,
2279            crate::auth::managed_policy::RESOURCE_TYPE_POLICY,
2280            "policy",
2281            "policy:*",
2282            &format!("policy:{CLOUD_PROTECT_MANAGED_POLICY}"),
2283            EvidenceRequirement::Metadata,
2284            now_ms,
2285        ),
2286        regulated_registry_entry(
2287            CLOUD_CONFIG_NAMESPACE,
2288            crate::auth::managed_config::RESOURCE_TYPE_CONFIG_NAMESPACE,
2289            "config_namespace",
2290            "config:write",
2291            &format!("config:{CLOUD_CONFIG_NAMESPACE}.*"),
2292            EvidenceRequirement::Metadata,
2293            now_ms,
2294        ),
2295    ];
2296    for entry in entries.iter().cloned() {
2297        runtime
2298            .config_registry()
2299            .restore_bootstrap_entry(entry)
2300            .map_err(|err| format!("install cloud registry entry: {err}"))?;
2301    }
2302    crate::cli::bootstrap_manifest::persist_registry_state(runtime, &entries)?;
2303    Ok(())
2304}
2305
2306fn apply_regulated_preset(
2307    runtime: &RedDBRuntime,
2308    auth_store: &Arc<AuthStore>,
2309) -> Result<(), String> {
2310    use crate::auth::policies::Policy;
2311    use crate::auth::registry::EvidenceRequirement;
2312    use crate::auth::store::{PrincipalRef, PUBLIC_IAM_GROUP};
2313
2314    runtime.query_audit().enable_infrastructure();
2315
2316    let policy = Policy::from_json_str(&format!(
2317        r#"{{
2318            "id": "{id}",
2319            "version": 1,
2320            "statements": [
2321                {{
2322                    "effect": "deny",
2323                    "actions": ["policy:put", "policy:drop", "policy:attach", "policy:detach"],
2324                    "resources": ["policy:{id}"]
2325                }},
2326                {{
2327                    "effect": "deny",
2328                    "actions": ["config:write"],
2329                    "resources": [
2330                        "config:{audit}.*",
2331                        "config:{evidence}.*",
2332                        "config:{query_audit}.*"
2333                    ]
2334                }}
2335            ]
2336        }}"#,
2337        id = REGULATED_PROTECT_MANAGED_POLICY,
2338        audit = REGULATED_AUDIT_CONFIG_NAMESPACE,
2339        evidence = REGULATED_EVIDENCE_CONFIG_NAMESPACE,
2340        query_audit = REGULATED_QUERY_AUDIT_CONFIG_NAMESPACE,
2341    ))
2342    .map_err(|err| format!("compile regulated guardrail policy: {err}"))?;
2343    auth_store
2344        .put_policy(policy)
2345        .map_err(|err| format!("install regulated guardrail policy: {err}"))?;
2346    auth_store
2347        .attach_policy(
2348            PrincipalRef::Group(PUBLIC_IAM_GROUP.to_string()),
2349            REGULATED_PROTECT_MANAGED_POLICY,
2350        )
2351        .map_err(|err| format!("attach regulated guardrail policy: {err}"))?;
2352
2353    let now_ms = crate::utils::now_unix_millis() as u128;
2354    let entries = vec![
2355        regulated_registry_entry(
2356            REGULATED_PROTECT_MANAGED_POLICY,
2357            crate::auth::managed_policy::RESOURCE_TYPE_POLICY,
2358            "iam_policy",
2359            "policy:*",
2360            &format!("policy:{REGULATED_PROTECT_MANAGED_POLICY}"),
2361            EvidenceRequirement::Metadata,
2362            now_ms,
2363        ),
2364        regulated_registry_entry(
2365            REGULATED_AUDIT_CONFIG_NAMESPACE,
2366            crate::auth::managed_config::RESOURCE_TYPE_CONFIG_NAMESPACE,
2367            "config_namespace",
2368            "config:write",
2369            &format!("config:{REGULATED_AUDIT_CONFIG_NAMESPACE}.*"),
2370            EvidenceRequirement::Metadata,
2371            now_ms,
2372        ),
2373        regulated_registry_entry(
2374            REGULATED_EVIDENCE_CONFIG_NAMESPACE,
2375            crate::auth::managed_config::RESOURCE_TYPE_CONFIG_NAMESPACE,
2376            "config_namespace",
2377            "config:write",
2378            &format!("config:{REGULATED_EVIDENCE_CONFIG_NAMESPACE}.*"),
2379            EvidenceRequirement::Metadata,
2380            now_ms,
2381        ),
2382        regulated_registry_entry(
2383            REGULATED_QUERY_AUDIT_CONFIG_NAMESPACE,
2384            crate::auth::managed_config::RESOURCE_TYPE_CONFIG_NAMESPACE,
2385            "config_namespace",
2386            "config:write",
2387            &format!("config:{REGULATED_QUERY_AUDIT_CONFIG_NAMESPACE}.*"),
2388            EvidenceRequirement::Metadata,
2389            now_ms,
2390        ),
2391    ];
2392
2393    for entry in entries.iter().cloned() {
2394        runtime
2395            .config_registry()
2396            .restore_bootstrap_entry(entry)
2397            .map_err(|err| format!("install regulated registry entry: {err}"))?;
2398    }
2399    crate::cli::bootstrap_manifest::persist_registry_state(runtime, &entries)?;
2400    Ok(())
2401}
2402
2403fn regulated_registry_entry(
2404    id: &str,
2405    resource_type: &str,
2406    schema: &str,
2407    required_action: &str,
2408    required_resource: &str,
2409    evidence_requirement: crate::auth::registry::EvidenceRequirement,
2410    updated_at_ms: u128,
2411) -> crate::auth::registry::ConfigRegistryEntry {
2412    crate::auth::registry::ConfigRegistryEntry {
2413        id: id.to_string(),
2414        version: 1,
2415        resource_type: resource_type.to_string(),
2416        schema: schema.to_string(),
2417        mutability: crate::auth::registry::Mutability::Immutable,
2418        sensitivity: crate::auth::registry::Sensitivity::Internal,
2419        managed: true,
2420        required_action: required_action.to_string(),
2421        required_resource: required_resource.to_string(),
2422        evidence_requirement,
2423        updated_by: "system:regulated-preset".to_string(),
2424        updated_at_ms,
2425    }
2426}
2427
2428fn persist_bootstrap_state(
2429    runtime: &RedDBRuntime,
2430    preset: &str,
2431    first_admin_id: Option<&str>,
2432) -> Result<(), String> {
2433    let store = runtime.db().store();
2434    let mut tree = crate::serde_json::Map::new();
2435    tree.insert(
2436        BOOTSTRAP_COMPLETED_KEY.to_string(),
2437        crate::serde_json::Value::Bool(true),
2438    );
2439    tree.insert(
2440        BOOTSTRAP_PRESET_KEY.to_string(),
2441        crate::serde_json::Value::String(preset.to_string()),
2442    );
2443    if let Some(id) = first_admin_id {
2444        tree.insert(
2445            BOOTSTRAP_FIRST_ADMIN_KEY.to_string(),
2446            crate::serde_json::Value::String(id.to_string()),
2447        );
2448    }
2449    let json = crate::serde_json::Value::Object(tree);
2450    store
2451        .try_set_config_tree("", &json)
2452        .map_err(|error| error.to_string())?;
2453    Ok(())
2454}
2455
2456/// Read `red.logging.*` keys from the persistent config store and
2457/// merge them into the CLI-built `TelemetryConfig`. Merge priority:
2458/// explicit CLI flag > red_config > built-in default.
2459///
2460/// The "was a flag passed" signal comes from the `*_explicit` bools
2461/// on `TelemetryConfig`, populated by the CLI parser. This replaces
2462/// an earlier equality-to-default heuristic that silently dropped
2463/// config whenever the CLI-derived default diverged from
2464/// `TelemetryConfig::default()` (e.g. path-derived `log_dir`,
2465/// non-TTY `format`) and that silently overrode `--no-log-file`.
2466fn merge_telemetry_with_config(
2467    mut cli: crate::telemetry::TelemetryConfig,
2468    runtime: &RedDBRuntime,
2469) -> crate::telemetry::TelemetryConfig {
2470    use reddb_types::Value;
2471
2472    let store = runtime.db().store();
2473
2474    if !cli.level_explicit {
2475        if let Some(Value::Text(v)) = store.get_config("red.logging.level") {
2476            cli.level_filter = v.to_string();
2477        }
2478    }
2479    if !cli.format_explicit {
2480        if let Some(Value::Text(v)) = store.get_config("red.logging.format") {
2481            if let Some(parsed) = crate::telemetry::LogFormat::parse(&v) {
2482                cli.format = parsed;
2483            }
2484        }
2485    }
2486    if !cli.rotation_keep_days_explicit {
2487        match store.get_config("red.logging.keep_days") {
2488            Some(Value::Integer(n)) if n >= 0 && n <= u16::MAX as i64 => {
2489                cli.rotation_keep_days = n as u16
2490            }
2491            Some(Value::UnsignedInteger(n)) if n <= u16::MAX as u64 => {
2492                cli.rotation_keep_days = n as u16
2493            }
2494            Some(Value::Text(v)) => {
2495                if let Ok(n) = v.parse::<u16>() {
2496                    cli.rotation_keep_days = n;
2497                }
2498            }
2499            _ => {}
2500        }
2501    }
2502    if !cli.file_prefix_explicit {
2503        if let Some(Value::Text(v)) = store.get_config("red.logging.file_prefix") {
2504            if !v.is_empty() {
2505                cli.file_prefix = v.to_string();
2506            }
2507        }
2508    }
2509    // --no-log-file is a kill-switch: config cannot resurrect the
2510    // file sink. Explicit --log-dir also wins.
2511    if !cli.log_dir_explicit && !cli.log_file_disabled {
2512        if let Some(Value::Text(v)) = store.get_config("red.logging.dir") {
2513            if !v.is_empty() {
2514                cli.log_dir = Some(std::path::PathBuf::from(v.as_ref()));
2515            }
2516        }
2517    }
2518
2519    cli
2520}
2521
2522#[cfg(test)]
2523mod telemetry_merge_tests {
2524    use super::*;
2525    use crate::telemetry::{LogFormat, TelemetryConfig};
2526
2527    fn fresh_runtime() -> RedDBRuntime {
2528        RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime")
2529    }
2530
2531    fn set_str(runtime: &RedDBRuntime, key: &str, value: &str) {
2532        runtime
2533            .db()
2534            .store()
2535            .set_config_tree(key, &crate::serde_json::Value::String(value.to_string()));
2536    }
2537
2538    fn cli_base() -> TelemetryConfig {
2539        // Emulate default_telemetry_for_path(Some(path)) on a non-TTY host:
2540        // log_dir = Some(...), format = Json. Nothing marked explicit.
2541        TelemetryConfig {
2542            log_dir: Some(std::path::PathBuf::from("/tmp/reddb-default/logs")),
2543            format: LogFormat::Json,
2544            ..Default::default()
2545        }
2546    }
2547
2548    #[test]
2549    fn config_log_dir_promoted_when_flag_absent() {
2550        let runtime = fresh_runtime();
2551        set_str(&runtime, "red.logging.dir", "/var/log/reddb");
2552        let merged = merge_telemetry_with_config(cli_base(), &runtime);
2553        assert_eq!(
2554            merged.log_dir.as_deref(),
2555            Some(std::path::Path::new("/var/log/reddb"))
2556        );
2557    }
2558
2559    #[test]
2560    fn explicit_log_dir_wins_over_config() {
2561        let runtime = fresh_runtime();
2562        set_str(&runtime, "red.logging.dir", "/var/log/reddb");
2563        let mut cli = cli_base();
2564        cli.log_dir = Some(std::path::PathBuf::from("/custom/dir"));
2565        cli.log_dir_explicit = true;
2566        let merged = merge_telemetry_with_config(cli, &runtime);
2567        assert_eq!(
2568            merged.log_dir.as_deref(),
2569            Some(std::path::Path::new("/custom/dir"))
2570        );
2571    }
2572
2573    #[test]
2574    fn no_log_file_beats_config_log_dir() {
2575        let runtime = fresh_runtime();
2576        set_str(&runtime, "red.logging.dir", "/var/log/reddb");
2577        let mut cli = cli_base();
2578        cli.log_dir = None;
2579        cli.log_file_disabled = true;
2580        let merged = merge_telemetry_with_config(cli, &runtime);
2581        assert!(
2582            merged.log_dir.is_none(),
2583            "--no-log-file must veto config dir"
2584        );
2585    }
2586
2587    #[test]
2588    fn config_format_promoted_on_non_tty_default() {
2589        // On non-TTY, default_telemetry_for_path yields format=Json even
2590        // though TelemetryConfig::default() is Pretty. The old equality
2591        // check silently dropped config here.
2592        let runtime = fresh_runtime();
2593        set_str(&runtime, "red.logging.format", "pretty");
2594        let merged = merge_telemetry_with_config(cli_base(), &runtime);
2595        assert_eq!(merged.format, LogFormat::Pretty);
2596    }
2597
2598    #[test]
2599    fn explicit_format_wins_over_config() {
2600        let runtime = fresh_runtime();
2601        set_str(&runtime, "red.logging.format", "pretty");
2602        let mut cli = cli_base();
2603        cli.format = LogFormat::Json;
2604        cli.format_explicit = true;
2605        let merged = merge_telemetry_with_config(cli, &runtime);
2606        assert_eq!(merged.format, LogFormat::Json);
2607    }
2608}
2609
2610#[inline(never)]
2611fn build_http_server(
2612    runtime: RedDBRuntime,
2613    auth_store: Arc<AuthStore>,
2614    bind_addr: String,
2615) -> RedDBServer {
2616    build_http_server_with_transport_readiness(
2617        runtime,
2618        auth_store,
2619        bind_addr,
2620        TransportReadiness::default(),
2621    )
2622}
2623
2624/// Apply the resolved HTTP limits to a freshly-built `RedDBServer`.
2625///
2626/// Centralised here so every `run_*` path goes through the same
2627/// resolver and the structured startup log line carries the same
2628/// `http_limits.*` fields regardless of transport combination.
2629fn apply_http_limits(
2630    server: RedDBServer,
2631    config: &ServerCommandConfig,
2632    runtime: &RedDBRuntime,
2633) -> RedDBServer {
2634    let store = runtime.db().store();
2635    let resolved =
2636        crate::server::http_limits::resolve_http_limits(&config.http_limits_cli, |key| match store
2637            .get_config(key)
2638        {
2639            Some(reddb_types::Value::Text(v)) => Some(v.to_string()),
2640            Some(reddb_types::Value::Integer(n)) if n >= 0 => Some(n.to_string()),
2641            Some(reddb_types::Value::UnsignedInteger(n)) => Some(n.to_string()),
2642            _ => None,
2643        });
2644    tracing::info!(
2645        target: "reddb::http_limits",
2646        max_handlers = resolved.max_handlers,
2647        handler_timeout_ms = resolved.handler_timeout_ms,
2648        retry_after_secs = resolved.retry_after_secs,
2649        max_inflight_per_principal = resolved.max_inflight_per_principal,
2650        "http_limits resolved"
2651    );
2652    server.with_http_limits(resolved)
2653}
2654
2655/// `red server --ui` (issue #1047, ADR 0051): attach the resolved red-ui
2656/// bundle directory to an HTTP server so it also serves the bundle as
2657/// static assets. No-op when `--ui` is off.
2658///
2659/// An explicit `--ui-dir <DIR>` is served as-is (no download); otherwise
2660/// the pinned bundle is resolved from the local cache, downloading on
2661/// first use (ADR 0050). A resolution failure is fatal: the operator
2662/// explicitly asked for the UI, so silently serving API-only would be
2663/// surprising and would mask an offline/checksum problem.
2664fn apply_ui_bundle(
2665    server: RedDBServer,
2666    config: &ServerCommandConfig,
2667) -> Result<RedDBServer, String> {
2668    if !config.ui {
2669        return Ok(server);
2670    }
2671    let ui_dir = match &config.ui_dir {
2672        Some(dir) => dir.clone(),
2673        None => {
2674            let cache_root = crate::server::ui_bundle_resolver::reddb_user_cache_root()
2675                .unwrap_or_else(|_| std::env::temp_dir().join("reddb"));
2676            crate::server::ui_bundle_resolver::resolve_ui_bundle(
2677                &cache_root,
2678                &crate::server::ui_bundle_resolver::HttpFetcher,
2679            )
2680            .map_err(|err| format!("resolve red-ui bundle for --ui: {err}"))?
2681        }
2682    };
2683    tracing::info!(target: "reddb::ui", dir = %ui_dir.display(), "serving red-ui bundle on HTTP surface");
2684    Ok(server.with_ui_dir(ui_dir))
2685}
2686
2687#[inline(never)]
2688fn build_http_server_with_transport_readiness(
2689    runtime: RedDBRuntime,
2690    auth_store: Arc<AuthStore>,
2691    bind_addr: String,
2692    transport_readiness: TransportReadiness,
2693) -> RedDBServer {
2694    RedDBServer::with_options(
2695        runtime,
2696        ServerOptions {
2697            bind_addr,
2698            transport_readiness,
2699            ..ServerOptions::default()
2700        },
2701    )
2702    .with_auth(auth_store)
2703}
2704
2705/// PLAN.md Phase 6.2 — build a listener that only serves
2706/// `/admin/*` + `/metrics` + `/health/*`. Defaults to `127.0.0.1`
2707/// when the env var has no host (loopback-only by default per spec).
2708#[inline(never)]
2709fn build_admin_only_server(
2710    runtime: RedDBRuntime,
2711    auth_store: Arc<AuthStore>,
2712    bind_addr: String,
2713) -> RedDBServer {
2714    RedDBServer::with_options(
2715        runtime,
2716        ServerOptions {
2717            bind_addr,
2718            surface: crate::server::ServerSurface::AdminOnly,
2719            ..ServerOptions::default()
2720        },
2721    )
2722    .with_auth(auth_store)
2723}
2724
2725/// PLAN.md Phase 6.2 — build a listener that only serves `/metrics`
2726/// + `/health/*`. Suitable for Prometheus scrape ports that may be
2727///   exposed wider than the admin port.
2728#[inline(never)]
2729fn build_metrics_only_server(
2730    runtime: RedDBRuntime,
2731    auth_store: Arc<AuthStore>,
2732    bind_addr: String,
2733) -> RedDBServer {
2734    RedDBServer::with_options(
2735        runtime,
2736        ServerOptions {
2737            bind_addr,
2738            surface: crate::server::ServerSurface::MetricsOnly,
2739            ..ServerOptions::default()
2740        },
2741    )
2742    .with_auth(auth_store)
2743}
2744
2745/// Spawn dedicated admin / metrics listeners when the operator set
2746/// `RED_ADMIN_BIND` / `RED_METRICS_BIND`. Both are optional; when
2747/// unset the existing listener keeps serving everything (back-compat).
2748fn spawn_admin_metrics_listeners(runtime: &RedDBRuntime, auth_store: &Arc<AuthStore>) {
2749    if let Some(addr) = env_nonempty("RED_ADMIN_BIND") {
2750        let server = build_admin_only_server(runtime.clone(), auth_store.clone(), addr.clone());
2751        let _ = server.serve_in_background();
2752        tracing::info!(transport = "http", surface = "admin", bind = %addr, "listener online");
2753    }
2754    if let Some(addr) = env_nonempty("RED_METRICS_BIND") {
2755        let server = build_metrics_only_server(runtime.clone(), auth_store.clone(), addr.clone());
2756        let _ = server.serve_in_background();
2757        tracing::info!(transport = "http", surface = "metrics", bind = %addr, "listener online");
2758    }
2759}
2760
2761/// Resolve the HTTP TLS config from CLI / env / dev defaults.
2762fn resolve_http_tls_config(
2763    config: &ServerCommandConfig,
2764) -> Result<crate::server::tls::HttpTlsConfig, String> {
2765    match (&config.http_tls_cert, &config.http_tls_key) {
2766        (Some(cert), Some(key)) => Ok(crate::server::tls::HttpTlsConfig {
2767            cert_path: cert.clone(),
2768            key_path: key.clone(),
2769            client_ca_path: config.http_tls_client_ca.clone(),
2770        }),
2771        (None, None) => {
2772            // Dev-mode auto-generate next to the data directory.
2773            let dir = config
2774                .path
2775                .as_ref()
2776                .and_then(|p| p.parent().map(std::path::PathBuf::from))
2777                .unwrap_or_else(|| std::path::PathBuf::from("."));
2778            let auto = crate::server::tls::auto_generate_dev_cert(&dir)
2779                .map_err(|err| format!("HTTP TLS dev: {err}"))?;
2780            Ok(crate::server::tls::HttpTlsConfig {
2781                cert_path: auto.cert_path,
2782                key_path: auto.key_path,
2783                client_ca_path: config.http_tls_client_ca.clone(),
2784            })
2785        }
2786        _ => Err("HTTP TLS requires both --http-tls-cert and --http-tls-key (or neither, with RED_HTTP_TLS_DEV=1)".to_string()),
2787    }
2788}
2789
2790#[cfg(test)]
2791mod tests {
2792    use super::*;
2793
2794    #[test]
2795    fn runtime_workers_use_both_cores_on_small_instances() {
2796        assert_eq!(suggested_worker_count(1), 1);
2797        assert_eq!(suggested_worker_count(2), 2);
2798        assert_eq!(suggested_worker_count(4), 3);
2799    }
2800
2801    #[test]
2802    fn render_systemd_unit_contains_expected_execstart() {
2803        let config = SystemdServiceConfig {
2804            service_name: "reddb".to_string(),
2805            binary_path: PathBuf::from("/usr/local/bin/red"),
2806            run_user: "reddb".to_string(),
2807            run_group: "reddb".to_string(),
2808            data_path: reddb_file::default_service_database_path(),
2809            router_bind_addr: None,
2810            grpc_bind_addr: Some("0.0.0.0:55055".to_string()),
2811            http_bind_addr: None,
2812        };
2813
2814        let unit = render_systemd_unit(&config);
2815        assert!(unit.contains("ExecStart=/usr/local/bin/red server --path /var/lib/reddb/data.rdb --grpc-bind 0.0.0.0:55055"));
2816        assert!(unit.contains("ReadWritePaths=/var/lib/reddb"));
2817    }
2818
2819    #[test]
2820    fn systemd_service_config_derives_paths() {
2821        let config = SystemdServiceConfig {
2822            service_name: "reddb-api".to_string(),
2823            binary_path: PathBuf::from("/usr/local/bin/red"),
2824            run_user: "reddb".to_string(),
2825            run_group: "reddb".to_string(),
2826            data_path: PathBuf::from("/srv/reddb/live/data.rdb"),
2827            router_bind_addr: None,
2828            grpc_bind_addr: None,
2829            http_bind_addr: Some("127.0.0.1:5000".to_string()),
2830        };
2831
2832        assert_eq!(config.data_dir(), PathBuf::from("/srv/reddb/live"));
2833        assert_eq!(
2834            config.unit_path(),
2835            PathBuf::from("/etc/systemd/system/reddb-api.service")
2836        );
2837    }
2838
2839    #[test]
2840    fn render_systemd_unit_supports_dual_transport() {
2841        let config = SystemdServiceConfig {
2842            service_name: "reddb".to_string(),
2843            binary_path: PathBuf::from("/usr/local/bin/red"),
2844            run_user: "reddb".to_string(),
2845            run_group: "reddb".to_string(),
2846            data_path: reddb_file::default_service_database_path(),
2847            router_bind_addr: None,
2848            grpc_bind_addr: Some("0.0.0.0:55055".to_string()),
2849            http_bind_addr: Some("0.0.0.0:5000".to_string()),
2850        };
2851
2852        let unit = render_systemd_unit(&config);
2853        assert!(unit.contains("--grpc-bind 0.0.0.0:55055"));
2854        assert!(unit.contains("--http-bind 0.0.0.0:5000"));
2855    }
2856
2857    #[test]
2858    fn render_systemd_unit_supports_router_mode() {
2859        let config = SystemdServiceConfig {
2860            service_name: "reddb".to_string(),
2861            binary_path: PathBuf::from("/usr/local/bin/red"),
2862            run_user: "reddb".to_string(),
2863            run_group: "reddb".to_string(),
2864            data_path: reddb_file::default_service_database_path(),
2865            router_bind_addr: Some(DEFAULT_ROUTER_BIND_ADDR.to_string()),
2866            grpc_bind_addr: None,
2867            http_bind_addr: None,
2868        };
2869
2870        let unit = render_systemd_unit(&config);
2871        assert!(unit.contains("--bind 127.0.0.1:5050"));
2872        assert!(!unit.contains("--grpc-bind"));
2873        assert!(!unit.contains("--http-bind"));
2874    }
2875
2876    #[test]
2877    fn explicit_bind_collision_is_fatal() {
2878        let held = TcpListener::bind("127.0.0.1:0").expect("hold test port");
2879        let addr = held.local_addr().expect("held addr").to_string();
2880        let mut readiness = TransportReadiness::default();
2881
2882        let error = bind_listener_for_startup(&mut readiness, "http", &addr, true).unwrap_err();
2883
2884        assert!(error.contains("explicit http listener bind"));
2885        assert_eq!(readiness.active.len(), 0);
2886        assert_eq!(readiness.failed.len(), 1);
2887        assert!(readiness.failed[0].explicit);
2888        assert_eq!(readiness.failed[0].bind_addr, addr);
2889    }
2890
2891    // ---------- Issue #663 — `--no-auth` / `--dev` ----------
2892
2893    // Env access in tests is process-global; serialise the two
2894    // `--no-auth` tests so the REDDB_USERNAME / REDDB_PASSWORD pair
2895    // one of them sets cannot leak into the other under cargo's
2896    // default parallel runner.
2897    fn no_auth_env_lock() -> &'static std::sync::Mutex<()> {
2898        static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
2899        LOCK.get_or_init(|| std::sync::Mutex::new(()))
2900    }
2901
2902    #[test]
2903    fn server_options_preserve_explicit_disk_residency() {
2904        let _guard = no_auth_env_lock().lock().unwrap();
2905        let mut config = no_auth_test_config(true);
2906        assert!(!config.to_db_options().unwrap().bounded_disk_residency);
2907        config.bounded_disk_residency = true;
2908        assert!(config.to_db_options().unwrap().bounded_disk_residency);
2909    }
2910
2911    fn no_auth_test_config(no_auth: bool) -> ServerCommandConfig {
2912        ServerCommandConfig {
2913            path: None,
2914            router_bind_addr: Some(DEFAULT_ROUTER_BIND_ADDR.to_string()),
2915            router_bind_explicit: false,
2916            grpc_bind_addr: None,
2917            grpc_bind_explicit: false,
2918            grpc_tls_bind_addr: None,
2919            grpc_tls_cert: None,
2920            grpc_tls_key: None,
2921            grpc_tls_client_ca: None,
2922            http_bind_addr: None,
2923            http_bind_explicit: false,
2924            http_tls_bind_addr: None,
2925            http_tls_cert: None,
2926            http_tls_key: None,
2927            http_tls_client_ca: None,
2928            wire_bind_addr: None,
2929            wire_bind_explicit: false,
2930            wire_tls_bind_addr: None,
2931            wire_tls_cert: None,
2932            wire_tls_key: None,
2933            pg_bind_addr: None,
2934            create_if_missing: true,
2935            bounded_disk_residency: false,
2936            read_only: false,
2937            role: "standalone".to_string(),
2938            primary_addr: None,
2939            storage_profile: StorageProfileSelection::embedded_single_file(),
2940            auth: false,
2941            require_auth: false,
2942            // Operator-set `--vault`: `--no-auth` must override this
2943            // alongside REDDB_USERNAME/PASSWORD.
2944            vault: true,
2945            no_auth,
2946            workers: None,
2947            telemetry: None,
2948            http_limits_cli: crate::server::HttpLimitsCliInput::default(),
2949            ui: false,
2950            ui_dir: None,
2951            bootstrap: BootstrapConfig::default(),
2952        }
2953    }
2954
2955    #[test]
2956    fn no_auth_flag_disables_every_auth_knob_and_stamps_metadata() {
2957        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
2958        // Pre-existing env that *would* turn auth on if `--no-auth`
2959        // weren't the last word. The acceptance criterion is that
2960        // the flag wins over env.
2961        // SAFETY: serialised by `no_auth_env_lock` above.
2962        unsafe {
2963            std::env::set_var("REDDB_USERNAME", "admin");
2964            std::env::set_var("REDDB_PASSWORD", "hunter2");
2965        }
2966        let config = no_auth_test_config(true);
2967        let options = config.to_db_options().expect("to_db_options");
2968
2969        assert!(no_auth_active(&options), "metadata should be stamped");
2970        assert!(!options.auth.enabled, "auth.enabled must be forced off");
2971        assert!(
2972            !options.auth.require_auth,
2973            "require_auth must be forced off"
2974        );
2975        assert!(
2976            !options.auth.vault_enabled,
2977            "vault_enabled must be forced off (overrides --vault)"
2978        );
2979        assert_eq!(
2980            options.metadata.get(NO_AUTH_META).map(String::as_str),
2981            Some("true"),
2982        );
2983
2984        // SAFETY: serialised by `no_auth_env_lock` above.
2985        unsafe {
2986            std::env::remove_var("REDDB_USERNAME");
2987            std::env::remove_var("REDDB_PASSWORD");
2988        }
2989    }
2990
2991    #[test]
2992    fn default_behaviour_without_no_auth_flag_is_unchanged() {
2993        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
2994        let config = no_auth_test_config(false);
2995        let options = config.to_db_options().expect("to_db_options");
2996
2997        assert!(
2998            !no_auth_active(&options),
2999            "default boot must not be marked no-auth"
3000        );
3001        assert!(
3002            options.metadata.get(NO_AUTH_META).is_none(),
3003            "metadata key must be absent when flag is off"
3004        );
3005        // `--vault` should still take effect when `--no-auth` is not set.
3006        assert!(options.auth.vault_enabled);
3007    }
3008
3009    #[test]
3010    fn no_auth_active_blocks_bootstrap_from_env() {
3011        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3012        // SAFETY: serialised by `no_auth_env_lock` above. The pair
3013        // would normally cause `AuthStore::bootstrap_from_env` to
3014        // create an admin; the boot pipeline must suppress that call
3015        // whenever `no_auth_active` is true.
3016        unsafe {
3017            std::env::set_var("REDDB_USERNAME", "admin");
3018            std::env::set_var("REDDB_PASSWORD", "hunter2");
3019        }
3020
3021        let options = no_auth_test_config(true)
3022            .to_db_options()
3023            .expect("to_db_options");
3024
3025        // Mirror the exact branch in `build_runtime_with_telemetry`:
3026        // build a non-vault AuthStore from `options.auth`, then call
3027        // `bootstrap_from_env` *only* when the no-auth gate is off.
3028        let auth_store = AuthStore::new(options.auth.clone());
3029        if !no_auth_active(&options) {
3030            auth_store.bootstrap_from_env();
3031        }
3032
3033        assert!(
3034            auth_store.needs_bootstrap(),
3035            "no admin user must be bootstrapped under --no-auth even with REDDB_USERNAME/PASSWORD set"
3036        );
3037
3038        // SAFETY: serialised by `no_auth_env_lock` above.
3039        unsafe {
3040            std::env::remove_var("REDDB_USERNAME");
3041            std::env::remove_var("REDDB_PASSWORD");
3042        }
3043    }
3044
3045    // ---------- Issue #650 — bootstrap presets ----------
3046
3047    // Preset tests mutate process-global env (`REDDB_PRESET`,
3048    // `REDDB_USERNAME`, `REDDB_PASSWORD`) and the global tracing
3049    // subscriber. Share the no_auth lock so they don't race with each
3050    // other or with the --no-auth tests above.
3051    fn clear_preset_env() {
3052        // SAFETY: callers hold `no_auth_env_lock()`.
3053        unsafe {
3054            std::env::remove_var(BOOTSTRAP_PRESET_ENV);
3055            std::env::remove_var(PRESET_ENV);
3056            std::env::remove_var("REDDB_BOOTSTRAP_MANIFEST");
3057            std::env::remove_var("REDDB_AUTH");
3058            std::env::remove_var("REDDB_REQUIRE_AUTH");
3059            std::env::remove_var("REDDB_NO_AUTH");
3060            std::env::remove_var("REDDB_DEV");
3061            std::env::remove_var("REDDB_VAULT");
3062            std::env::remove_var("REDDB_USERNAME");
3063            std::env::remove_var("REDDB_PASSWORD");
3064            std::env::remove_var("REDDB_USERNAME_FILE");
3065            std::env::remove_var("REDDB_PASSWORD_FILE");
3066            std::env::remove_var("REDDB_CLOUD_HEAD_ADMIN");
3067            std::env::remove_var("REDDB_CLOUD_HEAD_ADMIN_PASSWORD");
3068            std::env::remove_var("REDDB_CLOUD_HEAD_ADMIN_PASSWORD_FILE");
3069            std::env::remove_var("REDDB_CUSTOMER_ADMIN");
3070            std::env::remove_var("REDDB_CUSTOMER_ADMIN_PASSWORD");
3071            std::env::remove_var("REDDB_CUSTOMER_ADMIN_PASSWORD_FILE");
3072        }
3073    }
3074
3075    fn clear_backup_env() {
3076        // SAFETY: callers hold `no_auth_env_lock()`.
3077        unsafe {
3078            std::env::remove_var("REDDB_BACKUP_S3_ENDPOINT");
3079            std::env::remove_var("REDDB_BACKUP_S3_BUCKET");
3080            std::env::remove_var("REDDB_BACKUP_S3_PREFIX");
3081            std::env::remove_var("REDDB_BACKUP_S3_ACCESS_KEY_ID");
3082            std::env::remove_var("REDDB_BACKUP_S3_SECRET_ACCESS_KEY");
3083            std::env::remove_var("REDDB_BACKUP_S3_REGION");
3084            std::env::remove_var("REDDB_BACKUP_CHECKPOINT_INTERVAL_SECS");
3085            std::env::remove_var("REDDB_BACKUP_WAL_FLUSH_INTERVAL_SECS");
3086            std::env::remove_var("REDDB_BACKUP_PAUSE_ON_LAG_SECS");
3087        }
3088    }
3089
3090    fn fresh_runtime_and_store() -> (RedDBRuntime, Arc<AuthStore>) {
3091        let runtime = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime");
3092        let auth_store = Arc::new(AuthStore::new(crate::auth::AuthConfig::default()));
3093        (runtime, auth_store)
3094    }
3095
3096    #[test]
3097    fn auth_env_knobs_enable_auth_require_auth_and_vault() {
3098        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3099        clear_preset_env();
3100        // SAFETY: env serialised by `no_auth_env_lock`.
3101        unsafe {
3102            std::env::set_var("REDDB_AUTH", "true");
3103            std::env::set_var("REDDB_REQUIRE_AUTH", "true");
3104            std::env::set_var("REDDB_VAULT", "true");
3105        }
3106
3107        let mut config = no_auth_test_config(false);
3108        config.vault = false;
3109        let options = config.to_db_options().expect("to_db_options");
3110
3111        assert!(options.auth.enabled);
3112        assert!(options.auth.require_auth);
3113        assert!(options.auth.vault_enabled);
3114
3115        clear_preset_env();
3116    }
3117
3118    #[test]
3119    fn production_and_cloud_presets_force_auth_require_auth_and_vault() {
3120        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3121        clear_preset_env();
3122
3123        for preset in [PRESET_PRODUCTION, PRESET_CLOUD] {
3124            let mut config = no_auth_test_config(false);
3125            config.vault = false;
3126            config.bootstrap.preset = Some(preset.to_string());
3127
3128            let options = config.to_db_options().expect("to_db_options");
3129            assert!(options.auth.enabled, "{preset} should enable auth");
3130            assert!(
3131                options.auth.require_auth,
3132                "{preset} should require authenticated requests"
3133            );
3134            assert!(options.auth.vault_enabled, "{preset} should enable vault");
3135            assert!(!no_auth_active(&options));
3136        }
3137
3138        clear_preset_env();
3139    }
3140
3141    #[test]
3142    fn no_auth_env_overrides_preset_forced_auth() {
3143        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3144        clear_preset_env();
3145        // SAFETY: env serialised by `no_auth_env_lock`.
3146        unsafe {
3147            std::env::set_var("REDDB_NO_AUTH", "true");
3148            std::env::set_var(BOOTSTRAP_PRESET_ENV, PRESET_CLOUD);
3149        }
3150
3151        let mut config = no_auth_test_config(false);
3152        config.auth = true;
3153        config.require_auth = true;
3154        let options = config.to_db_options().expect("to_db_options");
3155
3156        assert!(no_auth_active(&options));
3157        assert!(!options.auth.enabled);
3158        assert!(!options.auth.require_auth);
3159        assert!(!options.auth.vault_enabled);
3160
3161        clear_preset_env();
3162    }
3163
3164    #[test]
3165    fn simple_preset_is_default_and_persists_state() {
3166        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3167        clear_preset_env();
3168
3169        let (runtime, auth_store) = fresh_runtime_and_store();
3170        apply_preset(&runtime, &auth_store).expect("simple preset applies cleanly");
3171
3172        // No admin was created — `simple` is anonymous-friendly.
3173        assert!(
3174            auth_store.needs_bootstrap(),
3175            "simple preset must not create an admin"
3176        );
3177
3178        // Bootstrap state persisted so the next boot is a no-op.
3179        let store = runtime.db().store();
3180        let completed = store
3181            .get_config(BOOTSTRAP_COMPLETED_KEY)
3182            .expect("completed key persisted");
3183        assert!(matches!(completed, reddb_types::Value::Boolean(true)));
3184        let preset = store
3185            .get_config(BOOTSTRAP_PRESET_KEY)
3186            .expect("preset key persisted");
3187        match preset {
3188            reddb_types::Value::Text(s) => assert_eq!(s.as_ref(), PRESET_SIMPLE),
3189            other => panic!("expected Text(simple), got {other:?}"),
3190        }
3191        assert!(
3192            store.get_config(BOOTSTRAP_FIRST_ADMIN_KEY).is_none(),
3193            "simple preset must not record a first admin"
3194        );
3195
3196        clear_preset_env();
3197    }
3198
3199    #[test]
3200    fn production_preset_creates_first_admin_with_allow_all_policy() {
3201        use crate::auth::policies::{EvalContext, ResourceRef};
3202        use crate::auth::UserId;
3203
3204        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3205        clear_preset_env();
3206        // SAFETY: env serialised by `no_auth_env_lock`.
3207        unsafe {
3208            std::env::set_var(PRESET_ENV, PRESET_PRODUCTION);
3209            std::env::set_var("REDDB_USERNAME", "ops");
3210            std::env::set_var("REDDB_PASSWORD", "hunter2");
3211        }
3212
3213        let (runtime, auth_store) = fresh_runtime_and_store();
3214        apply_preset(&runtime, &auth_store).expect("production preset applies cleanly");
3215
3216        // Admin exists and the auth store is sealed.
3217        assert!(
3218            !auth_store.needs_bootstrap(),
3219            "production preset must seal bootstrap"
3220        );
3221        let users = auth_store.list_users();
3222        assert_eq!(users.len(), 1);
3223        let admin = &users[0];
3224        assert_eq!(admin.username, "ops");
3225        assert!(
3226            admin.tenant_id.is_none(),
3227            "first admin must be platform-scoped (tenant=None)"
3228        );
3229
3230        // Allow-all policy was installed and attached to the first admin.
3231        let policy = auth_store
3232            .get_policy(FIRST_ADMIN_ALLOW_ALL_POLICY)
3233            .expect("allow-all policy installed");
3234        assert!(!policy.statements.is_empty());
3235
3236        // Verify policy-derived authority via the policy evaluator —
3237        // not a bypass. Any action on any resource must Allow.
3238        let actor = UserId::platform("ops");
3239        let ctx = EvalContext {
3240            principal_tenant: None,
3241            current_tenant: None,
3242            peer_ip: None,
3243            mfa_present: false,
3244            now_ms: 1_700_000_000_000,
3245            principal_is_admin_role: true,
3246            principal_is_platform_scoped: true,
3247        };
3248        let arbitrary_resource = ResourceRef::new("config", "red.config.audit.enabled");
3249        assert!(
3250            auth_store.check_policy_authz(&actor, "config:write", &arbitrary_resource, &ctx),
3251            "allow-all policy must grant arbitrary actions via the evaluator"
3252        );
3253
3254        // Persisted state records the first admin id.
3255        let store = runtime.db().store();
3256        match store
3257            .get_config(BOOTSTRAP_FIRST_ADMIN_KEY)
3258            .expect("first_admin_id persisted")
3259        {
3260            reddb_types::Value::Text(s) => assert_eq!(s.as_ref(), "ops"),
3261            other => panic!("expected Text(ops), got {other:?}"),
3262        }
3263        match store.get_config(BOOTSTRAP_PRESET_KEY).unwrap() {
3264            reddb_types::Value::Text(s) => assert_eq!(s.as_ref(), PRESET_PRODUCTION),
3265            other => panic!("expected Text(production), got {other:?}"),
3266        }
3267
3268        clear_preset_env();
3269    }
3270
3271    #[test]
3272    fn bootstrap_preset_env_takes_precedence_over_legacy_preset_env() {
3273        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3274        clear_preset_env();
3275        // SAFETY: env serialised by `no_auth_env_lock`.
3276        unsafe {
3277            std::env::set_var(BOOTSTRAP_PRESET_ENV, PRESET_REGULATED);
3278            std::env::set_var(PRESET_ENV, PRESET_SIMPLE);
3279        }
3280
3281        let options = no_auth_test_config(false)
3282            .to_db_options()
3283            .expect("regulated options");
3284        assert!(
3285            options.control_events.compliance_mode,
3286            "canonical REDDB_BOOTSTRAP_PRESET should win over REDDB_PRESET"
3287        );
3288        assert!(options.query_audit.enabled);
3289
3290        clear_preset_env();
3291    }
3292
3293    #[test]
3294    fn cloud_preset_creates_system_head_and_customer_admins() {
3295        use crate::auth::policies::{EvalContext, ResourceRef};
3296        use crate::auth::UserId;
3297
3298        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3299        clear_preset_env();
3300        // SAFETY: env serialised by `no_auth_env_lock`.
3301        unsafe {
3302            std::env::set_var(BOOTSTRAP_PRESET_ENV, PRESET_CLOUD);
3303            std::env::set_var("REDDB_CLOUD_HEAD_ADMIN", "head");
3304            std::env::set_var("REDDB_CLOUD_HEAD_ADMIN_PASSWORD", "head-pass");
3305            std::env::set_var("REDDB_CUSTOMER_ADMIN", "customer");
3306            std::env::set_var("REDDB_CUSTOMER_ADMIN_PASSWORD", "customer-pass");
3307        }
3308
3309        let (runtime, auth_store) = fresh_runtime_and_store();
3310        apply_preset(&runtime, &auth_store).expect("cloud preset applies cleanly");
3311
3312        let head = auth_store
3313            .get_user(None, "head")
3314            .expect("head admin should exist");
3315        assert_eq!(head.tenant_id, None);
3316        let customer = auth_store
3317            .get_user(None, "customer")
3318            .expect("customer admin should exist");
3319        assert_eq!(customer.tenant_id, None);
3320
3321        let ctx = EvalContext {
3322            principal_tenant: None,
3323            current_tenant: None,
3324            peer_ip: None,
3325            mfa_present: false,
3326            now_ms: 1_700_000_000_000,
3327            principal_is_admin_role: true,
3328            principal_is_platform_scoped: true,
3329        };
3330        assert!(auth_store.check_policy_authz(
3331            &UserId::platform("customer"),
3332            "config:write",
3333            &ResourceRef::new("config", "red.config.customer.enabled"),
3334            &ctx,
3335        ));
3336        assert!(
3337            auth_store.check_policy_authz(
3338                &UserId::platform("head"),
3339                "config:write",
3340                &ResourceRef::new("config", "red.config.cloud.enabled"),
3341                &ctx,
3342            ),
3343            "cloud head keeps allow-all authority over managed cloud config"
3344        );
3345        assert!(
3346            !auth_store.check_policy_authz(
3347                &UserId::platform("customer"),
3348                "config:write",
3349                &ResourceRef::new("config", "red.config.cloud.enabled"),
3350                &ctx,
3351            ),
3352            "cloud customer must be denied managed cloud config writes"
3353        );
3354        assert!(
3355            !auth_store.check_policy_authz(
3356                &UserId::platform("customer"),
3357                "policy:drop",
3358                &ResourceRef::new("policy", CLOUD_PROTECT_MANAGED_POLICY),
3359                &ctx,
3360            ),
3361            "cloud customer must be denied mutations of the managed guardrail policy"
3362        );
3363
3364        assert!(auth_store.get_user(None, "head").is_some());
3365        assert!(auth_store
3366            .get_policy(CLOUD_PROTECT_MANAGED_POLICY)
3367            .is_some());
3368        assert!(runtime
3369            .config_registry()
3370            .get_active(CLOUD_CONFIG_NAMESPACE)
3371            .is_some());
3372
3373        let store = runtime.db().store();
3374        match store
3375            .get_config(BOOTSTRAP_FIRST_ADMIN_KEY)
3376            .expect("head admin id persisted")
3377        {
3378            reddb_types::Value::Text(s) => assert_eq!(s.as_ref(), "head"),
3379            other => panic!("expected Text(head), got {other:?}"),
3380        }
3381        match store.get_config(BOOTSTRAP_PRESET_KEY).unwrap() {
3382            reddb_types::Value::Text(s) => assert_eq!(s.as_ref(), PRESET_CLOUD),
3383            other => panic!("expected Text(cloud), got {other:?}"),
3384        }
3385
3386        clear_preset_env();
3387    }
3388
3389    #[test]
3390    fn cloud_preset_customer_cannot_disable_head_admin_or_drop_guardrail_policy() {
3391        use crate::auth::Role;
3392        use crate::runtime::mvcc::{clear_current_auth_identity, set_current_auth_identity};
3393
3394        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3395        clear_preset_env();
3396
3397        let bootstrap = BootstrapConfig {
3398            preset: Some(PRESET_CLOUD.to_string()),
3399            cloud_head_admin: Some("red_admin".to_string()),
3400            cloud_head_admin_password: Some("head-pass".to_string()),
3401            customer_admin: Some("admin".to_string()),
3402            customer_admin_password: Some("customer-pass".to_string()),
3403            ..BootstrapConfig::default()
3404        };
3405        let (runtime, auth_store) = fresh_runtime_and_store();
3406        apply_preset_from_config(&runtime, &auth_store, &bootstrap)
3407            .expect("cloud preset applies cleanly");
3408        runtime.set_auth_store(Arc::clone(&auth_store));
3409
3410        set_current_auth_identity("admin".to_string(), Role::Admin);
3411        let disable_head = runtime.execute_query("ALTER USER red_admin DISABLE");
3412        let drop_guardrail =
3413            runtime.execute_query(&format!("DROP POLICY '{}'", CLOUD_PROTECT_MANAGED_POLICY));
3414        let create_user = runtime.execute_query("CREATE USER app_user WITH PASSWORD 'p' ROLE read");
3415        let disable_user = runtime.execute_query("ALTER USER app_user DISABLE");
3416        clear_current_auth_identity();
3417
3418        let disable_head_err = disable_head.expect_err("customer admin must not disable red_admin");
3419        assert!(
3420            disable_head_err.to_string().contains("user:disable"),
3421            "error should name the denied lifecycle action: {disable_head_err}"
3422        );
3423        assert!(
3424            auth_store
3425                .get_user(None, "red_admin")
3426                .expect("red_admin should still exist")
3427                .enabled,
3428            "denied mutation must leave red_admin enabled"
3429        );
3430
3431        let drop_guardrail_err =
3432            drop_guardrail.expect_err("customer admin must not drop cloud guardrail policy");
3433        assert!(
3434            drop_guardrail_err.to_string().contains("managed policy"),
3435            "error should name the managed policy guardrail: {drop_guardrail_err}"
3436        );
3437        assert!(auth_store
3438            .get_policy(CLOUD_PROTECT_MANAGED_POLICY)
3439            .is_some());
3440
3441        create_user.expect("customer admin should retain normal create-user authority");
3442        disable_user.expect("customer admin should retain normal user-disable authority");
3443        assert!(
3444            !auth_store
3445                .get_user(None, "app_user")
3446                .expect("app_user should exist")
3447                .enabled,
3448            "normal capability should still apply outside the reserved head admin"
3449        );
3450
3451        clear_preset_env();
3452    }
3453
3454    #[test]
3455    fn cloud_preset_cli_admin_alias_wins_over_cloud_env_password() {
3456        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3457        clear_preset_env();
3458        // SAFETY: env serialised by `no_auth_env_lock`.
3459        unsafe {
3460            std::env::set_var("REDDB_CLOUD_HEAD_ADMIN_PASSWORD", "env-head-pass");
3461        }
3462
3463        let bootstrap = BootstrapConfig {
3464            preset: Some(PRESET_CLOUD.to_string()),
3465            admin_username: Some("head".to_string()),
3466            admin_password: Some("cli-head-pass".to_string()),
3467            customer_admin: Some("customer".to_string()),
3468            customer_admin_password: Some("customer-pass".to_string()),
3469            ..BootstrapConfig::default()
3470        };
3471        let (runtime, auth_store) = fresh_runtime_and_store();
3472        apply_preset_from_config(&runtime, &auth_store, &bootstrap)
3473            .expect("cloud preset applies cleanly");
3474
3475        auth_store
3476            .authenticate("head", "cli-head-pass")
3477            .expect("CLI alias password should win");
3478        assert!(
3479            auth_store.authenticate("head", "env-head-pass").is_err(),
3480            "cloud-specific env password must not beat CLI alias"
3481        );
3482
3483        clear_preset_env();
3484    }
3485
3486    #[test]
3487    fn bootstrap_intent_manifest_matches_cloud_flag_path() {
3488        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3489        clear_preset_env();
3490
3491        let manifest_dir = std::env::current_dir()
3492            .expect("current dir")
3493            .join(".red/tmp/bootstrap-manifest-tests");
3494        std::fs::create_dir_all(&manifest_dir).expect("create manifest test dir");
3495        let unique = format!(
3496            "{}-{}",
3497            std::process::id(),
3498            std::time::SystemTime::now()
3499                .duration_since(std::time::UNIX_EPOCH)
3500                .unwrap_or_default()
3501                .as_millis()
3502        );
3503        let head_password = manifest_dir.join(format!("head-{unique}.secret"));
3504        let customer_password = manifest_dir.join(format!("customer-{unique}.secret"));
3505        let manifest_path = manifest_dir.join(format!("intent-{unique}.json"));
3506        std::fs::write(&head_password, "head-pass\n").expect("write head secret");
3507        std::fs::write(&customer_password, "customer-pass\n").expect("write customer secret");
3508        std::fs::write(
3509            &manifest_path,
3510            format!(
3511                r#"{{
3512                    "bootstrap": {{
3513                        "preset": "cloud",
3514                        "cloud_head_admin": {{
3515                            "username": "head",
3516                            "password_file": "{}"
3517                        }},
3518                        "customer_admin": {{
3519                            "username": "customer",
3520                            "password_file": "{}"
3521                        }}
3522                    }}
3523                }}"#,
3524                head_password.display(),
3525                customer_password.display()
3526            ),
3527        )
3528        .expect("write manifest");
3529
3530        let mut config = no_auth_test_config(false);
3531        config.bootstrap.manifest = Some(manifest_path.clone());
3532        let options = config.to_db_options().expect("manifest options");
3533        assert!(options.auth.enabled);
3534        assert!(options.auth.require_auth);
3535        assert!(options.auth.vault_enabled);
3536
3537        let (runtime, auth_store) = fresh_runtime_and_store();
3538        apply_preset_from_config(&runtime, &auth_store, &config.bootstrap)
3539            .expect("manifest intent applies cleanly");
3540
3541        auth_store
3542            .authenticate("head", "head-pass")
3543            .expect("head password comes from file");
3544        auth_store
3545            .authenticate("customer", "customer-pass")
3546            .expect("customer password comes from file");
3547        assert!(auth_store.get_user(None, "head").is_some());
3548        assert!(auth_store.get_user(None, "customer").is_some());
3549        assert!(auth_store
3550            .get_policy(CLOUD_PROTECT_MANAGED_POLICY)
3551            .is_some());
3552        match runtime
3553            .db()
3554            .store()
3555            .get_config(BOOTSTRAP_PRESET_KEY)
3556            .expect("preset key persisted")
3557        {
3558            reddb_types::Value::Text(s) => assert_eq!(s.as_ref(), PRESET_CLOUD),
3559            other => panic!("expected Text(cloud), got {other:?}"),
3560        }
3561
3562        apply_preset_from_config(&runtime, &auth_store, &config.bootstrap)
3563            .expect("second boot is idempotent");
3564
3565        let _ = std::fs::remove_file(&manifest_path);
3566        let _ = std::fs::remove_file(&head_password);
3567        let _ = std::fs::remove_file(&customer_password);
3568        clear_preset_env();
3569    }
3570
3571    #[test]
3572    fn regulated_preset_enables_query_audit_infrastructure_without_rules() {
3573        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3574        clear_preset_env();
3575        // SAFETY: env serialised by `no_auth_env_lock`.
3576        unsafe {
3577            std::env::set_var(PRESET_ENV, PRESET_REGULATED);
3578        }
3579
3580        let (runtime, auth_store) = fresh_runtime_and_store();
3581        apply_preset(&runtime, &auth_store).expect("regulated preset applies cleanly");
3582
3583        assert!(runtime.query_audit().is_enabled());
3584        assert!(runtime.query_audit().rules().is_empty());
3585        assert!(
3586            runtime
3587                .db()
3588                .store()
3589                .get_collection(crate::runtime::query_audit::QUERY_AUDIT_COLLECTION)
3590                .is_some(),
3591            "regulated preset should create the query-audit stream"
3592        );
3593
3594        runtime
3595            .execute_query("CREATE TABLE docs (id INT)")
3596            .expect("create table");
3597        runtime
3598            .execute_query("INSERT INTO docs (id) VALUES (1)")
3599            .expect("insert");
3600        runtime.execute_query("SELECT * FROM docs").expect("select");
3601        let rows = runtime
3602            .db()
3603            .store()
3604            .get_collection(crate::runtime::query_audit::QUERY_AUDIT_COLLECTION)
3605            .expect("query audit collection")
3606            .query_all(|_| true);
3607        assert!(
3608            rows.is_empty(),
3609            "regulated preset must not globally audit every query"
3610        );
3611
3612        clear_preset_env();
3613    }
3614
3615    #[test]
3616    fn managed_backup_env_rejects_primary_replica_single_file_storage() {
3617        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3618        clear_backup_env();
3619        // SAFETY: env serialised by `no_auth_env_lock`.
3620        unsafe {
3621            std::env::set_var("REDDB_BACKUP_S3_ENDPOINT", "https://s3.example.test");
3622            std::env::set_var("REDDB_BACKUP_S3_BUCKET", "reddb");
3623            std::env::set_var("REDDB_BACKUP_S3_PREFIX", "clusters/prod");
3624            std::env::set_var("REDDB_BACKUP_S3_ACCESS_KEY_ID", "AK");
3625            std::env::set_var("REDDB_BACKUP_S3_SECRET_ACCESS_KEY", "SK");
3626        }
3627
3628        let mut config = no_auth_test_config(false);
3629        config.role = "primary".to_string();
3630        config.storage_profile = crate::storage::StorageDeployPreset::PrimaryReplicaDev.selection();
3631
3632        let err = config.to_db_options().unwrap_err();
3633        assert!(err.contains("managed backup"), "got: {err}");
3634        assert!(err.contains("operational-directory"), "got: {err}");
3635
3636        clear_backup_env();
3637    }
3638
3639    #[test]
3640    fn regulated_preset_installs_managed_evidence_guardrails_end_to_end() {
3641        use crate::auth::policies::{EvalContext, Policy, ResourceRef};
3642        use crate::auth::store::PrincipalRef;
3643        use crate::auth::{Role, UserId};
3644        use crate::runtime::mvcc::{clear_current_auth_identity, set_current_auth_identity};
3645        use reddb_types::Value;
3646
3647        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3648        clear_preset_env();
3649        // SAFETY: env serialised by `no_auth_env_lock`.
3650        unsafe {
3651            std::env::set_var(PRESET_ENV, PRESET_REGULATED);
3652        }
3653
3654        let options = no_auth_test_config(false)
3655            .to_db_options()
3656            .expect("regulated options");
3657        assert!(
3658            options.control_events.compliance_mode,
3659            "regulated preset must enable fail-closed control evidence before runtime boot"
3660        );
3661        assert!(
3662            options.query_audit.enabled && options.query_audit.rules.is_empty(),
3663            "regulated preset must enable query-audit infrastructure without global rules"
3664        );
3665
3666        let runtime = RedDBRuntime::with_options(options).expect("runtime");
3667        let auth_store = Arc::new(AuthStore::new(crate::auth::AuthConfig::default()));
3668        apply_preset(&runtime, &auth_store).expect("regulated preset applies cleanly");
3669        runtime.set_auth_store(Arc::clone(&auth_store));
3670
3671        assert!(runtime.control_events_require_persistence());
3672        assert!(runtime.query_audit().is_enabled());
3673        assert!(runtime.query_audit().rules().is_empty());
3674        assert!(auth_store
3675            .get_policy(REGULATED_PROTECT_MANAGED_POLICY)
3676            .is_some());
3677
3678        let managed_policy = runtime
3679            .config_registry()
3680            .get_active(REGULATED_PROTECT_MANAGED_POLICY)
3681            .expect("regulated managed policy registry entry");
3682        assert!(managed_policy.managed);
3683        assert_eq!(managed_policy.resource_type, "policy");
3684        assert!(
3685            runtime
3686                .config_registry()
3687                .get_active(REGULATED_AUDIT_CONFIG_NAMESPACE)
3688                .expect("regulated audit config namespace")
3689                .managed
3690        );
3691
3692        let registry_rows = runtime
3693            .execute_query(&format!(
3694                "SELECT id, managed FROM red.registry WHERE id = '{}'",
3695                REGULATED_PROTECT_MANAGED_POLICY
3696            ))
3697            .expect("red.registry query");
3698        assert_eq!(registry_rows.result.records.len(), 1);
3699        assert_eq!(
3700            registry_rows.result.records[0].get("managed"),
3701            Some(&Value::Boolean(true))
3702        );
3703
3704        let managed_policy_rows = runtime
3705            .execute_query(&format!(
3706                "SELECT policy_id FROM red.managed_policies WHERE policy_id = '{}'",
3707                REGULATED_PROTECT_MANAGED_POLICY
3708            ))
3709            .expect("red.managed_policies query");
3710        assert_eq!(managed_policy_rows.result.records.len(), 1);
3711
3712        let capability_rows = runtime
3713            .execute_query(
3714                "SELECT action FROM red.control_capabilities WHERE action = 'evidence:export'",
3715            )
3716            .expect("red.control_capabilities query");
3717        assert_eq!(capability_rows.result.records.len(), 1);
3718
3719        auth_store
3720            .create_user("alice", "p", Role::Admin)
3721            .expect("create ordinary admin");
3722        let allow_all = Policy::from_json_str(
3723            r#"{
3724                "id": "alice-allow-all",
3725                "version": 1,
3726                "statements": [{
3727                    "effect": "allow",
3728                    "actions": ["*"],
3729                    "resources": ["*"]
3730                }]
3731            }"#,
3732        )
3733        .expect("allow-all policy");
3734        auth_store.put_policy(allow_all).expect("install allow-all");
3735        auth_store
3736            .attach_policy(
3737                PrincipalRef::User(UserId::platform("alice")),
3738                "alice-allow-all",
3739            )
3740            .expect("attach allow-all");
3741        let ctx = EvalContext {
3742            principal_tenant: None,
3743            current_tenant: None,
3744            peer_ip: None,
3745            mfa_present: false,
3746            now_ms: 1_700_000_000_000,
3747            principal_is_admin_role: true,
3748            principal_is_platform_scoped: true,
3749        };
3750        assert!(
3751            !auth_store.check_policy_authz(
3752                &UserId::platform("alice"),
3753                "policy:drop",
3754                &ResourceRef::new("policy", REGULATED_PROTECT_MANAGED_POLICY),
3755                &ctx,
3756            ),
3757            "managed guardrail deny policy must be effective for ordinary admins"
3758        );
3759
3760        set_current_auth_identity("alice".to_string(), Role::Admin);
3761        let denied = runtime.execute_query(&format!(
3762            "DROP POLICY '{}'",
3763            REGULATED_PROTECT_MANAGED_POLICY
3764        ));
3765        clear_current_auth_identity();
3766        let err = denied.expect_err("managed policy guardrail must deny ordinary admin");
3767        assert!(
3768            err.to_string().contains("managed policy"),
3769            "error should name the managed guardrail: {err}"
3770        );
3771        assert!(
3772            auth_store
3773                .get_policy(REGULATED_PROTECT_MANAGED_POLICY)
3774                .is_some(),
3775            "denied mutation must leave managed policy installed"
3776        );
3777
3778        let denied_events = runtime
3779            .execute_query(&format!(
3780                "SELECT action, resource, outcome FROM red.control_events \
3781                 WHERE action = 'policy:drop' AND resource = 'policy:{}'",
3782                REGULATED_PROTECT_MANAGED_POLICY
3783            ))
3784            .expect("red.control_events denied policy drop");
3785        assert_eq!(denied_events.result.records.len(), 1);
3786        assert_eq!(
3787            denied_events.result.records[0].get("outcome"),
3788            Some(&Value::text("denied"))
3789        );
3790
3791        set_current_auth_identity("alice".to_string(), Role::Admin);
3792        let config_denied = runtime.execute_query("SET CONFIG red.config.audit.enabled = true");
3793        clear_current_auth_identity();
3794        let err = config_denied.expect_err("managed config guardrail must deny ordinary admin");
3795        assert!(
3796            err.to_string().contains("managed config"),
3797            "error should name the managed config guardrail: {err}"
3798        );
3799
3800        let denied_config_events = runtime
3801            .execute_query(
3802                "SELECT action, resource, outcome FROM red.control_events \
3803                 WHERE action = 'config:write' AND resource = 'config:red.config.audit.enabled'",
3804            )
3805            .expect("red.control_events denied config write");
3806        assert_eq!(denied_config_events.result.records.len(), 1);
3807        assert_eq!(
3808            denied_config_events.result.records[0].get("outcome"),
3809            Some(&Value::text("denied"))
3810        );
3811
3812        runtime
3813            .execute_query("CREATE TABLE regulated_docs (id INT)")
3814            .expect("create user table");
3815        runtime
3816            .execute_query("SELECT * FROM regulated_docs")
3817            .expect("select user table");
3818        let audit_rows = runtime
3819            .db()
3820            .store()
3821            .get_collection(crate::runtime::query_audit::QUERY_AUDIT_COLLECTION)
3822            .expect("query audit collection")
3823            .query_all(|_| true);
3824        assert!(
3825            audit_rows.is_empty(),
3826            "regulated preset must not globally audit data-plane queries"
3827        );
3828
3829        clear_preset_env();
3830    }
3831
3832    #[test]
3833    fn bootstrap_manifest_installs_initial_users_policies_guardrails_and_config() {
3834        use crate::auth::policies::{EvalContext, ResourceRef};
3835        use crate::auth::UserId;
3836        use reddb_types::Value;
3837
3838        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3839        clear_preset_env();
3840
3841        let manifest_dir = std::env::current_dir()
3842            .expect("current dir")
3843            .join(".red/tmp/bootstrap-manifest-tests");
3844        std::fs::create_dir_all(&manifest_dir).expect("create manifest test dir");
3845        let manifest_path = manifest_dir.join(format!(
3846            "reddb-bootstrap-manifest-{}-{}.json",
3847            std::process::id(),
3848            std::time::SystemTime::now()
3849                .duration_since(std::time::UNIX_EPOCH)
3850                .unwrap_or_default()
3851                .as_millis()
3852        ));
3853        std::fs::write(
3854            &manifest_path,
3855            r#"{
3856                "users": [
3857                    {
3858                        "username": "ops",
3859                        "password": "hunter2",
3860                        "role": "admin"
3861                    }
3862                ],
3863                "policies": [
3864                    {
3865                        "id": "bootstrap-registry-admin",
3866                        "version": 1,
3867                        "statements": [
3868                            {
3869                                "effect": "allow",
3870                                "actions": ["red.registry:*", "policy:*", "config:write", "select"],
3871                                "resources": ["registry:*", "policy:*", "config:*", "collection:docs"]
3872                            }
3873                        ]
3874                    }
3875                ],
3876                "managed_policies": [
3877                    {
3878                        "id": "managed-deny-drop",
3879                        "version": 1,
3880                        "statements": [
3881                            {
3882                                "effect": "deny",
3883                                "actions": ["policy:drop"],
3884                                "resources": ["policy:managed-deny-drop"]
3885                            }
3886                        ],
3887                        "required_resource": "policy:managed-deny-drop",
3888                        "evidence": "full"
3889                    }
3890                ],
3891                "attachments": [
3892                    {"user": "ops", "policy": "bootstrap-registry-admin"}
3893                ],
3894                "managed_config_namespaces": [
3895                    {
3896                        "id": "red.ai",
3897                        "required_action": "config:write",
3898                        "required_resource": "config:red.ai.*",
3899                        "evidence": "metadata"
3900                    }
3901                ],
3902                "config": [
3903                    {"key": "red.ai.default.provider", "value": "openai"},
3904                    {
3905                        "key": "red.ai.openai.default.secret_ref",
3906                        "secret_ref": {"collection": "red.vault", "key": "openai"}
3907                    }
3908                ],
3909                "actor": "ops"
3910            }"#,
3911        )
3912        .expect("write manifest");
3913        // SAFETY: env serialised by `no_auth_env_lock`.
3914        unsafe {
3915            std::env::set_var("REDDB_BOOTSTRAP_MANIFEST", &manifest_path);
3916        }
3917
3918        let (runtime, auth_store) = fresh_runtime_and_store();
3919        apply_preset(&runtime, &auth_store).expect("manifest applies cleanly");
3920
3921        let users = auth_store.list_users();
3922        assert_eq!(users.len(), 1);
3923        assert_eq!(users[0].username, "ops");
3924        assert!(users[0].tenant_id.is_none());
3925
3926        let actor = UserId::platform("ops");
3927        let ctx = EvalContext {
3928            principal_tenant: None,
3929            current_tenant: None,
3930            peer_ip: None,
3931            mfa_present: false,
3932            now_ms: 1_700_000_000_000,
3933            principal_is_admin_role: true,
3934            principal_is_platform_scoped: true,
3935        };
3936        // Manifest fixture pins a canonical data-plane read action.
3937        assert!(auth_store.check_policy_authz(
3938            &actor,
3939            "select",
3940            &ResourceRef::new("collection", "docs"),
3941            &ctx
3942        ));
3943
3944        let managed_policy = runtime
3945            .config_registry()
3946            .get_active("managed-deny-drop")
3947            .expect("managed policy registry entry");
3948        assert!(managed_policy.managed);
3949        assert_eq!(managed_policy.resource_type, "policy");
3950        let managed_config = runtime
3951            .config_registry()
3952            .get_active("red.ai")
3953            .expect("managed config namespace registry entry");
3954        assert!(managed_config.managed);
3955        assert_eq!(managed_config.resource_type, "config_namespace");
3956
3957        let store = runtime.db().store();
3958        match store
3959            .get_config("red.ai.default.provider")
3960            .expect("plain config persisted")
3961        {
3962            Value::Text(s) => assert_eq!(s.as_ref(), "openai"),
3963            other => panic!("expected provider text, got {other:?}"),
3964        }
3965        let Value::Json(bytes) = store
3966            .get_config("red.ai.openai.default.secret_ref")
3967            .expect("secret ref config persisted")
3968        else {
3969            panic!("secret ref must be stored as structured JSON");
3970        };
3971        let reference: crate::serde_json::Value =
3972            crate::serde_json::from_slice(&bytes).expect("secret ref json");
3973        assert_eq!(
3974            reference.get("type").and_then(|v| v.as_str()),
3975            Some("secret_ref")
3976        );
3977        assert!(
3978            !String::from_utf8_lossy(&bytes).contains("hunter2"),
3979            "manifest password must not leak into secret ref config"
3980        );
3981
3982        let completed = store
3983            .get_config(BOOTSTRAP_COMPLETED_KEY)
3984            .expect("bootstrap completion persisted");
3985        assert!(matches!(completed, Value::Boolean(true)));
3986        assert!(
3987            store
3988                .get_config("system.bootstrap.manifest.registry_entries")
3989                .is_some(),
3990            "managed registry entries must be persisted internally"
3991        );
3992
3993        std::fs::remove_file(&manifest_path).expect("remove manifest after first boot");
3994        let restored_registry = Arc::new(crate::auth::registry::ConfigRegistry::new());
3995        crate::cli::bootstrap_manifest::rehydrate_manifest_registry(&runtime, &restored_registry)
3996            .expect("registry rehydrates without manifest file");
3997        assert!(restored_registry.get_active("managed-deny-drop").is_some());
3998        assert!(restored_registry.get_active("red.ai").is_some());
3999
4000        let fresh = Arc::new(AuthStore::new(crate::auth::AuthConfig::default()));
4001        apply_preset(&runtime, &fresh).expect("re-run must not need manifest file");
4002        assert!(fresh.needs_bootstrap());
4003
4004        clear_preset_env();
4005    }
4006
4007    #[test]
4008    fn production_preset_refuses_to_start_without_password() {
4009        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
4010        clear_preset_env();
4011        // SAFETY: env serialised by `no_auth_env_lock`.
4012        unsafe {
4013            std::env::set_var(PRESET_ENV, PRESET_PRODUCTION);
4014            std::env::set_var("REDDB_USERNAME", "ops");
4015        }
4016
4017        let (runtime, auth_store) = fresh_runtime_and_store();
4018        let err = apply_preset(&runtime, &auth_store).expect_err("must reject missing password");
4019        assert!(
4020            err.contains("REDDB_PASSWORD"),
4021            "error must name the missing env: {err}"
4022        );
4023
4024        // Nothing was persisted; nothing was created.
4025        assert!(auth_store.needs_bootstrap());
4026        assert!(runtime
4027            .db()
4028            .store()
4029            .get_config(BOOTSTRAP_COMPLETED_KEY)
4030            .is_none());
4031
4032        clear_preset_env();
4033    }
4034
4035    #[test]
4036    fn re_running_production_after_first_boot_is_a_silent_skip() {
4037        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
4038        clear_preset_env();
4039        // SAFETY: env serialised by `no_auth_env_lock`.
4040        unsafe {
4041            std::env::set_var(PRESET_ENV, PRESET_PRODUCTION);
4042            std::env::set_var("REDDB_USERNAME", "ops");
4043            std::env::set_var("REDDB_PASSWORD", "hunter2");
4044        }
4045
4046        let (runtime, auth_store) = fresh_runtime_and_store();
4047        apply_preset(&runtime, &auth_store).expect("first apply");
4048        assert_eq!(auth_store.list_users().len(), 1);
4049
4050        // Second invocation: same runtime/store, same env. Must be a
4051        // no-op — no error, no duplicate admin, no duplicate policy.
4052        // We do NOT reuse `auth_store` because production sealed it; the
4053        // idempotency hinge is the persisted config key, not the auth
4054        // store's in-memory seal. Build a fresh `AuthStore` as a restart
4055        // would and confirm `apply_preset` is a silent skip.
4056        let fresh = Arc::new(AuthStore::new(crate::auth::AuthConfig::default()));
4057        apply_preset(&runtime, &fresh).expect("re-run is silent-skip");
4058        assert!(
4059            fresh.needs_bootstrap(),
4060            "re-run must not create a second admin"
4061        );
4062        assert!(
4063            fresh.get_policy(FIRST_ADMIN_ALLOW_ALL_POLICY).is_none(),
4064            "re-run must not re-install the allow-all policy on the fresh store"
4065        );
4066
4067        clear_preset_env();
4068    }
4069
4070    #[test]
4071    fn unrecognised_preset_value_is_rejected() {
4072        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
4073        clear_preset_env();
4074        // SAFETY: env serialised by `no_auth_env_lock`.
4075        unsafe {
4076            std::env::set_var(PRESET_ENV, "weird");
4077        }
4078
4079        let (runtime, auth_store) = fresh_runtime_and_store();
4080        let err = apply_preset(&runtime, &auth_store).expect_err("must reject unknown preset");
4081        assert!(err.contains("weird"), "error must echo the value: {err}");
4082        assert!(auth_store.needs_bootstrap());
4083
4084        clear_preset_env();
4085    }
4086
4087    #[test]
4088    fn no_auth_short_circuits_preset_entirely() {
4089        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
4090        clear_preset_env();
4091        // SAFETY: env serialised by `no_auth_env_lock`. Production creds
4092        // are set but `--no-auth` must win — no admin, no bootstrap state.
4093        unsafe {
4094            std::env::set_var(PRESET_ENV, PRESET_PRODUCTION);
4095            std::env::set_var("REDDB_USERNAME", "ops");
4096            std::env::set_var("REDDB_PASSWORD", "hunter2");
4097        }
4098
4099        let options = no_auth_test_config(true)
4100            .to_db_options()
4101            .expect("to_db_options");
4102        assert!(no_auth_active(&options));
4103
4104        // Mirror `build_runtime_with_telemetry`: when no_auth_active,
4105        // `apply_preset` is never called.
4106        let (runtime, auth_store) = fresh_runtime_and_store();
4107        if !no_auth_active(&options) {
4108            apply_preset(&runtime, &auth_store).expect("would apply preset");
4109        }
4110
4111        assert!(
4112            auth_store.needs_bootstrap(),
4113            "--no-auth must prevent any admin creation"
4114        );
4115        assert!(
4116            runtime
4117                .db()
4118                .store()
4119                .get_config(BOOTSTRAP_COMPLETED_KEY)
4120                .is_none(),
4121            "--no-auth must skip bootstrap-state persistence"
4122        );
4123
4124        clear_preset_env();
4125    }
4126
4127    #[test]
4128    fn implicit_bind_collision_degrades() {
4129        let held = TcpListener::bind("127.0.0.1:0").expect("hold test port");
4130        let addr = held.local_addr().expect("held addr").to_string();
4131        let mut readiness = TransportReadiness::default();
4132
4133        let listener =
4134            bind_listener_for_startup(&mut readiness, "http", &addr, false).expect("nonfatal");
4135
4136        assert!(listener.is_none());
4137        assert_eq!(readiness.active.len(), 0);
4138        assert_eq!(readiness.failed.len(), 1);
4139        assert!(!readiness.failed[0].explicit);
4140        assert_eq!(readiness.failed[0].bind_addr, addr);
4141    }
4142}