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    if let Some(archive) = runtime.serverless_wal_archive() {
1865        let archive = Arc::clone(archive);
1866        auth_store.set_vault_persist_hook(Arc::new(move || archive.note_out_of_wal_write()));
1867    }
1868    // ADR 0058 — cluster bootstrap authority fail-closed seam. A
1869    // cluster-shaped boot may only run auth bootstrap when a concrete
1870    // reserved-range owner can be proven; none is implemented yet, so the
1871    // seam rejects credentialled cluster boots and allows only the explicit
1872    // `--no-auth` / `--dev` development carveout. Issue #663 — when
1873    // `--no-auth` is active, deliberately skip the preset machinery so a
1874    // stray `REDDB_USERNAME`+`REDDB_PASSWORD` pair cannot silently create an
1875    // admin, defeating the point of anonymous mode.
1876    //
1877    // Issue #1230 — the durable bootstrap completion marker
1878    // (`system.bootstrap.completed`) is the authority path's record that
1879    // first boot already produced global auth state. Observing it makes a
1880    // restart or duplicate bootstrap attempt idempotent: the seam returns
1881    // `AlreadyComplete` and the caller rehydrates read-only state only,
1882    // recreating no users, reissuing no vault certificate, and reapplying no
1883    // mutable config over operator changes.
1884    let bootstrap_already_completed = runtime
1885        .db()
1886        .store()
1887        .try_get_config(BOOTSTRAP_COMPLETED_KEY)
1888        .map_err(|error| error.to_string())?
1889        .is_some();
1890    ensure_persisted_auth_state(
1891        bootstrap_already_completed,
1892        db_options.auth.require_auth,
1893        auth_store.needs_bootstrap(),
1894    )?;
1895    let disposition = crate::cluster::authorize_cluster_bootstrap(
1896        db_options.storage_profile.deploy_profile,
1897        no_auth,
1898        bootstrap.auth_bootstrap_input(),
1899        bootstrap_already_completed,
1900    )?;
1901    // Issue #1231 — wire cluster vault first boot through the bootstrap
1902    // authority. The authorized disposition selects the vault plan: the owner
1903    // path (`ProceedLocal`) opens the vault against the real cluster-global
1904    // auth store (`auth_store`, backed by the runtime pager) and consumes the
1905    // env/`_FILE` secret inputs to mint the certificate; a restart after
1906    // completion (`AlreadyComplete`) reopens and unseals that same store
1907    // without consuming secret inputs. A non-owner cluster boot already failed
1908    // closed above, so no scratch or per-member vault is minted.
1909    let vault_plan = crate::cluster::plan_vault_bootstrap(disposition);
1910    match disposition {
1911        crate::cluster::BootstrapDisposition::SkipDevBypass => {
1912            debug_assert_eq!(vault_plan, crate::cluster::VaultBootstrapPlan::SkipNoVault);
1913            eprintln!("{NO_AUTH_WARNING}");
1914            tracing::warn!("{NO_AUTH_WARNING}");
1915        }
1916        crate::cluster::BootstrapDisposition::AlreadyComplete => {
1917            // First boot is over. Rehydrate the read-only manifest registry
1918            // so config-derived state is observable, but create no users,
1919            // reissue no vault material, and reapply no mutable config
1920            // (issue #1230). `apply_preset_from_config` does exactly this
1921            // when the completion marker is present — matching the unseal-only
1922            // vault plan (no secret inputs consumed).
1923            debug_assert_eq!(
1924                vault_plan,
1925                crate::cluster::VaultBootstrapPlan::OpenClusterGlobalStore {
1926                    consume_secret_inputs: false,
1927                }
1928            );
1929            apply_preset_from_config(&runtime, &auth_store, bootstrap)?;
1930            tracing::info!("bootstrap already completed, unsealing existing cluster auth store");
1931        }
1932        crate::cluster::BootstrapDisposition::ProceedLocal => {
1933            // Owner first boot: open the vault against the real cluster-global
1934            // auth store and consume the secret inputs to mint the certificate.
1935            debug_assert_eq!(
1936                vault_plan,
1937                crate::cluster::VaultBootstrapPlan::OpenClusterGlobalStore {
1938                    consume_secret_inputs: true,
1939                }
1940            );
1941            apply_preset_from_config(&runtime, &auth_store, bootstrap)?;
1942            maybe_apply_policy_break_glass(&auth_store);
1943        }
1944    }
1945
1946    // Background session purge (every 5 minutes)
1947    {
1948        let store = Arc::clone(&auth_store);
1949        std::thread::Builder::new()
1950            .name("reddb-session-purge".into())
1951            .spawn(move || loop {
1952                std::thread::sleep(std::time::Duration::from_secs(300));
1953                store.purge_expired_sessions();
1954            })
1955            .ok();
1956    }
1957
1958    // Bootstrap writes the auth vault outside the WAL. Capture it in a
1959    // generation before serving so the archive can resume immediately.
1960    if let Some(archive) = runtime.serverless_wal_archive() {
1961        if let Err(err) = archive.publish_if_out_of_wal_pending(&runtime) {
1962            tracing::warn!(
1963                target: "reddb::serverless::archive",
1964                error = %err,
1965                "boot-time generation for auth vault changes failed; the archive retries it"
1966            );
1967        }
1968    }
1969
1970    // Native wire listeners obtain their authentication authority from the
1971    // runtime, including deployments without an HTTP or gRPC server object.
1972    runtime.set_auth_store(Arc::clone(&auth_store));
1973    Ok((runtime, auth_store, telemetry_guard))
1974}
1975
1976/// Honour `REDDB_POLICY_BREAK_GLASS=1` at boot — see issue #713 and
1977/// the [`crate::auth::self_lock_guard`] module. Anything other than
1978/// `1`/`true`/`yes` (case-insensitive) is treated as not set.
1979fn maybe_apply_policy_break_glass(auth_store: &Arc<AuthStore>) {
1980    use crate::auth::self_lock_guard::BREAK_GLASS_ENV;
1981
1982    let enabled = std::env::var(BREAK_GLASS_ENV)
1983        .ok()
1984        .map(|v| {
1985            let trimmed = v.trim().to_ascii_lowercase();
1986            matches!(trimmed.as_str(), "1" | "true" | "yes")
1987        })
1988        .unwrap_or(false);
1989    if !enabled {
1990        return;
1991    }
1992    let now = crate::utils::now_unix_millis() as u128;
1993    match auth_store.apply_policy_break_glass(now) {
1994        Ok(()) => {
1995            tracing::warn!(env = BREAK_GLASS_ENV, "policy break-glass recovery applied");
1996        }
1997        Err(err) => {
1998            tracing::error!(env = BREAK_GLASS_ENV, %err, "policy break-glass recovery failed");
1999        }
2000    }
2001}
2002
2003/// Reserved config keys describing first-boot bootstrap state (issue #650).
2004/// Presence of [`BOOTSTRAP_COMPLETED_KEY`] is the idempotency hinge: when
2005/// it is set, [`apply_preset`] silently no-ops on subsequent boots so a
2006/// container restart with the same env is a no-op.
2007pub(crate) const BOOTSTRAP_COMPLETED_KEY: &str = "system.bootstrap.completed";
2008pub(crate) const BOOTSTRAP_PRESET_KEY: &str = "system.bootstrap.preset";
2009pub(crate) const BOOTSTRAP_FIRST_ADMIN_KEY: &str = "system.bootstrap.first_admin_id";
2010
2011/// Env vars selecting the bootstrap preset. `REDDB_BOOTSTRAP_PRESET`
2012/// is canonical; `REDDB_PRESET` remains accepted for compatibility.
2013pub(crate) const BOOTSTRAP_PRESET_ENV: &str = "REDDB_BOOTSTRAP_PRESET";
2014pub(crate) const PRESET_ENV: &str = "REDDB_PRESET";
2015/// Env equivalent of `--bootstrap-cert-out` (issue #1589). Honours the
2016/// `_FILE` companion via [`env_nonempty`].
2017pub(crate) const BOOTSTRAP_CERT_OUT_ENV: &str = "REDDB_BOOTSTRAP_CERT_OUT";
2018pub(crate) const PRESET_SIMPLE: &str = "simple";
2019pub(crate) const PRESET_PRODUCTION: &str = "production";
2020pub(crate) const PRESET_REGULATED: &str = "regulated";
2021pub(crate) const PRESET_CLOUD: &str = "cloud";
2022
2023/// Policy id installed by the `production` preset and attached to the
2024/// first admin. Grants `"*"` on `"*"` so the admin has policy-derived
2025/// broad authority (acceptance #3) — not an authorization bypass.
2026pub(crate) const FIRST_ADMIN_ALLOW_ALL_POLICY: &str = "system.bootstrap.first-admin-allow-all";
2027pub(crate) const REGULATED_PROTECT_MANAGED_POLICY: &str = "system.regulated.protect-managed";
2028pub(crate) const CLOUD_PROTECT_MANAGED_POLICY: &str = "system.cloud.protect-managed";
2029pub(crate) const CLOUD_CONFIG_NAMESPACE: &str = "red.config.cloud";
2030pub(crate) const REGULATED_AUDIT_CONFIG_NAMESPACE: &str = "red.config.audit";
2031pub(crate) const REGULATED_EVIDENCE_CONFIG_NAMESPACE: &str = "red.config.evidence";
2032pub(crate) const REGULATED_QUERY_AUDIT_CONFIG_NAMESPACE: &str = "red.config.query_audit";
2033
2034/// Apply the bootstrap preset selected by `REDDB_BOOTSTRAP_PRESET` (or
2035/// legacy `REDDB_PRESET`; default `simple`). Idempotent — if
2036/// `system.bootstrap.completed` is already set, this is a one-line
2037/// `tracing::info!` no-op and the server proceeds (issue #650
2038/// acceptance #5).
2039///
2040/// Caller must have already short-circuited the `--no-auth` / `--dev`
2041/// path (issue #663): when that flag is set, the preset must be skipped
2042/// entirely — no admin created, no bootstrap state written.
2043pub(crate) fn apply_preset(
2044    runtime: &RedDBRuntime,
2045    auth_store: &Arc<AuthStore>,
2046) -> Result<(), String> {
2047    let bootstrap = BootstrapConfig::default();
2048    apply_preset_from_config(runtime, auth_store, &bootstrap)
2049}
2050
2051fn apply_preset_from_config(
2052    runtime: &RedDBRuntime,
2053    auth_store: &Arc<AuthStore>,
2054    bootstrap: &BootstrapConfig,
2055) -> Result<(), String> {
2056    let store = runtime.db().store();
2057
2058    if store
2059        .try_get_config(BOOTSTRAP_COMPLETED_KEY)
2060        .map_err(|error| error.to_string())?
2061        .is_some()
2062    {
2063        crate::cli::bootstrap_manifest::rehydrate_manifest_registry(
2064            runtime,
2065            &runtime.config_registry(),
2066        )?;
2067        tracing::info!("bootstrap state present, skipping preset application");
2068        return Ok(());
2069    }
2070
2071    let preset = bootstrap.resolved_preset();
2072
2073    if let Some(path) = bootstrap.selected_manifest() {
2074        if let Some(manifest_bootstrap) =
2075            crate::cli::bootstrap_manifest::bootstrap_config_from_manifest_file(&path)?
2076        {
2077            apply_preset_from_config(runtime, auth_store, &manifest_bootstrap)?;
2078            return Ok(());
2079        }
2080        let first_admin_id = crate::cli::bootstrap_manifest::apply_manifest_file(
2081            runtime,
2082            auth_store,
2083            &runtime.config_registry(),
2084            &path,
2085        )?;
2086        persist_bootstrap_state(runtime, "manifest", Some(&first_admin_id))?;
2087        tracing::info!("bootstrap manifest applied");
2088        return Ok(());
2089    }
2090
2091    // The encrypted auth state is independently durable. If it already says
2092    // bootstrap completed, never reopen preset bootstrap merely because the
2093    // adjacent config marker was not flushed before an abrupt process exit.
2094    if !auth_store.needs_bootstrap() {
2095        persist_bootstrap_state(runtime, &preset, None)?;
2096        tracing::info!(preset = %preset, "durable auth state present, skipping preset bootstrap");
2097        return Ok(());
2098    }
2099
2100    // The simple preset does not create an administrator. With required auth,
2101    // leave the completion marker absent until a durable vault user exists so
2102    // a crash before the first HTTP/gRPC bootstrap does not turn into a
2103    // permanent lockout. Older volatile-auth installs that already carry the
2104    // marker still fail closed in `ensure_persisted_auth_state` above.
2105    if preset == PRESET_SIMPLE && auth_store.config().require_auth && auth_store.needs_bootstrap() {
2106        tracing::info!("required-auth simple preset is awaiting durable first-admin bootstrap");
2107        return Ok(());
2108    }
2109
2110    let mut certificate_output = if matches!(preset.as_str(), PRESET_PRODUCTION | PRESET_CLOUD)
2111        && auth_store.bootstrap_requires_certificate_delivery()
2112    {
2113        require_bootstrap_certificate_output(bootstrap, &preset)?;
2114        Some(open_bootstrap_certificate_output(bootstrap)?)
2115    } else {
2116        None
2117    };
2118    let first_admin_id = match preset.as_str() {
2119        PRESET_SIMPLE => {
2120            // `simple` is the default low-friction preset. Auth knobs
2121            // remain whatever the CLI/env set; we only persist the
2122            // bootstrap state so subsequent boots are idempotent.
2123            None
2124        }
2125        PRESET_PRODUCTION => Some(apply_production_preset_from_config(
2126            auth_store,
2127            bootstrap,
2128            &mut certificate_output,
2129        )?),
2130        PRESET_CLOUD => Some(apply_cloud_preset(
2131            runtime,
2132            auth_store,
2133            bootstrap,
2134            &mut certificate_output,
2135        )?),
2136        PRESET_REGULATED => {
2137            apply_regulated_preset(runtime, auth_store)?;
2138            None
2139        }
2140        other => {
2141            return Err(format!(
2142                "bootstrap preset {other:?} is not recognised (expected `simple`, `production`, `regulated`, or `cloud`)"
2143            ));
2144        }
2145    };
2146
2147    // Every preset mutation must be durable before the adjacent completion
2148    // marker can make bootstrap permanently ineligible on a later restart.
2149    auth_store
2150        .persist_to_vault_result()
2151        .map_err(|err| format!("persist bootstrap auth state: {err}"))?;
2152    persist_bootstrap_state(runtime, &preset, first_admin_id.as_deref())?;
2153    tracing::info!(preset = %preset, "bootstrap preset applied");
2154    Ok(())
2155}
2156
2157struct BootstrapCertificateOutput {
2158    path: PathBuf,
2159    file: Option<std::fs::File>,
2160    committed: bool,
2161}
2162
2163impl Drop for BootstrapCertificateOutput {
2164    fn drop(&mut self) {
2165        if self.committed {
2166            return;
2167        }
2168        self.file.take();
2169        let _ = std::fs::remove_file(&self.path);
2170    }
2171}
2172
2173/// Reserve the secure certificate destination before mutating bootstrap state.
2174/// A failed preset application removes the empty reservation on drop.
2175fn open_bootstrap_certificate_output(
2176    bootstrap: &BootstrapConfig,
2177) -> Result<BootstrapCertificateOutput, String> {
2178    let Some(path) = bootstrap.selected_cert_out() else {
2179        return Err("bootstrap certificate output is not configured".to_string());
2180    };
2181    let mut options = std::fs::OpenOptions::new();
2182    options.write(true).create_new(true);
2183    #[cfg(unix)]
2184    {
2185        use std::os::unix::fs::OpenOptionsExt;
2186        options.mode(0o600);
2187    }
2188    let file = options
2189        .open(&path)
2190        .map_err(|err| format!("create --bootstrap-cert-out {}: {err}", path.display()))?;
2191    Ok(BootstrapCertificateOutput {
2192        path,
2193        file: Some(file),
2194        committed: false,
2195    })
2196}
2197
2198fn stage_bootstrap_certificate(
2199    output: &mut BootstrapCertificateOutput,
2200    certificate_hex: &str,
2201) -> Result<(), String> {
2202    use std::io::Write;
2203    let path = output.path.clone();
2204    let file = output
2205        .file
2206        .as_mut()
2207        .ok_or_else(|| "bootstrap certificate output is closed".to_string())?;
2208    writeln!(file, "{certificate_hex}")
2209        .map_err(|err| format!("write --bootstrap-cert-out {}: {err}", path.display()))?;
2210    file.sync_all()
2211        .map_err(|err| format!("sync --bootstrap-cert-out {}: {err}", path.display()))?;
2212    Ok(())
2213}
2214
2215fn commit_bootstrap_certificate(mut output: BootstrapCertificateOutput) {
2216    let path = output.path.clone();
2217    output.committed = true;
2218    tracing::info!(
2219        target: "reddb::bootstrap",
2220        path = %path.display(),
2221        "first-boot self-bootstrap: wrote unseal certificate to --bootstrap-cert-out (consume via REDDB_CERTIFICATE_FILE on the next boot)"
2222    );
2223}
2224
2225fn bootstrap_with_certificate_output(
2226    auth_store: &Arc<AuthStore>,
2227    username: &str,
2228    password: &str,
2229    certificate_output: &mut Option<BootstrapCertificateOutput>,
2230) -> Result<crate::auth::store::BootstrapResult, String> {
2231    let mut certificate_staged = false;
2232    let result = auth_store
2233        .bootstrap_with_certificate_delivery(username, password, |certificate| {
2234            let output = certificate_output.as_mut().ok_or_else(|| {
2235                crate::auth::AuthError::Internal(
2236                    "bootstrap certificate output was not prepared".to_string(),
2237                )
2238            })?;
2239            stage_bootstrap_certificate(output, certificate)
2240                .map_err(crate::auth::AuthError::Internal)?;
2241            certificate_staged = true;
2242            Ok(())
2243        })
2244        .map_err(|err| format!("bootstrap first admin: {err}"))?;
2245
2246    // When the store was opened with an operator-supplied certificate there
2247    // is no newly generated seal to deliver before activation. Mirror that
2248    // existing credential into the requested file after bootstrap.
2249    if !certificate_staged {
2250        if let (Some(certificate), Some(output)) =
2251            (result.certificate.as_deref(), certificate_output.as_mut())
2252        {
2253            stage_bootstrap_certificate(output, certificate)?;
2254            certificate_staged = true;
2255        }
2256    }
2257    if certificate_staged {
2258        let output = certificate_output
2259            .take()
2260            .ok_or_else(|| "bootstrap certificate output was not prepared".to_string())?;
2261        commit_bootstrap_certificate(output);
2262    }
2263    Ok(result)
2264}
2265
2266fn ensure_persisted_auth_state(
2267    bootstrap_completed: bool,
2268    require_auth: bool,
2269    needs_bootstrap: bool,
2270) -> Result<(), String> {
2271    if bootstrap_completed && require_auth && needs_bootstrap {
2272        return Err(
2273            "persistent database is marked bootstrapped but its authentication state is empty; refusing to reopen public bootstrap"
2274                .to_string(),
2275        );
2276    }
2277    Ok(())
2278}
2279
2280fn require_bootstrap_certificate_output(
2281    bootstrap: &BootstrapConfig,
2282    preset: &str,
2283) -> Result<(), String> {
2284    if bootstrap.selected_cert_out().is_some() {
2285        return Ok(());
2286    }
2287    Err(format!(
2288        "bootstrap preset `{preset}` requires --bootstrap-cert-out (or REDDB_BOOTSTRAP_CERT_OUT); vault certificates are never written to logs"
2289    ))
2290}
2291
2292fn apply_production_preset_from_config(
2293    auth_store: &Arc<AuthStore>,
2294    bootstrap: &BootstrapConfig,
2295    certificate_output: &mut Option<BootstrapCertificateOutput>,
2296) -> Result<String, String> {
2297    use crate::auth::store::PrincipalRef;
2298    use crate::auth::UserId;
2299
2300    let username = bootstrap.production_username().ok_or_else(|| {
2301        "production preset requires --bootstrap-admin or REDDB_USERNAME (or REDDB_USERNAME_FILE)"
2302            .to_string()
2303    })?;
2304    let password = bootstrap.production_password().ok_or_else(|| {
2305        "production preset requires --bootstrap-admin-password or REDDB_PASSWORD (or REDDB_PASSWORD_FILE)"
2306            .to_string()
2307    })?;
2308
2309    // (1) Create the first admin as an ordinary platform-scoped user.
2310    // Managed guardrails are policy-derived; bootstrap does not stamp a
2311    // parallel ownership flag.
2312    let result =
2313        bootstrap_with_certificate_output(auth_store, &username, &password, certificate_output)?;
2314    if result.certificate.is_some() {
2315        tracing::warn!(
2316            "vault certificate issued by REDDB_PRESET=production and written to the configured certificate output"
2317        );
2318    }
2319    let first_admin = UserId::platform(result.user.username.clone());
2320
2321    // (2) Install the allow-all policy as an ordinary policy row.
2322    install_allow_all_policy(auth_store)?;
2323
2324    // (3) Attach the policy to the first admin.
2325    auth_store
2326        .attach_policy(
2327            PrincipalRef::User(first_admin.clone()),
2328            FIRST_ADMIN_ALLOW_ALL_POLICY,
2329        )
2330        .map_err(|err| format!("attach allow-all policy: {err}"))?;
2331
2332    Ok(first_admin.to_string())
2333}
2334
2335fn apply_cloud_preset(
2336    runtime: &RedDBRuntime,
2337    auth_store: &Arc<AuthStore>,
2338    bootstrap: &BootstrapConfig,
2339    certificate_output: &mut Option<BootstrapCertificateOutput>,
2340) -> Result<String, String> {
2341    use crate::auth::store::PrincipalRef;
2342    use crate::auth::{Role, UserId};
2343
2344    let head_username = bootstrap.cloud_head_username().ok_or_else(|| {
2345        "cloud preset requires --cloud-head-admin or REDDB_CLOUD_HEAD_ADMIN (or REDDB_USERNAME)"
2346            .to_string()
2347    })?;
2348    let head_password = bootstrap.cloud_head_password().ok_or_else(|| {
2349        "cloud preset requires --cloud-head-admin-password or REDDB_CLOUD_HEAD_ADMIN_PASSWORD (or REDDB_PASSWORD)"
2350            .to_string()
2351    })?;
2352    let customer_username = bootstrap.customer_username().ok_or_else(|| {
2353        "cloud preset requires --customer-admin or REDDB_CUSTOMER_ADMIN".to_string()
2354    })?;
2355    let customer_password = bootstrap.customer_password().ok_or_else(|| {
2356        "cloud preset requires --customer-admin-password or REDDB_CUSTOMER_ADMIN_PASSWORD"
2357            .to_string()
2358    })?;
2359    if head_username == customer_username {
2360        return Err("cloud preset requires distinct head and customer admin usernames".to_string());
2361    }
2362
2363    let head = bootstrap_with_certificate_output(
2364        auth_store,
2365        &head_username,
2366        &head_password,
2367        certificate_output,
2368    )
2369    .map_err(|err| format!("bootstrap cloud head admin: {err}"))?;
2370    let head_id = UserId::platform(head.user.username.clone());
2371
2372    auth_store
2373        .create_user(&customer_username, &customer_password, Role::Admin)
2374        .map_err(|err| format!("create cloud customer admin: {err}"))?;
2375    let customer_id = UserId::platform(customer_username.clone());
2376
2377    install_allow_all_policy(auth_store)?;
2378    for user_id in [&head_id, &customer_id] {
2379        auth_store
2380            .attach_policy(
2381                PrincipalRef::User(user_id.clone()),
2382                FIRST_ADMIN_ALLOW_ALL_POLICY,
2383            )
2384            .map_err(|err| format!("attach allow-all policy: {err}"))?;
2385    }
2386    install_cloud_guardrails(runtime, auth_store, &head_id)?;
2387    auth_store
2388        .attach_policy(
2389            PrincipalRef::User(customer_id),
2390            CLOUD_PROTECT_MANAGED_POLICY,
2391        )
2392        .map_err(|err| format!("attach cloud guardrail policy: {err}"))?;
2393
2394    Ok(head_id.to_string())
2395}
2396
2397pub(crate) fn install_allow_all_policy(auth_store: &AuthStore) -> Result<(), String> {
2398    use crate::auth::policies::Policy;
2399
2400    let policy = Policy::from_json_str(&format!(
2401        r#"{{
2402            "id": "{id}",
2403            "version": 1,
2404            "statements": [{{
2405                "effect": "allow",
2406                "actions": ["*"],
2407                "resources": ["*"]
2408            }}]
2409        }}"#,
2410        id = FIRST_ADMIN_ALLOW_ALL_POLICY
2411    ))
2412    .map_err(|err| format!("compile allow-all policy: {err}"))?;
2413    auth_store
2414        .put_policy(policy)
2415        .map_err(|err| format!("install allow-all policy: {err}"))
2416}
2417
2418fn install_cloud_guardrails(
2419    runtime: &RedDBRuntime,
2420    auth_store: &Arc<AuthStore>,
2421    head_admin: &crate::auth::UserId,
2422) -> Result<(), String> {
2423    use crate::auth::policies::Policy;
2424    use crate::auth::registry::EvidenceRequirement;
2425
2426    let policy = Policy::from_json_str(&format!(
2427        r#"{{
2428            "id": "{id}",
2429            "version": 1,
2430            "statements": [
2431                {{
2432                    "effect": "deny",
2433                    "actions": ["policy:put", "policy:drop", "policy:attach", "policy:detach"],
2434                    "resources": ["policy:{id}"]
2435                }},
2436                {{
2437                    "effect": "deny",
2438                    "actions": [
2439                        "user:delete",
2440                        "user:disable",
2441                        "user:password:change",
2442                        "user:role:update"
2443                    ],
2444                    "resources": ["user:{head_admin}"]
2445                }},
2446                {{
2447                    "effect": "deny",
2448                    "actions": ["config:write"],
2449                    "resources": ["config:{cloud}.*"]
2450                }}
2451            ]
2452        }}"#,
2453        id = CLOUD_PROTECT_MANAGED_POLICY,
2454        head_admin = head_admin,
2455        cloud = CLOUD_CONFIG_NAMESPACE,
2456    ))
2457    .map_err(|err| format!("compile cloud guardrail policy: {err}"))?;
2458    auth_store
2459        .put_policy(policy)
2460        .map_err(|err| format!("install cloud guardrail policy: {err}"))?;
2461
2462    let now_ms = crate::utils::now_unix_millis() as u128;
2463    let entries = vec![
2464        regulated_registry_entry(
2465            CLOUD_PROTECT_MANAGED_POLICY,
2466            crate::auth::managed_policy::RESOURCE_TYPE_POLICY,
2467            "policy",
2468            "policy:*",
2469            &format!("policy:{CLOUD_PROTECT_MANAGED_POLICY}"),
2470            EvidenceRequirement::Metadata,
2471            now_ms,
2472        ),
2473        regulated_registry_entry(
2474            CLOUD_CONFIG_NAMESPACE,
2475            crate::auth::managed_config::RESOURCE_TYPE_CONFIG_NAMESPACE,
2476            "config_namespace",
2477            "config:write",
2478            &format!("config:{CLOUD_CONFIG_NAMESPACE}.*"),
2479            EvidenceRequirement::Metadata,
2480            now_ms,
2481        ),
2482    ];
2483    for entry in entries.iter().cloned() {
2484        runtime
2485            .config_registry()
2486            .restore_bootstrap_entry(entry)
2487            .map_err(|err| format!("install cloud registry entry: {err}"))?;
2488    }
2489    crate::cli::bootstrap_manifest::persist_registry_state(runtime, &entries)?;
2490    Ok(())
2491}
2492
2493fn apply_regulated_preset(
2494    runtime: &RedDBRuntime,
2495    auth_store: &Arc<AuthStore>,
2496) -> Result<(), String> {
2497    use crate::auth::policies::Policy;
2498    use crate::auth::registry::EvidenceRequirement;
2499    use crate::auth::store::{PrincipalRef, PUBLIC_IAM_GROUP};
2500
2501    runtime.query_audit().enable_infrastructure();
2502
2503    let policy = Policy::from_json_str(&format!(
2504        r#"{{
2505            "id": "{id}",
2506            "version": 1,
2507            "statements": [
2508                {{
2509                    "effect": "deny",
2510                    "actions": ["policy:put", "policy:drop", "policy:attach", "policy:detach"],
2511                    "resources": ["policy:{id}"]
2512                }},
2513                {{
2514                    "effect": "deny",
2515                    "actions": ["config:write"],
2516                    "resources": [
2517                        "config:{audit}.*",
2518                        "config:{evidence}.*",
2519                        "config:{query_audit}.*"
2520                    ]
2521                }}
2522            ]
2523        }}"#,
2524        id = REGULATED_PROTECT_MANAGED_POLICY,
2525        audit = REGULATED_AUDIT_CONFIG_NAMESPACE,
2526        evidence = REGULATED_EVIDENCE_CONFIG_NAMESPACE,
2527        query_audit = REGULATED_QUERY_AUDIT_CONFIG_NAMESPACE,
2528    ))
2529    .map_err(|err| format!("compile regulated guardrail policy: {err}"))?;
2530    auth_store
2531        .put_policy(policy)
2532        .map_err(|err| format!("install regulated guardrail policy: {err}"))?;
2533    auth_store
2534        .attach_policy(
2535            PrincipalRef::Group(PUBLIC_IAM_GROUP.to_string()),
2536            REGULATED_PROTECT_MANAGED_POLICY,
2537        )
2538        .map_err(|err| format!("attach regulated guardrail policy: {err}"))?;
2539
2540    let now_ms = crate::utils::now_unix_millis() as u128;
2541    let entries = vec![
2542        regulated_registry_entry(
2543            REGULATED_PROTECT_MANAGED_POLICY,
2544            crate::auth::managed_policy::RESOURCE_TYPE_POLICY,
2545            "iam_policy",
2546            "policy:*",
2547            &format!("policy:{REGULATED_PROTECT_MANAGED_POLICY}"),
2548            EvidenceRequirement::Metadata,
2549            now_ms,
2550        ),
2551        regulated_registry_entry(
2552            REGULATED_AUDIT_CONFIG_NAMESPACE,
2553            crate::auth::managed_config::RESOURCE_TYPE_CONFIG_NAMESPACE,
2554            "config_namespace",
2555            "config:write",
2556            &format!("config:{REGULATED_AUDIT_CONFIG_NAMESPACE}.*"),
2557            EvidenceRequirement::Metadata,
2558            now_ms,
2559        ),
2560        regulated_registry_entry(
2561            REGULATED_EVIDENCE_CONFIG_NAMESPACE,
2562            crate::auth::managed_config::RESOURCE_TYPE_CONFIG_NAMESPACE,
2563            "config_namespace",
2564            "config:write",
2565            &format!("config:{REGULATED_EVIDENCE_CONFIG_NAMESPACE}.*"),
2566            EvidenceRequirement::Metadata,
2567            now_ms,
2568        ),
2569        regulated_registry_entry(
2570            REGULATED_QUERY_AUDIT_CONFIG_NAMESPACE,
2571            crate::auth::managed_config::RESOURCE_TYPE_CONFIG_NAMESPACE,
2572            "config_namespace",
2573            "config:write",
2574            &format!("config:{REGULATED_QUERY_AUDIT_CONFIG_NAMESPACE}.*"),
2575            EvidenceRequirement::Metadata,
2576            now_ms,
2577        ),
2578    ];
2579
2580    for entry in entries.iter().cloned() {
2581        runtime
2582            .config_registry()
2583            .restore_bootstrap_entry(entry)
2584            .map_err(|err| format!("install regulated registry entry: {err}"))?;
2585    }
2586    crate::cli::bootstrap_manifest::persist_registry_state(runtime, &entries)?;
2587    Ok(())
2588}
2589
2590fn regulated_registry_entry(
2591    id: &str,
2592    resource_type: &str,
2593    schema: &str,
2594    required_action: &str,
2595    required_resource: &str,
2596    evidence_requirement: crate::auth::registry::EvidenceRequirement,
2597    updated_at_ms: u128,
2598) -> crate::auth::registry::ConfigRegistryEntry {
2599    crate::auth::registry::ConfigRegistryEntry {
2600        id: id.to_string(),
2601        version: 1,
2602        resource_type: resource_type.to_string(),
2603        schema: schema.to_string(),
2604        mutability: crate::auth::registry::Mutability::Immutable,
2605        sensitivity: crate::auth::registry::Sensitivity::Internal,
2606        managed: true,
2607        required_action: required_action.to_string(),
2608        required_resource: required_resource.to_string(),
2609        evidence_requirement,
2610        updated_by: "system:regulated-preset".to_string(),
2611        updated_at_ms,
2612    }
2613}
2614
2615fn persist_bootstrap_state(
2616    runtime: &RedDBRuntime,
2617    preset: &str,
2618    first_admin_id: Option<&str>,
2619) -> Result<(), String> {
2620    let store = runtime.db().store();
2621    let mut tree = crate::serde_json::Map::new();
2622    tree.insert(
2623        BOOTSTRAP_COMPLETED_KEY.to_string(),
2624        crate::serde_json::Value::Bool(true),
2625    );
2626    tree.insert(
2627        BOOTSTRAP_PRESET_KEY.to_string(),
2628        crate::serde_json::Value::String(preset.to_string()),
2629    );
2630    if let Some(id) = first_admin_id {
2631        tree.insert(
2632            BOOTSTRAP_FIRST_ADMIN_KEY.to_string(),
2633            crate::serde_json::Value::String(id.to_string()),
2634        );
2635    }
2636    let json = crate::serde_json::Value::Object(tree);
2637    store
2638        .try_set_config_tree("", &json)
2639        .map_err(|error| error.to_string())?;
2640    Ok(())
2641}
2642
2643/// Read `logging.*` keys from the persistent config store and
2644/// merge them into the CLI-built `TelemetryConfig`. Merge priority:
2645/// explicit CLI flag > red.config > built-in default.
2646///
2647/// The "was a flag passed" signal comes from the `*_explicit` bools
2648/// on `TelemetryConfig`, populated by the CLI parser. This replaces
2649/// an earlier equality-to-default heuristic that silently dropped
2650/// config whenever the CLI-derived default diverged from
2651/// `TelemetryConfig::default()` (e.g. path-derived `log_dir`,
2652/// non-TTY `format`) and that silently overrode `--no-log-file`.
2653fn merge_telemetry_with_config(
2654    mut cli: crate::telemetry::TelemetryConfig,
2655    runtime: &RedDBRuntime,
2656) -> crate::telemetry::TelemetryConfig {
2657    use reddb_types::Value;
2658
2659    let store = runtime.db().store();
2660
2661    if !cli.level_explicit {
2662        if let Some(Value::Text(v)) = store.get_config("logging.level") {
2663            cli.level_filter = v.to_string();
2664        }
2665    }
2666    if !cli.format_explicit {
2667        if let Some(Value::Text(v)) = store.get_config("logging.format") {
2668            if let Some(parsed) = crate::telemetry::LogFormat::parse(&v) {
2669                cli.format = parsed;
2670            }
2671        }
2672    }
2673    if !cli.rotation_keep_days_explicit {
2674        match store.get_config("logging.keep_days") {
2675            Some(Value::Integer(n)) if n >= 0 && n <= u16::MAX as i64 => {
2676                cli.rotation_keep_days = n as u16
2677            }
2678            Some(Value::UnsignedInteger(n)) if n <= u16::MAX as u64 => {
2679                cli.rotation_keep_days = n as u16
2680            }
2681            Some(Value::Text(v)) => {
2682                if let Ok(n) = v.parse::<u16>() {
2683                    cli.rotation_keep_days = n;
2684                }
2685            }
2686            _ => {}
2687        }
2688    }
2689    if !cli.file_prefix_explicit {
2690        if let Some(Value::Text(v)) = store.get_config("logging.file_prefix") {
2691            if !v.is_empty() {
2692                cli.file_prefix = v.to_string();
2693            }
2694        }
2695    }
2696    // --no-log-file is a kill-switch: config cannot resurrect the
2697    // file sink. Explicit --log-dir also wins.
2698    if !cli.log_dir_explicit && !cli.log_file_disabled {
2699        if let Some(Value::Text(v)) = store.get_config("logging.dir") {
2700            if !v.is_empty() {
2701                cli.log_dir = Some(std::path::PathBuf::from(v.as_ref()));
2702            }
2703        }
2704    }
2705
2706    cli
2707}
2708
2709#[cfg(test)]
2710mod telemetry_merge_tests {
2711    use super::*;
2712    use crate::telemetry::{LogFormat, TelemetryConfig};
2713
2714    fn fresh_runtime() -> RedDBRuntime {
2715        RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime")
2716    }
2717
2718    fn set_str(runtime: &RedDBRuntime, key: &str, value: &str) {
2719        runtime
2720            .db()
2721            .store()
2722            .set_config_tree(key, &crate::serde_json::Value::String(value.to_string()));
2723    }
2724
2725    fn cli_base() -> TelemetryConfig {
2726        // Emulate default_telemetry_for_path(Some(path)) on a non-TTY host:
2727        // log_dir = Some(...), format = Json. Nothing marked explicit.
2728        TelemetryConfig {
2729            log_dir: Some(std::path::PathBuf::from("/tmp/reddb-default/logs")),
2730            format: LogFormat::Json,
2731            ..Default::default()
2732        }
2733    }
2734
2735    #[test]
2736    fn config_log_dir_promoted_when_flag_absent() {
2737        let runtime = fresh_runtime();
2738        set_str(&runtime, "logging.dir", "/var/log/reddb");
2739        let merged = merge_telemetry_with_config(cli_base(), &runtime);
2740        assert_eq!(
2741            merged.log_dir.as_deref(),
2742            Some(std::path::Path::new("/var/log/reddb"))
2743        );
2744    }
2745
2746    #[test]
2747    fn explicit_log_dir_wins_over_config() {
2748        let runtime = fresh_runtime();
2749        set_str(&runtime, "logging.dir", "/var/log/reddb");
2750        let mut cli = cli_base();
2751        cli.log_dir = Some(std::path::PathBuf::from("/custom/dir"));
2752        cli.log_dir_explicit = true;
2753        let merged = merge_telemetry_with_config(cli, &runtime);
2754        assert_eq!(
2755            merged.log_dir.as_deref(),
2756            Some(std::path::Path::new("/custom/dir"))
2757        );
2758    }
2759
2760    #[test]
2761    fn no_log_file_beats_config_log_dir() {
2762        let runtime = fresh_runtime();
2763        set_str(&runtime, "logging.dir", "/var/log/reddb");
2764        let mut cli = cli_base();
2765        cli.log_dir = None;
2766        cli.log_file_disabled = true;
2767        let merged = merge_telemetry_with_config(cli, &runtime);
2768        assert!(
2769            merged.log_dir.is_none(),
2770            "--no-log-file must veto config dir"
2771        );
2772    }
2773
2774    #[test]
2775    fn config_format_promoted_on_non_tty_default() {
2776        // On non-TTY, default_telemetry_for_path yields format=Json even
2777        // though TelemetryConfig::default() is Pretty. The old equality
2778        // check silently dropped config here.
2779        let runtime = fresh_runtime();
2780        set_str(&runtime, "logging.format", "pretty");
2781        let merged = merge_telemetry_with_config(cli_base(), &runtime);
2782        assert_eq!(merged.format, LogFormat::Pretty);
2783    }
2784
2785    #[test]
2786    fn explicit_format_wins_over_config() {
2787        let runtime = fresh_runtime();
2788        set_str(&runtime, "logging.format", "pretty");
2789        let mut cli = cli_base();
2790        cli.format = LogFormat::Json;
2791        cli.format_explicit = true;
2792        let merged = merge_telemetry_with_config(cli, &runtime);
2793        assert_eq!(merged.format, LogFormat::Json);
2794    }
2795}
2796
2797#[inline(never)]
2798fn build_http_server(
2799    runtime: RedDBRuntime,
2800    auth_store: Arc<AuthStore>,
2801    bind_addr: String,
2802) -> RedDBServer {
2803    build_http_server_with_transport_readiness(
2804        runtime,
2805        auth_store,
2806        bind_addr,
2807        TransportReadiness::default(),
2808    )
2809}
2810
2811/// Apply the resolved HTTP limits to a freshly-built `RedDBServer`.
2812///
2813/// Centralised here so every `run_*` path goes through the same
2814/// resolver and the structured startup log line carries the same
2815/// `http_limits.*` fields regardless of transport combination.
2816fn apply_http_limits(
2817    server: RedDBServer,
2818    config: &ServerCommandConfig,
2819    runtime: &RedDBRuntime,
2820) -> RedDBServer {
2821    let store = runtime.db().store();
2822    let resolved =
2823        crate::server::http_limits::resolve_http_limits(&config.http_limits_cli, |key| match store
2824            .get_config(key)
2825        {
2826            Some(reddb_types::Value::Text(v)) => Some(v.to_string()),
2827            Some(reddb_types::Value::Integer(n)) if n >= 0 => Some(n.to_string()),
2828            Some(reddb_types::Value::UnsignedInteger(n)) => Some(n.to_string()),
2829            _ => None,
2830        });
2831    tracing::info!(
2832        target: "reddb::http_limits",
2833        max_handlers = resolved.max_handlers,
2834        execution_workers = resolved.execution_workers,
2835        handler_timeout_ms = resolved.handler_timeout_ms,
2836        retry_after_secs = resolved.retry_after_secs,
2837        max_inflight_per_principal = resolved.max_inflight_per_principal,
2838        "http_limits resolved"
2839    );
2840    server.with_http_limits(resolved)
2841}
2842
2843/// `red server --ui` (issue #1047, ADR 0051): attach the resolved red-ui
2844/// bundle directory to an HTTP server so it also serves the bundle as
2845/// static assets. No-op when `--ui` is off.
2846///
2847/// An explicit `--ui-dir <DIR>` is served as-is (no download); otherwise
2848/// the pinned bundle is resolved from the local cache, downloading on
2849/// first use (ADR 0050). A resolution failure is fatal: the operator
2850/// explicitly asked for the UI, so silently serving API-only would be
2851/// surprising and would mask an offline/checksum problem.
2852fn apply_ui_bundle(
2853    server: RedDBServer,
2854    config: &ServerCommandConfig,
2855) -> Result<RedDBServer, String> {
2856    if !config.ui {
2857        return Ok(server);
2858    }
2859    let ui_dir = match &config.ui_dir {
2860        Some(dir) => dir.clone(),
2861        None => {
2862            let cache_root = crate::server::ui_bundle_resolver::reddb_user_cache_root()
2863                .unwrap_or_else(|_| std::env::temp_dir().join("reddb"));
2864            crate::server::ui_bundle_resolver::resolve_ui_bundle(
2865                &cache_root,
2866                &crate::server::ui_bundle_resolver::HttpFetcher,
2867            )
2868            .map_err(|err| format!("resolve red-ui bundle for --ui: {err}"))?
2869        }
2870    };
2871    tracing::info!(target: "reddb::ui", dir = %ui_dir.display(), "serving red-ui bundle on HTTP surface");
2872    Ok(server.with_ui_dir(ui_dir))
2873}
2874
2875#[inline(never)]
2876fn build_http_server_with_transport_readiness(
2877    runtime: RedDBRuntime,
2878    auth_store: Arc<AuthStore>,
2879    bind_addr: String,
2880    transport_readiness: TransportReadiness,
2881) -> RedDBServer {
2882    RedDBServer::with_options(
2883        runtime,
2884        ServerOptions {
2885            bind_addr,
2886            transport_readiness,
2887            ..ServerOptions::default()
2888        },
2889    )
2890    .with_auth(auth_store)
2891}
2892
2893/// PLAN.md Phase 6.2 — build a listener that only serves
2894/// `/admin/*` + `/metrics` + `/health/*`. Defaults to `127.0.0.1`
2895/// when the env var has no host (loopback-only by default per spec).
2896#[inline(never)]
2897fn build_admin_only_server(
2898    runtime: RedDBRuntime,
2899    auth_store: Arc<AuthStore>,
2900    bind_addr: String,
2901) -> RedDBServer {
2902    RedDBServer::with_options(
2903        runtime,
2904        ServerOptions {
2905            bind_addr,
2906            surface: crate::server::ServerSurface::AdminOnly,
2907            ..ServerOptions::default()
2908        },
2909    )
2910    .with_auth(auth_store)
2911}
2912
2913/// PLAN.md Phase 6.2 — build a listener that only serves `/metrics`
2914/// + `/health/*`. Suitable for Prometheus scrape ports that may be
2915///   exposed wider than the admin port.
2916#[inline(never)]
2917fn build_metrics_only_server(
2918    runtime: RedDBRuntime,
2919    auth_store: Arc<AuthStore>,
2920    bind_addr: String,
2921) -> RedDBServer {
2922    RedDBServer::with_options(
2923        runtime,
2924        ServerOptions {
2925            bind_addr,
2926            surface: crate::server::ServerSurface::MetricsOnly,
2927            ..ServerOptions::default()
2928        },
2929    )
2930    .with_auth(auth_store)
2931}
2932
2933/// Spawn dedicated admin / metrics listeners when the operator set
2934/// `RED_ADMIN_BIND` / `RED_METRICS_BIND`. Both are optional; when
2935/// unset the existing listener keeps serving everything (back-compat).
2936fn spawn_admin_metrics_listeners(runtime: &RedDBRuntime, auth_store: &Arc<AuthStore>) {
2937    if let Some(addr) = env_nonempty("RED_ADMIN_BIND") {
2938        let server = build_admin_only_server(runtime.clone(), auth_store.clone(), addr.clone());
2939        let _ = server.serve_in_background();
2940        tracing::info!(transport = "http", surface = "admin", bind = %addr, "listener online");
2941    }
2942    if let Some(addr) = env_nonempty("RED_METRICS_BIND") {
2943        let server = build_metrics_only_server(runtime.clone(), auth_store.clone(), addr.clone());
2944        let _ = server.serve_in_background();
2945        tracing::info!(transport = "http", surface = "metrics", bind = %addr, "listener online");
2946    }
2947}
2948
2949/// Resolve the HTTP TLS config from CLI / env / dev defaults.
2950fn resolve_http_tls_config(
2951    config: &ServerCommandConfig,
2952) -> Result<crate::server::tls::HttpTlsConfig, String> {
2953    match (&config.http_tls_cert, &config.http_tls_key) {
2954        (Some(cert), Some(key)) => Ok(crate::server::tls::HttpTlsConfig {
2955            cert_path: cert.clone(),
2956            key_path: key.clone(),
2957            client_ca_path: config.http_tls_client_ca.clone(),
2958        }),
2959        (None, None) => {
2960            // Dev-mode auto-generate next to the data directory.
2961            let dir = config
2962                .path
2963                .as_ref()
2964                .and_then(|p| p.parent().map(std::path::PathBuf::from))
2965                .unwrap_or_else(|| std::path::PathBuf::from("."));
2966            let auto = crate::server::tls::auto_generate_dev_cert(&dir)
2967                .map_err(|err| format!("HTTP TLS dev: {err}"))?;
2968            Ok(crate::server::tls::HttpTlsConfig {
2969                cert_path: auto.cert_path,
2970                key_path: auto.key_path,
2971                client_ca_path: config.http_tls_client_ca.clone(),
2972            })
2973        }
2974        _ => Err("HTTP TLS requires both --http-tls-cert and --http-tls-key (or neither, with RED_HTTP_TLS_DEV=1)".to_string()),
2975    }
2976}
2977
2978#[cfg(test)]
2979mod tests {
2980    use super::*;
2981
2982    #[test]
2983    fn server_runtime_receives_the_bootstrapped_auth_authority() {
2984        let mut options = RedDBOptions::in_memory();
2985        options.auth.enabled = true;
2986        let (runtime, store, _telemetry) =
2987            build_runtime_with_telemetry(options, None).expect("server runtime");
2988        let installed = runtime.auth_store().expect("runtime auth authority");
2989        assert!(Arc::ptr_eq(&store, &installed));
2990    }
2991
2992    #[test]
2993    fn runtime_workers_use_both_cores_on_small_instances() {
2994        assert_eq!(suggested_worker_count(1), 1);
2995        assert_eq!(suggested_worker_count(2), 2);
2996        assert_eq!(suggested_worker_count(4), 3);
2997    }
2998
2999    #[test]
3000    fn render_systemd_unit_contains_expected_execstart() {
3001        let config = SystemdServiceConfig {
3002            service_name: "reddb".to_string(),
3003            binary_path: PathBuf::from("/usr/local/bin/red"),
3004            run_user: "reddb".to_string(),
3005            run_group: "reddb".to_string(),
3006            data_path: reddb_file::default_service_database_path(),
3007            router_bind_addr: None,
3008            grpc_bind_addr: Some("0.0.0.0:55055".to_string()),
3009            http_bind_addr: None,
3010        };
3011
3012        let unit = render_systemd_unit(&config);
3013        assert!(unit.contains("ExecStart=/usr/local/bin/red server --path /var/lib/reddb/data.rdb --grpc-bind 0.0.0.0:55055"));
3014        assert!(unit.contains("ReadWritePaths=/var/lib/reddb"));
3015    }
3016
3017    #[test]
3018    fn systemd_service_config_derives_paths() {
3019        let config = SystemdServiceConfig {
3020            service_name: "reddb-api".to_string(),
3021            binary_path: PathBuf::from("/usr/local/bin/red"),
3022            run_user: "reddb".to_string(),
3023            run_group: "reddb".to_string(),
3024            data_path: PathBuf::from("/srv/reddb/live/data.rdb"),
3025            router_bind_addr: None,
3026            grpc_bind_addr: None,
3027            http_bind_addr: Some("127.0.0.1:5000".to_string()),
3028        };
3029
3030        assert_eq!(config.data_dir(), PathBuf::from("/srv/reddb/live"));
3031        assert_eq!(
3032            config.unit_path(),
3033            PathBuf::from("/etc/systemd/system/reddb-api.service")
3034        );
3035    }
3036
3037    #[test]
3038    fn render_systemd_unit_supports_dual_transport() {
3039        let config = SystemdServiceConfig {
3040            service_name: "reddb".to_string(),
3041            binary_path: PathBuf::from("/usr/local/bin/red"),
3042            run_user: "reddb".to_string(),
3043            run_group: "reddb".to_string(),
3044            data_path: reddb_file::default_service_database_path(),
3045            router_bind_addr: None,
3046            grpc_bind_addr: Some("0.0.0.0:55055".to_string()),
3047            http_bind_addr: Some("0.0.0.0:5000".to_string()),
3048        };
3049
3050        let unit = render_systemd_unit(&config);
3051        assert!(unit.contains("--grpc-bind 0.0.0.0:55055"));
3052        assert!(unit.contains("--http-bind 0.0.0.0:5000"));
3053    }
3054
3055    #[test]
3056    fn render_systemd_unit_supports_router_mode() {
3057        let config = SystemdServiceConfig {
3058            service_name: "reddb".to_string(),
3059            binary_path: PathBuf::from("/usr/local/bin/red"),
3060            run_user: "reddb".to_string(),
3061            run_group: "reddb".to_string(),
3062            data_path: reddb_file::default_service_database_path(),
3063            router_bind_addr: Some(DEFAULT_ROUTER_BIND_ADDR.to_string()),
3064            grpc_bind_addr: None,
3065            http_bind_addr: None,
3066        };
3067
3068        let unit = render_systemd_unit(&config);
3069        assert!(unit.contains("--bind 127.0.0.1:5050"));
3070        assert!(!unit.contains("--grpc-bind"));
3071        assert!(!unit.contains("--http-bind"));
3072    }
3073
3074    #[test]
3075    fn explicit_bind_collision_is_fatal() {
3076        let held = TcpListener::bind("127.0.0.1:0").expect("hold test port");
3077        let addr = held.local_addr().expect("held addr").to_string();
3078        let mut readiness = TransportReadiness::default();
3079
3080        let error = bind_listener_for_startup(&mut readiness, "http", &addr, true).unwrap_err();
3081
3082        assert!(error.contains("explicit http listener bind"));
3083        assert_eq!(readiness.active.len(), 0);
3084        assert_eq!(readiness.failed.len(), 1);
3085        assert!(readiness.failed[0].explicit);
3086        assert_eq!(readiness.failed[0].bind_addr, addr);
3087    }
3088
3089    // ---------- Issue #663 — `--no-auth` / `--dev` ----------
3090
3091    // Env access in tests is process-global; serialise the two
3092    // `--no-auth` tests so the REDDB_USERNAME / REDDB_PASSWORD pair
3093    // one of them sets cannot leak into the other under cargo's
3094    // default parallel runner.
3095    fn no_auth_env_lock() -> &'static std::sync::Mutex<()> {
3096        static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
3097        LOCK.get_or_init(|| std::sync::Mutex::new(()))
3098    }
3099
3100    fn bootstrap_cert_path(label: &str) -> PathBuf {
3101        std::env::temp_dir().join(format!(
3102            "reddb-{label}-{}-{}.cert",
3103            std::process::id(),
3104            std::time::SystemTime::now()
3105                .duration_since(std::time::UNIX_EPOCH)
3106                .unwrap_or_default()
3107                .as_nanos()
3108        ))
3109    }
3110
3111    #[test]
3112    fn secure_presets_require_certificate_file_delivery() {
3113        let _guard = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3114        unsafe {
3115            std::env::remove_var(BOOTSTRAP_CERT_OUT_ENV);
3116        }
3117        let missing = BootstrapConfig::default();
3118        assert!(require_bootstrap_certificate_output(&missing, PRESET_PRODUCTION).is_err());
3119
3120        let configured = BootstrapConfig {
3121            cert_out: Some(bootstrap_cert_path("required-output")),
3122            ..BootstrapConfig::default()
3123        };
3124        assert!(require_bootstrap_certificate_output(&configured, PRESET_PRODUCTION).is_ok());
3125    }
3126
3127    #[test]
3128    fn official_images_enable_persistent_vault_auth() {
3129        for dockerfile in [
3130            include_str!("../../../Dockerfile"),
3131            include_str!("../../../docker/Dockerfile.release"),
3132            include_str!("../../../docker/Dockerfile.musl"),
3133        ] {
3134            assert!(dockerfile.contains("REDDB_AUTH=true"));
3135            assert!(dockerfile.contains("REDDB_REQUIRE_AUTH=true"));
3136            assert!(dockerfile.contains("REDDB_VAULT=true"));
3137            assert!(!dockerfile.contains("REDDB_VAULT=false"));
3138        }
3139    }
3140
3141    #[test]
3142    fn completed_required_auth_database_cannot_reenter_bootstrap() {
3143        let error = ensure_persisted_auth_state(true, true, true)
3144            .expect_err("empty auth state after durable completion must fail closed");
3145        assert!(error.contains("refusing to reopen public bootstrap"));
3146
3147        assert!(ensure_persisted_auth_state(false, true, true).is_ok());
3148        assert!(ensure_persisted_auth_state(true, false, true).is_ok());
3149        assert!(ensure_persisted_auth_state(true, true, false).is_ok());
3150    }
3151
3152    #[test]
3153    fn failed_certificate_delivery_reservation_is_removed() {
3154        let path = bootstrap_cert_path("failed-reservation");
3155        let bootstrap = BootstrapConfig {
3156            cert_out: Some(path.clone()),
3157            ..BootstrapConfig::default()
3158        };
3159
3160        let output = open_bootstrap_certificate_output(&bootstrap).expect("reserve output");
3161        assert!(path.exists());
3162        #[cfg(unix)]
3163        {
3164            use std::os::unix::fs::PermissionsExt;
3165            let mode = std::fs::metadata(&path)
3166                .expect("certificate metadata")
3167                .permissions()
3168                .mode()
3169                & 0o777;
3170            assert_eq!(mode, 0o600);
3171        }
3172        drop(output);
3173        assert!(!path.exists());
3174    }
3175
3176    #[test]
3177    fn configured_vault_credentials_do_not_require_certificate_output() {
3178        use crate::storage::engine::pager::{Pager, PagerConfig};
3179
3180        let config = crate::auth::AuthConfig {
3181            enabled: true,
3182            require_auth: true,
3183            vault_enabled: true,
3184            ..crate::auth::AuthConfig::default()
3185        };
3186
3187        let passphrase_dir = bootstrap_cert_path("passphrase-vault");
3188        std::fs::create_dir_all(&passphrase_dir).expect("passphrase temp directory");
3189        let passphrase_pager = Arc::new(
3190            Pager::open(passphrase_dir.join("test.rdb"), PagerConfig::default())
3191                .expect("passphrase pager"),
3192        );
3193        let passphrase_store = Arc::new(
3194            AuthStore::with_vault_passphrase(
3195                config.clone(),
3196                Arc::clone(&passphrase_pager),
3197                "test-passphrase",
3198            )
3199            .expect("passphrase vault"),
3200        );
3201        assert!(!passphrase_store.bootstrap_requires_certificate_delivery());
3202        bootstrap_with_certificate_output(&passphrase_store, "admin", "secret", &mut None)
3203            .expect("passphrase bootstrap without certificate output");
3204        drop(passphrase_store);
3205        drop(passphrase_pager);
3206        let _ = std::fs::remove_dir_all(passphrase_dir);
3207
3208        let certificate_dir = bootstrap_cert_path("certificate-vault");
3209        std::fs::create_dir_all(&certificate_dir).expect("certificate temp directory");
3210        let certificate_pager = Arc::new(
3211            Pager::open(certificate_dir.join("test.rdb"), PagerConfig::default())
3212                .expect("certificate pager"),
3213        );
3214        let certificate = "11".repeat(32);
3215        let certificate_store = Arc::new(
3216            AuthStore::with_vault_certificate(config, Arc::clone(&certificate_pager), &certificate)
3217                .expect("certificate vault"),
3218        );
3219        assert!(!certificate_store.bootstrap_requires_certificate_delivery());
3220        bootstrap_with_certificate_output(&certificate_store, "admin", "secret", &mut None)
3221            .expect("certificate bootstrap without duplicate output");
3222        drop(certificate_store);
3223        drop(certificate_pager);
3224        let _ = std::fs::remove_dir_all(certificate_dir);
3225    }
3226
3227    #[test]
3228    fn required_auth_simple_preset_waits_for_durable_admin() {
3229        let _guard = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3230        let runtime = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime");
3231        let auth_store = Arc::new(AuthStore::new(crate::auth::AuthConfig {
3232            enabled: true,
3233            require_auth: true,
3234            vault_enabled: true,
3235            ..crate::auth::AuthConfig::default()
3236        }));
3237
3238        apply_preset(&runtime, &auth_store).expect("pending simple preset");
3239        assert!(runtime
3240            .db()
3241            .store()
3242            .try_get_config(BOOTSTRAP_COMPLETED_KEY)
3243            .expect("completion lookup")
3244            .is_none());
3245    }
3246
3247    #[test]
3248    fn server_options_preserve_explicit_disk_residency() {
3249        let _guard = no_auth_env_lock().lock().unwrap();
3250        let mut config = no_auth_test_config(true);
3251        assert!(!config.to_db_options().unwrap().bounded_disk_residency);
3252        config.bounded_disk_residency = true;
3253        assert!(config.to_db_options().unwrap().bounded_disk_residency);
3254    }
3255
3256    #[test]
3257    fn replication_term_parser_defaults_and_rejects_unsafe_values() {
3258        assert_eq!(
3259            parse_replication_term(None).expect("default term"),
3260            crate::replication::DEFAULT_REPLICATION_TERM
3261        );
3262        assert_eq!(parse_replication_term(Some("8")).expect("explicit term"), 8);
3263        for raw in ["", "0", "-1", "abc"] {
3264            let error = parse_replication_term(Some(raw)).expect_err("invalid term");
3265            assert!(error.contains("positive integer"), "{error}");
3266        }
3267    }
3268
3269    fn no_auth_test_config(no_auth: bool) -> ServerCommandConfig {
3270        ServerCommandConfig {
3271            path: None,
3272            router_bind_addr: Some(DEFAULT_ROUTER_BIND_ADDR.to_string()),
3273            router_bind_explicit: false,
3274            grpc_bind_addr: None,
3275            grpc_bind_explicit: false,
3276            grpc_tls_bind_addr: None,
3277            grpc_tls_cert: None,
3278            grpc_tls_key: None,
3279            grpc_tls_client_ca: None,
3280            http_bind_addr: None,
3281            http_bind_explicit: false,
3282            http_tls_bind_addr: None,
3283            http_tls_cert: None,
3284            http_tls_key: None,
3285            http_tls_client_ca: None,
3286            wire_bind_addr: None,
3287            wire_bind_explicit: false,
3288            wire_tls_bind_addr: None,
3289            wire_tls_cert: None,
3290            wire_tls_key: None,
3291            pg_bind_addr: None,
3292            create_if_missing: true,
3293            bounded_disk_residency: false,
3294            read_only: false,
3295            role: "standalone".to_string(),
3296            primary_addr: None,
3297            storage_profile: StorageProfileSelection::embedded_single_file(),
3298            auth: false,
3299            require_auth: false,
3300            // Operator-set `--vault`: `--no-auth` must override this
3301            // alongside REDDB_USERNAME/PASSWORD.
3302            vault: true,
3303            no_auth,
3304            workers: None,
3305            telemetry: None,
3306            http_limits_cli: crate::server::HttpLimitsCliInput::default(),
3307            ui: false,
3308            ui_dir: None,
3309            bootstrap: BootstrapConfig::default(),
3310        }
3311    }
3312
3313    #[test]
3314    fn no_auth_flag_disables_every_auth_knob_and_stamps_metadata() {
3315        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3316        // Pre-existing env that *would* turn auth on if `--no-auth`
3317        // weren't the last word. The acceptance criterion is that
3318        // the flag wins over env.
3319        // SAFETY: serialised by `no_auth_env_lock` above.
3320        unsafe {
3321            std::env::set_var("REDDB_USERNAME", "admin");
3322            std::env::set_var("REDDB_PASSWORD", "hunter2");
3323        }
3324        let config = no_auth_test_config(true);
3325        let options = config.to_db_options().expect("to_db_options");
3326
3327        assert!(no_auth_active(&options), "metadata should be stamped");
3328        assert!(!options.auth.enabled, "auth.enabled must be forced off");
3329        assert!(
3330            !options.auth.require_auth,
3331            "require_auth must be forced off"
3332        );
3333        assert!(
3334            !options.auth.vault_enabled,
3335            "vault_enabled must be forced off (overrides --vault)"
3336        );
3337        assert_eq!(
3338            options.metadata.get(NO_AUTH_META).map(String::as_str),
3339            Some("true"),
3340        );
3341
3342        // SAFETY: serialised by `no_auth_env_lock` above.
3343        unsafe {
3344            std::env::remove_var("REDDB_USERNAME");
3345            std::env::remove_var("REDDB_PASSWORD");
3346        }
3347    }
3348
3349    #[test]
3350    fn default_behaviour_without_no_auth_flag_is_unchanged() {
3351        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3352        let config = no_auth_test_config(false);
3353        let options = config.to_db_options().expect("to_db_options");
3354
3355        assert!(
3356            !no_auth_active(&options),
3357            "default boot must not be marked no-auth"
3358        );
3359        assert!(
3360            options.metadata.get(NO_AUTH_META).is_none(),
3361            "metadata key must be absent when flag is off"
3362        );
3363        // `--vault` should still take effect when `--no-auth` is not set.
3364        assert!(options.auth.vault_enabled);
3365    }
3366
3367    #[test]
3368    fn no_auth_active_blocks_bootstrap_from_env() {
3369        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3370        // SAFETY: serialised by `no_auth_env_lock` above. The pair
3371        // would normally cause `AuthStore::bootstrap_from_env` to
3372        // create an admin; the boot pipeline must suppress that call
3373        // whenever `no_auth_active` is true.
3374        unsafe {
3375            std::env::set_var("REDDB_USERNAME", "admin");
3376            std::env::set_var("REDDB_PASSWORD", "hunter2");
3377        }
3378
3379        let options = no_auth_test_config(true)
3380            .to_db_options()
3381            .expect("to_db_options");
3382
3383        // Mirror the exact branch in `build_runtime_with_telemetry`:
3384        // build a non-vault AuthStore from `options.auth`, then call
3385        // `bootstrap_from_env` *only* when the no-auth gate is off.
3386        let auth_store = AuthStore::new(options.auth.clone());
3387        if !no_auth_active(&options) {
3388            auth_store.bootstrap_from_env();
3389        }
3390
3391        assert!(
3392            auth_store.needs_bootstrap(),
3393            "no admin user must be bootstrapped under --no-auth even with REDDB_USERNAME/PASSWORD set"
3394        );
3395
3396        // SAFETY: serialised by `no_auth_env_lock` above.
3397        unsafe {
3398            std::env::remove_var("REDDB_USERNAME");
3399            std::env::remove_var("REDDB_PASSWORD");
3400        }
3401    }
3402
3403    // ---------- Issue #650 — bootstrap presets ----------
3404
3405    // Preset tests mutate process-global env (`REDDB_PRESET`,
3406    // `REDDB_USERNAME`, `REDDB_PASSWORD`) and the global tracing
3407    // subscriber. Share the no_auth lock so they don't race with each
3408    // other or with the --no-auth tests above.
3409    fn clear_preset_env() {
3410        // SAFETY: callers hold `no_auth_env_lock()`.
3411        unsafe {
3412            std::env::remove_var(BOOTSTRAP_PRESET_ENV);
3413            std::env::remove_var(PRESET_ENV);
3414            std::env::remove_var("REDDB_BOOTSTRAP_MANIFEST");
3415            std::env::remove_var("REDDB_AUTH");
3416            std::env::remove_var("REDDB_REQUIRE_AUTH");
3417            std::env::remove_var("REDDB_NO_AUTH");
3418            std::env::remove_var("REDDB_DEV");
3419            std::env::remove_var("REDDB_VAULT");
3420            std::env::remove_var("REDDB_USERNAME");
3421            std::env::remove_var("REDDB_PASSWORD");
3422            std::env::remove_var("REDDB_USERNAME_FILE");
3423            std::env::remove_var("REDDB_PASSWORD_FILE");
3424            std::env::remove_var(BOOTSTRAP_CERT_OUT_ENV);
3425            std::env::remove_var("REDDB_CLOUD_HEAD_ADMIN");
3426            std::env::remove_var("REDDB_CLOUD_HEAD_ADMIN_PASSWORD");
3427            std::env::remove_var("REDDB_CLOUD_HEAD_ADMIN_PASSWORD_FILE");
3428            std::env::remove_var("REDDB_CUSTOMER_ADMIN");
3429            std::env::remove_var("REDDB_CUSTOMER_ADMIN_PASSWORD");
3430            std::env::remove_var("REDDB_CUSTOMER_ADMIN_PASSWORD_FILE");
3431        }
3432    }
3433
3434    fn clear_backup_env() {
3435        // SAFETY: callers hold `no_auth_env_lock()`.
3436        unsafe {
3437            std::env::remove_var("REDDB_BACKUP_S3_ENDPOINT");
3438            std::env::remove_var("REDDB_BACKUP_S3_BUCKET");
3439            std::env::remove_var("REDDB_BACKUP_S3_PREFIX");
3440            std::env::remove_var("REDDB_BACKUP_S3_ACCESS_KEY_ID");
3441            std::env::remove_var("REDDB_BACKUP_S3_SECRET_ACCESS_KEY");
3442            std::env::remove_var("REDDB_BACKUP_S3_REGION");
3443            std::env::remove_var("REDDB_BACKUP_CHECKPOINT_INTERVAL_SECS");
3444            std::env::remove_var("REDDB_BACKUP_WAL_FLUSH_INTERVAL_SECS");
3445            std::env::remove_var("REDDB_BACKUP_PAUSE_ON_LAG_SECS");
3446        }
3447    }
3448
3449    fn fresh_runtime_and_store() -> (RedDBRuntime, Arc<AuthStore>) {
3450        let runtime = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime");
3451        let auth_store = Arc::new(AuthStore::new(crate::auth::AuthConfig::default()));
3452        (runtime, auth_store)
3453    }
3454
3455    #[test]
3456    fn auth_env_knobs_enable_auth_require_auth_and_vault() {
3457        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3458        clear_preset_env();
3459        // SAFETY: env serialised by `no_auth_env_lock`.
3460        unsafe {
3461            std::env::set_var("REDDB_AUTH", "true");
3462            std::env::set_var("REDDB_REQUIRE_AUTH", "true");
3463            std::env::set_var("REDDB_VAULT", "true");
3464        }
3465
3466        let mut config = no_auth_test_config(false);
3467        config.vault = false;
3468        let options = config.to_db_options().expect("to_db_options");
3469
3470        assert!(options.auth.enabled);
3471        assert!(options.auth.require_auth);
3472        assert!(options.auth.vault_enabled);
3473
3474        clear_preset_env();
3475    }
3476
3477    #[test]
3478    fn production_and_cloud_presets_force_auth_require_auth_and_vault() {
3479        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3480        clear_preset_env();
3481
3482        for preset in [PRESET_PRODUCTION, PRESET_CLOUD] {
3483            let mut config = no_auth_test_config(false);
3484            config.vault = false;
3485            config.bootstrap.preset = Some(preset.to_string());
3486
3487            let options = config.to_db_options().expect("to_db_options");
3488            assert!(options.auth.enabled, "{preset} should enable auth");
3489            assert!(
3490                options.auth.require_auth,
3491                "{preset} should require authenticated requests"
3492            );
3493            assert!(options.auth.vault_enabled, "{preset} should enable vault");
3494            assert!(!no_auth_active(&options));
3495        }
3496
3497        clear_preset_env();
3498    }
3499
3500    #[test]
3501    fn no_auth_env_overrides_preset_forced_auth() {
3502        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3503        clear_preset_env();
3504        // SAFETY: env serialised by `no_auth_env_lock`.
3505        unsafe {
3506            std::env::set_var("REDDB_NO_AUTH", "true");
3507            std::env::set_var(BOOTSTRAP_PRESET_ENV, PRESET_CLOUD);
3508        }
3509
3510        let mut config = no_auth_test_config(false);
3511        config.auth = true;
3512        config.require_auth = true;
3513        let options = config.to_db_options().expect("to_db_options");
3514
3515        assert!(no_auth_active(&options));
3516        assert!(!options.auth.enabled);
3517        assert!(!options.auth.require_auth);
3518        assert!(!options.auth.vault_enabled);
3519
3520        clear_preset_env();
3521    }
3522
3523    #[test]
3524    fn simple_preset_is_default_and_persists_state() {
3525        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3526        clear_preset_env();
3527
3528        let (runtime, auth_store) = fresh_runtime_and_store();
3529        apply_preset(&runtime, &auth_store).expect("simple preset applies cleanly");
3530
3531        // No admin was created — `simple` is anonymous-friendly.
3532        assert!(
3533            auth_store.needs_bootstrap(),
3534            "simple preset must not create an admin"
3535        );
3536
3537        // Bootstrap state persisted so the next boot is a no-op.
3538        let store = runtime.db().store();
3539        let completed = store
3540            .get_config(BOOTSTRAP_COMPLETED_KEY)
3541            .expect("completed key persisted");
3542        assert!(matches!(completed, reddb_types::Value::Boolean(true)));
3543        let preset = store
3544            .get_config(BOOTSTRAP_PRESET_KEY)
3545            .expect("preset key persisted");
3546        match preset {
3547            reddb_types::Value::Text(s) => assert_eq!(s.as_ref(), PRESET_SIMPLE),
3548            other => panic!("expected Text(simple), got {other:?}"),
3549        }
3550        assert!(
3551            store.get_config(BOOTSTRAP_FIRST_ADMIN_KEY).is_none(),
3552            "simple preset must not record a first admin"
3553        );
3554
3555        clear_preset_env();
3556    }
3557
3558    #[test]
3559    fn production_preset_creates_first_admin_with_allow_all_policy() {
3560        use crate::auth::policies::{EvalContext, ResourceRef};
3561        use crate::auth::UserId;
3562
3563        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3564        clear_preset_env();
3565        let cert_out = bootstrap_cert_path("production-admin");
3566        // SAFETY: env serialised by `no_auth_env_lock`.
3567        unsafe {
3568            std::env::set_var(PRESET_ENV, PRESET_PRODUCTION);
3569            std::env::set_var("REDDB_USERNAME", "ops");
3570            std::env::set_var("REDDB_PASSWORD", "hunter2");
3571            std::env::set_var(BOOTSTRAP_CERT_OUT_ENV, &cert_out);
3572        }
3573
3574        let (runtime, auth_store) = fresh_runtime_and_store();
3575        apply_preset(&runtime, &auth_store).expect("production preset applies cleanly");
3576
3577        // Admin exists and the auth store is sealed.
3578        assert!(
3579            !auth_store.needs_bootstrap(),
3580            "production preset must seal bootstrap"
3581        );
3582        let users = auth_store.list_users();
3583        assert_eq!(users.len(), 1);
3584        let admin = &users[0];
3585        assert_eq!(admin.username, "ops");
3586        assert!(
3587            admin.tenant_id.is_none(),
3588            "first admin must be platform-scoped (tenant=None)"
3589        );
3590
3591        // Allow-all policy was installed and attached to the first admin.
3592        let policy = auth_store
3593            .get_policy(FIRST_ADMIN_ALLOW_ALL_POLICY)
3594            .expect("allow-all policy installed");
3595        assert!(!policy.statements.is_empty());
3596
3597        // Verify policy-derived authority via the policy evaluator —
3598        // not a bypass. Any action on any resource must Allow.
3599        let actor = UserId::platform("ops");
3600        let ctx = EvalContext {
3601            principal_tenant: None,
3602            current_tenant: None,
3603            peer_ip: None,
3604            mfa_present: false,
3605            now_ms: 1_700_000_000_000,
3606            principal_is_admin_role: true,
3607            principal_is_platform_scoped: true,
3608        };
3609        let arbitrary_resource = ResourceRef::new("config", "red.config.audit.enabled");
3610        assert!(
3611            auth_store.check_policy_authz(&actor, "config:write", &arbitrary_resource, &ctx),
3612            "allow-all policy must grant arbitrary actions via the evaluator"
3613        );
3614
3615        // Persisted state records the first admin id.
3616        let store = runtime.db().store();
3617        match store
3618            .get_config(BOOTSTRAP_FIRST_ADMIN_KEY)
3619            .expect("first_admin_id persisted")
3620        {
3621            reddb_types::Value::Text(s) => assert_eq!(s.as_ref(), "ops"),
3622            other => panic!("expected Text(ops), got {other:?}"),
3623        }
3624        match store.get_config(BOOTSTRAP_PRESET_KEY).unwrap() {
3625            reddb_types::Value::Text(s) => assert_eq!(s.as_ref(), PRESET_PRODUCTION),
3626            other => panic!("expected Text(production), got {other:?}"),
3627        }
3628
3629        clear_preset_env();
3630        let _ = std::fs::remove_file(cert_out);
3631    }
3632
3633    #[test]
3634    fn bootstrap_preset_env_takes_precedence_over_legacy_preset_env() {
3635        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3636        clear_preset_env();
3637        // SAFETY: env serialised by `no_auth_env_lock`.
3638        unsafe {
3639            std::env::set_var(BOOTSTRAP_PRESET_ENV, PRESET_REGULATED);
3640            std::env::set_var(PRESET_ENV, PRESET_SIMPLE);
3641        }
3642
3643        let options = no_auth_test_config(false)
3644            .to_db_options()
3645            .expect("regulated options");
3646        assert!(
3647            options.control_events.compliance_mode,
3648            "canonical REDDB_BOOTSTRAP_PRESET should win over REDDB_PRESET"
3649        );
3650        assert!(options.query_audit.enabled);
3651
3652        clear_preset_env();
3653    }
3654
3655    #[test]
3656    fn cloud_preset_creates_system_head_and_customer_admins() {
3657        use crate::auth::policies::{EvalContext, ResourceRef};
3658        use crate::auth::UserId;
3659
3660        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3661        clear_preset_env();
3662        let cert_out = bootstrap_cert_path("cloud-admins");
3663        // SAFETY: env serialised by `no_auth_env_lock`.
3664        unsafe {
3665            std::env::set_var(BOOTSTRAP_PRESET_ENV, PRESET_CLOUD);
3666            std::env::set_var("REDDB_CLOUD_HEAD_ADMIN", "head");
3667            std::env::set_var("REDDB_CLOUD_HEAD_ADMIN_PASSWORD", "head-pass");
3668            std::env::set_var("REDDB_CUSTOMER_ADMIN", "customer");
3669            std::env::set_var("REDDB_CUSTOMER_ADMIN_PASSWORD", "customer-pass");
3670            std::env::set_var(BOOTSTRAP_CERT_OUT_ENV, &cert_out);
3671        }
3672
3673        let (runtime, auth_store) = fresh_runtime_and_store();
3674        apply_preset(&runtime, &auth_store).expect("cloud preset applies cleanly");
3675
3676        let head = auth_store
3677            .get_user(None, "head")
3678            .expect("head admin should exist");
3679        assert_eq!(head.tenant_id, None);
3680        let customer = auth_store
3681            .get_user(None, "customer")
3682            .expect("customer admin should exist");
3683        assert_eq!(customer.tenant_id, None);
3684
3685        let ctx = EvalContext {
3686            principal_tenant: None,
3687            current_tenant: None,
3688            peer_ip: None,
3689            mfa_present: false,
3690            now_ms: 1_700_000_000_000,
3691            principal_is_admin_role: true,
3692            principal_is_platform_scoped: true,
3693        };
3694        assert!(auth_store.check_policy_authz(
3695            &UserId::platform("customer"),
3696            "config:write",
3697            &ResourceRef::new("config", "red.config.customer.enabled"),
3698            &ctx,
3699        ));
3700        assert!(
3701            auth_store.check_policy_authz(
3702                &UserId::platform("head"),
3703                "config:write",
3704                &ResourceRef::new("config", "red.config.cloud.enabled"),
3705                &ctx,
3706            ),
3707            "cloud head keeps allow-all authority over managed cloud config"
3708        );
3709        assert!(
3710            !auth_store.check_policy_authz(
3711                &UserId::platform("customer"),
3712                "config:write",
3713                &ResourceRef::new("config", "red.config.cloud.enabled"),
3714                &ctx,
3715            ),
3716            "cloud customer must be denied managed cloud config writes"
3717        );
3718        assert!(
3719            !auth_store.check_policy_authz(
3720                &UserId::platform("customer"),
3721                "policy:drop",
3722                &ResourceRef::new("policy", CLOUD_PROTECT_MANAGED_POLICY),
3723                &ctx,
3724            ),
3725            "cloud customer must be denied mutations of the managed guardrail policy"
3726        );
3727
3728        assert!(auth_store.get_user(None, "head").is_some());
3729        assert!(auth_store
3730            .get_policy(CLOUD_PROTECT_MANAGED_POLICY)
3731            .is_some());
3732        assert!(runtime
3733            .config_registry()
3734            .get_active(CLOUD_CONFIG_NAMESPACE)
3735            .is_some());
3736
3737        let store = runtime.db().store();
3738        match store
3739            .get_config(BOOTSTRAP_FIRST_ADMIN_KEY)
3740            .expect("head admin id persisted")
3741        {
3742            reddb_types::Value::Text(s) => assert_eq!(s.as_ref(), "head"),
3743            other => panic!("expected Text(head), got {other:?}"),
3744        }
3745        match store.get_config(BOOTSTRAP_PRESET_KEY).unwrap() {
3746            reddb_types::Value::Text(s) => assert_eq!(s.as_ref(), PRESET_CLOUD),
3747            other => panic!("expected Text(cloud), got {other:?}"),
3748        }
3749
3750        clear_preset_env();
3751        let _ = std::fs::remove_file(cert_out);
3752    }
3753
3754    #[test]
3755    fn cloud_preset_customer_cannot_disable_head_admin_or_drop_guardrail_policy() {
3756        use crate::auth::Role;
3757        use crate::runtime::mvcc::{clear_current_auth_identity, set_current_auth_identity};
3758
3759        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3760        clear_preset_env();
3761
3762        let bootstrap = BootstrapConfig {
3763            preset: Some(PRESET_CLOUD.to_string()),
3764            cloud_head_admin: Some("red_admin".to_string()),
3765            cloud_head_admin_password: Some("head-pass".to_string()),
3766            customer_admin: Some("admin".to_string()),
3767            customer_admin_password: Some("customer-pass".to_string()),
3768            cert_out: Some(bootstrap_cert_path("cloud-guardrail")),
3769            ..BootstrapConfig::default()
3770        };
3771        let (runtime, auth_store) = fresh_runtime_and_store();
3772        apply_preset_from_config(&runtime, &auth_store, &bootstrap)
3773            .expect("cloud preset applies cleanly");
3774        runtime.set_auth_store(Arc::clone(&auth_store));
3775
3776        set_current_auth_identity("admin".to_string(), Role::Admin);
3777        let disable_head = runtime.execute_query("ALTER USER red_admin DISABLE");
3778        let drop_guardrail =
3779            runtime.execute_query(&format!("DROP POLICY '{}'", CLOUD_PROTECT_MANAGED_POLICY));
3780        let create_user = runtime.execute_query("CREATE USER app_user WITH PASSWORD 'p' ROLE read");
3781        let disable_user = runtime.execute_query("ALTER USER app_user DISABLE");
3782        clear_current_auth_identity();
3783
3784        let disable_head_err = disable_head.expect_err("customer admin must not disable red_admin");
3785        assert!(
3786            disable_head_err.to_string().contains("user:disable"),
3787            "error should name the denied lifecycle action: {disable_head_err}"
3788        );
3789        assert!(
3790            auth_store
3791                .get_user(None, "red_admin")
3792                .expect("red_admin should still exist")
3793                .enabled,
3794            "denied mutation must leave red_admin enabled"
3795        );
3796
3797        let drop_guardrail_err =
3798            drop_guardrail.expect_err("customer admin must not drop cloud guardrail policy");
3799        assert!(
3800            drop_guardrail_err.to_string().contains("managed policy"),
3801            "error should name the managed policy guardrail: {drop_guardrail_err}"
3802        );
3803        assert!(auth_store
3804            .get_policy(CLOUD_PROTECT_MANAGED_POLICY)
3805            .is_some());
3806
3807        create_user.expect("customer admin should retain normal create-user authority");
3808        disable_user.expect("customer admin should retain normal user-disable authority");
3809        assert!(
3810            !auth_store
3811                .get_user(None, "app_user")
3812                .expect("app_user should exist")
3813                .enabled,
3814            "normal capability should still apply outside the reserved head admin"
3815        );
3816
3817        let _ = bootstrap.cert_out.as_ref().map(std::fs::remove_file);
3818        clear_preset_env();
3819    }
3820
3821    #[test]
3822    fn cloud_preset_cli_admin_alias_wins_over_cloud_env_password() {
3823        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3824        clear_preset_env();
3825        // SAFETY: env serialised by `no_auth_env_lock`.
3826        unsafe {
3827            std::env::set_var("REDDB_CLOUD_HEAD_ADMIN_PASSWORD", "env-head-pass");
3828        }
3829
3830        let bootstrap = BootstrapConfig {
3831            preset: Some(PRESET_CLOUD.to_string()),
3832            admin_username: Some("head".to_string()),
3833            admin_password: Some("cli-head-pass".to_string()),
3834            customer_admin: Some("customer".to_string()),
3835            customer_admin_password: Some("customer-pass".to_string()),
3836            cert_out: Some(bootstrap_cert_path("cloud-alias")),
3837            ..BootstrapConfig::default()
3838        };
3839        let (runtime, auth_store) = fresh_runtime_and_store();
3840        apply_preset_from_config(&runtime, &auth_store, &bootstrap)
3841            .expect("cloud preset applies cleanly");
3842
3843        auth_store
3844            .authenticate("head", "cli-head-pass")
3845            .expect("CLI alias password should win");
3846        assert!(
3847            auth_store.authenticate("head", "env-head-pass").is_err(),
3848            "cloud-specific env password must not beat CLI alias"
3849        );
3850
3851        let _ = bootstrap.cert_out.as_ref().map(std::fs::remove_file);
3852        clear_preset_env();
3853    }
3854
3855    #[test]
3856    fn bootstrap_intent_manifest_matches_cloud_flag_path() {
3857        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3858        clear_preset_env();
3859
3860        let manifest_dir = tempfile::tempdir().expect("create manifest test dir");
3861        let head_password = manifest_dir.path().join("head.secret");
3862        let customer_password = manifest_dir.path().join("customer.secret");
3863        let manifest_path = manifest_dir.path().join("intent.json");
3864        std::fs::write(&head_password, "head-pass\n").expect("write head secret");
3865        std::fs::write(&customer_password, "customer-pass\n").expect("write customer secret");
3866        let manifest = ::serde_json::json!({
3867            "bootstrap": {
3868                "preset": "cloud",
3869                "cloud_head_admin": {
3870                    "username": "head",
3871                    "password_file": head_password,
3872                },
3873                "customer_admin": {
3874                    "username": "customer",
3875                    "password_file": customer_password,
3876                },
3877            },
3878        });
3879        std::fs::write(
3880            &manifest_path,
3881            ::serde_json::to_vec(&manifest).expect("serialize manifest"),
3882        )
3883        .expect("write manifest");
3884
3885        let mut config = no_auth_test_config(false);
3886        config.bootstrap.manifest = Some(manifest_path.clone());
3887        let options = config.to_db_options().expect("manifest options");
3888        assert!(options.auth.enabled);
3889        assert!(options.auth.require_auth);
3890        assert!(options.auth.vault_enabled);
3891
3892        let (runtime, auth_store) = fresh_runtime_and_store();
3893        apply_preset_from_config(&runtime, &auth_store, &config.bootstrap)
3894            .expect("manifest intent applies cleanly");
3895
3896        auth_store
3897            .authenticate("head", "head-pass")
3898            .expect("head password comes from file");
3899        auth_store
3900            .authenticate("customer", "customer-pass")
3901            .expect("customer password comes from file");
3902        assert!(auth_store.get_user(None, "head").is_some());
3903        assert!(auth_store.get_user(None, "customer").is_some());
3904        assert!(auth_store
3905            .get_policy(CLOUD_PROTECT_MANAGED_POLICY)
3906            .is_some());
3907        match runtime
3908            .db()
3909            .store()
3910            .get_config(BOOTSTRAP_PRESET_KEY)
3911            .expect("preset key persisted")
3912        {
3913            reddb_types::Value::Text(s) => assert_eq!(s.as_ref(), PRESET_CLOUD),
3914            other => panic!("expected Text(cloud), got {other:?}"),
3915        }
3916
3917        apply_preset_from_config(&runtime, &auth_store, &config.bootstrap)
3918            .expect("second boot is idempotent");
3919
3920        clear_preset_env();
3921    }
3922
3923    #[test]
3924    fn regulated_preset_enables_query_audit_infrastructure_without_rules() {
3925        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3926        clear_preset_env();
3927        // SAFETY: env serialised by `no_auth_env_lock`.
3928        unsafe {
3929            std::env::set_var(PRESET_ENV, PRESET_REGULATED);
3930        }
3931
3932        let (runtime, auth_store) = fresh_runtime_and_store();
3933        apply_preset(&runtime, &auth_store).expect("regulated preset applies cleanly");
3934
3935        assert!(runtime.query_audit().is_enabled());
3936        assert!(runtime.query_audit().rules().is_empty());
3937        assert!(
3938            runtime
3939                .db()
3940                .store()
3941                .get_collection(crate::runtime::query_audit::QUERY_AUDIT_COLLECTION)
3942                .is_some(),
3943            "regulated preset should create the query-audit stream"
3944        );
3945
3946        runtime
3947            .execute_query("CREATE TABLE docs (id INT)")
3948            .expect("create table");
3949        runtime
3950            .execute_query("INSERT INTO docs (id) VALUES (1)")
3951            .expect("insert");
3952        runtime.execute_query("SELECT * FROM docs").expect("select");
3953        let rows = runtime
3954            .db()
3955            .store()
3956            .get_collection(crate::runtime::query_audit::QUERY_AUDIT_COLLECTION)
3957            .expect("query audit collection")
3958            .query_all(|_| true);
3959        assert!(
3960            rows.is_empty(),
3961            "regulated preset must not globally audit every query"
3962        );
3963
3964        clear_preset_env();
3965    }
3966
3967    #[test]
3968    fn managed_backup_env_rejects_primary_replica_single_file_storage() {
3969        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3970        clear_backup_env();
3971        // SAFETY: env serialised by `no_auth_env_lock`.
3972        unsafe {
3973            std::env::set_var("REDDB_BACKUP_S3_ENDPOINT", "https://s3.example.test");
3974            std::env::set_var("REDDB_BACKUP_S3_BUCKET", "reddb");
3975            std::env::set_var("REDDB_BACKUP_S3_PREFIX", "clusters/prod");
3976            std::env::set_var("REDDB_BACKUP_S3_ACCESS_KEY_ID", "AK");
3977            std::env::set_var("REDDB_BACKUP_S3_SECRET_ACCESS_KEY", "SK");
3978        }
3979
3980        let mut config = no_auth_test_config(false);
3981        config.role = "primary".to_string();
3982        config.storage_profile = crate::storage::StorageDeployPreset::PrimaryReplicaDev.selection();
3983
3984        let err = config.to_db_options().unwrap_err();
3985        assert!(err.contains("managed backup"), "got: {err}");
3986        assert!(err.contains("operational-directory"), "got: {err}");
3987
3988        clear_backup_env();
3989    }
3990
3991    #[test]
3992    fn lease_only_backend_preserves_primary_replica_single_file_storage() {
3993        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
3994        clear_backup_env();
3995        // SAFETY: env serialised by `no_auth_env_lock`.
3996        unsafe {
3997            std::env::set_var("RED_BACKEND", "fs");
3998            std::env::set_var("RED_REMOTE_KEY", "lease-only-test");
3999        }
4000
4001        let mut config = no_auth_test_config(false);
4002        config.role = "primary".to_string();
4003        config.storage_profile = crate::storage::StorageDeployPreset::PrimaryReplicaDev.selection();
4004
4005        let options = config.to_db_options().expect("lease-only backend options");
4006        assert!(options.remote_backend_atomic.is_some());
4007        assert_eq!(
4008            options.storage_profile,
4009            crate::storage::StorageDeployPreset::PrimaryReplicaDev.selection()
4010        );
4011
4012        // SAFETY: env serialised by `no_auth_env_lock`.
4013        unsafe {
4014            std::env::remove_var("RED_BACKEND");
4015            std::env::remove_var("RED_REMOTE_KEY");
4016        }
4017    }
4018
4019    #[test]
4020    fn regulated_preset_installs_managed_evidence_guardrails_end_to_end() {
4021        use crate::auth::policies::{EvalContext, Policy, ResourceRef};
4022        use crate::auth::store::PrincipalRef;
4023        use crate::auth::{Role, UserId};
4024        use crate::runtime::mvcc::{clear_current_auth_identity, set_current_auth_identity};
4025        use reddb_types::Value;
4026
4027        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
4028        clear_preset_env();
4029        // SAFETY: env serialised by `no_auth_env_lock`.
4030        unsafe {
4031            std::env::set_var(PRESET_ENV, PRESET_REGULATED);
4032        }
4033
4034        let options = no_auth_test_config(false)
4035            .to_db_options()
4036            .expect("regulated options");
4037        assert!(
4038            options.control_events.compliance_mode,
4039            "regulated preset must enable fail-closed control evidence before runtime boot"
4040        );
4041        assert!(
4042            options.query_audit.enabled && options.query_audit.rules.is_empty(),
4043            "regulated preset must enable query-audit infrastructure without global rules"
4044        );
4045
4046        let runtime = RedDBRuntime::with_options(options).expect("runtime");
4047        let auth_store = Arc::new(AuthStore::new(crate::auth::AuthConfig::default()));
4048        apply_preset(&runtime, &auth_store).expect("regulated preset applies cleanly");
4049        runtime.set_auth_store(Arc::clone(&auth_store));
4050
4051        assert!(runtime.control_events_require_persistence());
4052        assert!(runtime.query_audit().is_enabled());
4053        assert!(runtime.query_audit().rules().is_empty());
4054        assert!(auth_store
4055            .get_policy(REGULATED_PROTECT_MANAGED_POLICY)
4056            .is_some());
4057
4058        let managed_policy = runtime
4059            .config_registry()
4060            .get_active(REGULATED_PROTECT_MANAGED_POLICY)
4061            .expect("regulated managed policy registry entry");
4062        assert!(managed_policy.managed);
4063        assert_eq!(managed_policy.resource_type, "policy");
4064        assert!(
4065            runtime
4066                .config_registry()
4067                .get_active(REGULATED_AUDIT_CONFIG_NAMESPACE)
4068                .expect("regulated audit config namespace")
4069                .managed
4070        );
4071
4072        let registry_rows = runtime
4073            .execute_query(&format!(
4074                "SELECT id, managed FROM red.registry WHERE id = '{}'",
4075                REGULATED_PROTECT_MANAGED_POLICY
4076            ))
4077            .expect("red.registry query");
4078        assert_eq!(registry_rows.result.records.len(), 1);
4079        assert_eq!(
4080            registry_rows.result.records[0].get("managed"),
4081            Some(&Value::Boolean(true))
4082        );
4083
4084        let managed_policy_rows = runtime
4085            .execute_query(&format!(
4086                "SELECT policy_id FROM red.managed_policies WHERE policy_id = '{}'",
4087                REGULATED_PROTECT_MANAGED_POLICY
4088            ))
4089            .expect("red.managed_policies query");
4090        assert_eq!(managed_policy_rows.result.records.len(), 1);
4091
4092        let capability_rows = runtime
4093            .execute_query(
4094                "SELECT action FROM red.control_capabilities WHERE action = 'evidence:export'",
4095            )
4096            .expect("red.control_capabilities query");
4097        assert_eq!(capability_rows.result.records.len(), 1);
4098
4099        auth_store
4100            .create_user("alice", "p", Role::Admin)
4101            .expect("create ordinary admin");
4102        let allow_all = Policy::from_json_str(
4103            r#"{
4104                "id": "alice-allow-all",
4105                "version": 1,
4106                "statements": [{
4107                    "effect": "allow",
4108                    "actions": ["*"],
4109                    "resources": ["*"]
4110                }]
4111            }"#,
4112        )
4113        .expect("allow-all policy");
4114        auth_store.put_policy(allow_all).expect("install allow-all");
4115        auth_store
4116            .attach_policy(
4117                PrincipalRef::User(UserId::platform("alice")),
4118                "alice-allow-all",
4119            )
4120            .expect("attach allow-all");
4121        let ctx = EvalContext {
4122            principal_tenant: None,
4123            current_tenant: None,
4124            peer_ip: None,
4125            mfa_present: false,
4126            now_ms: 1_700_000_000_000,
4127            principal_is_admin_role: true,
4128            principal_is_platform_scoped: true,
4129        };
4130        assert!(
4131            !auth_store.check_policy_authz(
4132                &UserId::platform("alice"),
4133                "policy:drop",
4134                &ResourceRef::new("policy", REGULATED_PROTECT_MANAGED_POLICY),
4135                &ctx,
4136            ),
4137            "managed guardrail deny policy must be effective for ordinary admins"
4138        );
4139
4140        set_current_auth_identity("alice".to_string(), Role::Admin);
4141        let denied = runtime.execute_query(&format!(
4142            "DROP POLICY '{}'",
4143            REGULATED_PROTECT_MANAGED_POLICY
4144        ));
4145        clear_current_auth_identity();
4146        let err = denied.expect_err("managed policy guardrail must deny ordinary admin");
4147        assert!(
4148            err.to_string().contains("managed policy"),
4149            "error should name the managed guardrail: {err}"
4150        );
4151        assert!(
4152            auth_store
4153                .get_policy(REGULATED_PROTECT_MANAGED_POLICY)
4154                .is_some(),
4155            "denied mutation must leave managed policy installed"
4156        );
4157
4158        let denied_events = runtime
4159            .execute_query(&format!(
4160                "SELECT action, resource, outcome FROM red.control_events \
4161                 WHERE action = 'policy:drop' AND resource = 'policy:{}'",
4162                REGULATED_PROTECT_MANAGED_POLICY
4163            ))
4164            .expect("red.control_events denied policy drop");
4165        assert_eq!(denied_events.result.records.len(), 1);
4166        assert_eq!(
4167            denied_events.result.records[0].get("outcome"),
4168            Some(&Value::text("denied"))
4169        );
4170
4171        set_current_auth_identity("alice".to_string(), Role::Admin);
4172        let config_denied = runtime.execute_query("SET CONFIG audit.enabled = true");
4173        clear_current_auth_identity();
4174        let err = config_denied.expect_err("managed config guardrail must deny ordinary admin");
4175        assert!(
4176            err.to_string().contains("managed config"),
4177            "error should name the managed config guardrail: {err}"
4178        );
4179
4180        let denied_config_events = runtime
4181            .execute_query(
4182                "SELECT action, resource, outcome FROM red.control_events \
4183                 WHERE action = 'config:write' AND resource = 'config:red.config/audit.enabled'",
4184            )
4185            .expect("red.control_events denied config write");
4186        assert_eq!(denied_config_events.result.records.len(), 1);
4187        assert_eq!(
4188            denied_config_events.result.records[0].get("outcome"),
4189            Some(&Value::text("denied"))
4190        );
4191
4192        runtime
4193            .execute_query("CREATE TABLE regulated_docs (id INT)")
4194            .expect("create user table");
4195        runtime
4196            .execute_query("SELECT * FROM regulated_docs")
4197            .expect("select user table");
4198        let audit_rows = runtime
4199            .db()
4200            .store()
4201            .get_collection(crate::runtime::query_audit::QUERY_AUDIT_COLLECTION)
4202            .expect("query audit collection")
4203            .query_all(|_| true);
4204        assert!(
4205            audit_rows.is_empty(),
4206            "regulated preset must not globally audit data-plane queries"
4207        );
4208
4209        clear_preset_env();
4210    }
4211
4212    #[test]
4213    fn bootstrap_manifest_installs_initial_users_policies_guardrails_and_config() {
4214        use crate::auth::policies::{EvalContext, ResourceRef};
4215        use crate::auth::UserId;
4216        use reddb_types::Value;
4217
4218        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
4219        clear_preset_env();
4220
4221        let manifest_dir = tempfile::tempdir().expect("create manifest test dir");
4222        let manifest_path = manifest_dir.path().join("reddb-bootstrap-manifest.json");
4223        std::fs::write(
4224            &manifest_path,
4225            r#"{
4226                "users": [
4227                    {
4228                        "username": "ops",
4229                        "password": "hunter2",
4230                        "role": "admin"
4231                    }
4232                ],
4233                "policies": [
4234                    {
4235                        "id": "bootstrap-registry-admin",
4236                        "version": 1,
4237                        "statements": [
4238                            {
4239                                "effect": "allow",
4240                                "actions": ["red.registry:*", "policy:*", "config:write", "select"],
4241                                "resources": ["registry:*", "policy:*", "config:*", "collection:docs"]
4242                            }
4243                        ]
4244                    }
4245                ],
4246                "managed_policies": [
4247                    {
4248                        "id": "managed-deny-drop",
4249                        "version": 1,
4250                        "statements": [
4251                            {
4252                                "effect": "deny",
4253                                "actions": ["policy:drop"],
4254                                "resources": ["policy:managed-deny-drop"]
4255                            }
4256                        ],
4257                        "required_resource": "policy:managed-deny-drop",
4258                        "evidence": "full"
4259                    }
4260                ],
4261                "attachments": [
4262                    {"user": "ops", "policy": "bootstrap-registry-admin"}
4263                ],
4264                "managed_config_namespaces": [
4265                    {
4266                        "id": "red.ai",
4267                        "required_action": "config:write",
4268                        "required_resource": "config:red.ai.*",
4269                        "evidence": "metadata"
4270                    }
4271                ],
4272                "config": [
4273                    {"key": "ai.default.provider", "value": "openai"},
4274                    {
4275                        "key": "ai.openai.default.secret_ref",
4276                        "secret_ref": {"collection": "red.vault", "key": "openai"}
4277                    }
4278                ],
4279                "actor": "ops"
4280            }"#,
4281        )
4282        .expect("write manifest");
4283        // SAFETY: env serialised by `no_auth_env_lock`.
4284        unsafe {
4285            std::env::set_var("REDDB_BOOTSTRAP_MANIFEST", &manifest_path);
4286        }
4287
4288        let (runtime, auth_store) = fresh_runtime_and_store();
4289        apply_preset(&runtime, &auth_store).expect("manifest applies cleanly");
4290
4291        let users = auth_store.list_users();
4292        assert_eq!(users.len(), 1);
4293        assert_eq!(users[0].username, "ops");
4294        assert!(users[0].tenant_id.is_none());
4295
4296        let actor = UserId::platform("ops");
4297        let ctx = EvalContext {
4298            principal_tenant: None,
4299            current_tenant: None,
4300            peer_ip: None,
4301            mfa_present: false,
4302            now_ms: 1_700_000_000_000,
4303            principal_is_admin_role: true,
4304            principal_is_platform_scoped: true,
4305        };
4306        // Manifest fixture pins a canonical data-plane read action.
4307        assert!(auth_store.check_policy_authz(
4308            &actor,
4309            "select",
4310            &ResourceRef::new("collection", "docs"),
4311            &ctx
4312        ));
4313
4314        let managed_policy = runtime
4315            .config_registry()
4316            .get_active("managed-deny-drop")
4317            .expect("managed policy registry entry");
4318        assert!(managed_policy.managed);
4319        assert_eq!(managed_policy.resource_type, "policy");
4320        let managed_config = runtime
4321            .config_registry()
4322            .get_active("red.ai")
4323            .expect("managed config namespace registry entry");
4324        assert!(managed_config.managed);
4325        assert_eq!(managed_config.resource_type, "config_namespace");
4326
4327        let store = runtime.db().store();
4328        match store
4329            .get_config("ai.default.provider")
4330            .expect("plain config persisted")
4331        {
4332            Value::Text(s) => assert_eq!(s.as_ref(), "openai"),
4333            other => panic!("expected provider text, got {other:?}"),
4334        }
4335        let Value::Json(bytes) = store
4336            .get_config("ai.openai.default.secret_ref")
4337            .expect("secret ref config persisted")
4338        else {
4339            panic!("secret ref must be stored as structured JSON");
4340        };
4341        let reference: crate::serde_json::Value =
4342            crate::serde_json::from_slice(&bytes).expect("secret ref json");
4343        assert_eq!(
4344            reference.get("type").and_then(|v| v.as_str()),
4345            Some("secret_ref")
4346        );
4347        assert!(
4348            !String::from_utf8_lossy(&bytes).contains("hunter2"),
4349            "manifest password must not leak into secret ref config"
4350        );
4351
4352        let completed = store
4353            .get_config(BOOTSTRAP_COMPLETED_KEY)
4354            .expect("bootstrap completion persisted");
4355        assert!(matches!(completed, Value::Boolean(true)));
4356        assert!(
4357            store
4358                .get_config("system.bootstrap.manifest.registry_entries")
4359                .is_some(),
4360            "managed registry entries must be persisted internally"
4361        );
4362
4363        std::fs::remove_file(&manifest_path).expect("remove manifest after first boot");
4364        let restored_registry = Arc::new(crate::auth::registry::ConfigRegistry::new());
4365        crate::cli::bootstrap_manifest::rehydrate_manifest_registry(&runtime, &restored_registry)
4366            .expect("registry rehydrates without manifest file");
4367        assert!(restored_registry.get_active("managed-deny-drop").is_some());
4368        assert!(restored_registry.get_active("red.ai").is_some());
4369
4370        let fresh = Arc::new(AuthStore::new(crate::auth::AuthConfig::default()));
4371        apply_preset(&runtime, &fresh).expect("re-run must not need manifest file");
4372        assert!(fresh.needs_bootstrap());
4373
4374        clear_preset_env();
4375    }
4376
4377    #[test]
4378    fn production_preset_refuses_to_start_without_password() {
4379        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
4380        clear_preset_env();
4381        let cert_out = bootstrap_cert_path("production-missing-password");
4382        // SAFETY: env serialised by `no_auth_env_lock`.
4383        unsafe {
4384            std::env::set_var(PRESET_ENV, PRESET_PRODUCTION);
4385            std::env::set_var("REDDB_USERNAME", "ops");
4386            std::env::set_var(BOOTSTRAP_CERT_OUT_ENV, &cert_out);
4387        }
4388
4389        let (runtime, auth_store) = fresh_runtime_and_store();
4390        let err = apply_preset(&runtime, &auth_store).expect_err("must reject missing password");
4391        assert!(
4392            err.contains("REDDB_PASSWORD"),
4393            "error must name the missing env: {err}"
4394        );
4395
4396        // Nothing was persisted; nothing was created.
4397        assert!(auth_store.needs_bootstrap());
4398        assert!(runtime
4399            .db()
4400            .store()
4401            .get_config(BOOTSTRAP_COMPLETED_KEY)
4402            .is_none());
4403        assert!(!cert_out.exists());
4404
4405        clear_preset_env();
4406    }
4407
4408    #[test]
4409    fn re_running_production_after_first_boot_is_a_silent_skip() {
4410        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
4411        clear_preset_env();
4412        let cert_out = bootstrap_cert_path("production-rerun");
4413        // SAFETY: env serialised by `no_auth_env_lock`.
4414        unsafe {
4415            std::env::set_var(PRESET_ENV, PRESET_PRODUCTION);
4416            std::env::set_var("REDDB_USERNAME", "ops");
4417            std::env::set_var("REDDB_PASSWORD", "hunter2");
4418            std::env::set_var(BOOTSTRAP_CERT_OUT_ENV, &cert_out);
4419        }
4420
4421        let (runtime, auth_store) = fresh_runtime_and_store();
4422        apply_preset(&runtime, &auth_store).expect("first apply");
4423        assert_eq!(auth_store.list_users().len(), 1);
4424
4425        // Second invocation: same runtime/store, same env. Must be a
4426        // no-op — no error, no duplicate admin, no duplicate policy.
4427        // We do NOT reuse `auth_store` because production sealed it; the
4428        // idempotency hinge is the persisted config key, not the auth
4429        // store's in-memory seal. Build a fresh `AuthStore` as a restart
4430        // would and confirm `apply_preset` is a silent skip.
4431        let fresh = Arc::new(AuthStore::new(crate::auth::AuthConfig::default()));
4432        apply_preset(&runtime, &fresh).expect("re-run is silent-skip");
4433        assert!(
4434            fresh.needs_bootstrap(),
4435            "re-run must not create a second admin"
4436        );
4437        assert!(
4438            fresh.get_policy(FIRST_ADMIN_ALLOW_ALL_POLICY).is_none(),
4439            "re-run must not re-install the allow-all policy on the fresh store"
4440        );
4441
4442        clear_preset_env();
4443        let _ = std::fs::remove_file(cert_out);
4444    }
4445
4446    #[test]
4447    fn unrecognised_preset_value_is_rejected() {
4448        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
4449        clear_preset_env();
4450        // SAFETY: env serialised by `no_auth_env_lock`.
4451        unsafe {
4452            std::env::set_var(PRESET_ENV, "weird");
4453        }
4454
4455        let (runtime, auth_store) = fresh_runtime_and_store();
4456        let err = apply_preset(&runtime, &auth_store).expect_err("must reject unknown preset");
4457        assert!(err.contains("weird"), "error must echo the value: {err}");
4458        assert!(auth_store.needs_bootstrap());
4459
4460        clear_preset_env();
4461    }
4462
4463    #[test]
4464    fn no_auth_short_circuits_preset_entirely() {
4465        let _g = no_auth_env_lock().lock().unwrap_or_else(|e| e.into_inner());
4466        clear_preset_env();
4467        // SAFETY: env serialised by `no_auth_env_lock`. Production creds
4468        // are set but `--no-auth` must win — no admin, no bootstrap state.
4469        unsafe {
4470            std::env::set_var(PRESET_ENV, PRESET_PRODUCTION);
4471            std::env::set_var("REDDB_USERNAME", "ops");
4472            std::env::set_var("REDDB_PASSWORD", "hunter2");
4473        }
4474
4475        let options = no_auth_test_config(true)
4476            .to_db_options()
4477            .expect("to_db_options");
4478        assert!(no_auth_active(&options));
4479
4480        // Mirror `build_runtime_with_telemetry`: when no_auth_active,
4481        // `apply_preset` is never called.
4482        let (runtime, auth_store) = fresh_runtime_and_store();
4483        if !no_auth_active(&options) {
4484            apply_preset(&runtime, &auth_store).expect("would apply preset");
4485        }
4486
4487        assert!(
4488            auth_store.needs_bootstrap(),
4489            "--no-auth must prevent any admin creation"
4490        );
4491        assert!(
4492            runtime
4493                .db()
4494                .store()
4495                .get_config(BOOTSTRAP_COMPLETED_KEY)
4496                .is_none(),
4497            "--no-auth must skip bootstrap-state persistence"
4498        );
4499
4500        clear_preset_env();
4501    }
4502
4503    #[test]
4504    fn implicit_bind_collision_degrades() {
4505        let held = TcpListener::bind("127.0.0.1:0").expect("hold test port");
4506        let addr = held.local_addr().expect("held addr").to_string();
4507        let mut readiness = TransportReadiness::default();
4508
4509        let listener =
4510            bind_listener_for_startup(&mut readiness, "http", &addr, false).expect("nonfatal");
4511
4512        assert!(listener.is_none());
4513        assert_eq!(readiness.active.len(), 0);
4514        assert_eq!(readiness.failed.len(), 1);
4515        assert!(!readiness.failed[0].explicit);
4516        assert_eq!(readiness.failed[0].bind_addr, addr);
4517    }
4518}