返回 CodeWhale
config_document.rs
根目录 / crates / config / src / config_document.rs
1 //! Lossless, serialized `config.toml` mutation.
2 //!
3 //! Every Codewhale config writer coordinates through the adjacent lock owned
4 //! here. Mutations re-read only after acquiring the lock, so a stale process
5 //! cannot resurrect revoked credential authority. Callers that still serialize
6 //! a full typed snapshot must supply the exact bytes they originally loaded and
7 //! fail on a concurrent change.
8
9 use std::fs;
10 use std::path::{Path, PathBuf};
11
12 use anyhow::{Context, Result, bail};
13
14 use crate::{
15 checked_path_exists, normalize_config_file_path, persistence, read_checked_config_file,
16 write_one_time_config_backup,
17 };
18
19 /// Parse the latest document under the shared write lock, apply `mutate`, and
20 /// atomically persist only the resulting delta.
21 pub fn mutate_config_document<T, F>(path: &Path, mutate: F) -> Result<T>
22 where
23 F: FnOnce(&mut toml_edit::DocumentMut) -> Result<T>,
24 {
25 mutate_config_document_with_migration(path, |doc, _| mutate(doc))
26 }
27
28 /// [`mutate_config_document`], also handing `mutate` the receipt of the legacy
29 /// top-level `base_url` / `api_key` move this same write made, so a caller can
30 /// tell a value it just moved from one that was already in its table.
31 pub fn mutate_config_document_with_migration<T, F>(path: &Path, mutate: F) -> Result<T>
32 where
33 F: FnOnce(&mut toml_edit::DocumentMut, &crate::legacy_root::LegacyRootMigration) -> Result<T>,
34 {
35 mutate_locked(path, mutate).map(|(result, _)| result)
36 }
37
38 /// [`mutate_config_document`], also returning what undoes exactly this write.
39 ///
40 /// Both halves are taken under the lock: the bytes this call left on disk and
41 /// the document as it stood just before `mutate` ran (after this writer's own
42 /// one-way repairs), or the file's absence. A caller whose follow-up step is
43 /// refused can then take back only its own change with
44 /// [`ConfigDocumentUndo::undo`].
45 pub fn mutate_config_document_undoable<T, F>(
46 path: &Path,
47 mutate: F,
48 ) -> Result<(T, ConfigDocumentUndo)>
49 where
50 F: FnOnce(&mut toml_edit::DocumentMut) -> Result<T>,
51 {
52 mutate_locked(path, |doc, _| mutate(doc))
53 }
54
55 /// The undoable write, also retaining the migration performed under this same
56 /// lock. The caller can validate a captured route against the freshly moved
57 /// document before writing its delta; undo still compares the exact written bytes.
58 pub fn mutate_config_document_undoable_with_migration<T, F>(
59 path: &Path,
60 mutate: F,
61 ) -> Result<(T, ConfigDocumentUndo)>
62 where
63 F: FnOnce(&mut toml_edit::DocumentMut, &crate::legacy_root::LegacyRootMigration) -> Result<T>,
64 {
65 mutate_locked(path, mutate)
66 }
67
68 fn mutate_locked<T, F>(path: &Path, mutate: F) -> Result<(T, ConfigDocumentUndo)>
69 where
70 F: FnOnce(&mut toml_edit::DocumentMut, &crate::legacy_root::LegacyRootMigration) -> Result<T>,
71 {
72 let requested = path.to_path_buf();
73 with_config_write_lock(path, |path| {
74 let original = read_optional_config(path)?;
75 let mut document = match original.as_deref() {
76 Some(raw) if !raw.trim().is_empty() => {
77 raw.parse::<toml_edit::DocumentMut>().map_err(|_| {
78 anyhow::anyhow!(
79 "failed to parse config at {}; file contents were omitted",
80 crate::quote_os_path(path)
81 )
82 })?
83 }
84 _ => toml_edit::DocumentMut::new(),
85 };
86 heal_extras_nesting(&mut document);
87 // Move legacy top-level `base_url` / `api_key` into their provider
88 // tables as part of this write (#6394). Conflicting pairs stay put
89 // unless this very write changes the table side.
90 let moved = crate::legacy_root::apply_to_document(&mut document, None);
91 let conflicts = crate::legacy_root::conflict_snapshot(&document);
92 let restore = original.as_ref().map(|_| document.to_string());
93 let result = mutate(&mut document, &moved)?;
94 crate::legacy_root::settle_conflicts_after_write(&mut document, conflicts);
95 let body = document.to_string();
96 if original.as_deref() == Some(body.as_str()) || (original.is_none() && body.is_empty()) {
97 let undo = ConfigDocumentUndo {
98 path: requested,
99 written: original,
100 restore,
101 };
102 return Ok((result, undo));
103 }
104 if moved.changes_file()
105 && let Some(original) = original.as_deref()
106 {
107 crate::note_legacy_root_file_migration(path, original)?;
108 }
109 persist_locked(path, original.as_deref(), body.as_bytes())?;
110 let undo = ConfigDocumentUndo {
111 path: requested,
112 written: Some(body),
113 restore,
114 };
115 Ok((result, undo))
116 })
117 }
118
119 /// Takes back one [`mutate_config_document_undoable`] write, and only that.
120 #[derive(Debug, Clone)]
121 pub struct ConfigDocumentUndo {
122 path: PathBuf,
123 /// The bytes that write left on disk; `None` when the file stayed absent.
124 written: Option<String>,
125 /// What `undo` puts back; `None` removes the file that write created.
126 restore: Option<String>,
127 }
128
129 impl ConfigDocumentUndo {
130 /// Put the document back as it was before the write, but only while the
131 /// file still holds exactly the bytes that write left: any newer save
132 /// wins. Returns `false` when the file changed since and was left alone.
133 pub fn undo(&self) -> Result<bool> {
134 with_config_write_lock(&self.path, |path| {
135 let current = read_optional_config(path)?;
136 if current == self.restore {
137 return Ok(true);
138 }
139 if current != self.written {
140 return Ok(false);
141 }
142 match self.restore.as_deref() {
143 Some(body) => persist_locked(path, current.as_deref(), body.as_bytes())?,
144 None => fs::remove_file(path).with_context(|| {
145 format!("failed to remove config at {}", crate::quote_os_path(path))
146 })?,
147 }
148 Ok(true)
149 })
150 }
151 }
152
153 /// Lift keys trapped under literal `[extras]` tables back to the top level.
154 ///
155 /// The config structs flatten unknown keys into an `extras` map; a historic
156 /// writer serialized that map under a literal `extras` key, and every
157 /// subsequent buggy round-trip nested it one level deeper
158 /// (`[extras.extras.extras.projects."..."]`). That silently strips real
159 /// state — workspace trust records, profiles, saved tokens — from every
160 /// reader that looks at the canonical top-level tables (2026-07-23 user
161 /// report: saved permission/trust ignored on each new session).
162 ///
163 /// Healing runs on every config mutation: entries move up one level per
164 /// pass (existing top-level values always win; shadowed duplicates are
165 /// dropped), until no literal `extras` table remains. Bounded passes keep a
166 /// pathological file from looping.
167 ///
168 /// An `extras` key that is *not* table-like (a string, array, or number) has
169 /// nothing to lift, so it is left exactly where it is. Removing it would
170 /// delete user data this function cannot heal, on every subsequent write.
171 pub fn heal_extras_nesting(document: &mut toml_edit::DocumentMut) -> bool {
172 let mut healed = false;
173 for _ in 0..16 {
174 if document
175 .get("extras")
176 .is_none_or(|item| !item.is_table_like())
177 {
178 break;
179 }
180 let Some(extras) = document
181 .remove("extras")
182 .and_then(|item| item.into_table().ok())
183 else {
184 break;
185 };
186 healed = true;
187 for (key, value) in extras {
188 if document.get(&key).is_none() {
189 document.insert(&key, value);
190 }
191 }
192 }
193 healed
194 }
195
196 /// What `codewhale config migrate` would do to the file at `path`, without
197 /// writing it (#6394).
198 pub fn preview_legacy_root_config(
199 path: &Path,
200 prefer: Option<crate::legacy_root::LegacyRootPrefer>,
201 ) -> Result<crate::legacy_root::LegacyRootMigration> {
202 let Some(raw) = read_optional_config(path)? else {
203 return Ok(crate::legacy_root::LegacyRootMigration::default());
204 };
205 let document = raw.parse::<toml_edit::DocumentMut>().map_err(|_| {
206 anyhow::anyhow!(
207 "failed to parse config at {}; file contents were omitted",
208 crate::quote_os_path(path)
209 )
210 })?;
211 crate::legacy_root::try_preview_document(&document, prefer)
212 }
213
214 /// Move legacy top-level `base_url` / `api_key` into their provider tables
215 /// on disk, keeping comments. A conflicting pair changes only when `prefer`
216 /// says which side to keep. Before the first write a one-time,
217 /// credential-free backup is kept; its path is returned when one exists.
218 pub fn migrate_legacy_root_config(
219 path: &Path,
220 prefer: Option<crate::legacy_root::LegacyRootPrefer>,
221 ) -> Result<(crate::legacy_root::LegacyRootMigration, Option<PathBuf>)> {
222 with_config_write_lock(path, |path| {
223 let Some(original) = read_optional_config(path)? else {
224 return Ok((crate::legacy_root::LegacyRootMigration::default(), None));
225 };
226 let mut document = original.parse::<toml_edit::DocumentMut>().map_err(|_| {
227 anyhow::anyhow!(
228 "failed to parse config at {}; file contents were omitted",
229 crate::quote_os_path(path)
230 )
231 })?;
232 let receipt = crate::legacy_root::try_apply_to_document(&mut document, prefer)?;
233 if !receipt.changes_file() {
234 return Ok((receipt, None));
235 }
236 let backup = crate::write_legacy_root_backup(path, &original)?;
237 persist_locked(path, Some(&original), document.to_string().as_bytes())?;
238 Ok((receipt, Some(backup)))
239 })
240 }
241
242 /// Create a config file only if it is still absent when the shared lock is
243 /// acquired. This closes the `exists()`/create race in first-run writers.
244 pub fn create_config_document(path: &Path, body: &str) -> Result<()> {
245 replace_config_document_if_unchanged(path, None, body)
246 }
247
248 /// Replace a full typed snapshot only when on-disk bytes still equal the
249 /// snapshot the caller originally loaded. `None` means the file was absent.
250 pub fn replace_config_document_if_unchanged(
251 path: &Path,
252 expected: Option<&str>,
253 body: &str,
254 ) -> Result<()> {
255 with_config_write_lock(path, |path| {
256 let current = read_optional_config(path)?;
257 if current.as_deref() == Some(body) {
258 return Ok(());
259 }
260 if current.as_deref() != expected {
261 bail!(
262 "config changed after it was loaded; reload {} and retry instead of overwriting concurrent changes",
263 crate::quote_os_path(path)
264 );
265 }
266 persist_locked(path, current.as_deref(), body.as_bytes())
267 })
268 }
269
270 /// Set a value at `segments`, creating implicit parent tables while preserving
271 /// existing key/value decor.
272 pub fn set_config_document_value(
273 doc: &mut toml_edit::DocumentMut,
274 segments: &[&str],
275 value: impl Into<toml_edit::Value>,
276 ) -> Result<()> {
277 let (key, parents) = segments
278 .split_last()
279 .context("config value path must not be empty")?;
280 let table = table_like_at_path_mut(doc.as_table_mut(), parents, PathLookup::Create)?
281 .expect("Create lookups always yield a table");
282 match table.get_mut(key) {
283 Some(item) => {
284 let mut value = value.into();
285 if let Some(existing) = item.as_value() {
286 *value.decor_mut() = existing.decor().clone();
287 }
288 *item = toml_edit::Item::Value(value);
289 }
290 None => {
291 table.insert(key, toml_edit::value(value));
292 }
293 }
294 Ok(())
295 }
296
297 /// Remove a value at `segments` without disturbing unrelated tables or decor.
298 pub fn unset_config_document_value(
299 doc: &mut toml_edit::DocumentMut,
300 segments: &[&str],
301 ) -> Result<bool> {
302 let (key, parents) = segments
303 .split_last()
304 .context("config value path must not be empty")?;
305 let orphaned_root_prefix = (parents.is_empty() && doc.as_table().len() == 1)
306 .then(|| leading_prefix_for_key(doc.as_table(), key))
307 .flatten();
308 let removed = {
309 let Some(table) =
310 table_like_at_path_mut(doc.as_table_mut(), parents, PathLookup::Existing)?
311 else {
312 return Ok(false);
313 };
314 remove_key_preserving_leading_decor(table, key)
315 };
316 if removed
317 && let Some(prefix) = orphaned_root_prefix
318 && prefix.as_str().is_some_and(|prefix| !prefix.is_empty())
319 {
320 let trailing = format!(
321 "{}{}",
322 prefix.as_str().unwrap_or_default(),
323 doc.trailing().as_str().unwrap_or_default()
324 );
325 doc.set_trailing(trailing);
326 }
327 Ok(removed)
328 }
329
330 /// Serialize a complete read-modify-write operation against a canonical
331 /// configuration path. The callback must not acquire this same lock again.
332 pub fn with_config_write_lock<T>(
333 path: &Path,
334 operation: impl FnOnce(&Path) -> Result<T>,
335 ) -> Result<T> {
336 let path = prepare_config_path(path)?;
337 let lock_path = adjacent_lock_path(&path)?;
338 super::reject_path_symlink(&lock_path)?;
339
340 let mut options = fs::OpenOptions::new();
341 options.read(true).write(true).create(true);
342 #[cfg(unix)]
343 {
344 use std::os::unix::fs::OpenOptionsExt as _;
345 options.mode(0o600).custom_flags(libc::O_NOFOLLOW);
346 }
347 #[cfg(windows)]
348 {
349 use std::os::windows::fs::OpenOptionsExt as _;
350 use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT;
351 options.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT);
352 }
353 let lock_file = options.open(&lock_path).with_context(|| {
354 format!(
355 "failed to open config lock at {}",
356 crate::quote_os_path(&lock_path)
357 )
358 })?;
359 // The lock is created at `0600`, so this only narrows a lock that an
360 // older version or a different umask left wider. It is applied to the
361 // handle that was just opened, not re-resolved by path: between the open
362 // and the `chmod` the path could name a different object, and this is the
363 // file the caller is about to lock. A mount that cannot apply modes is
364 // excused by `tighten_mode_of`; a filesystem that stores them keeps the
365 // error.
366 #[cfg(unix)]
367 crate::private_directory::tighten_mode_of(&lock_file, &lock_path, 0o600).with_context(
368 || {
369 format!(
370 "failed to secure config lock at {}",
371 crate::quote_os_path(&lock_path)
372 )
373 },
374 )?;
375 #[cfg(windows)]
376 validate_windows_lock_handle(&lock_file, &lock_path)?;
377 let mut lock = fd_lock::RwLock::new(lock_file);
378 let _guard = lock.write().with_context(|| {
379 format!(
380 "failed to acquire config lock at {}",
381 crate::quote_os_path(&lock_path)
382 )
383 })?;
384 operation(&path)
385 }
386
387 #[cfg(windows)]
388 fn validate_windows_lock_handle(file: &fs::File, expected_path: &Path) -> Result<()> {
389 use std::ffi::OsString;
390 use std::os::windows::ffi::OsStringExt as _;
391 use std::os::windows::fs::MetadataExt as _;
392 use std::os::windows::io::AsRawHandle as _;
393 use windows_sys::Win32::Storage::FileSystem::{
394 FILE_ATTRIBUTE_REPARSE_POINT, FILE_NAME_NORMALIZED, GetFinalPathNameByHandleW,
395 VOLUME_NAME_DOS,
396 };
397
398 let metadata = file.metadata().with_context(|| {
399 format!(
400 "failed to inspect config lock at {}",
401 crate::quote_os_path(expected_path)
402 )
403 })?;
404 if !metadata.file_type().is_file()
405 || metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0
406 {
407 bail!(
408 "refusing non-regular or reparse-point config lock at {}",
409 crate::quote_os_path(expected_path)
410 );
411 }
412
413 let handle = file.as_raw_handle();
414 let flags = FILE_NAME_NORMALIZED | VOLUME_NAME_DOS;
415 // SAFETY: `handle` remains owned by `file`; a null output buffer asks for
416 // the required UTF-16 length.
417 let needed = unsafe { GetFinalPathNameByHandleW(handle, std::ptr::null_mut(), 0, flags) };
418 if needed == 0 {
419 return Err(std::io::Error::last_os_error()).with_context(|| {
420 format!(
421 "failed to resolve config lock at {}",
422 crate::quote_os_path(expected_path)
423 )
424 });
425 }
426 let mut buffer = vec![0u16; needed as usize + 1];
427 // SAFETY: `buffer` is writable for its declared length and `handle` stays
428 // valid through the call.
429 let written = unsafe {
430 GetFinalPathNameByHandleW(handle, buffer.as_mut_ptr(), buffer.len() as u32, flags)
431 };
432 if written == 0 || written as usize >= buffer.len() {
433 return Err(std::io::Error::last_os_error()).with_context(|| {
434 format!(
435 "failed to resolve config lock at {}",
436 crate::quote_os_path(expected_path)
437 )
438 });
439 }
440 let actual = OsString::from_wide(&buffer[..written as usize]);
441 if normalize_windows_path_for_comparison(Path::new(&actual))?
442 != normalize_windows_path_for_comparison(expected_path)?
443 {
444 bail!(
445 "config lock was redirected while opening {}",
446 crate::quote_os_path(expected_path)
447 );
448 }
449 Ok(())
450 }
451
452 #[cfg(windows)]
453 fn normalize_windows_path_for_comparison(path: &Path) -> Result<String> {
454 let text = path.to_str().ok_or_else(|| {
455 anyhow::anyhow!(
456 "config lock path {} contains invalid Unicode and cannot be compared safely",
457 crate::quote_os_path(path)
458 )
459 })?;
460 let without_device_prefix = text.strip_prefix(r"\\?\").unwrap_or(text);
461 let normalized_prefix = without_device_prefix.strip_prefix("UNC\\").map_or_else(
462 || without_device_prefix.to_string(),
463 |rest| format!(r"\\{rest}"),
464 );
465 Ok(normalized_prefix
466 .replace('/', "\\")
467 .trim_end_matches('\\')
468 .to_lowercase())
469 }
470
471 fn prepare_config_path(path: &Path) -> Result<PathBuf> {
472 let absolute = if path.is_absolute() {
473 path.to_path_buf()
474 } else {
475 std::env::current_dir()
476 .context("failed to resolve current directory for config path")?
477 .join(path)
478 };
479 if let Some(parent) = absolute
480 .parent()
481 .filter(|parent| !parent.as_os_str().is_empty())
482 {
483 fs::create_dir_all(parent).with_context(|| {
484 format!(
485 "failed to create config directory {}",
486 crate::quote_os_path(parent)
487 )
488 })?;
489 }
490 normalize_config_file_path(absolute)
491 }
492
493 fn adjacent_lock_path(path: &Path) -> Result<PathBuf> {
494 let mut file_name = path
495 .file_name()
496 .context("config path must include a file name")?
497 .to_os_string();
498 file_name.push(".lock");
499 Ok(path
500 .parent()
501 .context("config path must include a parent directory")?
502 .join(file_name))
503 }
504
505 fn read_optional_config(path: &Path) -> Result<Option<String>> {
506 if checked_path_exists(path)? {
507 read_checked_config_file(path).map(Some)
508 } else {
509 Ok(None)
510 }
511 }
512
513 fn persist_locked(path: &Path, original: Option<&str>, body: &[u8]) -> Result<()> {
514 if original.is_some() {
515 write_one_time_config_backup(path)?;
516 }
517 persistence::atomic_write(path, body)
518 .with_context(|| format!("failed to write config at {}", crate::quote_os_path(path)))
519 }
520
521 pub(crate) fn remove_key_preserving_leading_decor(
522 table: &mut dyn toml_edit::TableLike,
523 key: &str,
524 ) -> bool {
525 let mut found = false;
526 let next_key = table.iter().find_map(|(candidate, _)| {
527 if found {
528 Some(candidate.to_owned())
529 } else {
530 found = candidate == key;
531 None
532 }
533 });
534 let leading_prefix = leading_prefix_for_key(table, key);
535 if table.remove(key).is_none() {
536 return false;
537 }
538 let Some(prefix) = leading_prefix else {
539 return true;
540 };
541 let Some(next_key) = next_key else {
542 return true;
543 };
544 if prefix.as_str() == Some("") {
545 return true;
546 }
547 if let Some(mut next_key_decor) = table.key_mut(&next_key)
548 && decor_prefix_is_empty(next_key_decor.leaf_decor())
549 {
550 next_key_decor.leaf_decor_mut().set_prefix(prefix);
551 }
552 true
553 }
554
555 fn decor_prefix_is_empty(decor: &toml_edit::Decor) -> bool {
556 match decor.prefix() {
557 Some(prefix) => prefix.as_str() == Some(""),
558 None => true,
559 }
560 }
561
562 fn leading_prefix_for_key(
563 table: &dyn toml_edit::TableLike,
564 key: &str,
565 ) -> Option<toml_edit::RawString> {
566 table
567 .key(key)
568 .and_then(|key| key.leaf_decor().prefix().cloned())
569 .or_else(|| {
570 table
571 .get(key)
572 .and_then(|item| item.as_value())
573 .and_then(|value| value.decor().prefix().cloned())
574 })
575 }
576
577 #[derive(Clone, Copy, PartialEq, Eq)]
578 enum PathLookup {
579 Create,
580 Existing,
581 }
582
583 fn table_like_at_path_mut<'a>(
584 root: &'a mut toml_edit::Table,
585 segments: &[&str],
586 lookup: PathLookup,
587 ) -> Result<Option<&'a mut dyn toml_edit::TableLike>> {
588 let mut current: &mut dyn toml_edit::TableLike = root;
589 for segment in segments {
590 if current.get(segment).is_none() {
591 match lookup {
592 PathLookup::Create => {
593 let mut table = toml_edit::Table::new();
594 table.set_implicit(true);
595 current.insert(segment, toml_edit::Item::Table(table));
596 }
597 PathLookup::Existing => return Ok(None),
598 }
599 }
600 let item = current
601 .get_mut(segment)
602 .expect("segment exists or was inserted above");
603 match item.as_table_like_mut() {
604 Some(table) => current = table,
605 None => match lookup {
606 PathLookup::Create => bail!("`{segment}` in config.toml must be a table"),
607 PathLookup::Existing => return Ok(None),
608 },
609 }
610 }
611 Ok(Some(current))
612 }
613
614 #[cfg(test)]
615 mod tests {
616 fn set_model(doc: &mut toml_edit::DocumentMut, model: &str) -> anyhow::Result<()> {
617 super::set_config_document_value(doc, &["model"], model)
618 }
619
620 #[test]
621 fn undo_restores_the_document_and_removes_a_file_it_created() {
622 let tmp = tempfile::tempdir().expect("tempdir");
623 let path = tmp.path().join("config.toml");
624 let before = "# keep me\nmodel = \"a\"\n";
625 std::fs::write(&path, before).expect("write fixture");
626 let ((), undo) = super::mutate_config_document_undoable(&path, |doc| set_model(doc, "b"))
627 .expect("write");
628 assert!(
629 std::fs::read_to_string(&path)
630 .expect("read")
631 .contains("\"b\"")
632 );
633 assert!(undo.undo().expect("undo"));
634 assert_eq!(std::fs::read_to_string(&path).expect("read"), before);
635
636 // A file this write created goes away again, not left behind empty.
637 let absent = tmp.path().join("fresh.toml");
638 let ((), undo) = super::mutate_config_document_undoable(&absent, |doc| set_model(doc, "b"))
639 .expect("write");
640 assert!(absent.exists());
641 assert!(undo.undo().expect("undo"));
642 assert!(!absent.exists(), "undo must not leave an empty config file");
643 }
644
645 #[test]
646 fn undo_never_overwrites_a_newer_save() {
647 let tmp = tempfile::tempdir().expect("tempdir");
648 let path = tmp.path().join("config.toml");
649 std::fs::write(&path, "model = \"a\"\n").expect("write fixture");
650 let ((), undo) = super::mutate_config_document_undoable(&path, |doc| set_model(doc, "b"))
651 .expect("write");
652 super::mutate_config_document(&path, |doc| set_model(doc, "c")).expect("newer save");
653 assert!(!undo.undo().expect("undo"), "a changed file is reported");
654 assert_eq!(
655 std::fs::read_to_string(&path).expect("read"),
656 "model = \"c\"\n"
657 );
658
659 // The same holds when the newer save removed a file the write created.
660 let absent = tmp.path().join("fresh.toml");
661 let ((), undo) = super::mutate_config_document_undoable(&absent, |doc| set_model(doc, "b"))
662 .expect("write");
663 std::fs::write(&absent, "model = \"c\"\n").expect("newer save");
664 assert!(!undo.undo().expect("undo"));
665 assert_eq!(
666 std::fs::read_to_string(&absent).expect("read"),
667 "model = \"c\"\n"
668 );
669 }
670
671 #[test]
672 fn healing_keeps_a_non_table_extras_key_it_cannot_lift() {
673 // `extras` is where the config structs flatten unknown keys, so a
674 // scalar or array under that exact name round-trips through the typed
675 // path as ordinary user data. Healing used to `remove()` it before
676 // discovering it was not a table, dropping it on the very next
677 // `codewhale config set` — and reporting `healed == false` while doing
678 // so.
679 for body in [
680 "extras = \"opaque\"\nmodel = \"m\"\n",
681 "extras = [1, 2]\nmodel = \"m\"\n",
682 "model = \"m\"\nextras = 7\n",
683 ] {
684 let tmp = tempfile::tempdir().expect("tempdir");
685 let path = tmp.path().join("config.toml");
686 std::fs::write(&path, body).expect("write fixture");
687
688 super::mutate_config_document(&path, |doc| {
689 super::set_config_document_value(doc, &["tui", "low_motion"], true)
690 })
691 .expect("mutate");
692
693 let saved = std::fs::read_to_string(&path).expect("read");
694 let parsed: toml::Value = toml::from_str(&saved).expect("parse");
695 assert!(
696 parsed.get("extras").is_some(),
697 "non-table `extras` was deleted by an unrelated write: {saved}"
698 );
699 assert!(saved.contains("low_motion = true"), "{saved}");
700 }
701 }
702
703 #[test]
704 fn healing_still_lifts_an_inline_extras_table() {
705 // The preservation guard above must not stop the real healing path:
706 // an inline table is table-like and still gets lifted.
707 let mut doc = "extras = { trust = true }\nmodel = \"m\"\n"
708 .parse::<toml_edit::DocumentMut>()
709 .expect("parse");
710 assert!(super::heal_extras_nesting(&mut doc));
711 let rendered = doc.to_string();
712 assert!(rendered.contains("trust = true"), "{rendered}");
713 assert!(!rendered.contains("extras"), "{rendered}");
714 }
715
716 #[test]
717 fn healing_lifts_nested_extras_towers_to_the_top_level() {
718 let tmp = tempfile::tempdir().expect("tempdir");
719 let path = tmp.path().join("config.toml");
720 std::fs::write(
721 &path,
722 concat!(
723 "reasoning_effort = \"high\"\n\n",
724 "[projects.\"/live\"]\n",
725 "trust_level = \"trusted\"\n\n",
726 "[extras.extras]\n",
727 "chatgpt_access_token = \"tok\"\n",
728 "reasoning_effort = \"low\"\n\n",
729 "[extras.extras.projects.\"/old\"]\n",
730 "trust_level = \"trusted\"\n",
731 ),
732 )
733 .expect("write fixture");
734
735 super::mutate_config_document(&path, |_| anyhow::Ok(())).expect("mutate heals");
736
737 let healed: toml::Value =
738 toml::from_str(&std::fs::read_to_string(&path).expect("read")).expect("parse");
739 assert!(
740 healed.get("extras").is_none(),
741 "tower must be gone: {healed}"
742 );
743 assert_eq!(
744 healed["chatgpt_access_token"].as_str(),
745 Some("tok"),
746 "trapped scalar lifted to the root"
747 );
748 assert_eq!(
749 healed["reasoning_effort"].as_str(),
750 Some("high"),
751 "existing top-level values win over shadowed duplicates"
752 );
753 assert_eq!(
754 healed["projects"]["/live"]["trust_level"].as_str(),
755 Some("trusted"),
756 "live records untouched"
757 );
758 // The nested projects table was shadowed by the live one at the
759 // first lift; healing never merges table contents, only lifts whole
760 // missing keys, so the shadowed duplicate is dropped.
761 }
762
763 #[test]
764 fn healing_recovers_project_tables_when_no_top_level_exists() {
765 let tmp = tempfile::tempdir().expect("tempdir");
766 let path = tmp.path().join("config.toml");
767 std::fs::write(
768 &path,
769 concat!(
770 "[extras.extras.extras.projects.\"/old\"]\n",
771 "trust_level = \"trusted\"\n",
772 ),
773 )
774 .expect("write fixture");
775
776 super::mutate_config_document(&path, |_| anyhow::Ok(())).expect("mutate heals");
777
778 let healed: toml::Value =
779 toml::from_str(&std::fs::read_to_string(&path).expect("read")).expect("parse");
780 assert!(healed.get("extras").is_none(), "{healed}");
781 assert_eq!(
782 healed["projects"]["/old"]["trust_level"].as_str(),
783 Some("trusted"),
784 "trapped trust record restored: {healed}"
785 );
786 }
787
788 use std::sync::{Arc, Barrier};
789 use std::thread;
790
791 use super::*;
792
793 #[test]
794 fn malformed_config_diagnostics_never_echo_secret_contents_or_keys() {
795 let dir = tempfile::tempdir().expect("tempdir");
796 let path = dir.path().join("config.toml");
797 let secret = "sentinel";
798 fs::write(
799 &path,
800 format!("[providers.xai]\napi_key = \"{secret}\" trailing-junk\n"),
801 )
802 .expect("seed malformed config");
803
804 let error = mutate_config_document(&path, |_| Ok(())).expect_err("must reject malformed");
805 let diagnostic = format!("{error:#}");
806 assert!(!diagnostic.contains(secret), "{diagnostic}");
807 assert!(!diagnostic.contains("api_key"), "{diagnostic}");
808 assert!(
809 diagnostic.contains("file contents were omitted"),
810 "{diagnostic}"
811 );
812 }
813
814 #[cfg(windows)]
815 #[test]
816 fn windows_lock_path_comparison_rejects_unpaired_utf16() {
817 use std::ffi::OsString;
818 use std::os::windows::ffi::OsStringExt as _;
819
820 let invalid = PathBuf::from(OsString::from_wide(&[
821 b'C' as u16,
822 b':' as u16,
823 b'\\' as u16,
824 0xd800,
825 ]));
826 assert!(normalize_windows_path_for_comparison(&invalid).is_err());
827 assert_eq!(
828 normalize_windows_path_for_comparison(Path::new(r"C:\Config\A\config.toml.lock"))
829 .unwrap(),
830 normalize_windows_path_for_comparison(Path::new(r"C:\Config\a\config.toml.lock"))
831 .unwrap(),
832 "Windows lock identity must compare case-insensitively"
833 );
834 }
835
836 #[test]
837 fn targeted_mutation_preserves_unknown_provider_data_and_comments() {
838 let dir = tempfile::tempdir().expect("tempdir");
839 let path = dir.path().join("config.toml");
840 let original = "# operator\n[providers.xai]\nreasoning_stream_style = \"structured\" # keep\nmax_concurrency = 7\ncustom_future = { preserve = true }\n\n[providers.my_private]\nkind = \"openai-compatible\"\napi_key_env = \"PRIVATE_KEY\"\n";
841 fs::write(&path, original).expect("seed");
842
843 mutate_config_document(&path, |doc| {
844 set_config_document_value(
845 doc,
846 &["providers", "xai", "external_credentials", "access"],
847 "read_only",
848 )
849 })
850 .expect("mutate");
851
852 let saved = fs::read_to_string(path).expect("read");
853 for expected in [
854 "# operator",
855 "reasoning_stream_style = \"structured\" # keep",
856 "max_concurrency = 7",
857 "custom_future = { preserve = true }",
858 "[providers.my_private]",
859 "api_key_env = \"PRIVATE_KEY\"",
860 ] {
861 assert!(saved.contains(expected), "missing {expected:?}:\n{saved}");
862 }
863 }
864
865 #[test]
866 fn shared_lock_makes_revoke_win_without_losing_unrelated_update() {
867 let dir = tempfile::tempdir().expect("tempdir");
868 let path = dir.path().join("config.toml");
869 fs::write(
870 &path,
871 "[providers.xai.external_credentials]\naccess = \"read_only\"\nprovider = \"xai\"\nsource = \"grok_cli\"\npath = \"/external/auth.json\"\nconsent_version = 1\n",
872 )
873 .expect("seed");
874 let entered = Arc::new(Barrier::new(2));
875 let release = Arc::new(Barrier::new(2));
876 let revoke_path = path.clone();
877 let entered_revoke = Arc::clone(&entered);
878 let release_revoke = Arc::clone(&release);
879 let revoke = thread::spawn(move || {
880 mutate_config_document(&revoke_path, |doc| {
881 entered_revoke.wait();
882 release_revoke.wait();
883 unset_config_document_value(doc, &["providers", "xai", "external_credentials"])?;
884 Ok(())
885 })
886 });
887 entered.wait();
888 let update_path = path.clone();
889 let update = thread::spawn(move || {
890 mutate_config_document(&update_path, |doc| {
891 set_config_document_value(doc, &["tui", "low_motion"], true)
892 })
893 });
894 release.wait();
895 revoke.join().expect("revoke thread").expect("revoke");
896 update.join().expect("update thread").expect("update");
897
898 let saved = fs::read_to_string(path).expect("read");
899 assert!(!saved.contains("external_credentials"), "{saved}");
900 assert!(saved.contains("low_motion = true"), "{saved}");
901 }
902 }
903
903 lines RUST