| 1 | use std::collections::{BTreeMap, BTreeSet}; |
| 2 | use std::fs::{self, File, OpenOptions}; |
| 3 | use std::io::{self, BufRead, BufReader, Write}; |
| 4 | use std::path::{Path, PathBuf}; |
| 5 | |
| 6 | use chrono::{DateTime, Utc}; |
| 7 | use serde::{Deserialize, Serialize}; |
| 8 | |
| 9 | use crate::sandbox::SandboxPolicy; |
| 10 | |
| 11 | const APPROVAL_LOG_FILE: &str = "approval_receipts.jsonl"; |
| 12 | const APPROVAL_LOCK_FILE: &str = "approval_receipts.lock"; |
| 13 | |
| 14 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 15 | #[serde(tag = "outcome", rename_all = "snake_case")] |
| 16 | pub(crate) enum ApprovalOutcome { |
| 17 | ApprovedOnce, |
| 18 | Denied, |
| 19 | /// The interactive approval card expired unanswered (#6101): the |
| 20 | /// configured bound denied the call, not the operator. |
| 21 | Timeout, |
| 22 | Cancelled, |
| 23 | Unavailable, |
| 24 | RetryWithPolicy { |
| 25 | policy: SandboxPolicy, |
| 26 | }, |
| 27 | } |
| 28 | |
| 29 | // Shared data ownership; persisted approval serialization remains unchanged. |
| 30 | pub(crate) use codewhale_command_contract::facets::ApprovalDecider; |
| 31 | |
| 32 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 33 | #[serde(tag = "phase", rename_all = "snake_case")] |
| 34 | pub(crate) enum ApprovalReceipt { |
| 35 | Asked { |
| 36 | approval_id: String, |
| 37 | tool_call_id: String, |
| 38 | tool_name: String, |
| 39 | created_at: DateTime<Utc>, |
| 40 | }, |
| 41 | Decided { |
| 42 | approval_id: String, |
| 43 | tool_call_id: String, |
| 44 | outcome: ApprovalOutcome, |
| 45 | created_at: DateTime<Utc>, |
| 46 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 47 | decided_by: Option<ApprovalDecider>, |
| 48 | }, |
| 49 | } |
| 50 | |
| 51 | impl ApprovalReceipt { |
| 52 | pub(crate) fn asked(tool_call_id: impl Into<String>, tool_name: impl Into<String>) -> Self { |
| 53 | let tool_call_id = tool_call_id.into(); |
| 54 | Self::Asked { |
| 55 | approval_id: tool_call_id.clone(), |
| 56 | tool_call_id, |
| 57 | tool_name: tool_name.into(), |
| 58 | created_at: Utc::now(), |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | /// A decision whose decider this call site does not know. |
| 63 | #[cfg(test)] |
| 64 | pub(crate) fn decided(tool_call_id: impl Into<String>, outcome: ApprovalOutcome) -> Self { |
| 65 | Self::decided_with(tool_call_id, outcome, None) |
| 66 | } |
| 67 | |
| 68 | pub(crate) fn decided_with( |
| 69 | tool_call_id: impl Into<String>, |
| 70 | outcome: ApprovalOutcome, |
| 71 | decided_by: Option<ApprovalDecider>, |
| 72 | ) -> Self { |
| 73 | let tool_call_id = tool_call_id.into(); |
| 74 | Self::Decided { |
| 75 | approval_id: tool_call_id.clone(), |
| 76 | tool_call_id, |
| 77 | outcome, |
| 78 | created_at: Utc::now(), |
| 79 | decided_by, |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | pub(crate) fn approval_id(&self) -> &str { |
| 84 | match self { |
| 85 | Self::Asked { approval_id, .. } | Self::Decided { approval_id, .. } => approval_id, |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | fn tool_call_id(&self) -> &str { |
| 90 | match self { |
| 91 | Self::Asked { tool_call_id, .. } | Self::Decided { tool_call_id, .. } => tool_call_id, |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | /// The tool the agent wanted to run — present on the ask half only. |
| 96 | pub(crate) fn tool_name(&self) -> Option<&str> { |
| 97 | match self { |
| 98 | Self::Asked { tool_name, .. } => Some(tool_name), |
| 99 | Self::Decided { .. } => None, |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | pub(crate) fn created_at(&self) -> DateTime<Utc> { |
| 104 | match self { |
| 105 | Self::Asked { created_at, .. } | Self::Decided { created_at, .. } => *created_at, |
| 106 | } |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 111 | pub(crate) struct CompletedApproval { |
| 112 | pub(crate) ask: ApprovalReceipt, |
| 113 | pub(crate) outcome: ApprovalOutcome, |
| 114 | pub(crate) decided_at: DateTime<Utc>, |
| 115 | pub(crate) decided_by: Option<ApprovalDecider>, |
| 116 | } |
| 117 | |
| 118 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 119 | pub(crate) struct ApprovalReplay { |
| 120 | pub(crate) completed: Vec<CompletedApproval>, |
| 121 | pub(crate) unmatched_asks: Vec<ApprovalReceipt>, |
| 122 | } |
| 123 | |
| 124 | impl ApprovalReplay { |
| 125 | pub(crate) fn from_receipts(receipts: &[ApprovalReceipt]) -> Result<Self, String> { |
| 126 | let mut open = BTreeMap::<String, ApprovalReceipt>::new(); |
| 127 | let mut closed = BTreeSet::<String>::new(); |
| 128 | let mut completed = Vec::new(); |
| 129 | |
| 130 | for receipt in receipts { |
| 131 | let approval_id = receipt.approval_id(); |
| 132 | if approval_id.trim().is_empty() || receipt.tool_call_id().trim().is_empty() { |
| 133 | return Err("approval receipt has an empty correlation id".to_string()); |
| 134 | } |
| 135 | match receipt { |
| 136 | ApprovalReceipt::Asked { |
| 137 | approval_id, |
| 138 | tool_call_id, |
| 139 | tool_name, |
| 140 | .. |
| 141 | } => { |
| 142 | if tool_name.trim().is_empty() { |
| 143 | return Err(format!( |
| 144 | "approval ask '{approval_id}' has an empty tool name" |
| 145 | )); |
| 146 | } |
| 147 | if approval_id != tool_call_id { |
| 148 | return Err(format!( |
| 149 | "approval ask '{approval_id}' does not match tool call '{tool_call_id}'" |
| 150 | )); |
| 151 | } |
| 152 | if closed.contains(approval_id) || open.contains_key(approval_id) { |
| 153 | return Err(format!("approval '{approval_id}' was asked more than once")); |
| 154 | } |
| 155 | open.insert(approval_id.clone(), receipt.clone()); |
| 156 | } |
| 157 | ApprovalReceipt::Decided { |
| 158 | approval_id, |
| 159 | tool_call_id, |
| 160 | outcome, |
| 161 | created_at, |
| 162 | decided_by, |
| 163 | } => { |
| 164 | if approval_id != tool_call_id { |
| 165 | return Err(format!( |
| 166 | "approval decision '{approval_id}' does not match tool call '{tool_call_id}'" |
| 167 | )); |
| 168 | } |
| 169 | let Some(ask) = open.remove(approval_id) else { |
| 170 | return Err(format!( |
| 171 | "approval decision '{approval_id}' has no unmatched ask" |
| 172 | )); |
| 173 | }; |
| 174 | closed.insert(approval_id.clone()); |
| 175 | completed.push(CompletedApproval { |
| 176 | ask, |
| 177 | outcome: outcome.clone(), |
| 178 | decided_at: *created_at, |
| 179 | decided_by: *decided_by, |
| 180 | }); |
| 181 | } |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | Ok(Self { |
| 186 | completed, |
| 187 | unmatched_asks: open.into_values().collect(), |
| 188 | }) |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | #[derive(Debug, Clone)] |
| 193 | pub(crate) struct ApprovalReceiptStore { |
| 194 | sessions_dir: PathBuf, |
| 195 | } |
| 196 | |
| 197 | #[derive(Default)] |
| 198 | struct ApprovalLogRead { |
| 199 | receipts: Vec<ApprovalReceipt>, |
| 200 | valid_bytes: u64, |
| 201 | torn_tail: Option<Vec<u8>>, |
| 202 | needs_newline: bool, |
| 203 | } |
| 204 | |
| 205 | fn preserve_torn_tail(parent: &Path, bytes: &[u8]) -> io::Result<()> { |
| 206 | // A unique sibling retains the original bytes without replacing earlier |
| 207 | // recovery evidence. Tempfiles are owner-only on Unix; elsewhere they |
| 208 | // inherit the session directory's access controls. Never log the payload. |
| 209 | let mut recovery = tempfile::Builder::new() |
| 210 | .prefix("approval_receipts-torn-") |
| 211 | .suffix(".recovery") |
| 212 | .tempfile_in(parent)?; |
| 213 | recovery.write_all(bytes)?; |
| 214 | recovery.as_file().sync_all()?; |
| 215 | let (_file, _path) = recovery.keep().map_err(|error| error.error)?; |
| 216 | // Unlike ordinary append's best-effort directory sync, losing this name |
| 217 | // after truncation would lose the only copy of the damaged bytes. |
| 218 | #[cfg(unix)] |
| 219 | File::open(parent)?.sync_all()?; |
| 220 | Ok(()) |
| 221 | } |
| 222 | |
| 223 | impl ApprovalReceiptStore { |
| 224 | pub(crate) fn new(sessions_dir: PathBuf) -> Self { |
| 225 | Self { sessions_dir } |
| 226 | } |
| 227 | |
| 228 | #[cfg_attr(test, allow(dead_code))] |
| 229 | pub(crate) fn default_location() -> io::Result<Self> { |
| 230 | crate::session_manager::default_sessions_dir().map(Self::new) |
| 231 | } |
| 232 | |
| 233 | fn validated_session_id(session_id: &str) -> io::Result<&str> { |
| 234 | let trimmed = session_id.trim(); |
| 235 | if trimmed.is_empty() |
| 236 | || !trimmed |
| 237 | .chars() |
| 238 | .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') |
| 239 | { |
| 240 | return Err(io::Error::new( |
| 241 | io::ErrorKind::InvalidInput, |
| 242 | format!("Invalid session id '{session_id}'"), |
| 243 | )); |
| 244 | } |
| 245 | Ok(trimmed) |
| 246 | } |
| 247 | |
| 248 | pub(crate) fn log_path(&self, session_id: &str) -> io::Result<PathBuf> { |
| 249 | let session_id = Self::validated_session_id(session_id)?; |
| 250 | Ok(self.sessions_dir.join(session_id).join(APPROVAL_LOG_FILE)) |
| 251 | } |
| 252 | |
| 253 | fn lock_path(&self, session_id: &str) -> io::Result<PathBuf> { |
| 254 | let session_id = Self::validated_session_id(session_id)?; |
| 255 | Ok(self.sessions_dir.join(session_id).join(APPROVAL_LOCK_FILE)) |
| 256 | } |
| 257 | |
| 258 | fn open_lock_file(&self, session_id: &str) -> io::Result<File> { |
| 259 | let path = self.lock_path(session_id)?; |
| 260 | let parent = path.parent().ok_or_else(|| { |
| 261 | io::Error::new(io::ErrorKind::InvalidInput, "approval lock has no parent") |
| 262 | })?; |
| 263 | fs::create_dir_all(parent)?; |
| 264 | let file = crate::utils::private_log_options() |
| 265 | .truncate(false) |
| 266 | .read(true) |
| 267 | .write(true) |
| 268 | .open(path)?; |
| 269 | crate::utils::restrict_to_owner(&file)?; |
| 270 | Ok(file) |
| 271 | } |
| 272 | |
| 273 | fn open_existing_lock_file(&self, session_id: &str) -> io::Result<Option<File>> { |
| 274 | let path = self.lock_path(session_id)?; |
| 275 | match OpenOptions::new().read(true).open(path) { |
| 276 | Ok(file) => Ok(Some(file)), |
| 277 | Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None), |
| 278 | Err(err) => Err(err), |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | fn load_unlocked(&self, session_id: &str) -> io::Result<Option<ApprovalLogRead>> { |
| 283 | let path = self.log_path(session_id)?; |
| 284 | let file = match File::open(path) { |
| 285 | Ok(file) => file, |
| 286 | Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(None), |
| 287 | Err(err) => return Err(err), |
| 288 | }; |
| 289 | let mut reader = BufReader::new(file); |
| 290 | let mut loaded = ApprovalLogRead::default(); |
| 291 | let mut line = Vec::new(); |
| 292 | let mut index = 0; |
| 293 | loop { |
| 294 | line.clear(); |
| 295 | if reader.read_until(b'\n', &mut line)? == 0 { |
| 296 | break; |
| 297 | } |
| 298 | index += 1; |
| 299 | let terminated = line.last() == Some(&b'\n'); |
| 300 | match serde_json::from_slice(&line) { |
| 301 | Ok(receipt) => { |
| 302 | loaded.receipts.push(receipt); |
| 303 | loaded.valid_bytes += line.len() as u64; |
| 304 | loaded.needs_newline = !terminated; |
| 305 | } |
| 306 | Err(error) if !terminated && (error.is_eof() || error.is_syntax()) => { |
| 307 | // Only malformed, unterminated EOF bytes can be a torn |
| 308 | // write. Complete lines and valid JSON with an invalid |
| 309 | // receipt schema remain fatal, as do replay violations. |
| 310 | loaded.torn_tail = Some(line); |
| 311 | break; |
| 312 | } |
| 313 | Err(_) => { |
| 314 | return Err(io::Error::new( |
| 315 | io::ErrorKind::InvalidData, |
| 316 | format!("invalid approval receipt at line {index}"), |
| 317 | )); |
| 318 | } |
| 319 | } |
| 320 | } |
| 321 | ApprovalReplay::from_receipts(&loaded.receipts) |
| 322 | .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?; |
| 323 | Ok(Some(loaded)) |
| 324 | } |
| 325 | |
| 326 | pub(crate) fn load(&self, session_id: &str) -> io::Result<Vec<ApprovalReceipt>> { |
| 327 | Ok(self.load_if_present(session_id)?.unwrap_or_default()) |
| 328 | } |
| 329 | |
| 330 | /// Preserve the distinction between a missing legacy log and an existing |
| 331 | /// authoritative log with no complete receipts, including a torn first write. |
| 332 | pub(crate) fn load_if_present( |
| 333 | &self, |
| 334 | session_id: &str, |
| 335 | ) -> io::Result<Option<Vec<ApprovalReceipt>>> { |
| 336 | let Some(lock_file) = self.open_existing_lock_file(session_id)? else { |
| 337 | // Imported or legacy snapshots can contain a receipt log without |
| 338 | // its ephemeral lock file. Preserve read-only session loading; |
| 339 | // live writers always publish the lock before creating the log. |
| 340 | return Ok(self |
| 341 | .load_unlocked(session_id)? |
| 342 | .map(|loaded| loaded.receipts)); |
| 343 | }; |
| 344 | let lock = fd_lock::RwLock::new(lock_file); |
| 345 | let _guard = lock.read()?; |
| 346 | Ok(self |
| 347 | .load_unlocked(session_id)? |
| 348 | .map(|loaded| loaded.receipts)) |
| 349 | } |
| 350 | |
| 351 | pub(crate) fn replay(&self, session_id: &str) -> io::Result<ApprovalReplay> { |
| 352 | let receipts = self.load(session_id)?; |
| 353 | ApprovalReplay::from_receipts(&receipts) |
| 354 | .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err)) |
| 355 | } |
| 356 | |
| 357 | /// Session ids that have an approval log. Only entries whose name is a |
| 358 | /// valid session id are considered, so a stray file in the sessions dir |
| 359 | /// can never become a path traversal. A missing or unreadable sessions |
| 360 | /// dir is an empty history, not an error. |
| 361 | pub(crate) fn sessions_with_logs(&self) -> Vec<String> { |
| 362 | let entries = match fs::read_dir(&self.sessions_dir) { |
| 363 | Ok(entries) => entries, |
| 364 | Err(_) => return Vec::new(), |
| 365 | }; |
| 366 | let mut ids = Vec::new(); |
| 367 | for entry in entries.flatten() { |
| 368 | let name = entry.file_name().to_string_lossy().into_owned(); |
| 369 | if Self::validated_session_id(&name).is_ok() |
| 370 | && entry.path().join(APPROVAL_LOG_FILE).exists() |
| 371 | { |
| 372 | ids.push(name); |
| 373 | } |
| 374 | } |
| 375 | ids |
| 376 | } |
| 377 | |
| 378 | pub(crate) fn append(&self, session_id: &str, receipt: &ApprovalReceipt) -> io::Result<()> { |
| 379 | self.append_with_preservation(session_id, receipt, preserve_torn_tail) |
| 380 | } |
| 381 | |
| 382 | fn append_with_preservation( |
| 383 | &self, |
| 384 | session_id: &str, |
| 385 | receipt: &ApprovalReceipt, |
| 386 | preserve: impl FnOnce(&Path, &[u8]) -> io::Result<()>, |
| 387 | ) -> io::Result<()> { |
| 388 | let lock_file = self.open_lock_file(session_id)?; |
| 389 | let mut lock = fd_lock::RwLock::new(lock_file); |
| 390 | let _guard = lock.write()?; |
| 391 | let path = self.log_path(session_id)?; |
| 392 | let mut loaded = self.load_unlocked(session_id)?.unwrap_or_default(); |
| 393 | loaded.receipts.push(receipt.clone()); |
| 394 | ApprovalReplay::from_receipts(&loaded.receipts) |
| 395 | .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?; |
| 396 | |
| 397 | let parent = path.parent().ok_or_else(|| { |
| 398 | io::Error::new(io::ErrorKind::InvalidInput, "approval log has no parent") |
| 399 | })?; |
| 400 | fs::create_dir_all(parent)?; |
| 401 | let mut line = serde_json::to_vec(receipt) |
| 402 | .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?; |
| 403 | if loaded.needs_newline { |
| 404 | // A complete final JSON receipt is authoritative even without LF. |
| 405 | line.insert(0, b'\n'); |
| 406 | } |
| 407 | line.push(b'\n'); |
| 408 | // Approval receipts are owner-only and never written through a link. |
| 409 | let mut file = crate::utils::private_log_options() |
| 410 | .append(true) |
| 411 | .open(&path)?; |
| 412 | crate::utils::restrict_to_owner(&file)?; |
| 413 | if let Some(tail) = &loaded.torn_tail { |
| 414 | // Validate the candidate and preserve evidence before touching the |
| 415 | // live log. Any preservation error leaves the original intact. |
| 416 | // Windows append handles lack the write access set_len requires. |
| 417 | let repair = OpenOptions::new().write(true).open(&path)?; |
| 418 | preserve(parent, tail)?; |
| 419 | repair.set_len(loaded.valid_bytes)?; |
| 420 | repair.sync_all()?; |
| 421 | } |
| 422 | file.write_all(&line)?; |
| 423 | file.sync_all()?; |
| 424 | if let Ok(dir) = File::open(parent) { |
| 425 | let _ = dir.sync_all(); |
| 426 | } |
| 427 | Ok(()) |
| 428 | } |
| 429 | |
| 430 | #[cfg(test)] |
| 431 | pub(crate) fn sessions_dir(&self) -> &std::path::Path { |
| 432 | &self.sessions_dir |
| 433 | } |
| 434 | } |
| 435 | |
| 436 | #[cfg(test)] |
| 437 | mod tests { |
| 438 | use super::*; |
| 439 | |
| 440 | fn completed_receipts(outcome: ApprovalOutcome) -> Vec<ApprovalReceipt> { |
| 441 | vec![ |
| 442 | ApprovalReceipt::asked("tool-1", "exec_shell"), |
| 443 | ApprovalReceipt::decided("tool-1", outcome), |
| 444 | ] |
| 445 | } |
| 446 | |
| 447 | #[test] |
| 448 | fn replay_reconstructs_every_closed_outcome() { |
| 449 | let outcomes = [ |
| 450 | ApprovalOutcome::ApprovedOnce, |
| 451 | ApprovalOutcome::Denied, |
| 452 | ApprovalOutcome::Cancelled, |
| 453 | ApprovalOutcome::Unavailable, |
| 454 | ApprovalOutcome::RetryWithPolicy { |
| 455 | policy: crate::sandbox::SandboxPolicy::DangerFullAccess, |
| 456 | }, |
| 457 | ]; |
| 458 | |
| 459 | for outcome in outcomes { |
| 460 | let replay = ApprovalReplay::from_receipts(&completed_receipts(outcome.clone())) |
| 461 | .expect("closed approval log replays"); |
| 462 | assert_eq!(replay.completed.len(), 1); |
| 463 | assert_eq!(replay.completed[0].outcome, outcome); |
| 464 | assert!(replay.unmatched_asks.is_empty()); |
| 465 | } |
| 466 | } |
| 467 | |
| 468 | #[test] |
| 469 | fn replay_detects_an_unmatched_ask_after_interruption() { |
| 470 | let ask = ApprovalReceipt::asked("tool-interrupted", "write_file"); |
| 471 | let replay = ApprovalReplay::from_receipts(std::slice::from_ref(&ask)) |
| 472 | .expect("an unmatched ask is valid crash evidence"); |
| 473 | |
| 474 | assert!(replay.completed.is_empty()); |
| 475 | assert_eq!(replay.unmatched_asks, vec![ask]); |
| 476 | } |
| 477 | |
| 478 | #[test] |
| 479 | fn replay_rejects_decisions_without_one_open_ask() { |
| 480 | let orphan = ApprovalReceipt::decided("tool-orphan", ApprovalOutcome::ApprovedOnce); |
| 481 | assert!(ApprovalReplay::from_receipts(&[orphan]).is_err()); |
| 482 | |
| 483 | let duplicate = vec![ |
| 484 | ApprovalReceipt::asked("tool-duplicate", "exec_shell"), |
| 485 | ApprovalReceipt::decided("tool-duplicate", ApprovalOutcome::Denied), |
| 486 | ApprovalReceipt::decided("tool-duplicate", ApprovalOutcome::ApprovedOnce), |
| 487 | ]; |
| 488 | assert!(ApprovalReplay::from_receipts(&duplicate).is_err()); |
| 489 | } |
| 490 | |
| 491 | #[test] |
| 492 | fn store_appends_and_replays_a_session_owned_log() { |
| 493 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 494 | let store = ApprovalReceiptStore::new(tmp.path().join("sessions")); |
| 495 | let ask = ApprovalReceipt::asked("tool-persisted", "edit_file"); |
| 496 | let decision = ApprovalReceipt::decided("tool-persisted", ApprovalOutcome::ApprovedOnce); |
| 497 | |
| 498 | store |
| 499 | .append("session-1", &ask) |
| 500 | .expect("persist approval ask"); |
| 501 | store |
| 502 | .append("session-1", &decision) |
| 503 | .expect("persist approval decision"); |
| 504 | |
| 505 | let receipts = store.load("session-1").expect("load approval log"); |
| 506 | assert_eq!(receipts, vec![ask, decision]); |
| 507 | let replay = ApprovalReplay::from_receipts(&receipts).expect("replay approval log"); |
| 508 | assert_eq!(replay.completed.len(), 1); |
| 509 | assert!(replay.unmatched_asks.is_empty()); |
| 510 | } |
| 511 | |
| 512 | #[test] |
| 513 | fn loading_missing_or_imported_logs_is_read_only() { |
| 514 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 515 | let sessions_dir = tmp.path().join("sessions"); |
| 516 | let store = ApprovalReceiptStore::new(sessions_dir.clone()); |
| 517 | |
| 518 | assert!(store.load("session-empty").expect("missing log").is_empty()); |
| 519 | assert!(!sessions_dir.join("session-empty").exists()); |
| 520 | |
| 521 | let imported_dir = sessions_dir.join("session-imported"); |
| 522 | fs::create_dir_all(&imported_dir).expect("imported session dir"); |
| 523 | let ask = ApprovalReceipt::asked("tool-imported", "exec_shell"); |
| 524 | let mut line = serde_json::to_vec(&ask).expect("serialize imported ask"); |
| 525 | line.push(b'\n'); |
| 526 | fs::write(imported_dir.join(APPROVAL_LOG_FILE), line).expect("imported log"); |
| 527 | |
| 528 | assert_eq!( |
| 529 | store.load("session-imported").expect("load imported log"), |
| 530 | vec![ask] |
| 531 | ); |
| 532 | assert!(!imported_dir.join(APPROVAL_LOCK_FILE).exists()); |
| 533 | } |
| 534 | |
| 535 | #[test] |
| 536 | fn torn_tail_loads_only_valid_prefix_without_changing_evidence() { |
| 537 | let tmp = tempfile::tempdir().unwrap(); |
| 538 | let store = ApprovalReceiptStore::new(tmp.path().join("sessions")); |
| 539 | let ask = ApprovalReceipt::asked("tool-interrupted", "write_file"); |
| 540 | let mut prefix = serde_json::to_vec(&ask).unwrap(); |
| 541 | prefix.push(b'\n'); |
| 542 | for (index, tail) in [ |
| 543 | b"{\"phase\":\"decided\",\"approval_id\":\"tool-interrupted\"".as_slice(), |
| 544 | b"{\"phase\":\"asked\",\"tool_name\":\"\xf0\x9f".as_slice(), |
| 545 | ] |
| 546 | .into_iter() |
| 547 | .enumerate() |
| 548 | { |
| 549 | let id = format!("session-torn-{index}"); |
| 550 | let path = store.log_path(&id).unwrap(); |
| 551 | fs::create_dir_all(path.parent().unwrap()).unwrap(); |
| 552 | let mut original = prefix.clone(); |
| 553 | original.extend_from_slice(tail); |
| 554 | fs::write(&path, &original).unwrap(); |
| 555 | let replay = store.replay(&id).unwrap(); |
| 556 | assert!(replay.completed.is_empty()); |
| 557 | assert_eq!(replay.unmatched_asks, vec![ask.clone()]); |
| 558 | assert_eq!(fs::read(&path).unwrap(), original); |
| 559 | assert_eq!(fs::read_dir(path.parent().unwrap()).unwrap().count(), 1); |
| 560 | } |
| 561 | } |
| 562 | |
| 563 | #[test] |
| 564 | fn reader_distinguishes_missing_empty_and_torn_first_logs() { |
| 565 | let tmp = tempfile::tempdir().unwrap(); |
| 566 | let store = ApprovalReceiptStore::new(tmp.path().join("sessions")); |
| 567 | assert!(store.load_unlocked("session-missing").unwrap().is_none()); |
| 568 | assert!(store.load_if_present("session-missing").unwrap().is_none()); |
| 569 | for (id, bytes) in [ |
| 570 | ("session-empty", b"".as_slice()), |
| 571 | ("session-torn", b"{\"phase\":\"asked\"".as_slice()), |
| 572 | ] { |
| 573 | let path = store.log_path(id).unwrap(); |
| 574 | fs::create_dir_all(path.parent().unwrap()).unwrap(); |
| 575 | fs::write(&path, bytes).unwrap(); |
| 576 | let loaded = store.load_unlocked(id).unwrap().expect("existing log"); |
| 577 | assert!(loaded.receipts.is_empty()); |
| 578 | assert_eq!(store.load_if_present(id).unwrap(), Some(Vec::new())); |
| 579 | assert_eq!(loaded.valid_bytes, 0); |
| 580 | assert_eq!(loaded.torn_tail.is_some(), !bytes.is_empty()); |
| 581 | assert_eq!(fs::read(path).unwrap(), bytes); |
| 582 | } |
| 583 | } |
| 584 | |
| 585 | #[test] |
| 586 | fn append_preserves_torn_bytes_before_repair_and_never_invents_a_decision() { |
| 587 | let tmp = tempfile::tempdir().unwrap(); |
| 588 | let store = ApprovalReceiptStore::new(tmp.path().join("sessions")); |
| 589 | let ask = ApprovalReceipt::asked("tool-interrupted", "write_file"); |
| 590 | store.append("session-repair", &ask).unwrap(); |
| 591 | let path = store.log_path("session-repair").unwrap(); |
| 592 | let prefix = fs::read(&path).unwrap(); |
| 593 | let tail = b"{\"phase\":\"decided\",\"outcome\":\"approved_once\",\"note\":\"\xf0\x9f"; |
| 594 | OpenOptions::new() |
| 595 | .append(true) |
| 596 | .open(&path) |
| 597 | .unwrap() |
| 598 | .write_all(tail) |
| 599 | .unwrap(); |
| 600 | |
| 601 | let new_ask = ApprovalReceipt::asked("tool-next", "read_file"); |
| 602 | store.append("session-repair", &new_ask).unwrap(); |
| 603 | let replay = store.replay("session-repair").unwrap(); |
| 604 | assert!(replay.completed.is_empty()); |
| 605 | assert_eq!(replay.unmatched_asks, vec![ask, new_ask]); |
| 606 | assert!(fs::read(&path).unwrap().starts_with(&prefix)); |
| 607 | let recovery = fs::read_dir(path.parent().unwrap()) |
| 608 | .unwrap() |
| 609 | .map(|entry| entry.unwrap().path()) |
| 610 | .filter(|path| path.extension().is_some_and(|ext| ext == "recovery")) |
| 611 | .collect::<Vec<_>>(); |
| 612 | assert_eq!(recovery.len(), 1); |
| 613 | assert_eq!(fs::read(&recovery[0]).unwrap(), tail); |
| 614 | #[cfg(unix)] |
| 615 | { |
| 616 | use std::os::unix::fs::PermissionsExt as _; |
| 617 | assert_eq!( |
| 618 | fs::metadata(&recovery[0]).unwrap().permissions().mode() & 0o777, |
| 619 | 0o600 |
| 620 | ); |
| 621 | } |
| 622 | } |
| 623 | |
| 624 | #[test] |
| 625 | fn failed_tail_preservation_keeps_original_log_and_grants_nothing() { |
| 626 | let tmp = tempfile::tempdir().unwrap(); |
| 627 | let store = ApprovalReceiptStore::new(tmp.path().join("sessions")); |
| 628 | let ask = ApprovalReceipt::asked("tool-pending", "exec_shell"); |
| 629 | store.append("session-preserve-error", &ask).unwrap(); |
| 630 | let path = store.log_path("session-preserve-error").unwrap(); |
| 631 | let mut original = fs::read(&path).unwrap(); |
| 632 | original.extend_from_slice(b"{\"phase\":\"decided\""); |
| 633 | fs::write(&path, &original).unwrap(); |
| 634 | let decision = ApprovalReceipt::decided("tool-pending", ApprovalOutcome::ApprovedOnce); |
| 635 | let error = store |
| 636 | .append_with_preservation("session-preserve-error", &decision, |_, _| { |
| 637 | Err(io::Error::other("simulated preservation failure")) |
| 638 | }) |
| 639 | .unwrap_err(); |
| 640 | assert_eq!(error.to_string(), "simulated preservation failure"); |
| 641 | assert_eq!(fs::read(&path).unwrap(), original); |
| 642 | let replay = store.replay("session-preserve-error").unwrap(); |
| 643 | assert!(replay.completed.is_empty()); |
| 644 | assert_eq!(replay.unmatched_asks, vec![ask]); |
| 645 | } |
| 646 | |
| 647 | #[test] |
| 648 | fn invalid_candidate_cannot_trigger_tail_repair() { |
| 649 | let tmp = tempfile::tempdir().unwrap(); |
| 650 | let store = ApprovalReceiptStore::new(tmp.path().join("sessions")); |
| 651 | let ask = ApprovalReceipt::asked("tool-pending", "exec_shell"); |
| 652 | store.append("session-invalid", &ask).unwrap(); |
| 653 | let path = store.log_path("session-invalid").unwrap(); |
| 654 | let mut original = fs::read(&path).unwrap(); |
| 655 | original.extend_from_slice(b"{\"phase\":\"decided\""); |
| 656 | fs::write(&path, &original).unwrap(); |
| 657 | assert!( |
| 658 | store |
| 659 | .append_with_preservation("session-invalid", &ask, |_, _| { |
| 660 | panic!("invalid duplicate ask must fail before preserving or truncating") |
| 661 | }) |
| 662 | .is_err() |
| 663 | ); |
| 664 | assert_eq!(fs::read(path).unwrap(), original); |
| 665 | } |
| 666 | |
| 667 | #[test] |
| 668 | fn complete_unterminated_receipts_survive_and_get_an_append_separator() { |
| 669 | let tmp = tempfile::tempdir().unwrap(); |
| 670 | let store = ApprovalReceiptStore::new(tmp.path().join("sessions")); |
| 671 | let receipts = completed_receipts(ApprovalOutcome::Denied); |
| 672 | for count in 1..=receipts.len() { |
| 673 | let id = format!("session-no-lf-{count}"); |
| 674 | let path = store.log_path(&id).unwrap(); |
| 675 | fs::create_dir_all(path.parent().unwrap()).unwrap(); |
| 676 | let original = receipts[..count] |
| 677 | .iter() |
| 678 | .map(|receipt| serde_json::to_string(receipt).unwrap()) |
| 679 | .collect::<Vec<_>>() |
| 680 | .join("\n"); |
| 681 | fs::write(&path, &original).unwrap(); |
| 682 | assert_eq!(store.load(&id).unwrap(), receipts[..count]); |
| 683 | let next = ApprovalReceipt::asked("tool-next", "read_file"); |
| 684 | store.append(&id, &next).unwrap(); |
| 685 | let mut expected = receipts[..count].to_vec(); |
| 686 | expected.push(next); |
| 687 | assert_eq!(store.load(&id).unwrap(), expected); |
| 688 | assert!( |
| 689 | fs::read_to_string(path) |
| 690 | .unwrap() |
| 691 | .starts_with(&format!("{original}\n")) |
| 692 | ); |
| 693 | } |
| 694 | } |
| 695 | |
| 696 | #[test] |
| 697 | fn malformed_complete_lines_and_invalid_receipts_still_fail_closed() { |
| 698 | let tmp = tempfile::tempdir().unwrap(); |
| 699 | let store = ApprovalReceiptStore::new(tmp.path().join("sessions")); |
| 700 | let ask = ApprovalReceipt::asked("tool-1", "exec_shell"); |
| 701 | let line = serde_json::to_string(&ask).unwrap(); |
| 702 | let orphan = ApprovalReceipt::decided("tool-orphan", ApprovalOutcome::ApprovedOnce); |
| 703 | for (index, original) in [ |
| 704 | format!("{line}\n{{broken\n"), |
| 705 | format!("{line}\n{{broken\n{line}\n"), |
| 706 | format!("{line}\n{line}"), |
| 707 | "{}".to_string(), |
| 708 | serde_json::to_string(&ApprovalReceipt::asked("", "exec_shell")).unwrap(), |
| 709 | serde_json::to_string(&orphan).unwrap(), |
| 710 | ] |
| 711 | .into_iter() |
| 712 | .enumerate() |
| 713 | { |
| 714 | let id = format!("session-invalid-{index}"); |
| 715 | let path = store.log_path(&id).unwrap(); |
| 716 | fs::create_dir_all(path.parent().unwrap()).unwrap(); |
| 717 | fs::write(&path, &original).unwrap(); |
| 718 | assert!(store.load(&id).is_err(), "case {index}"); |
| 719 | assert!( |
| 720 | store |
| 721 | .append(&id, &ApprovalReceipt::asked("tool-new", "read_file")) |
| 722 | .is_err() |
| 723 | ); |
| 724 | assert_eq!(fs::read_to_string(path).unwrap(), original); |
| 725 | } |
| 726 | } |
| 727 | |
| 728 | #[test] |
| 729 | fn store_serializes_competing_writers() { |
| 730 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 731 | let store = ApprovalReceiptStore::new(tmp.path().join("sessions")); |
| 732 | let barrier = std::sync::Arc::new(std::sync::Barrier::new(8)); |
| 733 | let mut writers = Vec::new(); |
| 734 | |
| 735 | for _ in 0..8 { |
| 736 | let store = store.clone(); |
| 737 | let barrier = barrier.clone(); |
| 738 | writers.push(std::thread::spawn(move || { |
| 739 | barrier.wait(); |
| 740 | store.append( |
| 741 | "session-race", |
| 742 | &ApprovalReceipt::asked("tool-race", "exec_shell"), |
| 743 | ) |
| 744 | })); |
| 745 | } |
| 746 | |
| 747 | let results = writers |
| 748 | .into_iter() |
| 749 | .map(|writer| writer.join().expect("writer thread")) |
| 750 | .collect::<Vec<_>>(); |
| 751 | assert_eq!(results.iter().filter(|result| result.is_ok()).count(), 1); |
| 752 | assert_eq!(results.iter().filter(|result| result.is_err()).count(), 7); |
| 753 | assert_eq!(store.load("session-race").expect("load receipts").len(), 1); |
| 754 | } |
| 755 | } |
| 756 |