Skip to main content

codewhale_config/
persistence.rs

1//! Transactional persistence, atomic writes, and secret redaction for the
2//! v0.8.67 constitution-first setup lane (#3410).
3//!
4//! This is the safety layer under every setup step. A setup session may touch
5//! several files (the setup-state sidecar, the user-global constitution, and —
6//! through the existing comment-preserving `ConfigStore` — `config.toml`). The
7//! contract this module guarantees:
8//!
9//! - **Preview writes nothing.** [`SetupTransaction::preview`] reports what
10//!   would change without touching the filesystem.
11//! - **Cancel leaves files unchanged.** A staged transaction that is dropped
12//!   without [`SetupTransaction::commit`] never wrote anything.
13//! - **Save is atomic.** Each file is written through a temp file + rename
14//!   ([`atomic_write`]); a multi-file commit either fully applies or fully
15//!   rolls back, so a partial failure never leaves a half-written file.
16//! - **Secrets never leak.** [`redact_secrets`] masks secret-bearing values for
17//!   any report, log line, or diagnostic that might echo config text.
18//!
19//! This module deliberately owns only the write / rollback / secret contract.
20//! Each setup step owns *which* fields it writes; see [`crate::setup_state`] and
21//! [`crate::user_constitution`].
22
23use std::fs;
24use std::path::{Path, PathBuf};
25
26use anyhow::{Context, Result};
27use serde::Serialize;
28
29#[cfg(unix)]
30use std::os::unix::fs::PermissionsExt;
31
32/// Restrictive file mode for setup-owned files (owner read/write only).
33#[cfg(unix)]
34const SETUP_FILE_MODE: u32 = 0o600;
35
36/// Atomically write `bytes` to `path` via a sibling temp file + rename.
37///
38/// The temp file is created in the same directory as `path` so the final
39/// `rename` is atomic on the same filesystem. On Unix the file is created with
40/// `0o600` so setup-owned state never lands world-readable. Parent directories
41/// are created as needed.
42pub fn atomic_write(path: &Path, bytes: &[u8]) -> Result<()> {
43    let parent = path.parent().filter(|p| !p.as_os_str().is_empty());
44    if let Some(parent) = parent {
45        fs::create_dir_all(parent)
46            .with_context(|| format!("failed to create directory {}", parent.display()))?;
47    }
48
49    let dir = parent.unwrap_or_else(|| Path::new("."));
50    let mut tmp = tempfile::NamedTempFile::new_in(dir)
51        .with_context(|| format!("failed to create temp file in {}", dir.display()))?;
52
53    use std::io::Write as _;
54    tmp.write_all(bytes)
55        .with_context(|| format!("failed to write temp file for {}", path.display()))?;
56    tmp.flush()
57        .with_context(|| format!("failed to flush temp file for {}", path.display()))?;
58
59    #[cfg(unix)]
60    {
61        let perms = fs::Permissions::from_mode(SETUP_FILE_MODE);
62        tmp.as_file()
63            .set_permissions(perms)
64            .with_context(|| format!("failed to set permissions for {}", path.display()))?;
65    }
66
67    tmp.persist(path)
68        .map_err(|e| e.error)
69        .with_context(|| format!("failed to persist {}", path.display()))?;
70    Ok(())
71}
72
73/// Atomically write `value` as pretty-printed JSON to `path`.
74///
75/// A trailing newline is appended so the file is well-formed for line-oriented
76/// tooling and diffs.
77pub fn atomic_write_json<T: Serialize>(path: &Path, value: &T) -> Result<()> {
78    let mut body = serde_json::to_string_pretty(value)
79        .with_context(|| format!("failed to serialize JSON for {}", path.display()))?;
80    body.push('\n');
81    atomic_write(path, body.as_bytes())
82}
83
84/// A staged multi-file write that either fully applies or fully rolls back.
85///
86/// Stage every file the setup step intends to write, then call [`commit`]. If
87/// any single write fails, every already-applied write in the transaction is
88/// restored to its pre-commit contents (or removed if it did not previously
89/// exist), and the original error is returned. A transaction that is dropped
90/// without committing leaves the filesystem untouched.
91///
92/// [`commit`]: SetupTransaction::commit
93#[derive(Debug, Default)]
94pub struct SetupTransaction {
95    writes: Vec<StagedWrite>,
96}
97
98#[derive(Debug, Clone)]
99struct StagedWrite {
100    path: PathBuf,
101    bytes: Vec<u8>,
102}
103
104/// A snapshot of a file's pre-commit state, captured so [`SetupTransaction`]
105/// can restore it during rollback.
106struct Snapshot {
107    path: PathBuf,
108    /// Original bytes, or `None` if the file did not exist before commit.
109    original: Option<Vec<u8>>,
110}
111
112impl SetupTransaction {
113    /// Create an empty transaction.
114    #[must_use]
115    pub fn new() -> Self {
116        Self::default()
117    }
118
119    /// Stage `bytes` to be written to `path` on [`commit`](Self::commit).
120    ///
121    /// Staging touches nothing on disk. A later stage for the same path
122    /// replaces an earlier one, so a step can revise its intended output before
123    /// committing.
124    pub fn stage(&mut self, path: impl Into<PathBuf>, bytes: impl Into<Vec<u8>>) -> &mut Self {
125        let path = path.into();
126        let bytes = bytes.into();
127        if let Some(existing) = self.writes.iter_mut().find(|w| w.path == path) {
128            existing.bytes = bytes;
129        } else {
130            self.writes.push(StagedWrite { path, bytes });
131        }
132        self
133    }
134
135    /// Stage `value` serialized as pretty JSON (with trailing newline).
136    pub fn stage_json<T: Serialize>(
137        &mut self,
138        path: impl Into<PathBuf>,
139        value: &T,
140    ) -> Result<&mut Self> {
141        let path = path.into();
142        let mut body = serde_json::to_string_pretty(value)
143            .with_context(|| format!("failed to serialize JSON for {}", path.display()))?;
144        body.push('\n');
145        Ok(self.stage(path, body.into_bytes()))
146    }
147
148    /// The paths that [`commit`](Self::commit) would write, in staging order.
149    /// Writes nothing — this is the preview surface.
150    #[must_use]
151    pub fn preview(&self) -> Vec<&Path> {
152        self.writes.iter().map(|w| w.path.as_path()).collect()
153    }
154
155    /// True when nothing is staged.
156    #[must_use]
157    pub fn is_empty(&self) -> bool {
158        self.writes.is_empty()
159    }
160
161    /// Apply every staged write atomically.
162    ///
163    /// On success all files are updated. On the first failure, every write that
164    /// already landed is rolled back to its captured pre-commit state and the
165    /// original error is returned (rollback failures are attached as context).
166    pub fn commit(self) -> Result<()> {
167        let mut snapshots: Vec<Snapshot> = Vec::with_capacity(self.writes.len());
168
169        for write in &self.writes {
170            // Capture the pre-commit state before mutating, so we can restore it.
171            let original = match fs::read(&write.path) {
172                Ok(bytes) => Some(bytes),
173                Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
174                Err(e) => {
175                    rollback(&snapshots);
176                    return Err(e).with_context(|| {
177                        format!(
178                            "failed to read existing {} before write; rolled back {} prior change(s)",
179                            write.path.display(),
180                            snapshots.len()
181                        )
182                    });
183                }
184            };
185
186            match atomic_write(&write.path, &write.bytes) {
187                Ok(()) => snapshots.push(Snapshot {
188                    path: write.path.clone(),
189                    original,
190                }),
191                Err(err) => {
192                    // This write did not land (atomic_write is all-or-nothing),
193                    // so roll back only the writes that came before it.
194                    rollback(&snapshots);
195                    return Err(err).with_context(|| {
196                        format!(
197                            "setup transaction failed writing {}; rolled back {} prior change(s)",
198                            write.path.display(),
199                            snapshots.len()
200                        )
201                    });
202                }
203            }
204        }
205
206        Ok(())
207    }
208}
209
210/// Restore every snapshot to its captured pre-commit state. Best-effort: a
211/// rollback error is logged but does not abort the remaining restores, because
212/// leaving as many files as possible in their original state is the goal.
213fn rollback(snapshots: &[Snapshot]) {
214    for snap in snapshots.iter().rev() {
215        let result = match &snap.original {
216            Some(bytes) => atomic_write(&snap.path, bytes),
217            None => match fs::remove_file(&snap.path) {
218                Ok(()) => Ok(()),
219                Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
220                Err(e) => Err(e.into()),
221            },
222        };
223        if let Err(e) = result {
224            tracing::error!(
225                target: "config::persistence",
226                "failed to roll back {} during setup transaction: {e:#}",
227                snap.path.display()
228            );
229        }
230    }
231}
232
233/// Substrings that mark a config/JSON/env key as carrying a secret value.
234const SENSITIVE_KEY_HINTS: &[&str] = &[
235    "api_key",
236    "apikey",
237    "api-key",
238    "secret",
239    "token",
240    "password",
241    "passwd",
242    "authorization",
243    "auth_token",
244    "access_key",
245    "client_secret",
246    "private_key",
247];
248
249/// Known opaque-token prefixes worth masking even when they appear bare (not as
250/// `key = value`). Conservative on purpose: only well-known provider/key shapes.
251const SECRET_TOKEN_PREFIXES: &[&str] = &["sk-", "sk_", "ghp_", "gho_", "xoxb-", "xoxp-", "pk-"];
252
253/// The placeholder substituted for any redacted secret value.
254pub const REDACTED: &str = "[redacted]";
255
256/// Redact secret-bearing values from arbitrary text so it is safe to put in a
257/// setup report, log line, error message, or test snapshot.
258///
259/// Two passes, both dependency-free:
260///
261/// 1. **Keyed assignments.** Lines shaped like `key = value`, `key: value`, or
262///    `key=value` whose key (case-insensitively, ignoring quotes) contains a
263///    `SENSITIVE_KEY_HINTS` substring have their value replaced with
264///    [`REDACTED`].
265/// 2. **Bare tokens.** Whitespace-delimited words beginning with a known
266///    `SECRET_TOKEN_PREFIXES` are replaced wholesale.
267///
268/// The goal is defense in depth: setup state and reports are built from safe
269/// summaries that never include secrets in the first place, and this is the
270/// backstop for anything that echoes raw config text.
271#[must_use]
272pub fn redact_secrets(input: &str) -> String {
273    let mut out = String::with_capacity(input.len());
274    let mut first = true;
275    for line in input.split_inclusive('\n') {
276        if !first {
277            // split_inclusive keeps the newline on the previous chunk, so we do
278            // not need to re-add separators here.
279        }
280        first = false;
281        out.push_str(&redact_line(line));
282    }
283    out
284}
285
286/// Redact a single line (which may include a trailing newline).
287fn redact_line(line: &str) -> String {
288    // Preserve any trailing newline so callers keep their line structure.
289    let (body, newline) = match line.strip_suffix('\n') {
290        Some(rest) => (rest, "\n"),
291        None => (line, ""),
292    };
293
294    if let Some(redacted) = redact_keyed_assignment(body) {
295        return format!("{redacted}{newline}");
296    }
297
298    // Bare-token pass: mask any whitespace-delimited word with a known prefix.
299    let mut changed = false;
300    let masked: Vec<String> = body
301        .split(' ')
302        .map(|word| {
303            let trimmed = word.trim_matches(|c| matches!(c, '"' | '\'' | ',' | ';'));
304            if !trimmed.is_empty() && looks_like_secret_token(trimmed) {
305                changed = true;
306                word.replace(trimmed, REDACTED)
307            } else {
308                word.to_string()
309            }
310        })
311        .collect();
312
313    if changed {
314        format!("{}{newline}", masked.join(" "))
315    } else {
316        format!("{body}{newline}")
317    }
318}
319
320/// If `body` is a `key <sep> value` assignment with a sensitive key, return the
321/// line with the value redacted; otherwise `None`.
322fn redact_keyed_assignment(body: &str) -> Option<String> {
323    // Find the first `=` or `:` that separates a key from a value.
324    let sep_idx = body.find(['=', ':'])?;
325    let (raw_key, rest) = body.split_at(sep_idx);
326    let sep = &rest[..1];
327    let raw_value = &rest[1..];
328
329    let key_norm = raw_key
330        .trim()
331        .trim_matches(|c| matches!(c, '"' | '\'' | '[' | ']'))
332        .to_ascii_lowercase();
333    if key_norm.is_empty() || !SENSITIVE_KEY_HINTS.iter().any(|h| key_norm.contains(h)) {
334        return None;
335    }
336
337    // Keep leading whitespace of the key and the original separator spacing so
338    // the redacted line reads naturally.
339    let key_lead_ws: String = raw_key.chars().take_while(|c| c.is_whitespace()).collect();
340    let value_lead_ws: String = raw_value
341        .chars()
342        .take_while(|c| c.is_whitespace())
343        .collect();
344    let value_rest = raw_value.trim_start();
345    // If the value is empty, there is nothing to hide.
346    if value_rest.is_empty() {
347        return None;
348    }
349    // Preserve surrounding quotes so structured files stay parseable-looking.
350    let quoted = value_rest.starts_with('"') || value_rest.starts_with('\'');
351    let replacement = if quoted {
352        format!("\"{REDACTED}\"")
353    } else {
354        REDACTED.to_string()
355    };
356    Some(format!(
357        "{key_lead_ws}{}{sep}{value_lead_ws}{replacement}",
358        raw_key.trim()
359    ))
360}
361
362fn looks_like_secret_token(word: &str) -> bool {
363    SECRET_TOKEN_PREFIXES
364        .iter()
365        .any(|p| word.len() > p.len() + 6 && word.starts_with(p))
366}
367
368#[cfg(test)]
369mod tests {
370    use super::*;
371
372    fn read(path: &Path) -> String {
373        fs::read_to_string(path).unwrap()
374    }
375
376    #[test]
377    fn atomic_write_creates_parent_dirs_and_content() {
378        let tmp = tempfile::tempdir().unwrap();
379        let path = tmp.path().join("nested/dir/state.json");
380        atomic_write(&path, b"hello").unwrap();
381        assert_eq!(read(&path), "hello");
382    }
383
384    #[cfg(unix)]
385    #[test]
386    fn atomic_write_uses_owner_only_permissions() {
387        let tmp = tempfile::tempdir().unwrap();
388        let path = tmp.path().join("state.json");
389        atomic_write(&path, b"x").unwrap();
390        let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
391        assert_eq!(mode, SETUP_FILE_MODE);
392    }
393
394    #[test]
395    fn atomic_write_replaces_existing_atomically() {
396        let tmp = tempfile::tempdir().unwrap();
397        let path = tmp.path().join("state.json");
398        atomic_write(&path, b"old").unwrap();
399        atomic_write(&path, b"new").unwrap();
400        assert_eq!(read(&path), "new");
401        // No stray temp files left behind.
402        let leftovers: Vec<_> = fs::read_dir(tmp.path())
403            .unwrap()
404            .filter_map(Result::ok)
405            .filter(|e| e.file_name() != "state.json")
406            .collect();
407        assert!(leftovers.is_empty(), "stray temp files: {leftovers:?}");
408    }
409
410    #[test]
411    fn transaction_preview_writes_nothing() {
412        let tmp = tempfile::tempdir().unwrap();
413        let a = tmp.path().join("a.json");
414        let b = tmp.path().join("b.json");
415        let mut tx = SetupTransaction::new();
416        tx.stage(a.clone(), b"1".to_vec())
417            .stage(b.clone(), b"2".to_vec());
418        let preview = tx.preview();
419        assert_eq!(preview, vec![a.as_path(), b.as_path()]);
420        assert!(!a.exists());
421        assert!(!b.exists());
422    }
423
424    #[test]
425    fn dropped_transaction_leaves_files_unchanged() {
426        let tmp = tempfile::tempdir().unwrap();
427        let a = tmp.path().join("a.json");
428        {
429            let mut tx = SetupTransaction::new();
430            tx.stage(a.clone(), b"staged".to_vec());
431            // tx dropped here without commit
432        }
433        assert!(!a.exists());
434    }
435
436    #[test]
437    fn transaction_commit_applies_all() {
438        let tmp = tempfile::tempdir().unwrap();
439        let a = tmp.path().join("a.json");
440        let b = tmp.path().join("sub/b.json");
441        let mut tx = SetupTransaction::new();
442        tx.stage(a.clone(), b"A".to_vec())
443            .stage(b.clone(), b"B".to_vec());
444        tx.commit().unwrap();
445        assert_eq!(read(&a), "A");
446        assert_eq!(read(&b), "B");
447    }
448
449    #[test]
450    fn transaction_rolls_back_on_partial_failure() {
451        let tmp = tempfile::tempdir().unwrap();
452        let good = tmp.path().join("good.json");
453        fs::write(&good, "ORIGINAL").unwrap();
454
455        // Second target is unwritable: a path whose parent is an existing file.
456        let blocker = tmp.path().join("blocker");
457        fs::write(&blocker, "i am a file").unwrap();
458        let bad = blocker.join("child.json"); // parent is a file → create_dir_all fails
459
460        let mut tx = SetupTransaction::new();
461        tx.stage(good.clone(), b"UPDATED".to_vec())
462            .stage(bad.clone(), b"NOPE".to_vec());
463        let err = tx.commit().unwrap_err();
464        assert!(format!("{err:#}").contains("rolled back"));
465
466        // The first file must be restored to its original contents.
467        assert_eq!(read(&good), "ORIGINAL");
468        assert!(!bad.exists());
469    }
470
471    #[test]
472    fn transaction_rollback_removes_newly_created_file() {
473        let tmp = tempfile::tempdir().unwrap();
474        let fresh = tmp.path().join("fresh.json"); // did not exist before
475        let blocker = tmp.path().join("blocker");
476        fs::write(&blocker, "file").unwrap();
477        let bad = blocker.join("child.json");
478
479        let mut tx = SetupTransaction::new();
480        tx.stage(fresh.clone(), b"created".to_vec())
481            .stage(bad, b"x".to_vec());
482        assert!(tx.commit().is_err());
483        // The newly created file must be removed on rollback, not left behind.
484        assert!(!fresh.exists());
485    }
486
487    #[test]
488    fn redact_masks_keyed_secrets_toml_and_json() {
489        let input = "\
490api_key = \"sk-supersecretvalue123\"
491provider = \"openai\"
492  \"token\": \"abc123def456ghi\",
493model = \"mimo-ultraspeed\"
494PASSWORD=hunter2hunter2";
495        let out = redact_secrets(input);
496        assert!(!out.contains("sk-supersecretvalue123"), "{out}");
497        assert!(!out.contains("abc123def456ghi"), "{out}");
498        assert!(!out.contains("hunter2hunter2"), "{out}");
499        // Non-secret values survive untouched.
500        assert!(out.contains("provider = \"openai\""));
501        assert!(out.contains("model = \"mimo-ultraspeed\""));
502        assert!(out.matches(REDACTED).count() >= 3, "{out}");
503    }
504
505    #[test]
506    fn redact_masks_bare_token_prefixes() {
507        let out = redact_secrets("the leaked key sk-abcdef1234567890 appeared in a log");
508        assert!(!out.contains("sk-abcdef1234567890"), "{out}");
509        assert!(out.contains(REDACTED));
510        assert!(out.contains("appeared in a log"));
511    }
512
513    #[test]
514    fn redact_preserves_line_structure() {
515        let input = "line1\nsecret = \"xyzsecretvalue\"\nline3";
516        let out = redact_secrets(input);
517        let lines: Vec<&str> = out.lines().collect();
518        assert_eq!(lines.len(), 3);
519        assert_eq!(lines[0], "line1");
520        assert_eq!(lines[2], "line3");
521        assert!(lines[1].contains(REDACTED));
522    }
523
524    #[test]
525    fn redact_leaves_plain_text_untouched() {
526        let input = "the quick brown fox = jumps over";
527        // `fox` key has no sensitive hint → unchanged.
528        assert_eq!(redact_secrets(input), input);
529    }
530}