返回 CodeWhale
config_backup.rs
根目录 / crates / config / src / config_backup.rs
1 use crate::display_redaction::is_sensitive_config_key;
2 use crate::path_io::{
3 normalize_config_file_path, read_checked_config_file, read_checked_toml_file,
4 reject_path_symlink,
5 };
6 use crate::provider_toml::CONFIG_FILE_NAME;
7 use crate::{config_document, legacy_root, persistence};
8 use anyhow::Context as _;
9 use anyhow::Result;
10 use std::ffi::{OsStr, OsString};
11 use std::path::{Path, PathBuf};
12
13 pub(crate) fn config_backup_file_name(path: &Path) -> OsString {
14 let mut file_name = path
15 .file_name()
16 .map(OsString::from)
17 .unwrap_or_else(|| OsString::from(CONFIG_FILE_NAME));
18 file_name.push(".bak");
19 file_name
20 }
21
22 pub(crate) fn config_sibling_path_unchecked(config_path: &Path, file_name: &OsStr) -> PathBuf {
23 config_path
24 .parent()
25 .unwrap_or_else(|| Path::new("."))
26 .join(file_name)
27 }
28
29 pub(crate) fn checked_config_sibling_path(
30 config_path: &Path,
31 file_name: &OsStr,
32 ) -> Result<PathBuf> {
33 let config_path = normalize_config_file_path(config_path.to_path_buf())?;
34 let parent = config_path
35 .parent()
36 .context("config path must include a parent directory")?;
37 let path = parent.join(file_name);
38 reject_path_symlink(&path)?;
39 Ok(path)
40 }
41
42 #[cfg(test)]
43 pub(crate) fn config_backup_path(path: &Path) -> PathBuf {
44 config_sibling_path_unchecked(path, &config_backup_file_name(path))
45 }
46
47 pub(crate) fn checked_config_backup_path(path: &Path) -> Result<PathBuf> {
48 checked_config_sibling_path(path, &config_backup_file_name(path))
49 }
50
51 /// Remove plaintext `api_key` entries from the one-time config backup, if it
52 /// exists.
53 ///
54 /// Credential migration deliberately preserves the rest of `config.toml.bak`
55 /// while ensuring that moving a key into the durable secret store does not
56 /// leave the same credential behind in an older backup.
57 pub fn scrub_plaintext_api_keys_from_config_backup(path: &Path) -> Result<()> {
58 scrub_credentials_from_backup_file(&checked_config_backup_path(path)?)
59 }
60
61 /// Rewrite an existing backup without credential-named keys; see
62 /// [`config_toml_without_plaintext_api_keys`].
63 pub(crate) fn scrub_credentials_from_backup_file(backup: &Path) -> Result<()> {
64 if !backup.exists() {
65 return Ok(());
66 }
67
68 let raw = read_checked_toml_file(backup, "config backup")?;
69 let scrubbed = config_toml_without_plaintext_api_keys(&raw).with_context(|| {
70 format!(
71 "failed to scrub plaintext API keys from config backup {}",
72 backup.display()
73 )
74 })?;
75 if scrubbed != raw {
76 persistence::atomic_write(backup, scrubbed.as_bytes()).with_context(|| {
77 format!(
78 "failed to write credential-free config backup {}",
79 backup.display()
80 )
81 })?;
82 }
83 Ok(())
84 }
85
86 /// Remove only retired Antigravity state from Codewhale's one-time config
87 /// backup. This never resolves, reads, writes, or revokes any external Google
88 /// or Antigravity session; it edits only the checked sibling `.bak` file owned
89 /// by Codewhale.
90 pub fn scrub_legacy_antigravity_from_config_backup(path: &Path) -> Result<()> {
91 let backup = checked_config_backup_path(path)?;
92 if !backup.exists() {
93 return Ok(());
94 }
95
96 let raw = read_checked_toml_file(&backup, "config backup")?;
97 let scrubbed = config_toml_without_legacy_antigravity(&raw).with_context(|| {
98 format!(
99 "failed to clear retired provider state from config backup {}",
100 backup.display()
101 )
102 })?;
103 if scrubbed != raw {
104 persistence::atomic_write(&backup, scrubbed.as_bytes()).with_context(|| {
105 format!(
106 "failed to write retired-provider-free config backup {}",
107 backup.display()
108 )
109 })?;
110 }
111 Ok(())
112 }
113
114 pub(crate) fn config_toml_without_legacy_antigravity(raw: &str) -> Result<String> {
115 let mut document = raw.parse::<toml_edit::DocumentMut>().map_err(|_| {
116 anyhow::anyhow!(
117 "failed to parse config TOML while clearing retired provider state; file contents were omitted"
118 )
119 })?;
120 let root = document.as_table_mut();
121
122 if root
123 .get("provider")
124 .and_then(toml_edit::Item::as_str)
125 .is_some_and(is_legacy_antigravity_name)
126 {
127 root.remove("provider");
128 }
129 if let Some(fallbacks) = root
130 .get_mut("fallback_providers")
131 .and_then(toml_edit::Item::as_array_mut)
132 {
133 fallbacks.retain(|value| !value.as_str().is_some_and(is_legacy_antigravity_name));
134 if fallbacks.is_empty() {
135 root.remove("fallback_providers");
136 }
137 }
138 if let Some(providers) = root
139 .get_mut("providers")
140 .and_then(toml_edit::Item::as_table_like_mut)
141 {
142 providers.remove("antigravity");
143 providers.remove("agy");
144 }
145
146 Ok(document.to_string())
147 }
148
149 pub(crate) fn is_legacy_antigravity_name(value: &str) -> bool {
150 value.eq_ignore_ascii_case("antigravity") || value.eq_ignore_ascii_case("agy")
151 }
152
153 /// Before a write moves legacy top-level keys (#6394), keep one credential-free
154 /// copy of the file as it was, and queue a one-line notice for the caller's
155 /// status channel. Does nothing when the original has nothing to move.
156 pub(crate) fn note_legacy_root_file_migration(path: &Path, original_raw: &str) -> Result<()> {
157 let Ok(document) = original_raw.parse::<toml_edit::DocumentMut>() else {
158 return Ok(());
159 };
160 let receipt = legacy_root::preview_document(&document, None);
161 if !receipt.changes_file() {
162 return Ok(());
163 }
164 let backup = write_legacy_root_backup(path, original_raw)?;
165 legacy_root::queue_notice(&receipt, &backup);
166 Ok(())
167 }
168
169 /// Keep one credential-free copy of the file as it was before legacy
170 /// top-level keys first moved. Later migrations never overwrite it.
171 pub(crate) fn write_legacy_root_backup(path: &Path, original_raw: &str) -> Result<PathBuf> {
172 let backup = checked_config_sibling_path(path, &pre_migrate_backup_file_name(path))?;
173 if backup.exists() {
174 // Written once and kept; still repair one left by a release that
175 // scrubbed only `api_key`. Best effort: an unreadable old backup must
176 // not block the save that is moving keys now.
177 if let Err(err) = scrub_credentials_from_backup_file(&backup) {
178 tracing::warn!("{err:#}");
179 }
180 } else {
181 let scrubbed = config_toml_without_plaintext_api_keys(original_raw)?;
182 persistence::atomic_write(&backup, scrubbed.as_bytes()).with_context(|| {
183 format!(
184 "failed to create config backup {} before moving top-level keys",
185 backup.display()
186 )
187 })?;
188 }
189 Ok(backup)
190 }
191
192 pub(crate) fn pre_migrate_backup_file_name(path: &Path) -> OsString {
193 let mut file_name = path
194 .file_name()
195 .map(OsString::from)
196 .unwrap_or_else(|| OsString::from(CONFIG_FILE_NAME));
197 file_name.push(".pre-migrate.bak");
198 file_name
199 }
200
201 /// Path of the one-time backup written before legacy top-level keys moved.
202 pub fn legacy_root_backup_path(path: &Path) -> Result<PathBuf> {
203 checked_config_sibling_path(path, &pre_migrate_backup_file_name(path))
204 }
205
206 pub(crate) fn write_one_time_config_backup(path: &Path) -> Result<()> {
207 let backup = checked_config_backup_path(path)?;
208 if backup.exists() {
209 return scrub_plaintext_api_keys_from_config_backup(path);
210 }
211
212 let raw = read_checked_config_file(path)?;
213 let scrubbed = config_toml_without_plaintext_api_keys(&raw).with_context(|| {
214 format!(
215 "failed to scrub plaintext API keys while creating config backup {}",
216 backup.display()
217 )
218 })?;
219 persistence::atomic_write(&backup, scrubbed.as_bytes()).with_context(|| {
220 format!(
221 "failed to create credential-free config backup {} from {}",
222 backup.display(),
223 path.display()
224 )
225 })?;
226 Ok(())
227 }
228
229 pub(crate) fn config_toml_without_plaintext_api_keys(raw: &str) -> Result<String> {
230 let mut document = raw
231 .parse::<toml_edit::DocumentMut>()
232 .map_err(|_| {
233 anyhow::anyhow!(
234 "failed to parse config TOML while removing plaintext API keys; file contents were omitted"
235 )
236 })?;
237 remove_plaintext_api_keys_recursive(document.as_table_mut());
238 scrub_backup_decor(document.as_table_mut().decor_mut());
239 if let Some(trailing) = document.trailing().as_str().map(scrub_backup_comments) {
240 document.set_trailing(trailing);
241 }
242 Ok(document.to_string())
243 }
244
245 /// Drop every credential-named key ([`is_sensitive_config_key`]: `api_key`,
246 /// `webhook_token`, `Authorization` under `http_headers`, ...) at any depth,
247 /// including tables inside arrays. The backups are kept indefinitely and are
248 /// described as credential-free, so a rotated secret must not live on there.
249 pub(crate) fn remove_plaintext_api_keys_recursive(table: &mut dyn toml_edit::TableLike) {
250 let sensitive: Vec<String> = table
251 .iter()
252 .filter(|(key, item)| {
253 is_sensitive_config_key(key) || item.as_value().is_some_and(backup_value_carries_secret)
254 })
255 .map(|(key, _)| key.to_owned())
256 .collect();
257 for key in sensitive {
258 // Keep a comment written above the key (often the file header).
259 config_document::remove_key_preserving_leading_decor(table, &key);
260 }
261 for (mut key, item) in table.iter_mut() {
262 scrub_backup_decor(key.leaf_decor_mut());
263 if let toml_edit::Item::Table(nested) = item {
264 scrub_backup_decor(nested.decor_mut());
265 }
266 if let toml_edit::Item::Value(value) = item {
267 scrub_backup_decor(value.decor_mut());
268 }
269 match item {
270 toml_edit::Item::ArrayOfTables(tables) => {
271 for nested in tables.iter_mut() {
272 scrub_backup_decor(nested.decor_mut());
273 remove_plaintext_api_keys_recursive(nested);
274 }
275 }
276 toml_edit::Item::Value(toml_edit::Value::Array(array)) => {
277 remove_plaintext_api_keys_in_array(array);
278 }
279 _ => {
280 if let Some(nested) = item.as_table_like_mut() {
281 remove_plaintext_api_keys_recursive(nested);
282 }
283 }
284 }
285 }
286 }
287
288 pub(crate) fn remove_plaintext_api_keys_in_array(array: &mut toml_edit::Array) {
289 array.retain(|value| !backup_value_carries_secret(value));
290 for value in array.iter_mut() {
291 scrub_backup_decor(value.decor_mut());
292 match value {
293 toml_edit::Value::InlineTable(table) => remove_plaintext_api_keys_recursive(table),
294 toml_edit::Value::Array(nested) => remove_plaintext_api_keys_in_array(nested),
295 _ => {}
296 }
297 }
298 }
299
300 pub(crate) fn backup_value_carries_secret(value: &toml_edit::Value) -> bool {
301 value
302 .as_str()
303 .is_some_and(codewhale_sanitize::sanitize::contains_secret)
304 }
305
306 pub(crate) fn scrub_backup_decor(decor: &mut toml_edit::Decor) {
307 let prefix = decor
308 .prefix()
309 .and_then(|text| text.as_str())
310 .map(scrub_backup_comments);
311 let suffix = decor
312 .suffix()
313 .and_then(|text| text.as_str())
314 .map(scrub_backup_comments);
315 if let Some(prefix) = prefix {
316 decor.set_prefix(prefix);
317 }
318 if let Some(suffix) = suffix {
319 decor.set_suffix(suffix);
320 }
321 }
322
323 pub(crate) fn scrub_backup_comments(text: &str) -> String {
324 text.split_inclusive('\n')
325 .filter(|line| {
326 !line
327 .trim_start()
328 .strip_prefix('#')
329 .map(str::trim)
330 .is_some_and(|comment| {
331 comment
332 .split_once('=')
333 .is_some_and(|(key, _)| is_sensitive_config_key(key))
334 || codewhale_sanitize::sanitize::contains_secret(comment)
335 })
336 })
337 .collect()
338 }
339
340 /// Merge comments and formatting from an original TOML file into a
341 /// freshly serialized document so user annotations (comments, whitespace,
342 /// disabled keys) survive config rewrites.
343 ///
344 /// `original_raw` is the raw text of the file before the change; the
345 /// function parses it internally with [`toml_edit`] so callers stay free
346 /// of that dependency.
347 pub fn merge_and_preserve_comments(serialized: &str, original_raw: &str) -> Result<String> {
348 let original = original_raw
349 .parse::<toml_edit::DocumentMut>()
350 .map_err(|_| {
351 anyhow::anyhow!(
352 "failed to parse original config for comment merge; file contents were omitted"
353 )
354 })?;
355
356 let mut new_doc = serialized.parse::<toml_edit::DocumentMut>().map_err(|_| {
357 anyhow::anyhow!(
358 "failed to parse serialized config for comment merge; file contents were omitted"
359 )
360 })?;
361
362 // Reuse the original document’s trailing text (file-footer comments /
363 // disabled keys) so they survive the rewrite.
364 new_doc.set_trailing(original.trailing().clone());
365
366 // Copy the top-level table's decor (document-header comments, whitespace
367 // before the first key) which `toml_edit` stores on the root `Table` itself.
368 *new_doc.as_table_mut().decor_mut() = original.as_table().decor().clone();
369
370 merge_decor_table(new_doc.as_table_mut(), original.as_table());
371
372 Ok(new_doc.to_string())
373 }
374
375 /// Recursively copy `decor` (prefix/suffix comments and whitespace) from
376 /// every key in `source` that also exists in `target`.
377 pub(crate) fn merge_decor_table(target: &mut toml_edit::Table, source: &toml_edit::Table) {
378 // Collect keys first — the borrow checker won't let us hold
379 // `get_key_value_mut` while iterating.
380 let keys: Vec<String> = source.iter().map(|(k, _)| k.to_owned()).collect();
381 for key in &keys {
382 let Some((source_key, source_item)) = source.get_key_value(key) else {
383 continue;
384 };
385 let Some((mut target_key_mut, target_item)) = target.get_key_value_mut(key) else {
386 continue;
387 };
388
389 // Copy the key-level decor (comments before the key itself)
390 *target_key_mut.leaf_decor_mut() = source_key.leaf_decor().clone();
391
392 copy_item_decor(target_item, source_item);
393
394 if let (Some(tt), Some(st)) = (target_item.as_table_mut(), source_item.as_table()) {
395 merge_decor_table(tt, st);
396 }
397
398 if let (Some(ta), Some(sa)) = (
399 target_item.as_array_of_tables_mut(),
400 source_item.as_array_of_tables(),
401 ) {
402 for (i, source_table) in sa.iter().enumerate() {
403 if let Some(target_table) = ta.get_mut(i) {
404 copy_item_decor_table(target_table, source_table);
405 merge_decor_table(target_table, source_table);
406 }
407 }
408 }
409 }
410 }
411
412 /// Copy the decor (comments and surrounding whitespace) from `source` to `target`,
413 /// respecting the concrete item type since [`toml_edit::Item`] has no uniform
414 /// `decor` accessor.
415 pub(crate) fn copy_item_decor(target: &mut toml_edit::Item, source: &toml_edit::Item) {
416 match (target, source) {
417 (toml_edit::Item::Table(tt), toml_edit::Item::Table(st)) => {
418 *tt.decor_mut() = st.decor().clone();
419 }
420 (toml_edit::Item::Value(tv), toml_edit::Item::Value(sv)) => {
421 *tv.decor_mut() = sv.decor().clone();
422 }
423 _ => {}
424 }
425 }
426
427 pub(crate) fn copy_item_decor_table(target: &mut toml_edit::Table, source: &toml_edit::Table) {
428 *target.decor_mut() = source.decor().clone();
429 }
430
430 lines RUST