Skip to main content

reddb_server/
service_cli.rs

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