| 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 | |
| 23 | use std::fs; |
| 24 | use std::path::{Path, PathBuf}; |
| 25 | |
| 26 | use anyhow::{Context, Result}; |
| 27 | use serde::Serialize; |
| 28 | |
| 29 | /// Restrictive file mode for setup-owned files (owner read/write only). |
| 30 | #[cfg(unix)] |
| 31 | const SETUP_FILE_MODE: u32 = 0o600; |
| 32 | |
| 33 | #[cfg(unix)] |
| 34 | fn is_unsupported_dir_sync_error(err: &std::io::Error) -> bool { |
| 35 | matches!( |
| 36 | err.kind(), |
| 37 | std::io::ErrorKind::Unsupported | std::io::ErrorKind::InvalidInput |
| 38 | ) || err.raw_os_error().is_some_and(|code| { |
| 39 | [ |
| 40 | libc::EINVAL, |
| 41 | libc::ENOTSUP, |
| 42 | libc::EOPNOTSUPP, |
| 43 | libc::EROFS, |
| 44 | libc::EBADF, |
| 45 | ] |
| 46 | .contains(&code) |
| 47 | }) |
| 48 | } |
| 49 | |
| 50 | #[cfg(unix)] |
| 51 | pub fn sync_parent_dir(dir: &Path) -> Result<()> { |
| 52 | match fs::File::open(dir).and_then(|file| file.sync_all()) { |
| 53 | Ok(()) => Ok(()), |
| 54 | Err(err) if is_unsupported_dir_sync_error(&err) => Ok(()), |
| 55 | Err(err) => Err(err).with_context(|| format!("failed to sync directory {}", dir.display())), |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | #[cfg(not(unix))] |
| 60 | pub fn sync_parent_dir(_dir: &Path) -> Result<()> { |
| 61 | Ok(()) |
| 62 | } |
| 63 | |
| 64 | pub(crate) fn sync_parent_dir_best_effort(dir: &Path, sync_dir: impl FnOnce(&Path) -> Result<()>) { |
| 65 | if let Err(err) = sync_dir(dir) { |
| 66 | tracing::warn!( |
| 67 | dir = %dir.display(), |
| 68 | error = %format!("{err:#}"), |
| 69 | "failed to sync parent directory after write; new file is already in place" |
| 70 | ); |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | fn prepare_parent_dir(path: &Path) -> Result<&Path> { |
| 75 | let parent = path.parent().filter(|p| !p.as_os_str().is_empty()); |
| 76 | if let Some(parent) = parent { |
| 77 | fs::create_dir_all(parent) |
| 78 | .with_context(|| format!("failed to create directory {}", parent.display()))?; |
| 79 | } |
| 80 | Ok(parent.unwrap_or_else(|| Path::new("."))) |
| 81 | } |
| 82 | |
| 83 | fn stage_temp_file(dir: &Path, path: &Path, bytes: &[u8]) -> Result<tempfile::NamedTempFile> { |
| 84 | let mut tmp = tempfile::NamedTempFile::new_in(dir) |
| 85 | .with_context(|| format!("failed to create temp file in {}", dir.display()))?; |
| 86 | |
| 87 | use std::io::Write as _; |
| 88 | tmp.write_all(bytes) |
| 89 | .with_context(|| format!("failed to write temp file for {}", path.display()))?; |
| 90 | tmp.flush() |
| 91 | .with_context(|| format!("failed to flush temp file for {}", path.display()))?; |
| 92 | |
| 93 | // A filesystem that assigns modes itself (HarmonyOS hmdfs) refuses the |
| 94 | // call outright; `tighten_mode` tolerates only that case and reports every |
| 95 | // other failure. The temp file sits in `path`'s directory, which is where |
| 96 | // the question about the mount is answered. |
| 97 | #[cfg(unix)] |
| 98 | crate::private_directory::tighten_mode_of(tmp.as_file(), tmp.path(), SETUP_FILE_MODE) |
| 99 | .with_context(|| format!("failed to set permissions for {}", path.display()))?; |
| 100 | |
| 101 | tmp.as_file() |
| 102 | .sync_all() |
| 103 | .with_context(|| format!("failed to sync temp file for {}", path.display()))?; |
| 104 | |
| 105 | Ok(tmp) |
| 106 | } |
| 107 | |
| 108 | /// Atomically write `bytes` to `path` via a sibling temp file + rename. |
| 109 | /// |
| 110 | /// The temp file is created in the same directory as `path` so the final |
| 111 | /// `rename` is atomic on the same filesystem. On Unix the file is created with |
| 112 | /// `0o600` so setup-owned state never lands world-readable. Parent directories |
| 113 | /// are created as needed. |
| 114 | pub fn atomic_write(path: &Path, bytes: &[u8]) -> Result<()> { |
| 115 | atomic_write_with_dir_sync(path, bytes, sync_parent_dir) |
| 116 | } |
| 117 | |
| 118 | fn atomic_write_with_dir_sync( |
| 119 | path: &Path, |
| 120 | bytes: &[u8], |
| 121 | sync_dir: impl FnOnce(&Path) -> Result<()>, |
| 122 | ) -> Result<()> { |
| 123 | let dir = prepare_parent_dir(path)?; |
| 124 | let mut tmp = stage_temp_file(dir, path, bytes)?; |
| 125 | |
| 126 | // Two Codewhale instances share one home. The loser of a race can find the |
| 127 | // destination held open for a read — Windows refuses the replacing rename |
| 128 | // for as long as that handle lives, because the reader does not pass |
| 129 | // `FILE_SHARE_DELETE`. That refusal is transient, so retry briefly instead |
| 130 | // of reporting a write the caller could have made. |
| 131 | let mut attempt: u32 = 0; |
| 132 | loop { |
| 133 | match tmp.persist(path) { |
| 134 | Ok(_) => { |
| 135 | sync_parent_dir_best_effort(dir, sync_dir); |
| 136 | return Ok(()); |
| 137 | } |
| 138 | Err(error) if attempt + 1 < PERSIST_ATTEMPTS && rename_is_retryable(&error.error) => { |
| 139 | attempt += 1; |
| 140 | tmp = error.file; |
| 141 | std::thread::sleep(std::time::Duration::from_millis( |
| 142 | u64::from(attempt) * PERSIST_RETRY_STEP_MS, |
| 143 | )); |
| 144 | } |
| 145 | Err(error) => { |
| 146 | // Some directories refuse every directory-entry rename for as |
| 147 | // long as they are held — Codewhale's own home is one of them |
| 148 | // here — and no amount of waiting changes that. Only that shape |
| 149 | // falls back: a full disk or a real permission refusal keeps its |
| 150 | // own error, because an in-place rewrite would fail there too and |
| 151 | // this way the caller learns the actual cause. |
| 152 | if !rename_is_retryable(&error.error) { |
| 153 | return Err(error.error) |
| 154 | .with_context(|| format!("failed to persist {}", path.display())); |
| 155 | } |
| 156 | tracing::warn!( |
| 157 | path = %path.display(), |
| 158 | error = %error.error, |
| 159 | "replacing rename refused; rewriting the file in place" |
| 160 | ); |
| 161 | rewrite_in_place(path, bytes)?; |
| 162 | sync_parent_dir_best_effort(dir, sync_dir); |
| 163 | return Ok(()); |
| 164 | } |
| 165 | } |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | pub fn atomic_write_if_absent(path: &Path, bytes: &[u8]) -> Result<bool> { |
| 170 | let dir = prepare_parent_dir(path)?; |
| 171 | let tmp = stage_temp_file(dir, path, bytes)?; |
| 172 | match tmp.persist_noclobber(path) { |
| 173 | Ok(_) => { |
| 174 | sync_parent_dir_best_effort(dir, sync_parent_dir); |
| 175 | Ok(true) |
| 176 | } |
| 177 | Err(error) if error.error.kind() == std::io::ErrorKind::AlreadyExists => Ok(false), |
| 178 | Err(error) => { |
| 179 | Err(error.error).with_context(|| format!("failed to persist {}", path.display())) |
| 180 | } |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | /// Last-resort delivery: rewrite the existing file without a rename. |
| 185 | /// |
| 186 | /// This is deliberately not atomic — an interruption between truncate and the |
| 187 | /// last byte can leave a partial file — so it runs only after every replacing |
| 188 | /// call has been refused. The alternative is a save that never lands at all, |
| 189 | /// which for a setup checkpoint means the same write is attempted and fails on |
| 190 | /// every launch. |
| 191 | fn rewrite_in_place(path: &Path, bytes: &[u8]) -> Result<()> { |
| 192 | use std::io::Write as _; |
| 193 | |
| 194 | let mut file = fs::OpenOptions::new() |
| 195 | .write(true) |
| 196 | .create(true) |
| 197 | .truncate(true) |
| 198 | .open(path) |
| 199 | .with_context(|| format!("failed to open {} for an in-place write", path.display()))?; |
| 200 | file.write_all(bytes) |
| 201 | .with_context(|| format!("failed to rewrite {} in place", path.display()))?; |
| 202 | file.sync_all() |
| 203 | .with_context(|| format!("failed to sync {} after an in-place write", path.display()))?; |
| 204 | Ok(()) |
| 205 | } |
| 206 | |
| 207 | /// How many times the replacing rename is attempted before the error surfaces. |
| 208 | const PERSIST_ATTEMPTS: u32 = 6; |
| 209 | |
| 210 | /// Backoff step; attempt *n* sleeps `n * step`, so the last wait is 250ms and the |
| 211 | /// whole budget is 750ms. A setup checkpoint is written on a user action, so it |
| 212 | /// can afford to outlast a scanner or a second instance holding the file for a |
| 213 | /// moment; it cannot afford to hang. |
| 214 | const PERSIST_RETRY_STEP_MS: u64 = 50; |
| 215 | |
| 216 | /// Whether a failed rename is worth retrying: another process holds the |
| 217 | /// destination open, which is a momentary condition rather than a refusal the |
| 218 | /// caller should hear about. |
| 219 | #[cfg(windows)] |
| 220 | fn rename_is_retryable(error: &std::io::Error) -> bool { |
| 221 | // 5 = ERROR_ACCESS_DENIED, 32 = ERROR_SHARING_VIOLATION, |
| 222 | // 33 = ERROR_LOCK_VIOLATION, 1175 = ERROR_UNABLE_TO_DELETE_FILE (what |
| 223 | // `ReplaceFileW` raises when it cannot displace the destination it must |
| 224 | // delete first). A reader holding the file raises 5 or 32. |
| 225 | matches!(error.raw_os_error(), Some(5 | 32 | 33 | 1175)) |
| 226 | } |
| 227 | |
| 228 | #[cfg(not(windows))] |
| 229 | fn rename_is_retryable(error: &std::io::Error) -> bool { |
| 230 | matches!(error.kind(), std::io::ErrorKind::PermissionDenied) |
| 231 | } |
| 232 | |
| 233 | /// Atomically write `value` as pretty-printed JSON to `path`. |
| 234 | /// |
| 235 | /// A trailing newline is appended so the file is well-formed for line-oriented |
| 236 | /// tooling and diffs. |
| 237 | pub fn atomic_write_json<T: Serialize>(path: &Path, value: &T) -> Result<()> { |
| 238 | let mut body = serde_json::to_string_pretty(value) |
| 239 | .with_context(|| format!("failed to serialize JSON for {}", path.display()))?; |
| 240 | body.push('\n'); |
| 241 | atomic_write(path, body.as_bytes()) |
| 242 | } |
| 243 | |
| 244 | /// A staged multi-file write that either fully applies or fully rolls back. |
| 245 | /// |
| 246 | /// Stage every file the setup step intends to write, then call [`commit`]. If |
| 247 | /// any single write fails, every already-applied write in the transaction is |
| 248 | /// restored to its pre-commit contents (or removed if it did not previously |
| 249 | /// exist), and the original error is returned. A transaction that is dropped |
| 250 | /// without committing leaves the filesystem untouched. |
| 251 | /// |
| 252 | /// [`commit`]: SetupTransaction::commit |
| 253 | #[derive(Debug, Default)] |
| 254 | pub struct SetupTransaction { |
| 255 | writes: Vec<StagedWrite>, |
| 256 | } |
| 257 | |
| 258 | #[derive(Debug, Clone)] |
| 259 | struct StagedWrite { |
| 260 | path: PathBuf, |
| 261 | bytes: Vec<u8>, |
| 262 | } |
| 263 | |
| 264 | /// A snapshot of a file's pre-commit state, captured so [`SetupTransaction`] |
| 265 | /// can restore it during rollback. |
| 266 | struct Snapshot { |
| 267 | path: PathBuf, |
| 268 | /// Original bytes, or `None` if the file did not exist before commit. |
| 269 | original: Option<Vec<u8>>, |
| 270 | } |
| 271 | |
| 272 | impl SetupTransaction { |
| 273 | /// Create an empty transaction. |
| 274 | #[must_use] |
| 275 | pub fn new() -> Self { |
| 276 | Self::default() |
| 277 | } |
| 278 | |
| 279 | /// Stage `bytes` to be written to `path` on [`commit`](Self::commit). |
| 280 | /// |
| 281 | /// Staging touches nothing on disk. A later stage for the same path |
| 282 | /// replaces an earlier one, so a step can revise its intended output before |
| 283 | /// committing. |
| 284 | pub fn stage(&mut self, path: impl Into<PathBuf>, bytes: impl Into<Vec<u8>>) -> &mut Self { |
| 285 | let path = path.into(); |
| 286 | let bytes = bytes.into(); |
| 287 | if let Some(existing) = self.writes.iter_mut().find(|w| w.path == path) { |
| 288 | existing.bytes = bytes; |
| 289 | } else { |
| 290 | self.writes.push(StagedWrite { path, bytes }); |
| 291 | } |
| 292 | self |
| 293 | } |
| 294 | |
| 295 | /// Stage `value` serialized as pretty JSON (with trailing newline). |
| 296 | pub fn stage_json<T: Serialize>( |
| 297 | &mut self, |
| 298 | path: impl Into<PathBuf>, |
| 299 | value: &T, |
| 300 | ) -> Result<&mut Self> { |
| 301 | let path = path.into(); |
| 302 | let mut body = serde_json::to_string_pretty(value) |
| 303 | .with_context(|| format!("failed to serialize JSON for {}", path.display()))?; |
| 304 | body.push('\n'); |
| 305 | Ok(self.stage(path, body.into_bytes())) |
| 306 | } |
| 307 | |
| 308 | /// The paths that [`commit`](Self::commit) would write, in staging order. |
| 309 | /// Writes nothing — this is the preview surface. |
| 310 | #[must_use] |
| 311 | pub fn preview(&self) -> Vec<&Path> { |
| 312 | self.writes.iter().map(|w| w.path.as_path()).collect() |
| 313 | } |
| 314 | |
| 315 | /// True when nothing is staged. |
| 316 | #[must_use] |
| 317 | pub fn is_empty(&self) -> bool { |
| 318 | self.writes.is_empty() |
| 319 | } |
| 320 | |
| 321 | /// Apply every staged write atomically. |
| 322 | /// |
| 323 | /// On success all files are updated. On the first failure, every write that |
| 324 | /// already landed is rolled back to its captured pre-commit state and the |
| 325 | /// original error is returned (rollback failures are attached as context). |
| 326 | pub fn commit(self) -> Result<()> { |
| 327 | let mut snapshots: Vec<Snapshot> = Vec::with_capacity(self.writes.len()); |
| 328 | |
| 329 | for write in &self.writes { |
| 330 | // Capture the pre-commit state before mutating, so we can restore it. |
| 331 | let original = match fs::read(&write.path) { |
| 332 | Ok(bytes) => Some(bytes), |
| 333 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, |
| 334 | Err(e) => { |
| 335 | rollback(&snapshots); |
| 336 | return Err(e).with_context(|| { |
| 337 | format!( |
| 338 | "failed to read existing {} before write; rolled back {} prior change(s)", |
| 339 | write.path.display(), |
| 340 | snapshots.len() |
| 341 | ) |
| 342 | }); |
| 343 | } |
| 344 | }; |
| 345 | |
| 346 | let result = atomic_write(&write.path, &write.bytes); |
| 347 | let landed = result.is_ok() || fs::read(&write.path).ok() != original; |
| 348 | if landed { |
| 349 | snapshots.push(Snapshot { |
| 350 | path: write.path.clone(), |
| 351 | original, |
| 352 | }); |
| 353 | } |
| 354 | match result { |
| 355 | Ok(()) => {} |
| 356 | Err(err) => { |
| 357 | rollback(&snapshots); |
| 358 | return Err(err).with_context(|| { |
| 359 | format!( |
| 360 | "setup transaction failed writing {}; rolled back {} prior change(s)", |
| 361 | write.path.display(), |
| 362 | snapshots.len() |
| 363 | ) |
| 364 | }); |
| 365 | } |
| 366 | } |
| 367 | } |
| 368 | |
| 369 | Ok(()) |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | /// Restore every snapshot to its captured pre-commit state. Best-effort: a |
| 374 | /// rollback error is logged but does not abort the remaining restores, because |
| 375 | /// leaving as many files as possible in their original state is the goal. |
| 376 | fn rollback(snapshots: &[Snapshot]) { |
| 377 | for snap in snapshots.iter().rev() { |
| 378 | let result = match &snap.original { |
| 379 | Some(bytes) => atomic_write(&snap.path, bytes), |
| 380 | None => match fs::remove_file(&snap.path) { |
| 381 | Ok(()) => Ok(()), |
| 382 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), |
| 383 | Err(e) => Err(e.into()), |
| 384 | }, |
| 385 | }; |
| 386 | if let Err(e) = result { |
| 387 | tracing::error!( |
| 388 | target: "config::persistence", |
| 389 | "failed to roll back {} during setup transaction: {e:#}", |
| 390 | snap.path.display() |
| 391 | ); |
| 392 | } |
| 393 | } |
| 394 | } |
| 395 | |
| 396 | // FEAT-025 D4: the pure secret-redaction primitives moved to |
| 397 | // `codewhale-sanitize::redact` so portable command helpers can share one |
| 398 | // implementation without depending on this crate. Re-exported here to keep |
| 399 | // the existing `codewhale_config::persistence::*` public API stable. |
| 400 | pub use codewhale_sanitize::redact::{ |
| 401 | REDACTED, RedactionPolicy, redact_json_model_bound_secrets, redact_json_secrets, |
| 402 | redact_model_bound_secrets, redact_secrets, redact_secrets_with, |
| 403 | }; |
| 404 | |
| 405 | #[cfg(test)] |
| 406 | mod tests { |
| 407 | use super::*; |
| 408 | |
| 409 | fn read(path: &Path) -> String { |
| 410 | fs::read_to_string(path).unwrap() |
| 411 | } |
| 412 | |
| 413 | fn synthetic_secret_fixture() -> String { |
| 414 | ["abc123", "def456", "ghi"].concat() |
| 415 | } |
| 416 | |
| 417 | /// The last-resort writer delivers the bytes by truncating the target. |
| 418 | /// |
| 419 | /// It is what runs when a directory refuses every replacing rename — |
| 420 | /// observed on Codewhale's own home, where a save otherwise never lands — |
| 421 | /// so it must actually replace a longer document with a shorter one, and |
| 422 | /// leave nothing of the old tail behind. |
| 423 | #[test] |
| 424 | fn an_in_place_rewrite_replaces_a_longer_document() { |
| 425 | let tmp = tempfile::tempdir().unwrap(); |
| 426 | let path = tmp.path().join("setup_state.json"); |
| 427 | fs::write(&path, b"{\"old\": true, \"padding\": \"aaaaaaaaaaaaaaaa\"}").unwrap(); |
| 428 | |
| 429 | rewrite_in_place(&path, b"{\"new\":1}").unwrap(); |
| 430 | |
| 431 | assert_eq!(read(&path), "{\"new\":1}"); |
| 432 | assert!( |
| 433 | !read(&path).contains("padding"), |
| 434 | "the old tail must be gone" |
| 435 | ); |
| 436 | } |
| 437 | |
| 438 | #[test] |
| 439 | fn atomic_write_creates_parent_dirs_and_content() { |
| 440 | let tmp = tempfile::tempdir().unwrap(); |
| 441 | let path = tmp.path().join("nested/dir/state.json"); |
| 442 | atomic_write(&path, b"hello").unwrap(); |
| 443 | assert_eq!(read(&path), "hello"); |
| 444 | } |
| 445 | |
| 446 | #[cfg(unix)] |
| 447 | #[test] |
| 448 | fn atomic_write_uses_owner_only_permissions() { |
| 449 | use std::os::unix::fs::PermissionsExt as _; |
| 450 | |
| 451 | let tmp = tempfile::tempdir().unwrap(); |
| 452 | let path = tmp.path().join("state.json"); |
| 453 | atomic_write(&path, b"x").unwrap(); |
| 454 | let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777; |
| 455 | assert_eq!(mode, SETUP_FILE_MODE); |
| 456 | } |
| 457 | |
| 458 | #[test] |
| 459 | fn atomic_write_replaces_existing_atomically() { |
| 460 | let tmp = tempfile::tempdir().unwrap(); |
| 461 | let path = tmp.path().join("state.json"); |
| 462 | atomic_write(&path, b"old").unwrap(); |
| 463 | atomic_write(&path, b"new").unwrap(); |
| 464 | assert_eq!(read(&path), "new"); |
| 465 | // No stray temp files left behind. |
| 466 | let leftovers: Vec<_> = fs::read_dir(tmp.path()) |
| 467 | .unwrap() |
| 468 | .filter_map(Result::ok) |
| 469 | .filter(|e| e.file_name() != "state.json") |
| 470 | .collect(); |
| 471 | assert!(leftovers.is_empty(), "stray temp files: {leftovers:?}"); |
| 472 | } |
| 473 | |
| 474 | #[test] |
| 475 | fn only_a_contended_rename_is_retried() { |
| 476 | // The retry exists for one situation: another instance holds the |
| 477 | // destination open while it reads the same sidecar. Anything else — |
| 478 | // a missing directory, a full disk — must surface at once instead of |
| 479 | // being retried five more times. |
| 480 | #[cfg(windows)] |
| 481 | { |
| 482 | // 1175 is the code `ReplaceFileW` raises when it cannot displace the |
| 483 | // destination it must delete first — the same contention as 32, one |
| 484 | // API further along. The pet-mode save hit it. |
| 485 | for code in [5, 32, 33, 1175] { |
| 486 | assert!( |
| 487 | rename_is_retryable(&std::io::Error::from_raw_os_error(code)), |
| 488 | "os error {code}" |
| 489 | ); |
| 490 | } |
| 491 | assert!(!rename_is_retryable(&std::io::Error::from_raw_os_error(2))); |
| 492 | assert!(!rename_is_retryable(&std::io::Error::from_raw_os_error( |
| 493 | 112 |
| 494 | ))); |
| 495 | } |
| 496 | #[cfg(not(windows))] |
| 497 | { |
| 498 | assert!(rename_is_retryable(&std::io::Error::from( |
| 499 | std::io::ErrorKind::PermissionDenied |
| 500 | ))); |
| 501 | assert!(!rename_is_retryable(&std::io::Error::from( |
| 502 | std::io::ErrorKind::NotFound |
| 503 | ))); |
| 504 | } |
| 505 | } |
| 506 | |
| 507 | #[test] |
| 508 | fn transaction_preview_writes_nothing() { |
| 509 | let tmp = tempfile::tempdir().unwrap(); |
| 510 | let a = tmp.path().join("a.json"); |
| 511 | let b = tmp.path().join("b.json"); |
| 512 | let mut tx = SetupTransaction::new(); |
| 513 | tx.stage(a.clone(), b"1".to_vec()) |
| 514 | .stage(b.clone(), b"2".to_vec()); |
| 515 | let preview = tx.preview(); |
| 516 | assert_eq!(preview, vec![a.as_path(), b.as_path()]); |
| 517 | assert!(!a.exists()); |
| 518 | assert!(!b.exists()); |
| 519 | } |
| 520 | |
| 521 | #[test] |
| 522 | fn dropped_transaction_leaves_files_unchanged() { |
| 523 | let tmp = tempfile::tempdir().unwrap(); |
| 524 | let a = tmp.path().join("a.json"); |
| 525 | { |
| 526 | let mut tx = SetupTransaction::new(); |
| 527 | tx.stage(a.clone(), b"staged".to_vec()); |
| 528 | // tx dropped here without commit |
| 529 | } |
| 530 | assert!(!a.exists()); |
| 531 | } |
| 532 | |
| 533 | #[test] |
| 534 | fn transaction_commit_applies_all() { |
| 535 | let tmp = tempfile::tempdir().unwrap(); |
| 536 | let a = tmp.path().join("a.json"); |
| 537 | let b = tmp.path().join("sub/b.json"); |
| 538 | let mut tx = SetupTransaction::new(); |
| 539 | tx.stage(a.clone(), b"A".to_vec()) |
| 540 | .stage(b.clone(), b"B".to_vec()); |
| 541 | tx.commit().unwrap(); |
| 542 | assert_eq!(read(&a), "A"); |
| 543 | assert_eq!(read(&b), "B"); |
| 544 | } |
| 545 | |
| 546 | #[test] |
| 547 | fn transaction_rolls_back_on_partial_failure() { |
| 548 | let tmp = tempfile::tempdir().unwrap(); |
| 549 | let good = tmp.path().join("good.json"); |
| 550 | fs::write(&good, "ORIGINAL").unwrap(); |
| 551 | |
| 552 | // Second target is unwritable: a path whose parent is an existing file. |
| 553 | let blocker = tmp.path().join("blocker"); |
| 554 | fs::write(&blocker, "i am a file").unwrap(); |
| 555 | let bad = blocker.join("child.json"); // parent is a file → create_dir_all fails |
| 556 | |
| 557 | let mut tx = SetupTransaction::new(); |
| 558 | tx.stage(good.clone(), b"UPDATED".to_vec()) |
| 559 | .stage(bad.clone(), b"NOPE".to_vec()); |
| 560 | let err = tx.commit().unwrap_err(); |
| 561 | assert!(format!("{err:#}").contains("rolled back")); |
| 562 | |
| 563 | // The first file must be restored to its original contents. |
| 564 | assert_eq!(read(&good), "ORIGINAL"); |
| 565 | assert!(!bad.exists()); |
| 566 | } |
| 567 | |
| 568 | #[test] |
| 569 | fn transaction_rollback_removes_newly_created_file() { |
| 570 | let tmp = tempfile::tempdir().unwrap(); |
| 571 | let fresh = tmp.path().join("fresh.json"); // did not exist before |
| 572 | let blocker = tmp.path().join("blocker"); |
| 573 | fs::write(&blocker, "file").unwrap(); |
| 574 | let bad = blocker.join("child.json"); |
| 575 | |
| 576 | let mut tx = SetupTransaction::new(); |
| 577 | tx.stage(fresh.clone(), b"created".to_vec()) |
| 578 | .stage(bad, b"x".to_vec()); |
| 579 | assert!(tx.commit().is_err()); |
| 580 | // The newly created file must be removed on rollback, not left behind. |
| 581 | assert!(!fresh.exists()); |
| 582 | } |
| 583 | |
| 584 | #[test] |
| 585 | fn compact_json_and_query_strings_mask_their_credentials() { |
| 586 | // A synthetic, unsigned test value, assembled from its three |
| 587 | // segments so the source holds no complete token literal. |
| 588 | let jwt = [ |
| 589 | "eyJhbGciOiJSUzI1NiJ9", |
| 590 | "eyJzdWIiOiJ1c2VyIn0", |
| 591 | "c2lnbmF0dXJlLXZhbHVl", |
| 592 | ] |
| 593 | .join("."); |
| 594 | let jwt = jwt.as_str(); |
| 595 | let refresh = "rt_Q2x9fK3mZ7pL1vB8nH4sT6wY0aE5cR2d"; |
| 596 | let cases = [ |
| 597 | format!( |
| 598 | r#"{{"tokens":{{"id_token":"{jwt}","access_token":"{jwt}","refresh_token":"{refresh}"}}}}"# |
| 599 | ), |
| 600 | format!(r#"{{"token_type":"Bearer","access_token":"{jwt}"}}"#), |
| 601 | format!(r#"[{{"Authorization":"Bearer {jwt}"}}]"#), |
| 602 | format!("https://example.test/cb?state=abc&access_token={jwt}&x=1"), |
| 603 | ]; |
| 604 | for policy in [RedactionPolicy::CredentialShaped, RedactionPolicy::KeyBased] { |
| 605 | for case in &cases { |
| 606 | let out = redact_secrets_with(case, policy); |
| 607 | assert!(!out.contains(jwt), "{policy:?} leaked a JWT: {out}"); |
| 608 | assert!( |
| 609 | !out.contains(refresh), |
| 610 | "{policy:?} leaked a refresh token: {out}" |
| 611 | ); |
| 612 | } |
| 613 | } |
| 614 | // Structure and harmless members stay byte-exact. |
| 615 | assert_eq!( |
| 616 | redact_model_bound_secrets(&cases[1]), |
| 617 | r#"{"token_type":"Bearer","access_token":"[redacted]"}"# |
| 618 | ); |
| 619 | let json = serde_json::json!({ |
| 620 | "summary": format!("{{\"access_token\":\"{jwt}\"}}"), |
| 621 | "stdout_summary": "token = make_token()", |
| 622 | "api_key": "short", |
| 623 | "access_token": jwt, |
| 624 | }); |
| 625 | let masked = redact_json_model_bound_secrets(&json); |
| 626 | assert!(!masked.to_string().contains(jwt), "{masked}"); |
| 627 | assert_eq!(masked["stdout_summary"], "token = make_token()"); |
| 628 | // A sensitive key's value is masked wholesale, credential-shaped or not. |
| 629 | assert_eq!(masked["api_key"], REDACTED); |
| 630 | } |
| 631 | |
| 632 | #[test] |
| 633 | fn model_bound_redaction_keeps_code_and_config_byte_exact() { |
| 634 | // Every line here is code or configuration that a model must be able |
| 635 | // to quote back for an exact-match edit (#5546). |
| 636 | let lines = [ |
| 637 | " \"jsonwebtoken\": \"^9.0.2\",", |
| 638 | " \"@types/jsonwebtoken\": \"^9.0.5\",", |
| 639 | " \"password-validator\": \"^5.3.0\",", |
| 640 | " \"authorization\": \"1.0.0\",", |
| 641 | " password: credentials?.password,", |
| 642 | " token = generate_verification_token()", |
| 643 | " secret: process.env.NEXTAUTH_SECRET!,", |
| 644 | " password?: string;", |
| 645 | " token: string;", |
| 646 | " \"tokenizer\": \"gpt2\",", |
| 647 | "max tokens = 8192", |
| 648 | "export const AUTH_TOKEN_HEADER = 'x-auth-token';", |
| 649 | "{\"id\":1, \"password\": \"x\", \"language\": \"en\"}", |
| 650 | "{\"id\":1, \"password\":\"x\", \"language\":\"en\"}", |
| 651 | "password = hunter2", |
| 652 | "api_key = os.environ[\"OPENAI_API_KEY\"]", |
| 653 | "let token = ${TOKEN_FROM_ENV}", |
| 654 | "auth_url = https://example.test/oauth/token", |
| 655 | ]; |
| 656 | for line in lines { |
| 657 | assert_eq!( |
| 658 | redact_model_bound_secrets(line), |
| 659 | line, |
| 660 | "line changed: {line}" |
| 661 | ); |
| 662 | } |
| 663 | let file = lines.join("\n"); |
| 664 | assert_eq!(redact_model_bound_secrets(&file), file); |
| 665 | } |
| 666 | |
| 667 | #[test] |
| 668 | fn model_bound_redaction_masks_credential_shaped_values() { |
| 669 | let hex40 = ["0123456789abcdef", "0123456789abcdef", "01234567"].concat(); |
| 670 | let sk = ["sk-", "abcdef1234567890abcdef"].concat(); |
| 671 | let jwt = [ |
| 672 | "eyJhbGciOiJIUzI1NiJ9", |
| 673 | ".", |
| 674 | "eyJzdWIiOiIxMjM0NTY3ODkwIn0", |
| 675 | ".", |
| 676 | "c2lnbmF0dXJlLXNpZ25hdHVyZQ", |
| 677 | ] |
| 678 | .concat(); |
| 679 | let ya = ["ya29.", "a0AfH6SMBx1234567890abcdefghij"].concat(); |
| 680 | let cases = [ |
| 681 | ( |
| 682 | format!("NEXTAUTH_SECRET={hex40}"), |
| 683 | "NEXTAUTH_SECRET=[redacted]".to_string(), |
| 684 | ), |
| 685 | ( |
| 686 | format!("api_key = \"{sk}\""), |
| 687 | "api_key = \"[redacted]\"".to_string(), |
| 688 | ), |
| 689 | ( |
| 690 | format!(" \"access_token\": \"{ya}\","), |
| 691 | " \"access_token\": \"[redacted]\",".to_string(), |
| 692 | ), |
| 693 | ( |
| 694 | format!("Authorization: Bearer {jwt}"), |
| 695 | "Authorization: [redacted]".to_string(), |
| 696 | ), |
| 697 | ( |
| 698 | format!("curl -H \"Authorization: Bearer {jwt}\" https://api.test"), |
| 699 | "curl -H \"Authorization: Bearer [redacted]\" https://api.test".to_string(), |
| 700 | ), |
| 701 | ( |
| 702 | format!("password = {hex40}, retries = 3"), |
| 703 | "password = [redacted], retries = 3".to_string(), |
| 704 | ), |
| 705 | ( |
| 706 | format!("found key {sk} in the log"), |
| 707 | "found key [redacted] in the log".to_string(), |
| 708 | ), |
| 709 | ]; |
| 710 | for (input, expected) in cases { |
| 711 | assert_eq!( |
| 712 | redact_model_bound_secrets(&input), |
| 713 | expected, |
| 714 | "input: {input}" |
| 715 | ); |
| 716 | } |
| 717 | } |
| 718 | |
| 719 | #[test] |
| 720 | fn private_key_blocks_are_masked_between_pem_markers() { |
| 721 | // Assemble the PEM markers at runtime so the source file never |
| 722 | // contains a literal private-key header for a scanner to match; the |
| 723 | // runtime strings are identical to a real block. |
| 724 | let begin = ["-----BEGIN RSA", " PRIVATE KEY-----"].concat(); |
| 725 | let end = ["-----END RSA", " PRIVATE KEY-----"].concat(); |
| 726 | let body = "MIIEpAIBAAKCAQEA0Z3VS5JJcds3xfn\nabcdefghijklmnopqrstuvwxyz012345"; |
| 727 | let pem = format!("{begin}\n{body}\n{end}\nnext_line = ok\n"); |
| 728 | let expected = format!("{begin}\n[redacted]\n[redacted]\n{end}\nnext_line = ok\n"); |
| 729 | assert_eq!(redact_model_bound_secrets(&pem), expected); |
| 730 | assert_eq!(redact_secrets(&pem), expected); |
| 731 | } |
| 732 | |
| 733 | #[test] |
| 734 | fn key_based_policy_is_unchanged_by_the_model_bound_mode() { |
| 735 | // The broad scrubber for logs/previews keeps masking key-only hits. |
| 736 | assert_eq!( |
| 737 | redact_secrets(" password: credentials?.password,"), |
| 738 | " password: [redacted]" |
| 739 | ); |
| 740 | assert_eq!( |
| 741 | redact_secrets(" \"password-validator\": \"^5.3.0\","), |
| 742 | " \"password-validator\": \"[redacted]\"" |
| 743 | ); |
| 744 | } |
| 745 | |
| 746 | #[test] |
| 747 | fn redact_masks_keyed_secrets_toml_and_json() { |
| 748 | let synthetic_secret = synthetic_secret_fixture(); |
| 749 | let input = format!( |
| 750 | "\ |
| 751 | api_key = \"sk-supersecretvalue123\" |
| 752 | provider = \"openai\" |
| 753 | \"token\": \"{synthetic_secret}\", |
| 754 | model = \"mimo-ultraspeed\" |
| 755 | PASSWORD=hunter2hunter2" |
| 756 | ); |
| 757 | let out = redact_secrets(&input); |
| 758 | assert!(!out.contains("sk-supersecretvalue123"), "{out}"); |
| 759 | assert!(!out.contains(&synthetic_secret), "{out}"); |
| 760 | assert!(!out.contains("hunter2hunter2"), "{out}"); |
| 761 | // Non-secret values survive untouched. |
| 762 | assert!(out.contains("provider = \"openai\"")); |
| 763 | assert!(out.contains("model = \"mimo-ultraspeed\"")); |
| 764 | assert!(out.matches(REDACTED).count() >= 3, "{out}"); |
| 765 | } |
| 766 | |
| 767 | #[test] |
| 768 | fn redact_json_masks_camel_case_and_dotted_secret_keys() { |
| 769 | let synthetic_secret = synthetic_secret_fixture(); |
| 770 | let input = serde_json::json!({ |
| 771 | "accessToken": synthetic_secret.clone(), |
| 772 | "refreshToken": synthetic_secret_fixture(), |
| 773 | "oauth.token": synthetic_secret_fixture(), |
| 774 | "APIKey": synthetic_secret_fixture(), |
| 775 | "maxTokens": 8192, |
| 776 | "tokenBudget": 4096, |
| 777 | "tokenCount": 1024, |
| 778 | "token_count": 512, |
| 779 | "tokenizer": "sentencepiece", |
| 780 | }); |
| 781 | |
| 782 | let out = redact_json_secrets(&input); |
| 783 | for key in ["accessToken", "refreshToken", "oauth.token", "APIKey"] { |
| 784 | assert_eq!(out[key], REDACTED, "{key}: {out}"); |
| 785 | } |
| 786 | assert_eq!(out["maxTokens"], 8192); |
| 787 | assert_eq!(out["tokenBudget"], 4096); |
| 788 | assert_eq!(out["tokenCount"], 1024); |
| 789 | assert_eq!(out["token_count"], 512); |
| 790 | assert_eq!(out["tokenizer"], "sentencepiece"); |
| 791 | assert!(!out.to_string().contains(&synthetic_secret), "{out}"); |
| 792 | } |
| 793 | |
| 794 | #[test] |
| 795 | fn redact_json_truncates_pathological_nesting() { |
| 796 | let mut value = serde_json::Value::String("leaf".to_string()); |
| 797 | for _ in 0..150 { |
| 798 | let mut map = serde_json::Map::new(); |
| 799 | map.insert("t".to_string(), value); |
| 800 | value = serde_json::Value::Object(map); |
| 801 | } |
| 802 | let out = redact_json_secrets(&value); |
| 803 | let mut cursor = &out; |
| 804 | let mut descended = 0; |
| 805 | while let serde_json::Value::Object(map) = cursor { |
| 806 | cursor = map.values().next().expect("single-key nesting"); |
| 807 | descended += 1; |
| 808 | } |
| 809 | assert_eq!( |
| 810 | cursor, |
| 811 | &serde_json::Value::String(REDACTED.to_string()), |
| 812 | "over-deep value must be redacted, not traversed" |
| 813 | ); |
| 814 | assert!(descended < 150, "guard must fire before the leaf"); |
| 815 | } |
| 816 | |
| 817 | #[test] |
| 818 | fn redact_text_masks_camel_case_and_dotted_secret_assignments() { |
| 819 | let synthetic_secret = synthetic_secret_fixture(); |
| 820 | for key in ["accessToken", "refreshToken", "oauth.token", "APIKey"] { |
| 821 | let out = redact_secrets(&format!("request failed: {key} = {synthetic_secret}")); |
| 822 | assert!(!out.contains(&synthetic_secret), "{key}: {out}"); |
| 823 | assert!(out.contains(REDACTED), "{key}: {out}"); |
| 824 | } |
| 825 | for key in ["tokenBudget", "tokenCount", "token_count"] { |
| 826 | let input = format!("model usage: {key} = 8192"); |
| 827 | assert_eq!(redact_secrets(&input), input, "{key}"); |
| 828 | } |
| 829 | } |
| 830 | |
| 831 | #[test] |
| 832 | fn redact_masks_bare_token_prefixes() { |
| 833 | let out = redact_secrets("the leaked key sk-abcdef1234567890 appeared in a log"); |
| 834 | assert!(!out.contains("sk-abcdef1234567890"), "{out}"); |
| 835 | assert!(out.contains(REDACTED)); |
| 836 | assert!(out.contains("appeared in a log")); |
| 837 | } |
| 838 | |
| 839 | #[test] |
| 840 | fn redact_masks_inline_sensitive_assignments_after_prose_prefixes() { |
| 841 | let out = redact_secrets( |
| 842 | "Decision: use token=plain-secret-value and api_key:another-secret-value", |
| 843 | ); |
| 844 | assert!(!out.contains("plain-secret-value"), "{out}"); |
| 845 | assert!(!out.contains("another-secret-value"), "{out}"); |
| 846 | assert_eq!(out.matches(REDACTED).count(), 2, "{out}"); |
| 847 | assert!(out.starts_with("Decision: use "), "{out}"); |
| 848 | } |
| 849 | |
| 850 | #[test] |
| 851 | fn redact_masks_spaced_assignment_that_is_not_the_first_separator() { |
| 852 | // The shape `redact_secrets(&format!("{error:#}"))` produces: an |
| 853 | // anyhow chain puts prose and its own `: ` separators in front of the |
| 854 | // assignment, so the sensitive key never owns the line's first |
| 855 | // separator and the whole-line pass declines the line. |
| 856 | let out = redact_secrets("request failed: api_key = AIzaSyDeadBeefLeak"); |
| 857 | assert!(!out.contains("AIzaSyDeadBeefLeak"), "{out}"); |
| 858 | assert!(out.contains(REDACTED), "{out}"); |
| 859 | |
| 860 | let synthetic_secret = synthetic_secret_fixture(); |
| 861 | let out = redact_secrets(&format!("note: the token = {synthetic_secret}")); |
| 862 | assert!(!out.contains(&synthetic_secret), "{out}"); |
| 863 | assert!(out.contains(REDACTED), "{out}"); |
| 864 | } |
| 865 | |
| 866 | #[test] |
| 867 | fn redact_masks_whole_multi_word_value_of_a_spaced_assignment() { |
| 868 | // Assemble the placeholder at runtime so secret scanners do not |
| 869 | // mistake a redaction fixture for a committed credential. |
| 870 | let bearer = ["Bear", "er"].concat(); |
| 871 | let credential = ["abc123", "def456", "ghi"].concat(); |
| 872 | let out = redact_secrets(&format!( |
| 873 | "mcp call failed: authorization = {bearer} {credential}" |
| 874 | )); |
| 875 | assert!(!out.contains(&credential), "{out}"); |
| 876 | assert!(!out.contains(&bearer), "{out}"); |
| 877 | assert!( |
| 878 | out.starts_with("mcp call failed: authorization = "), |
| 879 | "{out}" |
| 880 | ); |
| 881 | } |
| 882 | |
| 883 | #[test] |
| 884 | fn redact_spaced_pass_leaves_ordinary_prose_alone() { |
| 885 | // No sensitive key, so the spaced-assignment state machine must not |
| 886 | // start swallowing the rest of the line. |
| 887 | let input = "the quick brown fox = jumps over the lazy dog"; |
| 888 | assert_eq!(redact_secrets(input), input); |
| 889 | let input = "note: the model = deepseek-v4-pro and the seed = 7"; |
| 890 | assert_eq!(redact_secrets(input), input); |
| 891 | } |
| 892 | |
| 893 | #[test] |
| 894 | fn redact_leaves_token_count_diagnostics_intact() { |
| 895 | // "tokens" is the English plural of a usage metric, not a credential |
| 896 | // key. The spaced-assignment pass used to treat the "token" hint as a |
| 897 | // substring and then drop the rest of the line, which made the exact |
| 898 | // class of error people paste into issues unreadable. |
| 899 | for input in [ |
| 900 | "stream error: max tokens = 8192 but budget = 4096", |
| 901 | "error: token expired", |
| 902 | "request failed: token count: 4096 exceeds the model limit", |
| 903 | "http 401: authorization header rejected", |
| 904 | "warning: password policy requires 12 characters", |
| 905 | "note: secret scanning found 3 issues", |
| 906 | ] { |
| 907 | assert_eq!(redact_secrets(input), input, "{input}"); |
| 908 | } |
| 909 | } |
| 910 | |
| 911 | #[test] |
| 912 | fn redact_keeps_a_provider_refusal_reason_readable() { |
| 913 | // xAI answers an exhausted account with a 403 whose body is the whole |
| 914 | // explanation. The `Authorization failed:` prefix is our label, not a |
| 915 | // header, so the reason after it must survive to the error card. |
| 916 | let input = "Authorization failed: You have run out of credits or need a Grok \ |
| 917 | subscription. Add credits at https://grok.com/?_s=usage."; |
| 918 | assert_eq!(redact_secrets(input), input); |
| 919 | } |
| 920 | |
| 921 | #[test] |
| 922 | fn redact_still_masks_a_bearer_token_assignment() { |
| 923 | // Counterpart of the diagnostic test above: a real credential keyed |
| 924 | // as `token` (or `api_token`) must still be dropped, including a |
| 925 | // multi-word Bearer value that is not a known bare-token prefix. |
| 926 | // The JWT is assembled at runtime so no scanner-shaped literal sits |
| 927 | // in the source tree — same precedent as the AWS fixture in |
| 928 | // `crates/workflow/src/redaction.rs`. |
| 929 | let jwt = ["eyJhbGciOiJIUzI1NiJ9", "e30", "c2lnbmF0dXJl"].join("."); |
| 930 | let out = redact_secrets(&format!("stream error: token = Bearer {jwt}")); |
| 931 | assert!(!out.contains(&jwt), "{out}"); |
| 932 | assert!(!out.contains("Bearer"), "{out}"); |
| 933 | assert!(out.starts_with("stream error: token = "), "{out}"); |
| 934 | assert!(out.contains(REDACTED), "{out}"); |
| 935 | |
| 936 | let synthetic_secret = synthetic_secret_fixture(); |
| 937 | let out = redact_secrets(&format!("note: api_token = {synthetic_secret}")); |
| 938 | assert!(!out.contains(&synthetic_secret), "{out}"); |
| 939 | assert!(out.contains(REDACTED), "{out}"); |
| 940 | } |
| 941 | |
| 942 | #[test] |
| 943 | fn redact_preserves_line_structure() { |
| 944 | let input = "line1\nsecret = \"xyzsecretvalue\"\nline3"; |
| 945 | let out = redact_secrets(input); |
| 946 | let lines: Vec<&str> = out.lines().collect(); |
| 947 | assert_eq!(lines.len(), 3); |
| 948 | assert_eq!(lines[0], "line1"); |
| 949 | assert_eq!(lines[2], "line3"); |
| 950 | assert!(lines[1].contains(REDACTED)); |
| 951 | } |
| 952 | |
| 953 | #[test] |
| 954 | fn redact_leaves_plain_text_untouched() { |
| 955 | let input = "the quick brown fox = jumps over"; |
| 956 | // `fox` key has no sensitive hint → unchanged. |
| 957 | assert_eq!(redact_secrets(input), input); |
| 958 | } |
| 959 | |
| 960 | #[test] |
| 961 | fn atomic_write_syncs_parent_directory_without_failing_persisted_save() { |
| 962 | let tmp = tempfile::tempdir().unwrap(); |
| 963 | let path = tmp.path().join("state.json"); |
| 964 | let mut synced_dir = None; |
| 965 | atomic_write_with_dir_sync(&path, b"v1", |dir| { |
| 966 | synced_dir = Some(dir.to_path_buf()); |
| 967 | Ok(()) |
| 968 | }) |
| 969 | .unwrap(); |
| 970 | assert_eq!(synced_dir.as_deref(), Some(tmp.path())); |
| 971 | |
| 972 | atomic_write_with_dir_sync(&path, b"v2", |_| { |
| 973 | anyhow::bail!("injected directory sync failure") |
| 974 | }) |
| 975 | .expect("best-effort parent directory sync must not fail an already-persisted write"); |
| 976 | assert_eq!(read(&path), "v2"); |
| 977 | |
| 978 | #[cfg(unix)] |
| 979 | { |
| 980 | assert!(is_unsupported_dir_sync_error(&std::io::Error::new( |
| 981 | std::io::ErrorKind::Unsupported, |
| 982 | "not supported" |
| 983 | ))); |
| 984 | assert!(is_unsupported_dir_sync_error(&std::io::Error::new( |
| 985 | std::io::ErrorKind::InvalidInput, |
| 986 | "invalid argument" |
| 987 | ))); |
| 988 | assert!(!is_unsupported_dir_sync_error(&std::io::Error::new( |
| 989 | std::io::ErrorKind::PermissionDenied, |
| 990 | "denied" |
| 991 | ))); |
| 992 | } |
| 993 | } |
| 994 | |
| 995 | #[test] |
| 996 | fn atomic_write_if_absent_creates_once_and_never_clobbers_existing() { |
| 997 | let tmp = tempfile::tempdir().unwrap(); |
| 998 | let path = tmp.path().join("config.toml"); |
| 999 | |
| 1000 | assert!(atomic_write_if_absent(&path, b"first").unwrap()); |
| 1001 | assert_eq!(read(&path), "first"); |
| 1002 | |
| 1003 | assert!(!atomic_write_if_absent(&path, b"second").unwrap()); |
| 1004 | assert_eq!(read(&path), "first"); |
| 1005 | } |
| 1006 | } |
| 1007 |