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        execution_workers = resolved.execution_workers,
2648        handler_timeout_ms = resolved.handler_timeout_ms,
2649        retry_after_secs = resolved.retry_after_secs,
2650        max_inflight_per_principal = resolved.max_inflight_per_principal,
2651        "http_limits resolved"
2652    );
2653    server.with_http_limits(resolved)
2654}
2655
2656/// `red server --ui` (issue #1047, ADR 0051): attach the resolved red-ui
2657/// bundle directory to an HTTP server so it also serves the bundle as
2658/// static assets. No-op when `--ui` is off.
2659///
2660/// An explicit `--ui-dir <DIR>` is served as-is (no download); otherwise
2661/// the pinned bundle is resolved from the local cache, downloading on
2662/// first use (ADR 0050). A resolution failure is fatal: the operator
2663/// explicitly asked for the UI, so silently serving API-only would be
2664/// surprising and would mask an offline/checksum problem.
2665fn apply_ui_bundle(
2666    server: RedDBServer,
2667    config: &ServerCommandConfig,
2668) -> Result<RedDBServer, String> {
2669    if !config.ui {
2670        return Ok(server);
2671    }
2672    let ui_dir = match &config.ui_dir {
2673        Some(dir) => dir.clone(),
2674        None => {
2675            let cache_root = crate::server::ui_bundle_resolver::reddb_user_cache_root()
2676                .unwrap_or_else(|_| std::env::temp_dir().join("reddb"));
2677            crate::server::ui_bundle_resolver::resolve_ui_bundle(
2678                &cache_root,
2679                &crate::server::ui_bundle_resolver::HttpFetcher,
2680            )
2681            .map_err(|err| format!("resolve red-ui bundle for --ui: {err}"))?
2682        }
2683    };
2684    tracing::info!(target: "reddb::ui", dir = %ui_dir.display(), "serving red-ui bundle on HTTP surface");
2685    Ok(server.with_ui_dir(ui_dir))
2686}
2687
2688#[inline(never)]
2689fn build_http_server_with_transport_readiness(
2690    runtime: RedDBRuntime,
2691    auth_store: Arc<AuthStore>,
2692    bind_addr: String,
2693    transport_readiness: TransportReadiness,
2694) -> RedDBServer {
2695    RedDBServer::with_options(
2696        runtime,
2697        ServerOptions {
2698            bind_addr,
2699            transport_readiness,
2700            ..ServerOptions::default()
2701        },
2702    )
2703    .with_auth(auth_store)
2704}
2705
2706/// PLAN.md Phase 6.2 — build a listener that only serves
2707/// `/admin/*` + `/metrics` + `/health/*`. Defaults to `127.0.0.1`
2708/// when the env var has no host (loopback-only by default per spec).
2709#[inline(never)]
2710fn build_admin_only_server(
2711    runtime: RedDBRuntime,
2712    auth_store: Arc<AuthStore>,
2713    bind_addr: String,
2714) -> RedDBServer {
2715    RedDBServer::with_options(
2716        runtime,
2717        ServerOptions {
2718            bind_addr,
2719            surface: crate::server::ServerSurface::AdminOnly,
2720            ..ServerOptions::default()
2721        },
2722    )
2723    .with_auth(auth_store)
2724}
2725
2726/// PLAN.md Phase 6.2 — build a listener that only serves `/metrics`
2727/// + `/health/*`. Suitable for Prometheus scrape ports that may be
2728///   exposed wider than the admin port.
2729#[inline(never)]
2730fn build_metrics_only_server(
2731    runtime: RedDBRuntime,
2732    auth_store: Arc<AuthStore>,
2733    bind_addr: String,
2734) -> RedDBServer {
2735    RedDBServer::with_options(
2736        runtime,
2737        ServerOptions {
2738            bind_addr,
2739            surface: crate::server::ServerSurface::MetricsOnly,
2740            ..ServerOptions::default()
2741        },
2742    )
2743    .with_auth(auth_store)
2744}
2745
2746/// Spawn dedicated admin / metrics listeners when the operator set
2747/// `RED_ADMIN_BIND` / `RED_METRICS_BIND`. Both are optional; when
2748/// unset the existing listener keeps serving everything (back-compat).
2749fn spawn_admin_metrics_listeners(runtime: &RedDBRuntime, auth_store: &Arc<AuthStore>) {
2750    if let Some(addr) = env_nonempty("RED_ADMIN_BIND") {
2751        let server = build_admin_only_server(runtime.clone(), auth_store.clone(), addr.clone());
2752        let _ = server.serve_in_background();
2753        tracing::info!(transport = "http", surface = "admin", bind = %addr, "listener online");
2754    }
2755    if let Some(addr) = env_nonempty("RED_METRICS_BIND") {
2756        let server = build_metrics_only_server(runtime.clone(), auth_store.clone(), addr.clone());
2757        let _ = server.serve_in_background();
2758        tracing::info!(transport = "http", surface = "metrics", bind = %addr, "listener online");
2759    }
2760}
2761
2762/// Resolve the HTTP TLS config from CLI / env / dev defaults.
2763fn resolve_http_tls_config(
2764    config: &ServerCommandConfig,
2765) -> Result<crate::server::tls::HttpTlsConfig, String> {
2766    match (&config.http_tls_cert, &config.http_tls_key) {
2767        (Some(cert), Some(key)) => Ok(crate::server::tls::HttpTlsConfig {
2768            cert_path: cert.clone(),
2769            key_path: key.clone(),
2770            client_ca_path: config.http_tls_client_ca.clone(),
2771        }),
2772        (None, None) => {
2773            // Dev-mode auto-generate next to the data directory.
2774            let dir = config
2775                .path
2776                .as_ref()
2777                .and_then(|p| p.parent().map(std::path::PathBuf::from))
2778                .unwrap_or_else(|| std::path::PathBuf::from("."));
2779            let auto = crate::server::tls::auto_generate_dev_cert(&dir)
2780                .map_err(|err| format!("HTTP TLS dev: {err}"))?;
2781            Ok(crate::server::tls::HttpTlsConfig {
2782                cert_path: auto.cert_path,
2783                key_path: auto.key_path,
2784                client_ca_path: config.http_tls_client_ca.clone(),
2785            })
2786        }
2787        _ => Err("HTTP TLS requires both --http-tls-cert and --http-tls-key (or neither, with RED_HTTP_TLS_DEV=1)".to_string()),
2788    }
2789}
2790
2791#[cfg(test)]
2792mod tests {
2793    use super::*;
2794
2795    #[test]
2796    fn runtime_workers_use_both_cores_on_small_instances() {
2797        assert_eq!(suggested_worker_count(1), 1);
2798        assert_eq!(suggested_worker_count(2), 2);
2799        assert_eq!(suggested_worker_count(4), 3);
2800    }
2801
2802    #[test]
2803    fn render_systemd_unit_contains_expected_execstart() {
2804        let config = SystemdServiceConfig {
2805            service_name: "reddb".to_string(),
2806            binary_path: PathBuf::from("/usr/local/bin/red"),
2807            run_user: "reddb".to_string(),
2808            run_group: "reddb".to_string(),
2809            data_path: reddb_file::default_service_database_path(),
2810            router_bind_addr: None,
2811            grpc_bind_addr: Some("0.0.0.0:55055".to_string()),
2812            http_bind_addr: None,
2813        };
2814
2815        let unit = render_systemd_unit(&config);
2816        assert!(unit.contains("ExecStart=/usr/local/bin/red server --path /var/lib/reddb/data.rdb --grpc-bind 0.0.0.0:55055"));
2817        assert!(unit.contains("ReadWritePaths=/var/lib/reddb"));
2818    }
2819
2820    #[test]
2821    fn systemd_service_config_derives_paths() {
2822        let config = SystemdServiceConfig {
2823            service_name: "reddb-api".to_string(),
2824            binary_path: PathBuf::from("/usr/local/bin/red"),
2825            run_user: "reddb".to_string(),
2826            run_group: "reddb".to_string(),
2827            data_path: PathBuf::from("/srv/reddb/live/data.rdb"),
2828            router_bind_addr: None,
2829            grpc_bind_addr: None,
2830            http_bind_addr: Some("127.0.0.1:5000".to_string()),
2831        };
2832
2833        assert_eq!(config.data_dir(), PathBuf::from("/srv/reddb/live"));
2834        assert_eq!(
2835            config.unit_path(),
2836            PathBuf::from("/etc/systemd/system/reddb-api.service")
2837        );
2838    }
2839
2840    #[test]
2841    fn render_systemd_unit_supports_dual_transport() {
2842        let config = SystemdServiceConfig {
2843            service_name: "reddb".to_string(),
2844            binary_path: PathBuf::from("/usr/local/bin/red"),
2845            run_user: "reddb".to_string(),
2846            run_group: "reddb".to_string(),
2847            data_path: reddb_file::default_service_database_path(),
2848            router_bind_addr: None,
2849            grpc_bind_addr: Some("0.0.0.0:55055".to_string()),
2850            http_bind_addr: Some("0.0.0.0:5000".to_string()),
2851        };
2852
2853        let unit = render_systemd_unit(&config);
2854        assert!(unit.contains("--grpc-bind 0.0.0.0:55055"));
2855        assert!(unit.contains("--http-bind 0.0.0.0:5000"));
2856    }
2857
2858    #[test]
2859    fn render_systemd_unit_supports_router_mode() {
2860        let config = SystemdServiceConfig {
2861            service_name: "reddb".to_string(),
2862            binary_path: PathBuf::from("/usr/local/bin/red"),
2863            run_user: "reddb".to_string(),
2864            run_group: "reddb".to_string(),
2865            data_path: reddb_file::default_service_database_path(),
2866            router_bind_addr: Some(DEFAULT_ROUTER_BIND_ADDR.to_string()),
2867            grpc_bind_addr: None,
2868            http_bind_addr: None,
2869        };
2870
2871        let unit = render_systemd_unit(&config);
2872        assert!(unit.contains("--bind 127.0.0.1:5050"));
2873        assert!(!unit.contains("--grpc-bind"));
2874        assert!(!unit.contains("--http-bind"));
2875    }
2876
2877    #[test]
2878    fn explicit_bind_collision_is_fatal() {
2879        let held = TcpListener::bind("127.0.0.1:0").expect("hold test port");
2880        let addr = held.local_addr().expect("held addr").to_string();
2881        let mut readiness = TransportReadiness::default();
2882
2883        let error = bind_listener_for_startup(&mut readiness, "http", &addr, true).unwrap_err();
2884
2885        assert!(error.contains("explicit http listener bind"));
2886        assert_eq!(readiness.active.len(), 0);
2887        assert_eq!(readiness.failed.len(), 1);
2888        assert!(readiness.failed[0].explicit);
2889        assert_eq!(readiness.failed[0].bind_addr, addr);
2890    }
2891
2892    // ---------- Issue #663 — `--no-auth` / `--dev` ----------
2893
2894    // Env access in tests is process-global; serialise the two
2895    // `--no-auth` tests so the REDDB_USERNAME / REDDB_PASSWORD pair
2896    // one of them sets cannot leak into the other under cargo's
2897    // default parallel runner.
2898    fn no_auth_env_lock() -> &'static std::sync::Mutex<()> {
2899        static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
2900        LOCK.get_or_init(|| std::sync::Mutex::new(()))
2901    }
2902
2903    #[test]
2904    fn server_options_preserve_explicit_disk_residency() {
2905        let _guard = no_auth_env_lock().lock().unwrap();
2906        let mut config = no_auth_test_config(true);
2907        assert!(!config.to_db_options().unwrap().bounded_disk_residency);
2908        config.bounded_disk_residency = true;
2909        assert!(config.to_db_options().unwrap().bounded_disk_residency);
2910    }
2911
2912    fn no_auth_test_config(no_auth: bool) -> ServerCommandConfig {
2913        ServerCommandConfig {
2914            path: None,
2915            router_bind_addr: Some(DEFAULT_ROUTER_BIND_ADDR.to_string()),
2916            router_bind_explicit: false,
2917            grpc_bind_addr: None,
2918            grpc_bind_explicit: false,
2919            grpc_tls_bind_addr: None,
2920            grpc_tls_cert: None,
2921            grpc_tls_key: None,
2922            grpc_tls_client_ca: None,
2923            http_bind_addr: None,
2924            http_bind_explicit: false,
2925            http_tls_bind_addr: None,
2926            http_tls_cert: None,
2927            http_tls_key: None,
2928            http_tls_client_ca: None,
2929            wire_bind_addr: None,
2930            wire_bind_explicit: false,
2931            wire_tls_bind_addr: None,
2932            wire_tls_cert: None,
2933            wire_tls_key: None,
2934            pg_bind_addr: None,
2935            create_if_missing: true,
2936            bounded_disk_residency: false,
2937            read_only: false,
2938            role: "standalone".to_string(),
2939            primary_addr: None,
2940            storage_profile: StorageProfileSelection::embedded_single_file(),
2941            auth: false,
2942            require_auth: false,
2943            // Operator-set `--vault`: `--no-auth` must override this
2944            // alongside REDDB_USERNAME/PASSWORD.
2945            vault: true,
2946            no_auth,
2947            workers: None,
2948            telemetry: None,
2949            http_limits_cli: crate::server::HttpLimitsCliInput::default(),
2950            ui: false,
2951            ui_dir: None,
2952            bootstrap: BootstrapConfig::default(),
2953        }
2954    }
2955
2956    #[test]
2957    fn no_auth_flag_disables_every_auth_knob_and_stamps_metadata() {
2958        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
2959        // Pre-existing env that *would* turn auth on if `--no-auth`
2960        // weren't the last word. The acceptance criterion is that
2961        // the flag wins over env.
2962        // SAFETY: serialised by `no_auth_env_lock` above.
2963        unsafe {
2964            std::env::set_var("REDDB_USERNAME", "admin");
2965            std::env::set_var("REDDB_PASSWORD", "hunter2");
2966        }
2967        let config = no_auth_test_config(true);
2968        let options = config.to_db_options().expect("to_db_options");
2969
2970        assert!(no_auth_active(&options), "metadata should be stamped");
2971        assert!(!options.auth.enabled, "auth.enabled must be forced off");
2972        assert!(
2973            !options.auth.require_auth,
2974            "require_auth must be forced off"
2975        );
2976        assert!(
2977            !options.auth.vault_enabled,
2978            "vault_enabled must be forced off (overrides --vault)"
2979        );
2980        assert_eq!(
2981            options.metadata.get(NO_AUTH_META).map(String::as_str),
2982            Some("true"),
2983        );
2984
2985        // SAFETY: serialised by `no_auth_env_lock` above.
2986        unsafe {
2987            std::env::remove_var("REDDB_USERNAME");
2988            std::env::remove_var("REDDB_PASSWORD");
2989        }
2990    }
2991
2992    #[test]
2993    fn default_behaviour_without_no_auth_flag_is_unchanged() {
2994        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
2995        let config = no_auth_test_config(false);
2996        let options = config.to_db_options().expect("to_db_options");
2997
2998        assert!(
2999            !no_auth_active(&options),
3000            "default boot must not be marked no-auth"
3001        );
3002        assert!(
3003            options.metadata.get(NO_AUTH_META).is_none(),
3004            "metadata key must be absent when flag is off"
3005        );
3006        // `--vault` should still take effect when `--no-auth` is not set.
3007        assert!(options.auth.vault_enabled);
3008    }
3009
3010    #[test]
3011    fn no_auth_active_blocks_bootstrap_from_env() {
3012        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3013        // SAFETY: serialised by `no_auth_env_lock` above. The pair
3014        // would normally cause `AuthStore::bootstrap_from_env` to
3015        // create an admin; the boot pipeline must suppress that call
3016        // whenever `no_auth_active` is true.
3017        unsafe {
3018            std::env::set_var("REDDB_USERNAME", "admin");
3019            std::env::set_var("REDDB_PASSWORD", "hunter2");
3020        }
3021
3022        let options = no_auth_test_config(true)
3023            .to_db_options()
3024            .expect("to_db_options");
3025
3026        // Mirror the exact branch in `build_runtime_with_telemetry`:
3027        // build a non-vault AuthStore from `options.auth`, then call
3028        // `bootstrap_from_env` *only* when the no-auth gate is off.
3029        let auth_store = AuthStore::new(options.auth.clone());
3030        if !no_auth_active(&options) {
3031            auth_store.bootstrap_from_env();
3032        }
3033
3034        assert!(
3035            auth_store.needs_bootstrap(),
3036            "no admin user must be bootstrapped under --no-auth even with REDDB_USERNAME/PASSWORD set"
3037        );
3038
3039        // SAFETY: serialised by `no_auth_env_lock` above.
3040        unsafe {
3041            std::env::remove_var("REDDB_USERNAME");
3042            std::env::remove_var("REDDB_PASSWORD");
3043        }
3044    }
3045
3046    // ---------- Issue #650 — bootstrap presets ----------
3047
3048    // Preset tests mutate process-global env (`REDDB_PRESET`,
3049    // `REDDB_USERNAME`, `REDDB_PASSWORD`) and the global tracing
3050    // subscriber. Share the no_auth lock so they don't race with each
3051    // other or with the --no-auth tests above.
3052    fn clear_preset_env() {
3053        // SAFETY: callers hold `no_auth_env_lock()`.
3054        unsafe {
3055            std::env::remove_var(BOOTSTRAP_PRESET_ENV);
3056            std::env::remove_var(PRESET_ENV);
3057            std::env::remove_var("REDDB_BOOTSTRAP_MANIFEST");
3058            std::env::remove_var("REDDB_AUTH");
3059            std::env::remove_var("REDDB_REQUIRE_AUTH");
3060            std::env::remove_var("REDDB_NO_AUTH");
3061            std::env::remove_var("REDDB_DEV");
3062            std::env::remove_var("REDDB_VAULT");
3063            std::env::remove_var("REDDB_USERNAME");
3064            std::env::remove_var("REDDB_PASSWORD");
3065            std::env::remove_var("REDDB_USERNAME_FILE");
3066            std::env::remove_var("REDDB_PASSWORD_FILE");
3067            std::env::remove_var("REDDB_CLOUD_HEAD_ADMIN");
3068            std::env::remove_var("REDDB_CLOUD_HEAD_ADMIN_PASSWORD");
3069            std::env::remove_var("REDDB_CLOUD_HEAD_ADMIN_PASSWORD_FILE");
3070            std::env::remove_var("REDDB_CUSTOMER_ADMIN");
3071            std::env::remove_var("REDDB_CUSTOMER_ADMIN_PASSWORD");
3072            std::env::remove_var("REDDB_CUSTOMER_ADMIN_PASSWORD_FILE");
3073        }
3074    }
3075
3076    fn clear_backup_env() {
3077        // SAFETY: callers hold `no_auth_env_lock()`.
3078        unsafe {
3079            std::env::remove_var("REDDB_BACKUP_S3_ENDPOINT");
3080            std::env::remove_var("REDDB_BACKUP_S3_BUCKET");
3081            std::env::remove_var("REDDB_BACKUP_S3_PREFIX");
3082            std::env::remove_var("REDDB_BACKUP_S3_ACCESS_KEY_ID");
3083            std::env::remove_var("REDDB_BACKUP_S3_SECRET_ACCESS_KEY");
3084            std::env::remove_var("REDDB_BACKUP_S3_REGION");
3085            std::env::remove_var("REDDB_BACKUP_CHECKPOINT_INTERVAL_SECS");
3086            std::env::remove_var("REDDB_BACKUP_WAL_FLUSH_INTERVAL_SECS");
3087            std::env::remove_var("REDDB_BACKUP_PAUSE_ON_LAG_SECS");
3088        }
3089    }
3090
3091    fn fresh_runtime_and_store() -> (RedDBRuntime, Arc<AuthStore>) {
3092        let runtime = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime");
3093        let auth_store = Arc::new(AuthStore::new(crate::auth::AuthConfig::default()));
3094        (runtime, auth_store)
3095    }
3096
3097    #[test]
3098    fn auth_env_knobs_enable_auth_require_auth_and_vault() {
3099        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3100        clear_preset_env();
3101        // SAFETY: env serialised by `no_auth_env_lock`.
3102        unsafe {
3103            std::env::set_var("REDDB_AUTH", "true");
3104            std::env::set_var("REDDB_REQUIRE_AUTH", "true");
3105            std::env::set_var("REDDB_VAULT", "true");
3106        }
3107
3108        let mut config = no_auth_test_config(false);
3109        config.vault = false;
3110        let options = config.to_db_options().expect("to_db_options");
3111
3112        assert!(options.auth.enabled);
3113        assert!(options.auth.require_auth);
3114        assert!(options.auth.vault_enabled);
3115
3116        clear_preset_env();
3117    }
3118
3119    #[test]
3120    fn production_and_cloud_presets_force_auth_require_auth_and_vault() {
3121        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3122        clear_preset_env();
3123
3124        for preset in [PRESET_PRODUCTION, PRESET_CLOUD] {
3125            let mut config = no_auth_test_config(false);
3126            config.vault = false;
3127            config.bootstrap.preset = Some(preset.to_string());
3128
3129            let options = config.to_db_options().expect("to_db_options");
3130            assert!(options.auth.enabled, "{preset} should enable auth");
3131            assert!(
3132                options.auth.require_auth,
3133                "{preset} should require authenticated requests"
3134            );
3135            assert!(options.auth.vault_enabled, "{preset} should enable vault");
3136            assert!(!no_auth_active(&options));
3137        }
3138
3139        clear_preset_env();
3140    }
3141
3142    #[test]
3143    fn no_auth_env_overrides_preset_forced_auth() {
3144        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3145        clear_preset_env();
3146        // SAFETY: env serialised by `no_auth_env_lock`.
3147        unsafe {
3148            std::env::set_var("REDDB_NO_AUTH", "true");
3149            std::env::set_var(BOOTSTRAP_PRESET_ENV, PRESET_CLOUD);
3150        }
3151
3152        let mut config = no_auth_test_config(false);
3153        config.auth = true;
3154        config.require_auth = true;
3155        let options = config.to_db_options().expect("to_db_options");
3156
3157        assert!(no_auth_active(&options));
3158        assert!(!options.auth.enabled);
3159        assert!(!options.auth.require_auth);
3160        assert!(!options.auth.vault_enabled);
3161
3162        clear_preset_env();
3163    }
3164
3165    #[test]
3166    fn simple_preset_is_default_and_persists_state() {
3167        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3168        clear_preset_env();
3169
3170        let (runtime, auth_store) = fresh_runtime_and_store();
3171        apply_preset(&runtime, &auth_store).expect("simple preset applies cleanly");
3172
3173        // No admin was created — `simple` is anonymous-friendly.
3174        assert!(
3175            auth_store.needs_bootstrap(),
3176            "simple preset must not create an admin"
3177        );
3178
3179        // Bootstrap state persisted so the next boot is a no-op.
3180        let store = runtime.db().store();
3181        let completed = store
3182            .get_config(BOOTSTRAP_COMPLETED_KEY)
3183            .expect("completed key persisted");
3184        assert!(matches!(completed, reddb_types::Value::Boolean(true)));
3185        let preset = store
3186            .get_config(BOOTSTRAP_PRESET_KEY)
3187            .expect("preset key persisted");
3188        match preset {
3189            reddb_types::Value::Text(s) => assert_eq!(s.as_ref(), PRESET_SIMPLE),
3190            other => panic!("expected Text(simple), got {other:?}"),
3191        }
3192        assert!(
3193            store.get_config(BOOTSTRAP_FIRST_ADMIN_KEY).is_none(),
3194            "simple preset must not record a first admin"
3195        );
3196
3197        clear_preset_env();
3198    }
3199
3200    #[test]
3201    fn production_preset_creates_first_admin_with_allow_all_policy() {
3202        use crate::auth::policies::{EvalContext, ResourceRef};
3203        use crate::auth::UserId;
3204
3205        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3206        clear_preset_env();
3207        // SAFETY: env serialised by `no_auth_env_lock`.
3208        unsafe {
3209            std::env::set_var(PRESET_ENV, PRESET_PRODUCTION);
3210            std::env::set_var("REDDB_USERNAME", "ops");
3211            std::env::set_var("REDDB_PASSWORD", "hunter2");
3212        }
3213
3214        let (runtime, auth_store) = fresh_runtime_and_store();
3215        apply_preset(&runtime, &auth_store).expect("production preset applies cleanly");
3216
3217        // Admin exists and the auth store is sealed.
3218        assert!(
3219            !auth_store.needs_bootstrap(),
3220            "production preset must seal bootstrap"
3221        );
3222        let users = auth_store.list_users();
3223        assert_eq!(users.len(), 1);
3224        let admin = &users[0];
3225        assert_eq!(admin.username, "ops");
3226        assert!(
3227            admin.tenant_id.is_none(),
3228            "first admin must be platform-scoped (tenant=None)"
3229        );
3230
3231        // Allow-all policy was installed and attached to the first admin.
3232        let policy = auth_store
3233            .get_policy(FIRST_ADMIN_ALLOW_ALL_POLICY)
3234            .expect("allow-all policy installed");
3235        assert!(!policy.statements.is_empty());
3236
3237        // Verify policy-derived authority via the policy evaluator —
3238        // not a bypass. Any action on any resource must Allow.
3239        let actor = UserId::platform("ops");
3240        let ctx = EvalContext {
3241            principal_tenant: None,
3242            current_tenant: None,
3243            peer_ip: None,
3244            mfa_present: false,
3245            now_ms: 1_700_000_000_000,
3246            principal_is_admin_role: true,
3247            principal_is_platform_scoped: true,
3248        };
3249        let arbitrary_resource = ResourceRef::new("config", "red.config.audit.enabled");
3250        assert!(
3251            auth_store.check_policy_authz(&actor, "config:write", &arbitrary_resource, &ctx),
3252            "allow-all policy must grant arbitrary actions via the evaluator"
3253        );
3254
3255        // Persisted state records the first admin id.
3256        let store = runtime.db().store();
3257        match store
3258            .get_config(BOOTSTRAP_FIRST_ADMIN_KEY)
3259            .expect("first_admin_id persisted")
3260        {
3261            reddb_types::Value::Text(s) => assert_eq!(s.as_ref(), "ops"),
3262            other => panic!("expected Text(ops), got {other:?}"),
3263        }
3264        match store.get_config(BOOTSTRAP_PRESET_KEY).unwrap() {
3265            reddb_types::Value::Text(s) => assert_eq!(s.as_ref(), PRESET_PRODUCTION),
3266            other => panic!("expected Text(production), got {other:?}"),
3267        }
3268
3269        clear_preset_env();
3270    }
3271
3272    #[test]
3273    fn bootstrap_preset_env_takes_precedence_over_legacy_preset_env() {
3274        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3275        clear_preset_env();
3276        // SAFETY: env serialised by `no_auth_env_lock`.
3277        unsafe {
3278            std::env::set_var(BOOTSTRAP_PRESET_ENV, PRESET_REGULATED);
3279            std::env::set_var(PRESET_ENV, PRESET_SIMPLE);
3280        }
3281
3282        let options = no_auth_test_config(false)
3283            .to_db_options()
3284            .expect("regulated options");
3285        assert!(
3286            options.control_events.compliance_mode,
3287            "canonical REDDB_BOOTSTRAP_PRESET should win over REDDB_PRESET"
3288        );
3289        assert!(options.query_audit.enabled);
3290
3291        clear_preset_env();
3292    }
3293
3294    #[test]
3295    fn cloud_preset_creates_system_head_and_customer_admins() {
3296        use crate::auth::policies::{EvalContext, ResourceRef};
3297        use crate::auth::UserId;
3298
3299        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3300        clear_preset_env();
3301        // SAFETY: env serialised by `no_auth_env_lock`.
3302        unsafe {
3303            std::env::set_var(BOOTSTRAP_PRESET_ENV, PRESET_CLOUD);
3304            std::env::set_var("REDDB_CLOUD_HEAD_ADMIN", "head");
3305            std::env::set_var("REDDB_CLOUD_HEAD_ADMIN_PASSWORD", "head-pass");
3306            std::env::set_var("REDDB_CUSTOMER_ADMIN", "customer");
3307            std::env::set_var("REDDB_CUSTOMER_ADMIN_PASSWORD", "customer-pass");
3308        }
3309
3310        let (runtime, auth_store) = fresh_runtime_and_store();
3311        apply_preset(&runtime, &auth_store).expect("cloud preset applies cleanly");
3312
3313        let head = auth_store
3314            .get_user(None, "head")
3315            .expect("head admin should exist");
3316        assert_eq!(head.tenant_id, None);
3317        let customer = auth_store
3318            .get_user(None, "customer")
3319            .expect("customer admin should exist");
3320        assert_eq!(customer.tenant_id, None);
3321
3322        let ctx = EvalContext {
3323            principal_tenant: None,
3324            current_tenant: None,
3325            peer_ip: None,
3326            mfa_present: false,
3327            now_ms: 1_700_000_000_000,
3328            principal_is_admin_role: true,
3329            principal_is_platform_scoped: true,
3330        };
3331        assert!(auth_store.check_policy_authz(
3332            &UserId::platform("customer"),
3333            "config:write",
3334            &ResourceRef::new("config", "red.config.customer.enabled"),
3335            &ctx,
3336        ));
3337        assert!(
3338            auth_store.check_policy_authz(
3339                &UserId::platform("head"),
3340                "config:write",
3341                &ResourceRef::new("config", "red.config.cloud.enabled"),
3342                &ctx,
3343            ),
3344            "cloud head keeps allow-all authority over managed cloud config"
3345        );
3346        assert!(
3347            !auth_store.check_policy_authz(
3348                &UserId::platform("customer"),
3349                "config:write",
3350                &ResourceRef::new("config", "red.config.cloud.enabled"),
3351                &ctx,
3352            ),
3353            "cloud customer must be denied managed cloud config writes"
3354        );
3355        assert!(
3356            !auth_store.check_policy_authz(
3357                &UserId::platform("customer"),
3358                "policy:drop",
3359                &ResourceRef::new("policy", CLOUD_PROTECT_MANAGED_POLICY),
3360                &ctx,
3361            ),
3362            "cloud customer must be denied mutations of the managed guardrail policy"
3363        );
3364
3365        assert!(auth_store.get_user(None, "head").is_some());
3366        assert!(auth_store
3367            .get_policy(CLOUD_PROTECT_MANAGED_POLICY)
3368            .is_some());
3369        assert!(runtime
3370            .config_registry()
3371            .get_active(CLOUD_CONFIG_NAMESPACE)
3372            .is_some());
3373
3374        let store = runtime.db().store();
3375        match store
3376            .get_config(BOOTSTRAP_FIRST_ADMIN_KEY)
3377            .expect("head admin id persisted")
3378        {
3379            reddb_types::Value::Text(s) => assert_eq!(s.as_ref(), "head"),
3380            other => panic!("expected Text(head), got {other:?}"),
3381        }
3382        match store.get_config(BOOTSTRAP_PRESET_KEY).unwrap() {
3383            reddb_types::Value::Text(s) => assert_eq!(s.as_ref(), PRESET_CLOUD),
3384            other => panic!("expected Text(cloud), got {other:?}"),
3385        }
3386
3387        clear_preset_env();
3388    }
3389
3390    #[test]
3391    fn cloud_preset_customer_cannot_disable_head_admin_or_drop_guardrail_policy() {
3392        use crate::auth::Role;
3393        use crate::runtime::mvcc::{clear_current_auth_identity, set_current_auth_identity};
3394
3395        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3396        clear_preset_env();
3397
3398        let bootstrap = BootstrapConfig {
3399            preset: Some(PRESET_CLOUD.to_string()),
3400            cloud_head_admin: Some("red_admin".to_string()),
3401            cloud_head_admin_password: Some("head-pass".to_string()),
3402            customer_admin: Some("admin".to_string()),
3403            customer_admin_password: Some("customer-pass".to_string()),
3404            ..BootstrapConfig::default()
3405        };
3406        let (runtime, auth_store) = fresh_runtime_and_store();
3407        apply_preset_from_config(&runtime, &auth_store, &bootstrap)
3408            .expect("cloud preset applies cleanly");
3409        runtime.set_auth_store(Arc::clone(&auth_store));
3410
3411        set_current_auth_identity("admin".to_string(), Role::Admin);
3412        let disable_head = runtime.execute_query("ALTER USER red_admin DISABLE");
3413        let drop_guardrail =
3414            runtime.execute_query(&format!("DROP POLICY '{}'", CLOUD_PROTECT_MANAGED_POLICY));
3415        let create_user = runtime.execute_query("CREATE USER app_user WITH PASSWORD 'p' ROLE read");
3416        let disable_user = runtime.execute_query("ALTER USER app_user DISABLE");
3417        clear_current_auth_identity();
3418
3419        let disable_head_err = disable_head.expect_err("customer admin must not disable red_admin");
3420        assert!(
3421            disable_head_err.to_string().contains("user:disable"),
3422            "error should name the denied lifecycle action: {disable_head_err}"
3423        );
3424        assert!(
3425            auth_store
3426                .get_user(None, "red_admin")
3427                .expect("red_admin should still exist")
3428                .enabled,
3429            "denied mutation must leave red_admin enabled"
3430        );
3431
3432        let drop_guardrail_err =
3433            drop_guardrail.expect_err("customer admin must not drop cloud guardrail policy");
3434        assert!(
3435            drop_guardrail_err.to_string().contains("managed policy"),
3436            "error should name the managed policy guardrail: {drop_guardrail_err}"
3437        );
3438        assert!(auth_store
3439            .get_policy(CLOUD_PROTECT_MANAGED_POLICY)
3440            .is_some());
3441
3442        create_user.expect("customer admin should retain normal create-user authority");
3443        disable_user.expect("customer admin should retain normal user-disable authority");
3444        assert!(
3445            !auth_store
3446                .get_user(None, "app_user")
3447                .expect("app_user should exist")
3448                .enabled,
3449            "normal capability should still apply outside the reserved head admin"
3450        );
3451
3452        clear_preset_env();
3453    }
3454
3455    #[test]
3456    fn cloud_preset_cli_admin_alias_wins_over_cloud_env_password() {
3457        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3458        clear_preset_env();
3459        // SAFETY: env serialised by `no_auth_env_lock`.
3460        unsafe {
3461            std::env::set_var("REDDB_CLOUD_HEAD_ADMIN_PASSWORD", "env-head-pass");
3462        }
3463
3464        let bootstrap = BootstrapConfig {
3465            preset: Some(PRESET_CLOUD.to_string()),
3466            admin_username: Some("head".to_string()),
3467            admin_password: Some("cli-head-pass".to_string()),
3468            customer_admin: Some("customer".to_string()),
3469            customer_admin_password: Some("customer-pass".to_string()),
3470            ..BootstrapConfig::default()
3471        };
3472        let (runtime, auth_store) = fresh_runtime_and_store();
3473        apply_preset_from_config(&runtime, &auth_store, &bootstrap)
3474            .expect("cloud preset applies cleanly");
3475
3476        auth_store
3477            .authenticate("head", "cli-head-pass")
3478            .expect("CLI alias password should win");
3479        assert!(
3480            auth_store.authenticate("head", "env-head-pass").is_err(),
3481            "cloud-specific env password must not beat CLI alias"
3482        );
3483
3484        clear_preset_env();
3485    }
3486
3487    #[test]
3488    fn bootstrap_intent_manifest_matches_cloud_flag_path() {
3489        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3490        clear_preset_env();
3491
3492        let manifest_dir = std::env::current_dir()
3493            .expect("current dir")
3494            .join(".red/tmp/bootstrap-manifest-tests");
3495        std::fs::create_dir_all(&manifest_dir).expect("create manifest test dir");
3496        let unique = format!(
3497            "{}-{}",
3498            std::process::id(),
3499            std::time::SystemTime::now()
3500                .duration_since(std::time::UNIX_EPOCH)
3501                .unwrap_or_default()
3502                .as_millis()
3503        );
3504        let head_password = manifest_dir.join(format!("head-{unique}.secret"));
3505        let customer_password = manifest_dir.join(format!("customer-{unique}.secret"));
3506        let manifest_path = manifest_dir.join(format!("intent-{unique}.json"));
3507        std::fs::write(&head_password, "head-pass\n").expect("write head secret");
3508        std::fs::write(&customer_password, "customer-pass\n").expect("write customer secret");
3509        std::fs::write(
3510            &manifest_path,
3511            format!(
3512                r#"{{
3513                    "bootstrap": {{
3514                        "preset": "cloud",
3515                        "cloud_head_admin": {{
3516                            "username": "head",
3517                            "password_file": "{}"
3518                        }},
3519                        "customer_admin": {{
3520                            "username": "customer",
3521                            "password_file": "{}"
3522                        }}
3523                    }}
3524                }}"#,
3525                head_password.display(),
3526                customer_password.display()
3527            ),
3528        )
3529        .expect("write manifest");
3530
3531        let mut config = no_auth_test_config(false);
3532        config.bootstrap.manifest = Some(manifest_path.clone());
3533        let options = config.to_db_options().expect("manifest options");
3534        assert!(options.auth.enabled);
3535        assert!(options.auth.require_auth);
3536        assert!(options.auth.vault_enabled);
3537
3538        let (runtime, auth_store) = fresh_runtime_and_store();
3539        apply_preset_from_config(&runtime, &auth_store, &config.bootstrap)
3540            .expect("manifest intent applies cleanly");
3541
3542        auth_store
3543            .authenticate("head", "head-pass")
3544            .expect("head password comes from file");
3545        auth_store
3546            .authenticate("customer", "customer-pass")
3547            .expect("customer password comes from file");
3548        assert!(auth_store.get_user(None, "head").is_some());
3549        assert!(auth_store.get_user(None, "customer").is_some());
3550        assert!(auth_store
3551            .get_policy(CLOUD_PROTECT_MANAGED_POLICY)
3552            .is_some());
3553        match runtime
3554            .db()
3555            .store()
3556            .get_config(BOOTSTRAP_PRESET_KEY)
3557            .expect("preset key persisted")
3558        {
3559            reddb_types::Value::Text(s) => assert_eq!(s.as_ref(), PRESET_CLOUD),
3560            other => panic!("expected Text(cloud), got {other:?}"),
3561        }
3562
3563        apply_preset_from_config(&runtime, &auth_store, &config.bootstrap)
3564            .expect("second boot is idempotent");
3565
3566        let _ = std::fs::remove_file(&manifest_path);
3567        let _ = std::fs::remove_file(&head_password);
3568        let _ = std::fs::remove_file(&customer_password);
3569        clear_preset_env();
3570    }
3571
3572    #[test]
3573    fn regulated_preset_enables_query_audit_infrastructure_without_rules() {
3574        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3575        clear_preset_env();
3576        // SAFETY: env serialised by `no_auth_env_lock`.
3577        unsafe {
3578            std::env::set_var(PRESET_ENV, PRESET_REGULATED);
3579        }
3580
3581        let (runtime, auth_store) = fresh_runtime_and_store();
3582        apply_preset(&runtime, &auth_store).expect("regulated preset applies cleanly");
3583
3584        assert!(runtime.query_audit().is_enabled());
3585        assert!(runtime.query_audit().rules().is_empty());
3586        assert!(
3587            runtime
3588                .db()
3589                .store()
3590                .get_collection(crate::runtime::query_audit::QUERY_AUDIT_COLLECTION)
3591                .is_some(),
3592            "regulated preset should create the query-audit stream"
3593        );
3594
3595        runtime
3596            .execute_query("CREATE TABLE docs (id INT)")
3597            .expect("create table");
3598        runtime
3599            .execute_query("INSERT INTO docs (id) VALUES (1)")
3600            .expect("insert");
3601        runtime.execute_query("SELECT * FROM docs").expect("select");
3602        let rows = runtime
3603            .db()
3604            .store()
3605            .get_collection(crate::runtime::query_audit::QUERY_AUDIT_COLLECTION)
3606            .expect("query audit collection")
3607            .query_all(|_| true);
3608        assert!(
3609            rows.is_empty(),
3610            "regulated preset must not globally audit every query"
3611        );
3612
3613        clear_preset_env();
3614    }
3615
3616    #[test]
3617    fn managed_backup_env_rejects_primary_replica_single_file_storage() {
3618        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3619        clear_backup_env();
3620        // SAFETY: env serialised by `no_auth_env_lock`.
3621        unsafe {
3622            std::env::set_var("REDDB_BACKUP_S3_ENDPOINT", "https://s3.example.test");
3623            std::env::set_var("REDDB_BACKUP_S3_BUCKET", "reddb");
3624            std::env::set_var("REDDB_BACKUP_S3_PREFIX", "clusters/prod");
3625            std::env::set_var("REDDB_BACKUP_S3_ACCESS_KEY_ID", "AK");
3626            std::env::set_var("REDDB_BACKUP_S3_SECRET_ACCESS_KEY", "SK");
3627        }
3628
3629        let mut config = no_auth_test_config(false);
3630        config.role = "primary".to_string();
3631        config.storage_profile = crate::storage::StorageDeployPreset::PrimaryReplicaDev.selection();
3632
3633        let err = config.to_db_options().unwrap_err();
3634        assert!(err.contains("managed backup"), "got: {err}");
3635        assert!(err.contains("operational-directory"), "got: {err}");
3636
3637        clear_backup_env();
3638    }
3639
3640    #[test]
3641    fn regulated_preset_installs_managed_evidence_guardrails_end_to_end() {
3642        use crate::auth::policies::{EvalContext, Policy, ResourceRef};
3643        use crate::auth::store::PrincipalRef;
3644        use crate::auth::{Role, UserId};
3645        use crate::runtime::mvcc::{clear_current_auth_identity, set_current_auth_identity};
3646        use reddb_types::Value;
3647
3648        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3649        clear_preset_env();
3650        // SAFETY: env serialised by `no_auth_env_lock`.
3651        unsafe {
3652            std::env::set_var(PRESET_ENV, PRESET_REGULATED);
3653        }
3654
3655        let options = no_auth_test_config(false)
3656            .to_db_options()
3657            .expect("regulated options");
3658        assert!(
3659            options.control_events.compliance_mode,
3660            "regulated preset must enable fail-closed control evidence before runtime boot"
3661        );
3662        assert!(
3663            options.query_audit.enabled && options.query_audit.rules.is_empty(),
3664            "regulated preset must enable query-audit infrastructure without global rules"
3665        );
3666
3667        let runtime = RedDBRuntime::with_options(options).expect("runtime");
3668        let auth_store = Arc::new(AuthStore::new(crate::auth::AuthConfig::default()));
3669        apply_preset(&runtime, &auth_store).expect("regulated preset applies cleanly");
3670        runtime.set_auth_store(Arc::clone(&auth_store));
3671
3672        assert!(runtime.control_events_require_persistence());
3673        assert!(runtime.query_audit().is_enabled());
3674        assert!(runtime.query_audit().rules().is_empty());
3675        assert!(auth_store
3676            .get_policy(REGULATED_PROTECT_MANAGED_POLICY)
3677            .is_some());
3678
3679        let managed_policy = runtime
3680            .config_registry()
3681            .get_active(REGULATED_PROTECT_MANAGED_POLICY)
3682            .expect("regulated managed policy registry entry");
3683        assert!(managed_policy.managed);
3684        assert_eq!(managed_policy.resource_type, "policy");
3685        assert!(
3686            runtime
3687                .config_registry()
3688                .get_active(REGULATED_AUDIT_CONFIG_NAMESPACE)
3689                .expect("regulated audit config namespace")
3690                .managed
3691        );
3692
3693        let registry_rows = runtime
3694            .execute_query(&format!(
3695                "SELECT id, managed FROM red.registry WHERE id = '{}'",
3696                REGULATED_PROTECT_MANAGED_POLICY
3697            ))
3698            .expect("red.registry query");
3699        assert_eq!(registry_rows.result.records.len(), 1);
3700        assert_eq!(
3701            registry_rows.result.records[0].get("managed"),
3702            Some(&Value::Boolean(true))
3703        );
3704
3705        let managed_policy_rows = runtime
3706            .execute_query(&format!(
3707                "SELECT policy_id FROM red.managed_policies WHERE policy_id = '{}'",
3708                REGULATED_PROTECT_MANAGED_POLICY
3709            ))
3710            .expect("red.managed_policies query");
3711        assert_eq!(managed_policy_rows.result.records.len(), 1);
3712
3713        let capability_rows = runtime
3714            .execute_query(
3715                "SELECT action FROM red.control_capabilities WHERE action = 'evidence:export'",
3716            )
3717            .expect("red.control_capabilities query");
3718        assert_eq!(capability_rows.result.records.len(), 1);
3719
3720        auth_store
3721            .create_user("alice", "p", Role::Admin)
3722            .expect("create ordinary admin");
3723        let allow_all = Policy::from_json_str(
3724            r#"{
3725                "id": "alice-allow-all",
3726                "version": 1,
3727                "statements": [{
3728                    "effect": "allow",
3729                    "actions": ["*"],
3730                    "resources": ["*"]
3731                }]
3732            }"#,
3733        )
3734        .expect("allow-all policy");
3735        auth_store.put_policy(allow_all).expect("install allow-all");
3736        auth_store
3737            .attach_policy(
3738                PrincipalRef::User(UserId::platform("alice")),
3739                "alice-allow-all",
3740            )
3741            .expect("attach allow-all");
3742        let ctx = EvalContext {
3743            principal_tenant: None,
3744            current_tenant: None,
3745            peer_ip: None,
3746            mfa_present: false,
3747            now_ms: 1_700_000_000_000,
3748            principal_is_admin_role: true,
3749            principal_is_platform_scoped: true,
3750        };
3751        assert!(
3752            !auth_store.check_policy_authz(
3753                &UserId::platform("alice"),
3754                "policy:drop",
3755                &ResourceRef::new("policy", REGULATED_PROTECT_MANAGED_POLICY),
3756                &ctx,
3757            ),
3758            "managed guardrail deny policy must be effective for ordinary admins"
3759        );
3760
3761        set_current_auth_identity("alice".to_string(), Role::Admin);
3762        let denied = runtime.execute_query(&format!(
3763            "DROP POLICY '{}'",
3764            REGULATED_PROTECT_MANAGED_POLICY
3765        ));
3766        clear_current_auth_identity();
3767        let err = denied.expect_err("managed policy guardrail must deny ordinary admin");
3768        assert!(
3769            err.to_string().contains("managed policy"),
3770            "error should name the managed guardrail: {err}"
3771        );
3772        assert!(
3773            auth_store
3774                .get_policy(REGULATED_PROTECT_MANAGED_POLICY)
3775                .is_some(),
3776            "denied mutation must leave managed policy installed"
3777        );
3778
3779        let denied_events = runtime
3780            .execute_query(&format!(
3781                "SELECT action, resource, outcome FROM red.control_events \
3782                 WHERE action = 'policy:drop' AND resource = 'policy:{}'",
3783                REGULATED_PROTECT_MANAGED_POLICY
3784            ))
3785            .expect("red.control_events denied policy drop");
3786        assert_eq!(denied_events.result.records.len(), 1);
3787        assert_eq!(
3788            denied_events.result.records[0].get("outcome"),
3789            Some(&Value::text("denied"))
3790        );
3791
3792        set_current_auth_identity("alice".to_string(), Role::Admin);
3793        let config_denied = runtime.execute_query("SET CONFIG red.config.audit.enabled = true");
3794        clear_current_auth_identity();
3795        let err = config_denied.expect_err("managed config guardrail must deny ordinary admin");
3796        assert!(
3797            err.to_string().contains("managed config"),
3798            "error should name the managed config guardrail: {err}"
3799        );
3800
3801        let denied_config_events = runtime
3802            .execute_query(
3803                "SELECT action, resource, outcome FROM red.control_events \
3804                 WHERE action = 'config:write' AND resource = 'config:red.config.audit.enabled'",
3805            )
3806            .expect("red.control_events denied config write");
3807        assert_eq!(denied_config_events.result.records.len(), 1);
3808        assert_eq!(
3809            denied_config_events.result.records[0].get("outcome"),
3810            Some(&Value::text("denied"))
3811        );
3812
3813        runtime
3814            .execute_query("CREATE TABLE regulated_docs (id INT)")
3815            .expect("create user table");
3816        runtime
3817            .execute_query("SELECT * FROM regulated_docs")
3818            .expect("select user table");
3819        let audit_rows = runtime
3820            .db()
3821            .store()
3822            .get_collection(crate::runtime::query_audit::QUERY_AUDIT_COLLECTION)
3823            .expect("query audit collection")
3824            .query_all(|_| true);
3825        assert!(
3826            audit_rows.is_empty(),
3827            "regulated preset must not globally audit data-plane queries"
3828        );
3829
3830        clear_preset_env();
3831    }
3832
3833    #[test]
3834    fn bootstrap_manifest_installs_initial_users_policies_guardrails_and_config() {
3835        use crate::auth::policies::{EvalContext, ResourceRef};
3836        use crate::auth::UserId;
3837        use reddb_types::Value;
3838
3839        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3840        clear_preset_env();
3841
3842        let manifest_dir = std::env::current_dir()
3843            .expect("current dir")
3844            .join(".red/tmp/bootstrap-manifest-tests");
3845        std::fs::create_dir_all(&manifest_dir).expect("create manifest test dir");
3846        let manifest_path = manifest_dir.join(format!(
3847            "reddb-bootstrap-manifest-{}-{}.json",
3848            std::process::id(),
3849            std::time::SystemTime::now()
3850                .duration_since(std::time::UNIX_EPOCH)
3851                .unwrap_or_default()
3852                .as_millis()
3853        ));
3854        std::fs::write(
3855            &manifest_path,
3856            r#"{
3857                "users": [
3858                    {
3859                        "username": "ops",
3860                        "password": "hunter2",
3861                        "role": "admin"
3862                    }
3863                ],
3864                "policies": [
3865                    {
3866                        "id": "bootstrap-registry-admin",
3867                        "version": 1,
3868                        "statements": [
3869                            {
3870                                "effect": "allow",
3871                                "actions": ["red.registry:*", "policy:*", "config:write", "select"],
3872                                "resources": ["registry:*", "policy:*", "config:*", "collection:docs"]
3873                            }
3874                        ]
3875                    }
3876                ],
3877                "managed_policies": [
3878                    {
3879                        "id": "managed-deny-drop",
3880                        "version": 1,
3881                        "statements": [
3882                            {
3883                                "effect": "deny",
3884                                "actions": ["policy:drop"],
3885                                "resources": ["policy:managed-deny-drop"]
3886                            }
3887                        ],
3888                        "required_resource": "policy:managed-deny-drop",
3889                        "evidence": "full"
3890                    }
3891                ],
3892                "attachments": [
3893                    {"user": "ops", "policy": "bootstrap-registry-admin"}
3894                ],
3895                "managed_config_namespaces": [
3896                    {
3897                        "id": "red.ai",
3898                        "required_action": "config:write",
3899                        "required_resource": "config:red.ai.*",
3900                        "evidence": "metadata"
3901                    }
3902                ],
3903                "config": [
3904                    {"key": "red.ai.default.provider", "value": "openai"},
3905                    {
3906                        "key": "red.ai.openai.default.secret_ref",
3907                        "secret_ref": {"collection": "red.vault", "key": "openai"}
3908                    }
3909                ],
3910                "actor": "ops"
3911            }"#,
3912        )
3913        .expect("write manifest");
3914        // SAFETY: env serialised by `no_auth_env_lock`.
3915        unsafe {
3916            std::env::set_var("REDDB_BOOTSTRAP_MANIFEST", &manifest_path);
3917        }
3918
3919        let (runtime, auth_store) = fresh_runtime_and_store();
3920        apply_preset(&runtime, &auth_store).expect("manifest applies cleanly");
3921
3922        let users = auth_store.list_users();
3923        assert_eq!(users.len(), 1);
3924        assert_eq!(users[0].username, "ops");
3925        assert!(users[0].tenant_id.is_none());
3926
3927        let actor = UserId::platform("ops");
3928        let ctx = EvalContext {
3929            principal_tenant: None,
3930            current_tenant: None,
3931            peer_ip: None,
3932            mfa_present: false,
3933            now_ms: 1_700_000_000_000,
3934            principal_is_admin_role: true,
3935            principal_is_platform_scoped: true,
3936        };
3937        // Manifest fixture pins a canonical data-plane read action.
3938        assert!(auth_store.check_policy_authz(
3939            &actor,
3940            "select",
3941            &ResourceRef::new("collection", "docs"),
3942            &ctx
3943        ));
3944
3945        let managed_policy = runtime
3946            .config_registry()
3947            .get_active("managed-deny-drop")
3948            .expect("managed policy registry entry");
3949        assert!(managed_policy.managed);
3950        assert_eq!(managed_policy.resource_type, "policy");
3951        let managed_config = runtime
3952            .config_registry()
3953            .get_active("red.ai")
3954            .expect("managed config namespace registry entry");
3955        assert!(managed_config.managed);
3956        assert_eq!(managed_config.resource_type, "config_namespace");
3957
3958        let store = runtime.db().store();
3959        match store
3960            .get_config("red.ai.default.provider")
3961            .expect("plain config persisted")
3962        {
3963            Value::Text(s) => assert_eq!(s.as_ref(), "openai"),
3964            other => panic!("expected provider text, got {other:?}"),
3965        }
3966        let Value::Json(bytes) = store
3967            .get_config("red.ai.openai.default.secret_ref")
3968            .expect("secret ref config persisted")
3969        else {
3970            panic!("secret ref must be stored as structured JSON");
3971        };
3972        let reference: crate::serde_json::Value =
3973            crate::serde_json::from_slice(&bytes).expect("secret ref json");
3974        assert_eq!(
3975            reference.get("type").and_then(|v| v.as_str()),
3976            Some("secret_ref")
3977        );
3978        assert!(
3979            !String::from_utf8_lossy(&bytes).contains("hunter2"),
3980            "manifest password must not leak into secret ref config"
3981        );
3982
3983        let completed = store
3984            .get_config(BOOTSTRAP_COMPLETED_KEY)
3985            .expect("bootstrap completion persisted");
3986        assert!(matches!(completed, Value::Boolean(true)));
3987        assert!(
3988            store
3989                .get_config("system.bootstrap.manifest.registry_entries")
3990                .is_some(),
3991            "managed registry entries must be persisted internally"
3992        );
3993
3994        std::fs::remove_file(&manifest_path).expect("remove manifest after first boot");
3995        let restored_registry = Arc::new(crate::auth::registry::ConfigRegistry::new());
3996        crate::cli::bootstrap_manifest::rehydrate_manifest_registry(&runtime, &restored_registry)
3997            .expect("registry rehydrates without manifest file");
3998        assert!(restored_registry.get_active("managed-deny-drop").is_some());
3999        assert!(restored_registry.get_active("red.ai").is_some());
4000
4001        let fresh = Arc::new(AuthStore::new(crate::auth::AuthConfig::default()));
4002        apply_preset(&runtime, &fresh).expect("re-run must not need manifest file");
4003        assert!(fresh.needs_bootstrap());
4004
4005        clear_preset_env();
4006    }
4007
4008    #[test]
4009    fn production_preset_refuses_to_start_without_password() {
4010        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
4011        clear_preset_env();
4012        // SAFETY: env serialised by `no_auth_env_lock`.
4013        unsafe {
4014            std::env::set_var(PRESET_ENV, PRESET_PRODUCTION);
4015            std::env::set_var("REDDB_USERNAME", "ops");
4016        }
4017
4018        let (runtime, auth_store) = fresh_runtime_and_store();
4019        let err = apply_preset(&runtime, &auth_store).expect_err("must reject missing password");
4020        assert!(
4021            err.contains("REDDB_PASSWORD"),
4022            "error must name the missing env: {err}"
4023        );
4024
4025        // Nothing was persisted; nothing was created.
4026        assert!(auth_store.needs_bootstrap());
4027        assert!(runtime
4028            .db()
4029            .store()
4030            .get_config(BOOTSTRAP_COMPLETED_KEY)
4031            .is_none());
4032
4033        clear_preset_env();
4034    }
4035
4036    #[test]
4037    fn re_running_production_after_first_boot_is_a_silent_skip() {
4038        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
4039        clear_preset_env();
4040        // SAFETY: env serialised by `no_auth_env_lock`.
4041        unsafe {
4042            std::env::set_var(PRESET_ENV, PRESET_PRODUCTION);
4043            std::env::set_var("REDDB_USERNAME", "ops");
4044            std::env::set_var("REDDB_PASSWORD", "hunter2");
4045        }
4046
4047        let (runtime, auth_store) = fresh_runtime_and_store();
4048        apply_preset(&runtime, &auth_store).expect("first apply");
4049        assert_eq!(auth_store.list_users().len(), 1);
4050
4051        // Second invocation: same runtime/store, same env. Must be a
4052        // no-op — no error, no duplicate admin, no duplicate policy.
4053        // We do NOT reuse `auth_store` because production sealed it; the
4054        // idempotency hinge is the persisted config key, not the auth
4055        // store's in-memory seal. Build a fresh `AuthStore` as a restart
4056        // would and confirm `apply_preset` is a silent skip.
4057        let fresh = Arc::new(AuthStore::new(crate::auth::AuthConfig::default()));
4058        apply_preset(&runtime, &fresh).expect("re-run is silent-skip");
4059        assert!(
4060            fresh.needs_bootstrap(),
4061            "re-run must not create a second admin"
4062        );
4063        assert!(
4064            fresh.get_policy(FIRST_ADMIN_ALLOW_ALL_POLICY).is_none(),
4065            "re-run must not re-install the allow-all policy on the fresh store"
4066        );
4067
4068        clear_preset_env();
4069    }
4070
4071    #[test]
4072    fn unrecognised_preset_value_is_rejected() {
4073        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
4074        clear_preset_env();
4075        // SAFETY: env serialised by `no_auth_env_lock`.
4076        unsafe {
4077            std::env::set_var(PRESET_ENV, "weird");
4078        }
4079
4080        let (runtime, auth_store) = fresh_runtime_and_store();
4081        let err = apply_preset(&runtime, &auth_store).expect_err("must reject unknown preset");
4082        assert!(err.contains("weird"), "error must echo the value: {err}");
4083        assert!(auth_store.needs_bootstrap());
4084
4085        clear_preset_env();
4086    }
4087
4088    #[test]
4089    fn no_auth_short_circuits_preset_entirely() {
4090        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
4091        clear_preset_env();
4092        // SAFETY: env serialised by `no_auth_env_lock`. Production creds
4093        // are set but `--no-auth` must win — no admin, no bootstrap state.
4094        unsafe {
4095            std::env::set_var(PRESET_ENV, PRESET_PRODUCTION);
4096            std::env::set_var("REDDB_USERNAME", "ops");
4097            std::env::set_var("REDDB_PASSWORD", "hunter2");
4098        }
4099
4100        let options = no_auth_test_config(true)
4101            .to_db_options()
4102            .expect("to_db_options");
4103        assert!(no_auth_active(&options));
4104
4105        // Mirror `build_runtime_with_telemetry`: when no_auth_active,
4106        // `apply_preset` is never called.
4107        let (runtime, auth_store) = fresh_runtime_and_store();
4108        if !no_auth_active(&options) {
4109            apply_preset(&runtime, &auth_store).expect("would apply preset");
4110        }
4111
4112        assert!(
4113            auth_store.needs_bootstrap(),
4114            "--no-auth must prevent any admin creation"
4115        );
4116        assert!(
4117            runtime
4118                .db()
4119                .store()
4120                .get_config(BOOTSTRAP_COMPLETED_KEY)
4121                .is_none(),
4122            "--no-auth must skip bootstrap-state persistence"
4123        );
4124
4125        clear_preset_env();
4126    }
4127
4128    #[test]
4129    fn implicit_bind_collision_degrades() {
4130        let held = TcpListener::bind("127.0.0.1:0").expect("hold test port");
4131        let addr = held.local_addr().expect("held addr").to_string();
4132        let mut readiness = TransportReadiness::default();
4133
4134        let listener =
4135            bind_listener_for_startup(&mut readiness, "http", &addr, false).expect("nonfatal");
4136
4137        assert!(listener.is_none());
4138        assert_eq!(readiness.active.len(), 0);
4139        assert_eq!(readiness.failed.len(), 1);
4140        assert!(!readiness.failed[0].explicit);
4141        assert_eq!(readiness.failed[0].bind_addr, addr);
4142    }
4143}