Skip to main content

reddb_server/runtime/
impl_config_secret.rs

1//! Runtime config / secret / KV resolution.
2//!
3//! Extracted verbatim from `impl_core.rs` (impl_core slice 7/10, issue #1628).
4//! Houses the config-tier readers, secret encrypt/decrypt pipeline, and vault
5//! KV accessors:
6//!
7//! - **Free helpers** — `seed_storage_deploy_config`, `show_secrets_allows_key`,
8//!   `secret_sql_value_to_string`, `insert_config_json_path`,
9//!   `insert_config_json_segments`, `show_config_json_result`.
10//! - **Methods** — `vault_kv_get`, `vault_kv_try_set`, `secret_aes_key`,
11//!   `config_bool`, `binary_document_body_enabled`, `config_u64`, `config_f64`,
12//!   `config_string`, `secret_auto_encrypt`.
13use super::*;
14
15pub(crate) fn seed_storage_deploy_config(
16    store: &crate::storage::UnifiedStore,
17    selection: crate::storage::StorageProfileSelection,
18) {
19    store.set_config_tree(
20        "storage.deploy",
21        &crate::json!({
22            "profile": selection.deploy_profile.as_str(),
23            "packaging": selection.packaging.as_str(),
24            "preset": selection.preset_name(),
25            "replica_count": selection.replica_count,
26            "managed_backup": selection.managed_backup,
27            "wal_retention": selection.wal_retention,
28        }),
29    );
30}
31
32pub(crate) fn show_secrets_allows_key(key: &str) -> bool {
33    ![
34        "red.secret.",
35        "red.config.",
36        "red.iam.",
37        "red.acl.",
38        "red.vault.",
39    ]
40    .iter()
41    .any(|prefix| key.starts_with(prefix))
42}
43
44pub(crate) fn secret_sql_value_to_string(value: &Value) -> RedDBResult<String> {
45    match value {
46        Value::Text(s) => Ok(s.to_string()),
47        Value::Integer(n) => Ok(n.to_string()),
48        Value::UnsignedInteger(n) => Ok(n.to_string()),
49        Value::Float(n) => Ok(n.to_string()),
50        Value::Boolean(b) => Ok(b.to_string()),
51        Value::Null => Err(RedDBError::Query(
52            "SET SECRET key = NULL deletes the secret; use DELETE SECRET for explicit deletes"
53                .to_string(),
54        )),
55        Value::Password(_) | Value::Secret(_) => Err(RedDBError::Query(
56            "SET SECRET accepts plain scalar literals; PASSWORD() and SECRET() are for typed columns"
57                .to_string(),
58        )),
59        _ => Err(RedDBError::Query(format!(
60            "SET SECRET does not support value type {:?} yet",
61            value.data_type()
62        ))),
63    }
64}
65
66#[cfg(test)]
67mod tests {
68    use super::*;
69
70    #[test]
71    fn show_secrets_allows_only_user_managed_keys() {
72        assert!(!show_secrets_allows_key("red.secret.aes_key"));
73        assert!(!show_secrets_allows_key(
74            "red.secret.ai.providers.anthropic.tokens.default"
75        ));
76        assert!(!show_secrets_allows_key("red.config.ai.default.provider"));
77        assert!(show_secrets_allows_key("acme.key"));
78    }
79
80    #[test]
81    fn typed_config_readers_preserve_cold_values_and_live_updates() {
82        let directory = tempfile::tempdir().expect("config fixture");
83        let runtime = RedDBRuntime::with_options(
84            RedDBOptions::persistent(directory.path().join("config.rdb"))
85                .with_memory_budget(32 * 1024 * 1024)
86                .with_bounded_disk_residency(true),
87        )
88        .expect("runtime");
89        let store = runtime.db().store();
90        store
91            .try_set_config_tree(
92                "probe",
93                &crate::json!({"boolean": false, "integer": 42, "float": 1.5, "string": "saved"}),
94            )
95            .expect("persist configuration");
96        store
97            .try_set_config_tree("queue.max_wait_ms", &crate::json!(1))
98            .expect("queue wait limit");
99        store.persist().expect("checkpoint");
100        let manager = store
101            .get_collection("red.config")
102            .expect("config collection");
103        assert!(manager.has_backing(), "fixture must read persisted rows");
104        assert!(
105            manager.query_all(|_| true).is_empty(),
106            "fixture must be cold"
107        );
108        assert_eq!(
109            store.try_get_config("probe.integer").unwrap(),
110            Some(Value::UnsignedInteger(42))
111        );
112        assert!(!runtime.config_bool("probe.boolean", true));
113        assert_eq!(runtime.config_u64("probe.integer", 9), 42);
114        assert_eq!(runtime.config_f64("probe.float", 9.0), 1.5);
115        assert_eq!(runtime.config_string("probe.string", "default"), "saved");
116        assert!(runtime.redwire_queue_wait_cap_check(5).is_err());
117        store
118            .try_set_config_tree("probe.integer", &crate::json!(73))
119            .expect("live replacement");
120        assert_eq!(runtime.config_u64("probe.integer", 9), 73);
121        assert_eq!(runtime.config_u64("probe.missing", 9), 9);
122    }
123
124    #[test]
125    fn show_config_lists_values_that_are_on_disk() {
126        let directory = tempfile::tempdir().expect("config fixture");
127        let runtime = RedDBRuntime::with_options(
128            RedDBOptions::persistent(directory.path().join("config.rdb"))
129                .with_memory_budget(32 * 1024 * 1024)
130                .with_bounded_disk_residency(true),
131        )
132        .expect("runtime");
133        let shown = |runtime: &RedDBRuntime| -> Vec<Value> {
134            runtime
135                .execute_query("SHOW CONFIG probe.string")
136                .expect("show")
137                .result
138                .records
139                .iter()
140                .filter_map(|record| record.get("value").cloned())
141                .collect()
142        };
143        runtime
144            .execute_query("SET CONFIG probe.string = 'saved'")
145            .expect("set");
146        let store = runtime.db().store();
147        store.persist().expect("checkpoint");
148        let manager = store
149            .get_collection("red.config")
150            .expect("config collection");
151        assert!(manager.has_backing(), "fixture must read persisted rows");
152        assert!(
153            manager.query_all(|_| true).is_empty(),
154            "fixture must be cold"
155        );
156        assert_eq!(shown(&runtime), vec![Value::text("saved")]);
157
158        // A value set afterwards is resident and replaces the one on disk.
159        runtime
160            .execute_query("SET CONFIG probe.string = 'newer'")
161            .expect("replace");
162        assert_eq!(shown(&runtime), vec![Value::text("newer")]);
163    }
164
165    #[test]
166    fn boot_defaults_and_overlay_preserve_cold_operator_configuration() {
167        let directory = tempfile::tempdir().expect("config fixture");
168        let runtime = RedDBRuntime::with_options(
169            RedDBOptions::persistent(directory.path().join("config.rdb"))
170                .with_memory_budget(32 * 1024 * 1024)
171                .with_bounded_disk_residency(true),
172        )
173        .expect("runtime");
174        let store = runtime.db().store();
175        store
176            .try_set_config_tree("concurrency.locking.enabled", &crate::json!(false))
177            .expect("operator configuration");
178        store.persist().expect("checkpoint");
179        super::super::config_matrix::heal_critical_keys(store.as_ref());
180        assert_eq!(
181            store.try_get_config("concurrency.locking.enabled").unwrap(),
182            Some(Value::Boolean(false))
183        );
184        let overlay = directory.path().join("overlay.json");
185        std::fs::write(&overlay, r#"{"concurrency":{"locking":{"enabled":true}}}"#)
186            .expect("overlay fixture");
187        assert_eq!(
188            super::super::config_overlay::apply_config_file(
189                store.as_ref(),
190                overlay.to_str().unwrap()
191            ),
192            0
193        );
194        assert_eq!(
195            store.try_get_config("concurrency.locking.enabled").unwrap(),
196            Some(Value::Boolean(false))
197        );
198    }
199
200    #[test]
201    fn fresh_boot_never_persists_a_redundant_red_config_prefix() {
202        let runtime = RedDBRuntime::in_memory().expect("runtime");
203        let manager = runtime
204            .db()
205            .store()
206            .get_collection("red.config")
207            .expect("red.config");
208        let mut invalid = Vec::new();
209        manager.for_each_entity(|entity| {
210            if let Some(Value::Text(key)) =
211                entity.data.as_row().and_then(|row| row.get_field("key"))
212            {
213                if key.starts_with("red.") {
214                    invalid.push(key.to_string());
215                }
216            }
217            true
218        });
219        assert!(
220            invalid.is_empty(),
221            "fresh red.config contains redundant prefixes: {invalid:?}"
222        );
223    }
224
225    #[test]
226    fn sql_config_surfaces_reject_redundant_red_prefixes() {
227        let runtime = RedDBRuntime::in_memory().expect("runtime");
228        for query in ["SET CONFIG red.auth.enabled = true", "SHOW CONFIG red.auth"] {
229            let error = match runtime.execute_query(query) {
230                Ok(_) => panic!("legacy config key unexpectedly accepted: {query}"),
231                Err(error) => error,
232            };
233            assert!(
234                error
235                    .to_string()
236                    .contains("omit the redundant `red.` prefix"),
237                "unexpected error for {query}: {error}"
238            );
239        }
240    }
241}
242
243pub(crate) fn insert_config_json_path(
244    root: &mut crate::serde_json::Value,
245    path: &str,
246    value: crate::serde_json::Value,
247) {
248    let segments: Vec<&str> = path
249        .split('.')
250        .filter(|segment| !segment.is_empty())
251        .collect();
252    insert_config_json_segments(root, &segments, value);
253}
254
255fn insert_config_json_segments(
256    root: &mut crate::serde_json::Value,
257    segments: &[&str],
258    value: crate::serde_json::Value,
259) {
260    if segments.is_empty() {
261        *root = value;
262        return;
263    }
264
265    if !matches!(root, crate::serde_json::Value::Object(_)) {
266        *root = crate::serde_json::Value::Object(crate::serde_json::Map::new());
267    }
268
269    let crate::serde_json::Value::Object(map) = root else {
270        return;
271    };
272    if segments.len() == 1 {
273        map.insert(segments[0].to_string(), value);
274        return;
275    }
276    let entry = map
277        .entry(segments[0].to_string())
278        .or_insert_with(|| crate::serde_json::Value::Object(crate::serde_json::Map::new()));
279    insert_config_json_segments(entry, &segments[1..], value);
280}
281
282pub(crate) fn show_config_json_result(
283    query: &str,
284    mode: reddb_rql::modes::QueryMode,
285    prefix: &Option<String>,
286    value: crate::serde_json::Value,
287) -> RuntimeQueryResult {
288    let mut result = UnifiedResult::with_columns(vec!["key".into(), "value".into()]);
289    let mut record = UnifiedRecord::new();
290    record.set(
291        "key",
292        prefix
293            .as_ref()
294            .map(|key| Value::text(key.clone()))
295            .unwrap_or(Value::Null),
296    );
297    record.set("value", Value::Json(value.to_string_compact().into_bytes()));
298    result.push(record);
299    RuntimeQueryResult {
300        query: query.to_string(),
301        mode,
302        statement: "show_config_json",
303        engine: "runtime-config",
304        result,
305        affected_rows: 0,
306        statement_type: "select",
307        bookmark: None,
308        notice: None,
309    }
310}
311
312impl RedDBRuntime {
313    pub(crate) fn set_internal_provider_secret(
314        &self,
315        key: &str,
316        value: Option<String>,
317    ) -> RedDBResult<()> {
318        self.reject_vault_transaction()?;
319        if super::execution_context::current_tenant().is_some() {
320            return Err(RedDBError::Query(
321                "system provider credentials are platform-scoped".into(),
322            ));
323        }
324        let auth =
325            self.inner.auth_store.read().clone().ok_or_else(|| {
326                RedDBError::Query("secret storage requires an enabled vault".into())
327            })?;
328        self.check_secret_write_privilege(&auth, key)?;
329        match value {
330            Some(value) => auth.vault_kv_try_set(key.into(), value),
331            None => auth.vault_kv_try_delete(key).map(|_| ()),
332        }
333        .map_err(|err| RedDBError::Query(err.to_string()))?;
334        self.invalidate_result_cache();
335        Ok(())
336    }
337
338    /// Read a vault KV secret from the configured AuthStore, if present.
339    pub fn vault_kv_get(&self, key: &str) -> Option<String> {
340        self.inner
341            .auth_store
342            .read()
343            .as_ref()
344            .and_then(|store| store.vault_kv_get(key))
345    }
346
347    /// Write a vault KV secret and fail if the encrypted vault write is
348    /// unavailable or cannot be made durable.
349    pub fn vault_kv_try_set(&self, key: String, value: String) -> RedDBResult<()> {
350        let store = self.inner.auth_store.read().clone().ok_or_else(|| {
351            RedDBError::Query("secret storage requires an enabled, unsealed vault".to_string())
352        })?;
353        store
354            .vault_kv_try_set(key, value)
355            .map_err(|err| RedDBError::Query(err.to_string()))
356    }
357
358    /// Returns the vault AES key (`red.secret.aes_key`) if an auth
359    /// store is wired and a key has been generated. Used by the
360    /// `Value::Secret` encrypt/decrypt pipeline.
361    pub(crate) fn secret_aes_key(&self) -> Option<[u8; 32]> {
362        let guard = self.inner.auth_store.read();
363        guard.as_ref().and_then(|s| s.vault_secret_key())
364    }
365
366    /// Resolve a boolean flag from `red.config`. Defaults to `default`
367    /// when the key is missing or not coercible. If the same key has
368    /// been written multiple times (SET CONFIG appends new rows), the
369    /// most recent entity wins. Env-var overrides
370    /// (`REDDB_<UP_DOTTED>`) take highest precedence.
371    pub(crate) fn config_bool(&self, key: &str, default: bool) -> bool {
372        if let Some(raw) = self.inner.env_config_overrides.get(key) {
373            if let Some(reddb_types::Value::Boolean(b)) =
374                crate::runtime::config_overlay::coerce_env_value(key, raw)
375            {
376                return b;
377            }
378        }
379        match self.inner.db.store().get_config(key) {
380            Some(Value::Boolean(value)) => value,
381            Some(Value::Text(value)) => matches!(value.as_ref(), "true" | "TRUE" | "True" | "1"),
382            Some(Value::Integer(value)) => value != 0,
383            _ => default,
384        }
385    }
386
387    /// Whether DOCUMENT writes should store the body as the native binary
388    /// container (PRD-1398, ADR-0063). On by default after the production
389    /// cutover. Reads decode the container transparently regardless of this
390    /// flag.
391    pub(crate) fn binary_document_body_enabled(&self) -> bool {
392        self.config_bool("storage.binary_document_body", true)
393    }
394
395    pub(crate) fn config_u64(&self, key: &str, default: u64) -> u64 {
396        if let Some(raw) = self.inner.env_config_overrides.get(key) {
397            if let Some(Value::UnsignedInteger(value)) =
398                crate::runtime::config_overlay::coerce_env_value(key, raw)
399            {
400                return value;
401            }
402        }
403        match self.inner.db.store().get_config(key) {
404            Some(Value::Integer(value)) => value as u64,
405            Some(Value::UnsignedInteger(value)) => value,
406            Some(Value::Text(value)) => value.parse::<u64>().unwrap_or(default),
407            _ => default,
408        }
409    }
410
411    pub(crate) fn config_f64(&self, key: &str, default: f64) -> f64 {
412        if let Some(raw) = self.inner.env_config_overrides.get(key) {
413            if let Ok(value) = raw.parse::<f64>() {
414                return value;
415            }
416        }
417        match self.inner.db.store().get_config(key) {
418            Some(Value::Float(value)) => value,
419            Some(Value::Integer(value)) => value as f64,
420            Some(Value::UnsignedInteger(value)) => value as f64,
421            Some(Value::Text(value)) => value.parse::<f64>().unwrap_or(default),
422            _ => default,
423        }
424    }
425
426    pub(crate) fn config_string(&self, key: &str, default: &str) -> String {
427        if let Some(raw) = self.inner.env_config_overrides.get(key) {
428            return raw.clone();
429        }
430        match self.inner.db.store().get_config(key) {
431            Some(Value::Text(value)) => value.to_string(),
432            _ => default.to_string(),
433        }
434    }
435
436    /// Whether `SECRET('...')` literals should be encrypted with the
437    /// vault AES key on INSERT. Default `true`.
438    pub(crate) fn secret_auto_encrypt(&self) -> bool {
439        self.config_bool("secret.auto_encrypt", true)
440    }
441}