| 1 | //! Find and scrub credentials that older builds stored in saved sessions. |
| 2 | //! |
| 3 | //! Tool output is redacted as it enters the transcript now (B1), so new |
| 4 | //! session files never hold a live token. Sessions written before that fix |
| 5 | //! can: the redaction used to run only when a request was built, while the |
| 6 | //! transcript on disk kept the raw tool output (a `cat ~/.codex/auth.json` |
| 7 | //! result, a printed bearer token). Nothing rewrites those files on its own — |
| 8 | //! `codewhale doctor` reports them and `codewhale sessions scrub-secrets` |
| 9 | //! rewrites them on request. |
| 10 | //! |
| 11 | //! Only transcript tool results, transcript tool-call arguments and Runtime |
| 12 | //! tool receipts (including event copies) are touched, including the |
| 13 | //! pre-compaction snapshots under each session's artifacts directory that the |
| 14 | //! context archive tools read back. Cleanup masks credential |
| 15 | //! shapes and currently configured secret values; bare secrets absent from |
| 16 | //! current configuration cannot be recovered. |
| 17 | //! Runtime rewrites require the exclusive process lease, and session rewrites |
| 18 | //! the session's live lease; busy stores and sessions open in an interactive |
| 19 | //! surface are reported and left untouched while the remaining files are |
| 20 | //! scrubbed. |
| 21 | |
| 22 | use std::io; |
| 23 | use std::path::{Path, PathBuf}; |
| 24 | |
| 25 | use serde_json::Value; |
| 26 | |
| 27 | /// The documented command that rewrites affected sessions. |
| 28 | pub const SCRUB_COMMAND: &str = "codewhale sessions scrub-secrets"; |
| 29 | |
| 30 | /// What a scan found (and, when applied, rewrote). |
| 31 | #[derive(Debug, Default, Clone, PartialEq, Eq)] |
| 32 | pub struct ScrubReport { |
| 33 | /// Session, checkpoint, and Runtime receipt files examined. |
| 34 | pub files_scanned: usize, |
| 35 | /// Files holding at least one unredacted credential in tool output. |
| 36 | pub flagged_files: Vec<PathBuf>, |
| 37 | /// Tool-result text fields that contained a credential. |
| 38 | pub flagged_tool_results: usize, |
| 39 | /// Files the scan could not read or parse, left untouched. |
| 40 | pub unreadable: Vec<PathBuf>, |
| 41 | /// Credential-bearing files left untouched because their Runtime store is |
| 42 | /// live or their session is open in an interactive surface. |
| 43 | pub busy: Vec<PathBuf>, |
| 44 | } |
| 45 | |
| 46 | /// Session/checkpoint JSON and Runtime items/events, newest first. Resolve the |
| 47 | /// user-selected roots (including the fixed checkpoints root), but never follow |
| 48 | /// symlink entries discovered inside those roots. Enumeration failures are partial |
| 49 | /// coverage, not a reason to discard the files that can still be scrubbed. |
| 50 | pub fn session_files( |
| 51 | sessions_dir: &Path, |
| 52 | standalone_runtime: &Path, |
| 53 | unreadable: &mut Vec<PathBuf>, |
| 54 | ) -> Vec<PathBuf> { |
| 55 | let sessions_root = canonical_store_root(sessions_dir, unreadable); |
| 56 | let mut dirs = Vec::new(); |
| 57 | let mut runtime_roots = Vec::new(); |
| 58 | if let Some(root) = canonical_store_root(standalone_runtime, unreadable) { |
| 59 | runtime_roots.push(root); |
| 60 | } |
| 61 | if let Some(root) = sessions_root { |
| 62 | if let Some(checkpoints) = canonical_store_root(&root.join("checkpoints"), unreadable) { |
| 63 | dirs.push(checkpoints); |
| 64 | } |
| 65 | // Pre-import transcript copies hold the same tool output. Session |
| 66 | // deletion does not follow a linked archive directory, so neither does |
| 67 | // the scrub: it is reported as not covered instead. |
| 68 | let archive = root.join(crate::session_manager::WORK_GRAPH_IMPORT_ARCHIVE_DIR); |
| 69 | match std::fs::symlink_metadata(&archive) { |
| 70 | Ok(metadata) if metadata.is_dir() => dirs.push(archive), |
| 71 | Err(error) if error.kind() == io::ErrorKind::NotFound => {} |
| 72 | _ => unreadable.push(archive), |
| 73 | } |
| 74 | for session in directory_entries(&root, unreadable) { |
| 75 | if !entry_has_type(&session, true, unreadable) { |
| 76 | continue; |
| 77 | } |
| 78 | for runtime in directory_entries(&session.path(), unreadable) { |
| 79 | let name = runtime.file_name(); |
| 80 | let name = name.to_string_lossy(); |
| 81 | if (name == "runtime" || name.starts_with("runtime-recovered-")) |
| 82 | && entry_has_type(&runtime, true, unreadable) |
| 83 | { |
| 84 | runtime_roots.push(runtime.path()); |
| 85 | } else if name == crate::compaction_archive::TRANSFER_DIR_NAME |
| 86 | && entry_has_type(&runtime, true, unreadable) |
| 87 | { |
| 88 | dirs.push(runtime.path()); |
| 89 | } |
| 90 | } |
| 91 | } |
| 92 | dirs.push(root); |
| 93 | } |
| 94 | for root in runtime_roots { |
| 95 | dirs.push(root.join("items")); |
| 96 | dirs.push(root.join("events")); |
| 97 | } |
| 98 | let mut files = Vec::new(); |
| 99 | for dir in dirs { |
| 100 | for entry in directory_entries(&dir, unreadable) { |
| 101 | let path = entry.path(); |
| 102 | if path |
| 103 | .parent() |
| 104 | .and_then(Path::file_name) |
| 105 | .is_some_and(|dir| dir == crate::compaction_archive::TRANSFER_DIR_NAME) |
| 106 | && !is_transfer_snapshot(&path) |
| 107 | { |
| 108 | continue; |
| 109 | } |
| 110 | if !entry_has_type(&entry, false, unreadable) |
| 111 | || !matches!( |
| 112 | path.extension().and_then(|ext| ext.to_str()), |
| 113 | Some("json" | "jsonl") |
| 114 | ) |
| 115 | { |
| 116 | continue; |
| 117 | } |
| 118 | match entry.metadata() { |
| 119 | Ok(meta) => files.push((meta.modified().unwrap_or(std::time::UNIX_EPOCH), path)), |
| 120 | Err(_) => unreadable.push(path), |
| 121 | } |
| 122 | } |
| 123 | } |
| 124 | files.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1))); |
| 125 | files.dedup_by(|a, b| a.1 == b.1); |
| 126 | unreadable.sort(); |
| 127 | unreadable.dedup(); |
| 128 | files.into_iter().map(|(_, path)| path).collect() |
| 129 | } |
| 130 | |
| 131 | fn canonical_store_root(dir: &Path, unreadable: &mut Vec<PathBuf>) -> Option<PathBuf> { |
| 132 | match std::fs::canonicalize(dir) { |
| 133 | Ok(root) => Some(root), |
| 134 | Err(error) if error.kind() == io::ErrorKind::NotFound => None, |
| 135 | Err(_) => { |
| 136 | unreadable.push(dir.to_path_buf()); |
| 137 | None |
| 138 | } |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | pub(crate) fn entry_has_type( |
| 143 | entry: &std::fs::DirEntry, |
| 144 | directory: bool, |
| 145 | unreadable: &mut Vec<PathBuf>, |
| 146 | ) -> bool { |
| 147 | match entry.file_type() { |
| 148 | Ok(kind) => { |
| 149 | if directory { |
| 150 | kind.is_dir() |
| 151 | } else { |
| 152 | kind.is_file() |
| 153 | } |
| 154 | } |
| 155 | Err(_) => { |
| 156 | unreadable.push(entry.path()); |
| 157 | false |
| 158 | } |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | pub(crate) fn directory_entries( |
| 163 | dir: &Path, |
| 164 | unreadable: &mut Vec<PathBuf>, |
| 165 | ) -> Vec<std::fs::DirEntry> { |
| 166 | let entries = match std::fs::symlink_metadata(dir) { |
| 167 | Err(error) if error.kind() == io::ErrorKind::NotFound => return Vec::new(), |
| 168 | Ok(meta) if meta.is_dir() => std::fs::read_dir(dir).ok(), |
| 169 | _ => None, |
| 170 | }; |
| 171 | let Some(entries) = entries else { |
| 172 | unreadable.push(dir.to_path_buf()); |
| 173 | return Vec::new(); |
| 174 | }; |
| 175 | entries |
| 176 | .filter_map(|entry| match entry { |
| 177 | Ok(entry) => Some(entry), |
| 178 | Err(_) => { |
| 179 | unreadable.push(dir.to_path_buf()); |
| 180 | None |
| 181 | } |
| 182 | }) |
| 183 | .collect() |
| 184 | } |
| 185 | |
| 186 | /// Reserve an independent budget for transcripts/checkpoints and Runtime receipts, |
| 187 | /// so one busy Runtime cannot evict every saved conversation from doctor's scan. |
| 188 | pub fn doctor_files(files: Vec<PathBuf>, per_category: usize) -> Vec<PathBuf> { |
| 189 | let mut counts = [0, 0]; |
| 190 | files |
| 191 | .into_iter() |
| 192 | .filter(|path| { |
| 193 | let count = &mut counts[usize::from(runtime_root(path).is_some())]; |
| 194 | *count += 1; |
| 195 | *count <= per_category |
| 196 | }) |
| 197 | .collect() |
| 198 | } |
| 199 | |
| 200 | /// Called once per command from its blocking worker. This is read-only, including |
| 201 | /// active-key resolution; the resulting values must never appear in a report. |
| 202 | pub fn configured_secrets( |
| 203 | config_path: Option<PathBuf>, |
| 204 | profile: Option<&str>, |
| 205 | ) -> anyhow::Result<Vec<String>> { |
| 206 | let config = codewhale_plugins::providers::load_config(config_path, profile)?; |
| 207 | Ok(crate::client::active_model_bound_secret_values(&config)) |
| 208 | } |
| 209 | |
| 210 | /// Whether `path` sits directly in `manager`'s pre-import archive directory |
| 211 | /// (never a linked one; see [`session_files`]). |
| 212 | fn is_import_archive(path: &Path, manager: &crate::session_manager::SessionManager) -> bool { |
| 213 | let archive = manager |
| 214 | .sessions_dir() |
| 215 | .join(crate::session_manager::WORK_GRAPH_IMPORT_ARCHIVE_DIR); |
| 216 | std::fs::symlink_metadata(&archive).is_ok_and(|metadata| metadata.is_dir()) |
| 217 | && std::fs::canonicalize(&archive) |
| 218 | .is_ok_and(|archive| path.parent() == Some(archive.as_path())) |
| 219 | } |
| 220 | |
| 221 | /// Compaction writes each pre-compaction snapshot once under a fresh name and |
| 222 | /// never rewrites it, so a scrub can replace it atomically without a session |
| 223 | /// lock; its stem is a checkpoint, not a session id. |
| 224 | fn is_transfer_snapshot(path: &Path) -> bool { |
| 225 | path.parent() |
| 226 | .and_then(Path::file_name) |
| 227 | .is_some_and(|dir| dir == crate::compaction_archive::TRANSFER_DIR_NAME) |
| 228 | && path |
| 229 | .file_name() |
| 230 | .and_then(|name| name.to_str()) |
| 231 | .is_some_and(|name| name.starts_with("context-transfer-")) |
| 232 | } |
| 233 | |
| 234 | fn runtime_root(path: &Path) -> Option<&Path> { |
| 235 | let parent = path.parent()?; |
| 236 | matches!(parent.file_name()?.to_str()?, "items" | "events") |
| 237 | .then(|| parent.parent()) |
| 238 | .flatten() |
| 239 | } |
| 240 | |
| 241 | /// Scan `files`; with `apply`, rewrite each affected file atomically with its |
| 242 | /// tool-result credentials masked. Each rewrite re-reads its file under the |
| 243 | /// same per-session lock every session save takes, so a live session saving |
| 244 | /// at the same moment is never overwritten with older content. |
| 245 | pub fn scrub_files( |
| 246 | files: &[PathBuf], |
| 247 | apply: Option<&crate::session_manager::SessionManager>, |
| 248 | secrets: &[String], |
| 249 | ) -> io::Result<ScrubReport> { |
| 250 | let mut report = ScrubReport::default(); |
| 251 | for path in files { |
| 252 | report.files_scanned += 1; |
| 253 | // The scan is read-only; its counts are what the report prints. |
| 254 | let scan = scrub_file(path, false, secrets)?; |
| 255 | let scan = match (apply, scan) { |
| 256 | (Some(_), FileScan::Dirty(_)) if runtime_root(path).is_some() => { |
| 257 | let _lease = match crate::runtime_threads::RuntimeProcessOwnerLock::acquire( |
| 258 | runtime_root(path).unwrap(), |
| 259 | ) { |
| 260 | Ok(lease) => lease, |
| 261 | Err(error) |
| 262 | if error |
| 263 | .downcast_ref::<io::Error>() |
| 264 | .is_some_and(|error| error.kind() == io::ErrorKind::WouldBlock) => |
| 265 | { |
| 266 | report.busy.push(path.clone()); |
| 267 | continue; |
| 268 | } |
| 269 | Err(error) => return Err(io::Error::other(error)), |
| 270 | }; |
| 271 | scrub_file(path, true, secrets)? |
| 272 | } |
| 273 | (Some(_), FileScan::Dirty(_)) if is_transfer_snapshot(path) => { |
| 274 | scrub_file(path, true, secrets)? |
| 275 | } |
| 276 | (Some(manager), FileScan::Dirty(redacted)) => { |
| 277 | // `<id>.json` and `checkpoints/<id>.json` share the id's lock. |
| 278 | // The rewrite re-reads the file under that lock, so it masks |
| 279 | // whatever the file holds at that moment. |
| 280 | let session_id = path.file_stem().and_then(|stem| stem.to_str()); |
| 281 | match session_id.map(|id| { |
| 282 | manager |
| 283 | .with_session_file_lock(id, || scrub_file(path, true, secrets).map(|_| ())) |
| 284 | }) { |
| 285 | Some(Ok(Some(()))) => FileScan::Dirty(redacted), |
| 286 | // A pre-import copy an earlier build left behind when it |
| 287 | // deleted the session. Finish that deletion: rewriting it |
| 288 | // would keep a deleted transcript, and could put back a |
| 289 | // copy a concurrent delete had just removed. |
| 290 | Some(Ok(None)) if is_import_archive(path, manager) => { |
| 291 | match std::fs::remove_file(path) { |
| 292 | Ok(()) => {} |
| 293 | Err(error) if error.kind() == io::ErrorKind::NotFound => {} |
| 294 | Err(error) => return Err(error), |
| 295 | } |
| 296 | FileScan::Dirty(redacted) |
| 297 | } |
| 298 | // A deleted session is not resurrected by a rewrite. |
| 299 | Some(Ok(None)) => FileScan::Clean, |
| 300 | // No lockable session id: leave the file untouched. |
| 301 | None => FileScan::Unreadable, |
| 302 | Some(Err(error)) if error.kind() == io::ErrorKind::InvalidInput => { |
| 303 | FileScan::Unreadable |
| 304 | } |
| 305 | // Open in an interactive session, whose next autosave |
| 306 | // would put the credential back: report and leave it. |
| 307 | Some(Err(error)) if error.kind() == io::ErrorKind::ResourceBusy => { |
| 308 | report.busy.push(path.clone()); |
| 309 | continue; |
| 310 | } |
| 311 | Some(Err(error)) => return Err(error), |
| 312 | } |
| 313 | } |
| 314 | (_, scan) => scan, |
| 315 | }; |
| 316 | match scan { |
| 317 | FileScan::Unreadable => report.unreadable.push(path.clone()), |
| 318 | FileScan::Clean => {} |
| 319 | FileScan::Dirty(redacted) => { |
| 320 | report.flagged_tool_results += redacted; |
| 321 | report.flagged_files.push(path.clone()); |
| 322 | } |
| 323 | } |
| 324 | } |
| 325 | Ok(report) |
| 326 | } |
| 327 | |
| 328 | enum FileScan { |
| 329 | Unreadable, |
| 330 | Clean, |
| 331 | Dirty(usize), |
| 332 | } |
| 333 | |
| 334 | fn scrub_file(path: &Path, apply: bool, secrets: &[String]) -> io::Result<FileScan> { |
| 335 | let Ok(raw) = std::fs::read(path) else { |
| 336 | return Ok(FileScan::Unreadable); |
| 337 | }; |
| 338 | let jsonl = path.extension().and_then(|ext| ext.to_str()) == Some("jsonl"); |
| 339 | let parsed = if jsonl { |
| 340 | serde_json::Deserializer::from_slice(&raw) |
| 341 | .into_iter::<Value>() |
| 342 | .collect::<Result<Vec<_>, _>>() |
| 343 | } else { |
| 344 | serde_json::from_slice::<Value>(&raw).map(|value| vec![value]) |
| 345 | }; |
| 346 | let Ok(mut values) = parsed else { |
| 347 | return Ok(FileScan::Unreadable); |
| 348 | }; |
| 349 | let redacted = values |
| 350 | .iter_mut() |
| 351 | .map(|value| scrub_value(value, secrets)) |
| 352 | .sum(); |
| 353 | if redacted == 0 { |
| 354 | return Ok(FileScan::Clean); |
| 355 | } |
| 356 | if apply { |
| 357 | let mut bytes = Vec::new(); |
| 358 | for value in values { |
| 359 | if jsonl { |
| 360 | serde_json::to_writer(&mut bytes, &value).map_err(io::Error::other)?; |
| 361 | bytes.push(b'\n'); |
| 362 | } else { |
| 363 | serde_json::to_writer_pretty(&mut bytes, &value).map_err(io::Error::other)?; |
| 364 | } |
| 365 | } |
| 366 | codewhale_config::persistence::atomic_write(path, &bytes).map_err(io::Error::other)?; |
| 367 | } |
| 368 | Ok(FileScan::Dirty(redacted)) |
| 369 | } |
| 370 | |
| 371 | /// Mask credentials in every `tool_result` and `tool_call` argument below |
| 372 | /// `value`. Returns how many fields changed. |
| 373 | fn scrub_value(value: &mut Value, secrets: &[String]) -> usize { |
| 374 | match value { |
| 375 | Value::Object(map) => { |
| 376 | let mut changed = 0; |
| 377 | // Owned, so the two `get_mut` calls below can borrow the map. |
| 378 | let block_type = map.get("type").and_then(Value::as_str).map(str::to_string); |
| 379 | if block_type.as_deref() == Some("tool_result") { |
| 380 | if let Some(Value::String(content)) = map.get_mut("content") { |
| 381 | changed += usize::from(scrub_text(content, secrets)); |
| 382 | } |
| 383 | if let Some(Value::Array(blocks)) = map.get_mut("content_blocks") { |
| 384 | for block in blocks { |
| 385 | if block.get("type").and_then(Value::as_str) == Some("text") |
| 386 | && let Some(Value::String(text)) = block.get_mut("text") |
| 387 | { |
| 388 | changed += usize::from(scrub_text(text, secrets)); |
| 389 | } |
| 390 | } |
| 391 | } |
| 392 | } |
| 393 | if matches!(block_type.as_deref(), Some("tool_use" | "server_tool_use")) |
| 394 | && let Some(input) = map.get_mut("input") |
| 395 | { |
| 396 | let redacted = crate::client::redact_json_model_bound_text(input, secrets); |
| 397 | if *input != redacted { |
| 398 | *input = redacted; |
| 399 | changed += 1; |
| 400 | } |
| 401 | } |
| 402 | if map.get("kind").and_then(Value::as_str) == Some("tool_call") { |
| 403 | for key in ["summary", "detail", "metadata"] { |
| 404 | if let Some(value) = map.get_mut(key) { |
| 405 | let redacted = crate::client::redact_json_model_bound_text(value, secrets); |
| 406 | if *value != redacted { |
| 407 | *value = redacted; |
| 408 | changed += 1; |
| 409 | } |
| 410 | } |
| 411 | } |
| 412 | } |
| 413 | // Strings below are only rewritten through a tool_result or receipt above, |
| 414 | // so walking the rest (including this object's own fields) never |
| 415 | // double-counts. |
| 416 | changed |
| 417 | + map |
| 418 | .values_mut() |
| 419 | .map(|value| scrub_value(value, secrets)) |
| 420 | .sum::<usize>() |
| 421 | } |
| 422 | Value::Array(items) => items |
| 423 | .iter_mut() |
| 424 | .map(|value| scrub_value(value, secrets)) |
| 425 | .sum(), |
| 426 | _ => 0, |
| 427 | } |
| 428 | } |
| 429 | |
| 430 | fn scrub_text(text: &mut String, secrets: &[String]) -> bool { |
| 431 | let redacted = crate::client::redact_model_bound_text(text, secrets); |
| 432 | if redacted == *text { |
| 433 | return false; |
| 434 | } |
| 435 | *text = redacted; |
| 436 | true |
| 437 | } |
| 438 | |
| 439 | #[cfg(test)] |
| 440 | mod tests { |
| 441 | use super::*; |
| 442 | use serde_json::json; |
| 443 | |
| 444 | const TOKEN: &str = "sk-ant-oat01-AbCdEfGhIjKlMnOpQrStUvWxYz0123456789abcdefghij"; |
| 445 | |
| 446 | fn session_with_tool_output(output: &str) -> Value { |
| 447 | json!({ |
| 448 | "schema_version": 1, |
| 449 | "metadata": {"id": "s1"}, |
| 450 | "messages": [ |
| 451 | {"role": "user", "content": [{"type": "text", "text": "show auth"}]}, |
| 452 | {"role": "user", "content": [{ |
| 453 | "type": "tool_result", |
| 454 | "tool_use_id": "call-1", |
| 455 | "content": output, |
| 456 | "content_blocks": [{"type": "text", "text": output}] |
| 457 | }]} |
| 458 | ], |
| 459 | "journal": {"entries": [{"message": {"role": "user", "content": [{ |
| 460 | "type": "tool_result", "tool_use_id": "call-1", "content": output |
| 461 | }]}}]} |
| 462 | }) |
| 463 | } |
| 464 | |
| 465 | #[test] |
| 466 | fn scan_reports_and_scrub_masks_stored_tool_output_tokens() { |
| 467 | let dir = tempfile::tempdir().expect("tempdir"); |
| 468 | let output = format!("{{\"access_token\": \"{TOKEN}\"}}"); |
| 469 | let dirty = dir.path().join("dirty.json"); |
| 470 | std::fs::write(&dirty, session_with_tool_output(&output).to_string()).unwrap(); |
| 471 | let clean = dir.path().join("clean.json"); |
| 472 | std::fs::write( |
| 473 | &clean, |
| 474 | session_with_tool_output("nothing secret").to_string(), |
| 475 | ) |
| 476 | .unwrap(); |
| 477 | std::fs::create_dir_all(dir.path().join("checkpoints")).unwrap(); |
| 478 | let checkpoint = dir.path().join("checkpoints").join("dirty.json"); |
| 479 | std::fs::write(&checkpoint, session_with_tool_output(&output).to_string()).unwrap(); |
| 480 | std::fs::write(dir.path().join("broken.json"), "{not json").unwrap(); |
| 481 | |
| 482 | let files = session_files(dir.path(), &dir.path().join("standalone"), &mut Vec::new()); |
| 483 | assert_eq!(files.len(), 4, "{files:?}"); |
| 484 | |
| 485 | let report = scrub_files(&files, None, &[]).expect("scan"); |
| 486 | assert_eq!(report.files_scanned, 4); |
| 487 | assert_eq!(report.flagged_files.len(), 2, "{report:?}"); |
| 488 | assert_eq!(report.flagged_tool_results, 6); |
| 489 | assert_eq!( |
| 490 | report.unreadable, |
| 491 | vec![dir.path().join("broken.json").canonicalize().unwrap()] |
| 492 | ); |
| 493 | assert!( |
| 494 | std::fs::read_to_string(&dirty).unwrap().contains(TOKEN), |
| 495 | "a scan must not rewrite anything" |
| 496 | ); |
| 497 | |
| 498 | let manager = |
| 499 | crate::session_manager::SessionManager::new(dir.path().to_path_buf()).expect("manager"); |
| 500 | let applied = scrub_files(&files, Some(&manager), &[]).expect("scrub"); |
| 501 | assert_eq!(applied.flagged_files.len(), 2); |
| 502 | assert_eq!( |
| 503 | applied.unreadable, |
| 504 | vec![dir.path().join("broken.json").canonicalize().unwrap()] |
| 505 | ); |
| 506 | for path in [&dirty, &checkpoint] { |
| 507 | let text = std::fs::read_to_string(path).unwrap(); |
| 508 | assert!(!text.contains(TOKEN), "{text}"); |
| 509 | let value: Value = serde_json::from_str(&text).expect("still valid JSON"); |
| 510 | assert_eq!(value["metadata"]["id"], "s1"); |
| 511 | assert_eq!(value["messages"][0]["content"][0]["text"], "show auth"); |
| 512 | } |
| 513 | assert_eq!( |
| 514 | scrub_files(&files, None, &[]) |
| 515 | .expect("rescan") |
| 516 | .flagged_files, |
| 517 | Vec::<PathBuf>::new(), |
| 518 | "a scrubbed store scans clean" |
| 519 | ); |
| 520 | } |
| 521 | |
| 522 | /// The pre-import copy of a transcript holds the same tool output. It is |
| 523 | /// scrubbed with the sessions. A copy an earlier build left behind for a |
| 524 | /// session it deleted is removed, finishing that deletion. |
| 525 | #[test] |
| 526 | fn work_graph_import_archive_copies_are_scrubbed() { |
| 527 | let dir = tempfile::tempdir().expect("tempdir"); |
| 528 | let output = format!("{{\"access_token\": \"{TOKEN}\"}}"); |
| 529 | let manager = |
| 530 | crate::session_manager::SessionManager::new(dir.path().to_path_buf()).expect("manager"); |
| 531 | manager |
| 532 | .save_session( |
| 533 | &crate::session_manager::create_saved_session_with_id_and_mode( |
| 534 | "gone".to_string(), |
| 535 | &[], |
| 536 | "test-model", |
| 537 | dir.path(), |
| 538 | 0, |
| 539 | None, |
| 540 | None, |
| 541 | ), |
| 542 | ) |
| 543 | .expect("save"); |
| 544 | manager.delete_session("gone").expect("delete"); |
| 545 | let archive_dir = dir |
| 546 | .path() |
| 547 | .join(crate::session_manager::WORK_GRAPH_IMPORT_ARCHIVE_DIR); |
| 548 | std::fs::create_dir_all(&archive_dir).unwrap(); |
| 549 | let kept = archive_dir.join("kept.json"); |
| 550 | let orphan = archive_dir.join("gone.json"); |
| 551 | for path in [&kept, &orphan] { |
| 552 | std::fs::write(path, session_with_tool_output(&output).to_string()).unwrap(); |
| 553 | } |
| 554 | |
| 555 | let files = session_files(dir.path(), &dir.path().join("standalone"), &mut Vec::new()); |
| 556 | let report = scrub_files(&files, Some(&manager), &[]).expect("scrub"); |
| 557 | |
| 558 | assert_eq!(report.flagged_files.len(), 2, "{report:?}"); |
| 559 | let text = std::fs::read_to_string(&kept).unwrap(); |
| 560 | assert!(!text.contains(TOKEN), "{text}"); |
| 561 | assert!(!orphan.exists(), "the deleted session's copy is removed"); |
| 562 | } |
| 563 | |
| 564 | /// A linked archive directory is not followed, matching session deletion. |
| 565 | #[cfg(unix)] |
| 566 | #[test] |
| 567 | fn a_linked_import_archive_is_reported_not_followed() { |
| 568 | let dir = tempfile::tempdir().expect("tempdir"); |
| 569 | let sessions = dir.path().join("sessions"); |
| 570 | let elsewhere = dir.path().join("elsewhere"); |
| 571 | std::fs::create_dir_all(&sessions).unwrap(); |
| 572 | std::fs::create_dir_all(&elsewhere).unwrap(); |
| 573 | let outside = elsewhere.join("gone.json"); |
| 574 | let output = format!("{{\"access_token\": \"{TOKEN}\"}}"); |
| 575 | std::fs::write(&outside, session_with_tool_output(&output).to_string()).unwrap(); |
| 576 | std::os::unix::fs::symlink( |
| 577 | &elsewhere, |
| 578 | sessions.join(crate::session_manager::WORK_GRAPH_IMPORT_ARCHIVE_DIR), |
| 579 | ) |
| 580 | .unwrap(); |
| 581 | |
| 582 | let mut unreadable = Vec::new(); |
| 583 | let files = session_files(&sessions, &dir.path().join("standalone"), &mut unreadable); |
| 584 | |
| 585 | assert!( |
| 586 | !files.iter().any(|file| file.ends_with("gone.json")), |
| 587 | "{files:?}" |
| 588 | ); |
| 589 | assert_eq!(unreadable.len(), 1, "{unreadable:?}"); |
| 590 | assert!(unreadable[0].ends_with(crate::session_manager::WORK_GRAPH_IMPORT_ARCHIVE_DIR)); |
| 591 | assert!(std::fs::read_to_string(&outside).unwrap().contains(TOKEN)); |
| 592 | } |
| 593 | |
| 594 | /// An interactive session holds the conversation in memory; its next |
| 595 | /// autosave would put a masked credential back. Such a session is |
| 596 | /// reported busy and left byte-for-byte, like a live Runtime store. |
| 597 | #[test] |
| 598 | fn a_session_open_in_an_interactive_surface_is_reported_busy() { |
| 599 | let dir = tempfile::tempdir().expect("tempdir"); |
| 600 | let output = format!("{{\"access_token\": \"{TOKEN}\"}}"); |
| 601 | let open = dir.path().join("open-elsewhere.json"); |
| 602 | std::fs::write(&open, session_with_tool_output(&output).to_string()).unwrap(); |
| 603 | let before = std::fs::read(&open).unwrap(); |
| 604 | let manager = |
| 605 | crate::session_manager::SessionManager::new(dir.path().to_path_buf()).expect("manager"); |
| 606 | let _held = manager.hold_live_lease_elsewhere("open-elsewhere"); |
| 607 | |
| 608 | let files = session_files(dir.path(), &dir.path().join("standalone"), &mut Vec::new()); |
| 609 | let report = scrub_files(&files, Some(&manager), &[]).expect("scrub"); |
| 610 | assert_eq!( |
| 611 | report.busy, |
| 612 | vec![open.canonicalize().unwrap()], |
| 613 | "{report:?}" |
| 614 | ); |
| 615 | assert!(report.flagged_files.is_empty(), "{report:?}"); |
| 616 | assert_eq!(std::fs::read(&open).unwrap(), before); |
| 617 | } |
| 618 | |
| 619 | #[test] |
| 620 | fn busy_runtime_does_not_abort_scrub() { |
| 621 | let dir = tempfile::tempdir().unwrap(); |
| 622 | let sessions = dir.path().join("sessions"); |
| 623 | let standalone = dir.path().join("standalone"); |
| 624 | let roots = [sessions.join("s1/runtime"), standalone.clone()]; |
| 625 | let item = json!({"id":"item1", "turn_id":"turn1", "kind":"tool_call", "status":"completed", "summary": TOKEN, "detail": TOKEN, "metadata":{"stdout_summary":TOKEN, "exit_code":0}}); |
| 626 | let event = json!({"seq": 7, "payload":{"item":item}}); |
| 627 | for root in &roots { |
| 628 | std::fs::create_dir_all(root.join("items")).unwrap(); |
| 629 | std::fs::create_dir_all(root.join("events")).unwrap(); |
| 630 | std::fs::write(root.join("items/item1.json"), item.to_string()).unwrap(); |
| 631 | std::fs::write(root.join("events/thread1.jsonl"), format!("{event}\n")).unwrap(); |
| 632 | } |
| 633 | let files = session_files(&sessions, &standalone, &mut Vec::new()); |
| 634 | let report = scrub_files(&files, None, &[]).unwrap(); |
| 635 | assert_eq!(report.files_scanned, 4); |
| 636 | assert_eq!(report.flagged_files.len(), 4); |
| 637 | assert_eq!(report.flagged_tool_results, 12); |
| 638 | let transcript = sessions.join("s1.json"); |
| 639 | std::fs::write(&transcript, session_with_tool_output(TOKEN).to_string()).unwrap(); |
| 640 | let manager = crate::session_manager::SessionManager::new(sessions).unwrap(); |
| 641 | let lease = crate::runtime_threads::RuntimeProcessOwnerLock::acquire(&standalone).unwrap(); |
| 642 | let standalone_file = standalone.join("items/item1.json"); |
| 643 | let report = scrub_files( |
| 644 | &[standalone_file.clone(), transcript.clone()], |
| 645 | Some(&manager), |
| 646 | &[], |
| 647 | ) |
| 648 | .unwrap(); |
| 649 | assert_eq!(report.busy, vec![standalone_file.clone()]); |
| 650 | assert_eq!(report.flagged_files, vec![transcript.clone()]); |
| 651 | assert_eq!(report.files_scanned, 2); |
| 652 | assert!( |
| 653 | !std::fs::read_to_string(&transcript) |
| 654 | .unwrap() |
| 655 | .contains(TOKEN) |
| 656 | ); |
| 657 | assert!( |
| 658 | std::fs::read_to_string(&standalone_file) |
| 659 | .unwrap() |
| 660 | .contains(TOKEN) |
| 661 | ); |
| 662 | drop(lease); |
| 663 | // Non-contention failures still propagate, rather than masquerading as busy. |
| 664 | let lock_path = standalone.join("runtime-process.owner.lock"); |
| 665 | std::fs::remove_file(&lock_path).unwrap(); |
| 666 | std::fs::create_dir(&lock_path).unwrap(); |
| 667 | assert!(scrub_files(std::slice::from_ref(&standalone_file), Some(&manager), &[]).is_err()); |
| 668 | std::fs::remove_dir(&lock_path).unwrap(); |
| 669 | scrub_files(&files, Some(&manager), &[]).unwrap(); |
| 670 | assert!( |
| 671 | scrub_files(&files, None, &[]) |
| 672 | .unwrap() |
| 673 | .flagged_files |
| 674 | .is_empty() |
| 675 | ); |
| 676 | for path in &files { |
| 677 | let raw = std::fs::read_to_string(path).unwrap(); |
| 678 | assert!(!raw.contains(TOKEN)); |
| 679 | let value: Value = serde_json::from_str(&raw).unwrap(); |
| 680 | let item = if runtime_root(path).unwrap().join("items") == path.parent().unwrap() { |
| 681 | &value |
| 682 | } else { |
| 683 | &value["payload"]["item"] |
| 684 | }; |
| 685 | assert_eq!(item["metadata"]["exit_code"], 0); |
| 686 | assert_eq!(item["turn_id"], "turn1"); |
| 687 | } |
| 688 | } |
| 689 | |
| 690 | #[cfg(unix)] |
| 691 | #[test] |
| 692 | fn symlinked_roots_scan_without_following_entries() { |
| 693 | use std::os::unix::fs::symlink; |
| 694 | let tmp = tempfile::tempdir().unwrap(); |
| 695 | let root = tmp.path().canonicalize().unwrap(); |
| 696 | let sessions = root.join("sessions-real"); |
| 697 | let checkpoints = root.join("checkpoints-real"); |
| 698 | let runtime = root.join("runtime-real"); |
| 699 | for dir in [&sessions, &checkpoints, &runtime.join("items")] { |
| 700 | std::fs::create_dir_all(dir).unwrap(); |
| 701 | } |
| 702 | let transcript = sessions.join("s1.json"); |
| 703 | let checkpoint = checkpoints.join("s1.json"); |
| 704 | let item = runtime.join("items/item.json"); |
| 705 | for path in [&transcript, &checkpoint, &item] { |
| 706 | std::fs::write(path, session_with_tool_output(TOKEN).to_string()).unwrap(); |
| 707 | } |
| 708 | symlink(&sessions, root.join("sessions")).unwrap(); |
| 709 | symlink(&checkpoints, sessions.join("checkpoints")).unwrap(); |
| 710 | symlink(&runtime, root.join("runtime")).unwrap(); |
| 711 | // Discovered file and session-directory links must not expand the scan. |
| 712 | symlink(&transcript, sessions.join("outside.json")).unwrap(); |
| 713 | symlink(&runtime, sessions.join("outside-session")).unwrap(); |
| 714 | std::fs::create_dir(sessions.join("s1")).unwrap(); |
| 715 | symlink(&runtime, sessions.join("s1/runtime")).unwrap(); |
| 716 | let mut unreadable = Vec::new(); |
| 717 | let files = session_files( |
| 718 | &root.join("sessions"), |
| 719 | &root.join("runtime"), |
| 720 | &mut unreadable, |
| 721 | ); |
| 722 | assert!(unreadable.is_empty(), "{unreadable:?}"); |
| 723 | assert_eq!(files.len(), 3); |
| 724 | for path in [&transcript, &checkpoint, &item] { |
| 725 | assert!(files.contains(path)); |
| 726 | } |
| 727 | let manager = crate::session_manager::SessionManager::new(root.join("sessions")).unwrap(); |
| 728 | assert_eq!( |
| 729 | scrub_files(&files, Some(&manager), &[]) |
| 730 | .unwrap() |
| 731 | .flagged_files |
| 732 | .len(), |
| 733 | 3 |
| 734 | ); |
| 735 | assert!( |
| 736 | scrub_files(&files, None, &[]) |
| 737 | .unwrap() |
| 738 | .flagged_files |
| 739 | .is_empty() |
| 740 | ); |
| 741 | } |
| 742 | |
| 743 | #[test] |
| 744 | fn configured_bare_secret_is_scrubbed() { |
| 745 | use crate::test_support::{EnvVarGuard, lock_test_env}; |
| 746 | let _env = lock_test_env(); |
| 747 | let tmp = tempfile::tempdir().unwrap(); |
| 748 | let _home = EnvVarGuard::set("CODEWHALE_HOME", tmp.path()); |
| 749 | let _user_home = EnvVarGuard::set("HOME", tmp.path()); |
| 750 | let _profile = EnvVarGuard::set("USERPROFILE", tmp.path()); |
| 751 | let config = tmp.path().join("config.toml"); |
| 752 | let _config = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", &config); |
| 753 | let secret = "abcdefghijklmnopqrst"; |
| 754 | std::fs::write(&config, format!("sandbox_api_key = \"{secret}\"\n")).unwrap(); |
| 755 | let secrets = configured_secrets(Some(config), None).unwrap(); |
| 756 | assert!(secrets.iter().any(|value| value == secret)); |
| 757 | let sessions = tmp.path().join("sessions"); |
| 758 | let runtime = sessions.join("s1/runtime"); |
| 759 | std::fs::create_dir_all(runtime.join("items")).unwrap(); |
| 760 | std::fs::create_dir_all(runtime.join("events")).unwrap(); |
| 761 | let transcript = sessions.join("s1.json"); |
| 762 | let item = runtime.join("items/item.json"); |
| 763 | let event = runtime.join("events/thread.jsonl"); |
| 764 | let receipt = json!({"kind":"tool_call", "summary":secret, "detail":secret, "metadata":{"stdout_summary":secret, "exit_code":0}}); |
| 765 | std::fs::write(&transcript, session_with_tool_output(secret).to_string()).unwrap(); |
| 766 | std::fs::write(&item, receipt.to_string()).unwrap(); |
| 767 | std::fs::write(&event, format!("{}\n", json!({"payload":{"item":receipt}}))).unwrap(); |
| 768 | let files = vec![transcript, item, event]; |
| 769 | assert!( |
| 770 | scrub_files(&files, None, &[]) |
| 771 | .unwrap() |
| 772 | .flagged_files |
| 773 | .is_empty() |
| 774 | ); |
| 775 | let report = scrub_files(&files, None, &secrets).unwrap(); |
| 776 | assert_eq!(report.flagged_files.len(), 3); |
| 777 | assert_eq!(report.flagged_tool_results, 9); |
| 778 | let manager = crate::session_manager::SessionManager::new(sessions).unwrap(); |
| 779 | scrub_files(&files, Some(&manager), &secrets).unwrap(); |
| 780 | for path in files { |
| 781 | let raw = std::fs::read_to_string(path).unwrap(); |
| 782 | assert!(!raw.contains(secret)); |
| 783 | assert!(raw.contains(codewhale_config::persistence::REDACTED)); |
| 784 | } |
| 785 | } |
| 786 | |
| 787 | #[test] |
| 788 | fn non_tool_result_text_is_left_alone() { |
| 789 | let mut value = json!({ |
| 790 | "messages": [{"role": "user", "content": [{"type": "text", "text": TOKEN}]}] |
| 791 | }); |
| 792 | assert_eq!(scrub_value(&mut value, &[]), 0); |
| 793 | assert_eq!(value["messages"][0]["content"][0]["text"], TOKEN); |
| 794 | } |
| 795 | } |
| 796 |