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