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