| 1 | use std::collections::{BTreeMap, BTreeSet}; |
| 2 | use std::fs::{self, File}; |
| 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 codewhale_sandbox::SandboxPolicy; |
| 10 | use codewhale_util::files::WorkspaceFile; |
| 11 | |
| 12 | const APPROVAL_LOG_FILE: &str = "approval_receipts.jsonl"; |
| 13 | const APPROVAL_LOCK_FILE: &str = "approval_receipts.lock"; |
| 14 | |
| 15 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 16 | #[serde(tag = "outcome", rename_all = "snake_case")] |
| 17 | pub enum ApprovalOutcome { |
| 18 | ApprovedOnce, |
| 19 | Denied, |
| 20 | /// The interactive approval card expired unanswered (#6101): the |
| 21 | /// configured bound denied the call, not the operator. |
| 22 | Timeout, |
| 23 | Cancelled, |
| 24 | Unavailable, |
| 25 | RetryWithPolicy { |
| 26 | policy: SandboxPolicy, |
| 27 | }, |
| 28 | } |
| 29 | |
| 30 | // Shared data ownership; persisted approval serialization remains unchanged. |
| 31 | pub use codewhale_command_contract::facets::ApprovalDecider; |
| 32 | |
| 33 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 34 | #[serde(tag = "phase", rename_all = "snake_case")] |
| 35 | pub enum ApprovalReceipt { |
| 36 | Asked { |
| 37 | approval_id: String, |
| 38 | tool_call_id: String, |
| 39 | tool_name: String, |
| 40 | created_at: DateTime<Utc>, |
| 41 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 42 | target: Option<String>, |
| 43 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 44 | summary: Option<String>, |
| 45 | }, |
| 46 | Decided { |
| 47 | approval_id: String, |
| 48 | tool_call_id: String, |
| 49 | outcome: ApprovalOutcome, |
| 50 | created_at: DateTime<Utc>, |
| 51 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 52 | decided_by: Option<ApprovalDecider>, |
| 53 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 54 | grant_id: Option<String>, |
| 55 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 56 | matched_label: Option<String>, |
| 57 | }, |
| 58 | } |
| 59 | |
| 60 | impl ApprovalReceipt { |
| 61 | pub fn asked(tool_call_id: impl Into<String>, tool_name: impl Into<String>) -> Self { |
| 62 | let tool_call_id = tool_call_id.into(); |
| 63 | Self::Asked { |
| 64 | approval_id: tool_call_id.clone(), |
| 65 | tool_call_id, |
| 66 | tool_name: tool_name.into(), |
| 67 | created_at: Utc::now(), |
| 68 | target: None, |
| 69 | summary: None, |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | pub fn asked_with( |
| 74 | tool_call_id: impl Into<String>, |
| 75 | tool_name: impl Into<String>, |
| 76 | input: &serde_json::Value, |
| 77 | description: &str, |
| 78 | workspace: &Path, |
| 79 | ) -> Self { |
| 80 | let mut ask = Self::asked(tool_call_id, tool_name); |
| 81 | if let Self::Asked { |
| 82 | target, summary, .. |
| 83 | } = &mut ask |
| 84 | { |
| 85 | *target = ask_target(input, workspace); |
| 86 | *summary = ask_summary(input, description, workspace); |
| 87 | } |
| 88 | ask |
| 89 | } |
| 90 | |
| 91 | pub fn target(&self) -> Option<&str> { |
| 92 | match self { |
| 93 | Self::Asked { target, .. } => target.as_deref(), |
| 94 | Self::Decided { .. } => None, |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | pub fn summary(&self) -> Option<&str> { |
| 99 | match self { |
| 100 | Self::Asked { summary, .. } => summary.as_deref(), |
| 101 | Self::Decided { .. } => None, |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | /// A decision whose decider this call site does not know. |
| 106 | #[cfg(any(test, feature = "test-support"))] |
| 107 | pub fn decided(tool_call_id: impl Into<String>, outcome: ApprovalOutcome) -> Self { |
| 108 | Self::decided_with(tool_call_id, outcome, None) |
| 109 | } |
| 110 | |
| 111 | pub fn decided_with( |
| 112 | tool_call_id: impl Into<String>, |
| 113 | outcome: ApprovalOutcome, |
| 114 | decided_by: Option<ApprovalDecider>, |
| 115 | ) -> Self { |
| 116 | let tool_call_id = tool_call_id.into(); |
| 117 | Self::Decided { |
| 118 | approval_id: tool_call_id.clone(), |
| 119 | tool_call_id, |
| 120 | outcome, |
| 121 | created_at: Utc::now(), |
| 122 | decided_by, |
| 123 | grant_id: None, |
| 124 | matched_label: None, |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | pub fn with_grant(mut self, grant: &crate::core::authority::grants::GrantRef) -> Self { |
| 129 | if let Self::Decided { |
| 130 | grant_id, |
| 131 | matched_label, |
| 132 | .. |
| 133 | } = &mut self |
| 134 | { |
| 135 | *grant_id = Some(grant.grant_id.clone()); |
| 136 | *matched_label = Some(grant.label.clone()); |
| 137 | } |
| 138 | self |
| 139 | } |
| 140 | |
| 141 | pub fn approval_id(&self) -> &str { |
| 142 | match self { |
| 143 | Self::Asked { approval_id, .. } | Self::Decided { approval_id, .. } => approval_id, |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | fn tool_call_id(&self) -> &str { |
| 148 | match self { |
| 149 | Self::Asked { tool_call_id, .. } | Self::Decided { tool_call_id, .. } => tool_call_id, |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | /// The tool the agent wanted to run — present on the ask half only. |
| 154 | pub fn tool_name(&self) -> Option<&str> { |
| 155 | match self { |
| 156 | Self::Asked { tool_name, .. } => Some(tool_name), |
| 157 | Self::Decided { .. } => None, |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | pub fn created_at(&self) -> DateTime<Utc> { |
| 162 | match self { |
| 163 | Self::Asked { created_at, .. } | Self::Decided { created_at, .. } => *created_at, |
| 164 | } |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | const ASK_TEXT_CAP: usize = 120; |
| 169 | |
| 170 | fn cap_ask_text(text: &str) -> Option<String> { |
| 171 | let collapsed = text.split_whitespace().collect::<Vec<_>>().join(" "); |
| 172 | if collapsed.is_empty() { |
| 173 | return None; |
| 174 | } |
| 175 | if collapsed.chars().count() <= ASK_TEXT_CAP { |
| 176 | return Some(collapsed); |
| 177 | } |
| 178 | let head: String = collapsed.chars().take(ASK_TEXT_CAP - 1).collect(); |
| 179 | Some(format!("{head}…")) |
| 180 | } |
| 181 | |
| 182 | fn safe_path(token: &str, workspace: &Path) -> String { |
| 183 | let root = workspace.to_string_lossy(); |
| 184 | let root = root.trim_end_matches('/'); |
| 185 | if !root.is_empty() |
| 186 | && let Some(rest) = token.strip_prefix(root) |
| 187 | { |
| 188 | if rest.is_empty() { |
| 189 | return ".".to_string(); |
| 190 | } |
| 191 | if rest.starts_with('/') { |
| 192 | return format!(".{rest}"); |
| 193 | } |
| 194 | } |
| 195 | if token.starts_with('/') || token.starts_with('~') { |
| 196 | let base = token |
| 197 | .rsplit('/') |
| 198 | .find(|part| !part.is_empty()) |
| 199 | .unwrap_or(""); |
| 200 | return format!(".../{base}"); |
| 201 | } |
| 202 | token.to_string() |
| 203 | } |
| 204 | |
| 205 | fn split_shell_words(text: &str) -> Vec<&str> { |
| 206 | let mut words = Vec::new(); |
| 207 | let mut start = None; |
| 208 | let mut quote: Option<char> = None; |
| 209 | for (at, c) in text.char_indices() { |
| 210 | match (quote, c) { |
| 211 | (Some(q), _) if c == q => quote = None, |
| 212 | (Some(_), _) => {} |
| 213 | (None, '"' | '\'' | '`') => { |
| 214 | quote = Some(c); |
| 215 | start.get_or_insert(at); |
| 216 | } |
| 217 | (None, c) if c.is_whitespace() => { |
| 218 | if let Some(s) = start.take() { |
| 219 | words.push(&text[s..at]); |
| 220 | } |
| 221 | } |
| 222 | _ => { |
| 223 | start.get_or_insert(at); |
| 224 | } |
| 225 | } |
| 226 | } |
| 227 | if let Some(s) = start { |
| 228 | words.push(&text[s..]); |
| 229 | } |
| 230 | words |
| 231 | } |
| 232 | |
| 233 | fn plain_word(word: &str) -> bool { |
| 234 | const SENSITIVE: [&str; 11] = [ |
| 235 | "pass", "token", "secret", "key", "auth", "cred", "user", "cookie", "bearer", "header", |
| 236 | "private", |
| 237 | ]; |
| 238 | if word.is_empty() || word.chars().count() > 64 { |
| 239 | return false; |
| 240 | } |
| 241 | if !word |
| 242 | .chars() |
| 243 | .all(|c| c.is_ascii_alphanumeric() || "_./~+,%-".contains(c)) |
| 244 | { |
| 245 | return false; |
| 246 | } |
| 247 | if let Some(flag) = word.strip_prefix("--") { |
| 248 | let lower = flag.to_ascii_lowercase(); |
| 249 | return !flag.is_empty() && !SENSITIVE.iter().any(|s| lower.contains(s)); |
| 250 | } |
| 251 | if let Some(flag) = word.strip_prefix('-') { |
| 252 | return word.len() > 1 && flag.len() == 1 && "alrRfnvih".contains(flag); |
| 253 | } |
| 254 | true |
| 255 | } |
| 256 | |
| 257 | fn redact_ask_text(text: &str, workspace: &Path, command: bool) -> Option<String> { |
| 258 | let words = split_shell_words(text); |
| 259 | let redacted = if command { |
| 260 | let program = words.first().copied().filter(|w| plain_word(w)); |
| 261 | match program { |
| 262 | None => "[command redacted]".to_string(), |
| 263 | Some(program) => { |
| 264 | let name = safe_path(program, workspace); |
| 265 | let name = name.rsplit('/').next().unwrap_or(&name).to_string(); |
| 266 | let rest = &words[1..]; |
| 267 | if rest.iter().all(|w| plain_word(w)) { |
| 268 | let mut out = vec![name]; |
| 269 | out.extend(rest.iter().map(|w| safe_path(w, workspace))); |
| 270 | out.join(" ") |
| 271 | } else { |
| 272 | format!("{name} [args redacted]") |
| 273 | } |
| 274 | } |
| 275 | } |
| 276 | } else { |
| 277 | words |
| 278 | .iter() |
| 279 | .map(|w| { |
| 280 | if plain_word(w) |
| 281 | || w.chars() |
| 282 | .all(|c| c.is_alphanumeric() || ".,:;()".contains(c)) |
| 283 | { |
| 284 | safe_path(w, workspace) |
| 285 | } else { |
| 286 | "[redacted]".to_string() |
| 287 | } |
| 288 | }) |
| 289 | .collect::<Vec<_>>() |
| 290 | .join(" ") |
| 291 | }; |
| 292 | let (redacted, _) = crate::session_peek::redact(&redacted); |
| 293 | cap_ask_text(&redacted) |
| 294 | } |
| 295 | |
| 296 | fn ask_target(input: &serde_json::Value, workspace: &Path) -> Option<String> { |
| 297 | for key in ["url", "uri"] { |
| 298 | if let Some(raw) = input.get(key).and_then(|v| v.as_str()) |
| 299 | && let Ok(url) = reqwest::Url::parse(raw.trim()) |
| 300 | && let Some(host) = url.host_str() |
| 301 | { |
| 302 | return cap_ask_text(host); |
| 303 | } |
| 304 | } |
| 305 | for key in ["path", "file_path", "filepath", "filename"] { |
| 306 | if let Some(raw) = input.get(key).and_then(|v| v.as_str()) { |
| 307 | let raw = raw.trim(); |
| 308 | if raw.is_empty() || raw.contains(char::is_whitespace) { |
| 309 | return redact_ask_text(raw, workspace, false); |
| 310 | } |
| 311 | return cap_ask_text(&safe_path(raw, workspace)); |
| 312 | } |
| 313 | } |
| 314 | None |
| 315 | } |
| 316 | |
| 317 | fn ask_summary(input: &serde_json::Value, description: &str, workspace: &Path) -> Option<String> { |
| 318 | match input |
| 319 | .get("command") |
| 320 | .and_then(|v| v.as_str()) |
| 321 | .filter(|c| !c.trim().is_empty()) |
| 322 | { |
| 323 | Some(command) => redact_ask_text(command, workspace, true), |
| 324 | None => redact_ask_text(description, workspace, false), |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 329 | pub struct CompletedApproval { |
| 330 | pub ask: ApprovalReceipt, |
| 331 | pub outcome: ApprovalOutcome, |
| 332 | pub decided_at: DateTime<Utc>, |
| 333 | pub decided_by: Option<ApprovalDecider>, |
| 334 | } |
| 335 | |
| 336 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 337 | pub struct ApprovalReplay { |
| 338 | pub completed: Vec<CompletedApproval>, |
| 339 | pub unmatched_asks: Vec<ApprovalReceipt>, |
| 340 | } |
| 341 | |
| 342 | impl ApprovalReplay { |
| 343 | pub fn from_receipts(receipts: &[ApprovalReceipt]) -> Result<Self, String> { |
| 344 | let mut open = BTreeMap::<String, ApprovalReceipt>::new(); |
| 345 | let mut closed = BTreeSet::<String>::new(); |
| 346 | let mut completed = Vec::new(); |
| 347 | |
| 348 | for receipt in receipts { |
| 349 | let approval_id = receipt.approval_id(); |
| 350 | if approval_id.trim().is_empty() || receipt.tool_call_id().trim().is_empty() { |
| 351 | return Err("approval receipt has an empty correlation id".to_string()); |
| 352 | } |
| 353 | match receipt { |
| 354 | ApprovalReceipt::Asked { |
| 355 | approval_id, |
| 356 | tool_call_id, |
| 357 | tool_name, |
| 358 | .. |
| 359 | } => { |
| 360 | if tool_name.trim().is_empty() { |
| 361 | return Err(format!( |
| 362 | "approval ask '{approval_id}' has an empty tool name" |
| 363 | )); |
| 364 | } |
| 365 | if approval_id != tool_call_id { |
| 366 | return Err(format!( |
| 367 | "approval ask '{approval_id}' does not match tool call '{tool_call_id}'" |
| 368 | )); |
| 369 | } |
| 370 | if closed.contains(approval_id) || open.contains_key(approval_id) { |
| 371 | return Err(format!("approval '{approval_id}' was asked more than once")); |
| 372 | } |
| 373 | open.insert(approval_id.clone(), receipt.clone()); |
| 374 | } |
| 375 | ApprovalReceipt::Decided { |
| 376 | approval_id, |
| 377 | tool_call_id, |
| 378 | outcome, |
| 379 | created_at, |
| 380 | decided_by, |
| 381 | .. |
| 382 | } => { |
| 383 | if approval_id != tool_call_id { |
| 384 | return Err(format!( |
| 385 | "approval decision '{approval_id}' does not match tool call '{tool_call_id}'" |
| 386 | )); |
| 387 | } |
| 388 | let Some(ask) = open.remove(approval_id) else { |
| 389 | return Err(format!( |
| 390 | "approval decision '{approval_id}' has no unmatched ask" |
| 391 | )); |
| 392 | }; |
| 393 | closed.insert(approval_id.clone()); |
| 394 | completed.push(CompletedApproval { |
| 395 | ask, |
| 396 | outcome: outcome.clone(), |
| 397 | decided_at: *created_at, |
| 398 | decided_by: *decided_by, |
| 399 | }); |
| 400 | } |
| 401 | } |
| 402 | } |
| 403 | |
| 404 | Ok(Self { |
| 405 | completed, |
| 406 | unmatched_asks: open.into_values().collect(), |
| 407 | }) |
| 408 | } |
| 409 | } |
| 410 | |
| 411 | #[derive(Debug, Clone)] |
| 412 | pub struct ApprovalReceiptStore { |
| 413 | sessions_dir: PathBuf, |
| 414 | } |
| 415 | |
| 416 | #[derive(Default)] |
| 417 | struct ApprovalLogRead { |
| 418 | receipts: Vec<ApprovalReceipt>, |
| 419 | valid_bytes: u64, |
| 420 | torn_tail: Option<Vec<u8>>, |
| 421 | needs_newline: bool, |
| 422 | } |
| 423 | |
| 424 | fn preserve_torn_tail(log: &WorkspaceFile, bytes: &[u8]) -> io::Result<()> { |
| 425 | log.sibling(&format!( |
| 426 | "approval_receipts-torn-{}.recovery", |
| 427 | uuid::Uuid::new_v4() |
| 428 | ))? |
| 429 | .publish(bytes) |
| 430 | } |
| 431 | |
| 432 | impl ApprovalReceiptStore { |
| 433 | pub fn new(sessions_dir: PathBuf) -> Self { |
| 434 | Self { sessions_dir } |
| 435 | } |
| 436 | |
| 437 | pub fn default_location() -> io::Result<Self> { |
| 438 | crate::session_manager::default_sessions_dir().map(Self::new) |
| 439 | } |
| 440 | |
| 441 | fn validated_session_id(session_id: &str) -> io::Result<&str> { |
| 442 | let trimmed = session_id.trim(); |
| 443 | if trimmed.is_empty() |
| 444 | || !trimmed |
| 445 | .chars() |
| 446 | .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') |
| 447 | { |
| 448 | return Err(io::Error::new( |
| 449 | io::ErrorKind::InvalidInput, |
| 450 | format!("Invalid session id '{session_id}'"), |
| 451 | )); |
| 452 | } |
| 453 | Ok(trimmed) |
| 454 | } |
| 455 | |
| 456 | pub fn log_path(&self, session_id: &str) -> io::Result<PathBuf> { |
| 457 | let session_id = Self::validated_session_id(session_id)?; |
| 458 | Ok(self.sessions_dir.join(session_id).join(APPROVAL_LOG_FILE)) |
| 459 | } |
| 460 | |
| 461 | fn log_file(&self, session_id: &str, create: bool) -> io::Result<WorkspaceFile> { |
| 462 | let session_id = Self::validated_session_id(session_id)?; |
| 463 | if create { |
| 464 | fs::create_dir_all(&self.sessions_dir)?; |
| 465 | } |
| 466 | WorkspaceFile::open_resolved_root( |
| 467 | &self.sessions_dir, |
| 468 | &PathBuf::from(session_id).join(APPROVAL_LOG_FILE), |
| 469 | create, |
| 470 | ) |
| 471 | } |
| 472 | |
| 473 | fn load_unlocked(log: &WorkspaceFile) -> io::Result<Option<ApprovalLogRead>> { |
| 474 | let file = match log.open_file_shared() { |
| 475 | Ok(file) => file, |
| 476 | Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(None), |
| 477 | Err(err) => return Err(err), |
| 478 | }; |
| 479 | Self::decode_log(file).map(Some) |
| 480 | } |
| 481 | |
| 482 | fn decode_log(file: File) -> io::Result<ApprovalLogRead> { |
| 483 | let mut reader = BufReader::new(file); |
| 484 | let mut loaded = ApprovalLogRead::default(); |
| 485 | let mut line = Vec::new(); |
| 486 | let mut index = 0; |
| 487 | loop { |
| 488 | line.clear(); |
| 489 | if reader.read_until(b'\n', &mut line)? == 0 { |
| 490 | break; |
| 491 | } |
| 492 | index += 1; |
| 493 | let terminated = line.last() == Some(&b'\n'); |
| 494 | match serde_json::from_slice(&line) { |
| 495 | Ok(receipt) => { |
| 496 | loaded.receipts.push(receipt); |
| 497 | loaded.valid_bytes += line.len() as u64; |
| 498 | loaded.needs_newline = !terminated; |
| 499 | } |
| 500 | Err(error) if !terminated && (error.is_eof() || error.is_syntax()) => { |
| 501 | // Only malformed, unterminated EOF bytes can be a torn |
| 502 | // write. Complete lines and valid JSON with an invalid |
| 503 | // receipt schema remain fatal, as do replay violations. |
| 504 | loaded.torn_tail = Some(line); |
| 505 | break; |
| 506 | } |
| 507 | Err(_) => { |
| 508 | return Err(io::Error::new( |
| 509 | io::ErrorKind::InvalidData, |
| 510 | format!("invalid approval receipt at line {index}"), |
| 511 | )); |
| 512 | } |
| 513 | } |
| 514 | } |
| 515 | ApprovalReplay::from_receipts(&loaded.receipts) |
| 516 | .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?; |
| 517 | Ok(loaded) |
| 518 | } |
| 519 | |
| 520 | pub fn load(&self, session_id: &str) -> io::Result<Vec<ApprovalReceipt>> { |
| 521 | Ok(self.load_if_present(session_id)?.unwrap_or_default()) |
| 522 | } |
| 523 | |
| 524 | /// Preserve the distinction between a missing legacy log and an existing |
| 525 | /// authoritative log with no complete receipts, including a torn first write. |
| 526 | pub fn load_if_present(&self, session_id: &str) -> io::Result<Option<Vec<ApprovalReceipt>>> { |
| 527 | let log = match self.log_file(session_id, false) { |
| 528 | Ok(log) => log, |
| 529 | Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), |
| 530 | Err(error) => return Err(error), |
| 531 | }; |
| 532 | let lock_file = match log.sibling(APPROVAL_LOCK_FILE)?.open_file_shared() { |
| 533 | Ok(file) => file, |
| 534 | Err(error) if error.kind() == io::ErrorKind::NotFound => { |
| 535 | return Ok(Self::load_unlocked(&log)?.map(|loaded| loaded.receipts)); |
| 536 | } |
| 537 | Err(error) => return Err(error), |
| 538 | }; |
| 539 | let lock = fd_lock::RwLock::new(lock_file); |
| 540 | let _guard = lock.read()?; |
| 541 | Ok(Self::load_unlocked(&log)?.map(|loaded| loaded.receipts)) |
| 542 | } |
| 543 | |
| 544 | pub fn replay(&self, session_id: &str) -> io::Result<ApprovalReplay> { |
| 545 | let receipts = self.load(session_id)?; |
| 546 | ApprovalReplay::from_receipts(&receipts) |
| 547 | .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err)) |
| 548 | } |
| 549 | |
| 550 | /// Session ids that have an approval log. Only entries whose name is a |
| 551 | /// valid session id are considered, so a stray file in the sessions dir |
| 552 | /// can never become a path traversal. A missing or unreadable sessions |
| 553 | /// dir is an empty history, not an error. |
| 554 | pub fn sessions_with_logs(&self) -> Vec<String> { |
| 555 | let entries = match fs::read_dir(&self.sessions_dir) { |
| 556 | Ok(entries) => entries, |
| 557 | Err(_) => return Vec::new(), |
| 558 | }; |
| 559 | let mut ids = Vec::new(); |
| 560 | for entry in entries.flatten() { |
| 561 | let name = entry.file_name().to_string_lossy().into_owned(); |
| 562 | if Self::validated_session_id(&name).is_ok() |
| 563 | && entry.path().join(APPROVAL_LOG_FILE).exists() |
| 564 | { |
| 565 | ids.push(name); |
| 566 | } |
| 567 | } |
| 568 | ids |
| 569 | } |
| 570 | |
| 571 | pub fn append(&self, session_id: &str, receipt: &ApprovalReceipt) -> io::Result<()> { |
| 572 | self.append_with_preservation(session_id, receipt, preserve_torn_tail) |
| 573 | } |
| 574 | |
| 575 | fn append_with_preservation( |
| 576 | &self, |
| 577 | session_id: &str, |
| 578 | receipt: &ApprovalReceipt, |
| 579 | preserve: impl FnOnce(&WorkspaceFile, &[u8]) -> io::Result<()>, |
| 580 | ) -> io::Result<()> { |
| 581 | let log = self.log_file(session_id, true)?; |
| 582 | let lock_file = log.sibling(APPROVAL_LOCK_FILE)?.open_update(true, false)?; |
| 583 | codewhale_runtime::private_log::restrict_to_owner(&lock_file)?; |
| 584 | let mut lock = fd_lock::RwLock::new(lock_file); |
| 585 | let _guard = lock.write()?; |
| 586 | let mut loaded = Self::load_unlocked(&log)?.unwrap_or_default(); |
| 587 | loaded.receipts.push(receipt.clone()); |
| 588 | ApprovalReplay::from_receipts(&loaded.receipts) |
| 589 | .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?; |
| 590 | |
| 591 | let mut line = serde_json::to_vec(receipt) |
| 592 | .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?; |
| 593 | if loaded.needs_newline { |
| 594 | // A complete final JSON receipt is authoritative even without LF. |
| 595 | line.insert(0, b'\n'); |
| 596 | } |
| 597 | line.push(b'\n'); |
| 598 | // Approval receipts are owner-only and never written through a link. |
| 599 | let mut file = log.open_update(true, true)?; |
| 600 | codewhale_runtime::private_log::restrict_to_owner(&file)?; |
| 601 | if let Some(tail) = &loaded.torn_tail { |
| 602 | // Validate the candidate and preserve evidence before touching the |
| 603 | // live log. Any preservation error leaves the original intact. |
| 604 | // Windows append handles lack the write access set_len requires. |
| 605 | let repair = log.open_update(false, false)?; |
| 606 | preserve(&log, tail)?; |
| 607 | repair.set_len(loaded.valid_bytes)?; |
| 608 | repair.sync_all()?; |
| 609 | } |
| 610 | file.write_all(&line)?; |
| 611 | file.sync_all()?; |
| 612 | codewhale_util::utils::report_directory_sync( |
| 613 | &self.sessions_dir.join(session_id), |
| 614 | log.sync_parent(), |
| 615 | ); |
| 616 | Ok(()) |
| 617 | } |
| 618 | |
| 619 | #[cfg(any(test, feature = "test-support"))] |
| 620 | pub fn sessions_dir(&self) -> &std::path::Path { |
| 621 | &self.sessions_dir |
| 622 | } |
| 623 | } |
| 624 | |
| 625 | #[cfg(test)] |
| 626 | mod tests { |
| 627 | use super::*; |
| 628 | use std::fs::OpenOptions; |
| 629 | |
| 630 | #[cfg(unix)] |
| 631 | #[test] |
| 632 | fn repair_keeps_evidence_and_mutations_in_the_opened_parent() -> io::Result<()> { |
| 633 | for fail_preservation in [false, true] { |
| 634 | let temp = tempfile::tempdir()?; |
| 635 | let root = temp.path().canonicalize()?; |
| 636 | let selected = root.join("sessions"); |
| 637 | let retained = root.join("retained-sessions"); |
| 638 | let store = ApprovalReceiptStore::new(selected.clone()); |
| 639 | let ask = ApprovalReceipt::asked("original-tool", "exec_shell"); |
| 640 | store.append("target", &ask)?; |
| 641 | let path = store.log_path("target")?; |
| 642 | let tail = b"{\"phase\":\"decided\""; |
| 643 | OpenOptions::new() |
| 644 | .append(true) |
| 645 | .open(&path)? |
| 646 | .write_all(tail)?; |
| 647 | let original = fs::read(&path)?; |
| 648 | let decision = ApprovalReceipt::decided("original-tool", ApprovalOutcome::Denied); |
| 649 | let mut replacement_snapshot = None; |
| 650 | let result = store.append_with_preservation("target", &decision, |log, bytes| { |
| 651 | assert_eq!(bytes, tail); |
| 652 | fs::rename(&selected, &retained)?; |
| 653 | let replacement = ApprovalReceiptStore::new(selected.clone()); |
| 654 | replacement.append( |
| 655 | "target", |
| 656 | &ApprovalReceipt::asked("replacement-tool", "read_file"), |
| 657 | )?; |
| 658 | let replacement_path = replacement.log_path("target")?; |
| 659 | replacement_snapshot = |
| 660 | Some((replacement_path.clone(), fs::read(replacement_path)?)); |
| 661 | fs::write(selected.join("canary"), b"unrelated replacement")?; |
| 662 | if fail_preservation { |
| 663 | return Err(io::Error::other("simulated preservation failure")); |
| 664 | } |
| 665 | preserve_torn_tail(log, bytes)?; |
| 666 | assert_eq!( |
| 667 | fs::read(retained.join("target").join(APPROVAL_LOG_FILE))?, |
| 668 | original, |
| 669 | "evidence publication must precede truncation" |
| 670 | ); |
| 671 | Ok(()) |
| 672 | }); |
| 673 | if fail_preservation { |
| 674 | assert_eq!( |
| 675 | result.unwrap_err().to_string(), |
| 676 | "simulated preservation failure" |
| 677 | ); |
| 678 | assert_eq!( |
| 679 | fs::read(retained.join("target").join(APPROVAL_LOG_FILE))?, |
| 680 | original |
| 681 | ); |
| 682 | } else { |
| 683 | result?; |
| 684 | } |
| 685 | let (replacement_path, bytes) = replacement_snapshot.unwrap(); |
| 686 | assert_eq!(fs::read(replacement_path)?, bytes); |
| 687 | assert_eq!(fs::read(selected.join("canary"))?, b"unrelated replacement"); |
| 688 | let preserved = ApprovalReceiptStore::new(retained.clone()); |
| 689 | assert_eq!( |
| 690 | preserved.load("target")?, |
| 691 | if fail_preservation { |
| 692 | vec![ask] |
| 693 | } else { |
| 694 | vec![ask, decision] |
| 695 | } |
| 696 | ); |
| 697 | let recovery = fs::read_dir(retained.join("target"))? |
| 698 | .map(|entry| entry.map(|entry| entry.path())) |
| 699 | .collect::<io::Result<Vec<_>>>()? |
| 700 | .into_iter() |
| 701 | .filter(|path| path.extension().is_some_and(|ext| ext == "recovery")) |
| 702 | .collect::<Vec<_>>(); |
| 703 | assert_eq!(recovery.len(), usize::from(!fail_preservation)); |
| 704 | if !fail_preservation { |
| 705 | assert_eq!(fs::read(&recovery[0])?, tail); |
| 706 | } |
| 707 | assert!(fs::read_dir(selected.join("target"))?.all(|entry| { |
| 708 | !entry |
| 709 | .unwrap() |
| 710 | .path() |
| 711 | .extension() |
| 712 | .is_some_and(|ext| ext == "recovery") |
| 713 | })); |
| 714 | } |
| 715 | Ok(()) |
| 716 | } |
| 717 | |
| 718 | #[test] |
| 719 | fn reads_preserve_absent_roots_and_legacy_logs_without_locks() -> io::Result<()> { |
| 720 | let temp = tempfile::tempdir()?; |
| 721 | let selected = temp.path().join("sessions"); |
| 722 | let store = ApprovalReceiptStore::new(selected.clone()); |
| 723 | assert!(store.load_if_present("missing")?.is_none()); |
| 724 | assert!(store.load("missing")?.is_empty()); |
| 725 | assert!(!selected.try_exists()?); |
| 726 | assert!( |
| 727 | store |
| 728 | .append("../invalid", &ApprovalReceipt::asked("tool", "read_file")) |
| 729 | .is_err() |
| 730 | ); |
| 731 | assert!(!selected.try_exists()?); |
| 732 | let ask = ApprovalReceipt::asked("legacy-tool", "read_file"); |
| 733 | let log = store.log_path("legacy")?; |
| 734 | fs::create_dir_all(log.parent().unwrap())?; |
| 735 | let mut bytes = serde_json::to_vec(&ask).map_err(io::Error::other)?; |
| 736 | bytes.push(b'\n'); |
| 737 | fs::write(&log, &bytes)?; |
| 738 | assert_eq!(store.load("legacy")?, vec![ask]); |
| 739 | assert_eq!(fs::read(&log)?, bytes); |
| 740 | assert_eq!(fs::read_dir(log.parent().unwrap())?.count(), 1); |
| 741 | assert!(store.load_if_present("still-missing")?.is_none()); |
| 742 | assert!(!selected.join("still-missing").try_exists()?); |
| 743 | Ok(()) |
| 744 | } |
| 745 | |
| 746 | #[cfg(unix)] |
| 747 | #[test] |
| 748 | fn linked_session_directory_is_not_an_approval_transaction_parent() -> io::Result<()> { |
| 749 | let temp = tempfile::tempdir()?; |
| 750 | let selected = temp.path().join("sessions"); |
| 751 | let foreign = temp.path().join("foreign"); |
| 752 | fs::create_dir_all(&selected)?; |
| 753 | fs::create_dir(&foreign)?; |
| 754 | fs::write(foreign.join("canary"), b"unrelated owner")?; |
| 755 | std::os::unix::fs::symlink(&foreign, selected.join("target"))?; |
| 756 | let store = ApprovalReceiptStore::new(selected); |
| 757 | assert!( |
| 758 | store |
| 759 | .append("target", &ApprovalReceipt::asked("tool", "read_file")) |
| 760 | .is_err() |
| 761 | ); |
| 762 | assert!(store.load_if_present("target").is_err()); |
| 763 | assert_eq!(fs::read(foreign.join("canary"))?, b"unrelated owner"); |
| 764 | assert_eq!(fs::read_dir(foreign)?.count(), 1); |
| 765 | Ok(()) |
| 766 | } |
| 767 | |
| 768 | fn completed_receipts(outcome: ApprovalOutcome) -> Vec<ApprovalReceipt> { |
| 769 | vec![ |
| 770 | ApprovalReceipt::asked("tool-1", "exec_shell"), |
| 771 | ApprovalReceipt::decided("tool-1", outcome), |
| 772 | ] |
| 773 | } |
| 774 | |
| 775 | #[test] |
| 776 | fn replay_reconstructs_every_closed_outcome() { |
| 777 | let outcomes = [ |
| 778 | ApprovalOutcome::ApprovedOnce, |
| 779 | ApprovalOutcome::Denied, |
| 780 | ApprovalOutcome::Cancelled, |
| 781 | ApprovalOutcome::Unavailable, |
| 782 | ApprovalOutcome::RetryWithPolicy { |
| 783 | policy: codewhale_sandbox::SandboxPolicy::DangerFullAccess, |
| 784 | }, |
| 785 | ]; |
| 786 | |
| 787 | for outcome in outcomes { |
| 788 | let replay = ApprovalReplay::from_receipts(&completed_receipts(outcome.clone())) |
| 789 | .expect("closed approval log replays"); |
| 790 | assert_eq!(replay.completed.len(), 1); |
| 791 | assert_eq!(replay.completed[0].outcome, outcome); |
| 792 | assert!(replay.unmatched_asks.is_empty()); |
| 793 | } |
| 794 | } |
| 795 | |
| 796 | #[test] |
| 797 | fn replay_detects_an_unmatched_ask_after_interruption() { |
| 798 | let ask = ApprovalReceipt::asked("tool-interrupted", "write_file"); |
| 799 | let replay = ApprovalReplay::from_receipts(std::slice::from_ref(&ask)) |
| 800 | .expect("an unmatched ask is valid crash evidence"); |
| 801 | |
| 802 | assert!(replay.completed.is_empty()); |
| 803 | assert_eq!(replay.unmatched_asks, vec![ask]); |
| 804 | } |
| 805 | |
| 806 | #[test] |
| 807 | fn replay_rejects_decisions_without_one_open_ask() { |
| 808 | let orphan = ApprovalReceipt::decided("tool-orphan", ApprovalOutcome::ApprovedOnce); |
| 809 | assert!(ApprovalReplay::from_receipts(&[orphan]).is_err()); |
| 810 | |
| 811 | let duplicate = vec![ |
| 812 | ApprovalReceipt::asked("tool-duplicate", "exec_shell"), |
| 813 | ApprovalReceipt::decided("tool-duplicate", ApprovalOutcome::Denied), |
| 814 | ApprovalReceipt::decided("tool-duplicate", ApprovalOutcome::ApprovedOnce), |
| 815 | ]; |
| 816 | assert!(ApprovalReplay::from_receipts(&duplicate).is_err()); |
| 817 | } |
| 818 | |
| 819 | #[test] |
| 820 | fn store_appends_and_replays_a_session_owned_log() { |
| 821 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 822 | let store = ApprovalReceiptStore::new(tmp.path().join("sessions")); |
| 823 | let ask = ApprovalReceipt::asked("tool-persisted", "edit_file"); |
| 824 | let decision = ApprovalReceipt::decided("tool-persisted", ApprovalOutcome::ApprovedOnce); |
| 825 | |
| 826 | store |
| 827 | .append("session-1", &ask) |
| 828 | .expect("persist approval ask"); |
| 829 | store |
| 830 | .append("session-1", &decision) |
| 831 | .expect("persist approval decision"); |
| 832 | |
| 833 | let receipts = store.load("session-1").expect("load approval log"); |
| 834 | assert_eq!(receipts, vec![ask, decision]); |
| 835 | let replay = ApprovalReplay::from_receipts(&receipts).expect("replay approval log"); |
| 836 | assert_eq!(replay.completed.len(), 1); |
| 837 | assert!(replay.unmatched_asks.is_empty()); |
| 838 | } |
| 839 | |
| 840 | #[test] |
| 841 | fn loading_missing_or_imported_logs_is_read_only() { |
| 842 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 843 | let sessions_dir = tmp.path().join("sessions"); |
| 844 | let store = ApprovalReceiptStore::new(sessions_dir.clone()); |
| 845 | |
| 846 | assert!(store.load("session-empty").expect("missing log").is_empty()); |
| 847 | assert!(!sessions_dir.join("session-empty").exists()); |
| 848 | |
| 849 | let imported_dir = sessions_dir.join("session-imported"); |
| 850 | fs::create_dir_all(&imported_dir).expect("imported session dir"); |
| 851 | let ask = ApprovalReceipt::asked("tool-imported", "exec_shell"); |
| 852 | let mut line = serde_json::to_vec(&ask).expect("serialize imported ask"); |
| 853 | line.push(b'\n'); |
| 854 | fs::write(imported_dir.join(APPROVAL_LOG_FILE), line).expect("imported log"); |
| 855 | |
| 856 | assert_eq!( |
| 857 | store.load("session-imported").expect("load imported log"), |
| 858 | vec![ask] |
| 859 | ); |
| 860 | assert!(!imported_dir.join(APPROVAL_LOCK_FILE).exists()); |
| 861 | } |
| 862 | |
| 863 | #[test] |
| 864 | fn torn_tail_loads_only_valid_prefix_without_changing_evidence() { |
| 865 | let tmp = tempfile::tempdir().unwrap(); |
| 866 | let store = ApprovalReceiptStore::new(tmp.path().join("sessions")); |
| 867 | let ask = ApprovalReceipt::asked("tool-interrupted", "write_file"); |
| 868 | let mut prefix = serde_json::to_vec(&ask).unwrap(); |
| 869 | prefix.push(b'\n'); |
| 870 | for (index, tail) in [ |
| 871 | b"{\"phase\":\"decided\",\"approval_id\":\"tool-interrupted\"".as_slice(), |
| 872 | b"{\"phase\":\"asked\",\"tool_name\":\"\xf0\x9f".as_slice(), |
| 873 | ] |
| 874 | .into_iter() |
| 875 | .enumerate() |
| 876 | { |
| 877 | let id = format!("session-torn-{index}"); |
| 878 | let path = store.log_path(&id).unwrap(); |
| 879 | fs::create_dir_all(path.parent().unwrap()).unwrap(); |
| 880 | let mut original = prefix.clone(); |
| 881 | original.extend_from_slice(tail); |
| 882 | fs::write(&path, &original).unwrap(); |
| 883 | let replay = store.replay(&id).unwrap(); |
| 884 | assert!(replay.completed.is_empty()); |
| 885 | assert_eq!(replay.unmatched_asks, vec![ask.clone()]); |
| 886 | assert_eq!(fs::read(&path).unwrap(), original); |
| 887 | assert_eq!(fs::read_dir(path.parent().unwrap()).unwrap().count(), 1); |
| 888 | } |
| 889 | } |
| 890 | |
| 891 | #[test] |
| 892 | fn reader_distinguishes_missing_empty_and_torn_first_logs() { |
| 893 | let tmp = tempfile::tempdir().unwrap(); |
| 894 | let store = ApprovalReceiptStore::new(tmp.path().join("sessions")); |
| 895 | assert!(store.load_if_present("session-missing").unwrap().is_none()); |
| 896 | for (id, bytes) in [ |
| 897 | ("session-empty", b"".as_slice()), |
| 898 | ("session-torn", b"{\"phase\":\"asked\"".as_slice()), |
| 899 | ] { |
| 900 | let path = store.log_path(id).unwrap(); |
| 901 | fs::create_dir_all(path.parent().unwrap()).unwrap(); |
| 902 | fs::write(&path, bytes).unwrap(); |
| 903 | let loaded = ApprovalReceiptStore::load_unlocked(&store.log_file(id, false).unwrap()) |
| 904 | .unwrap() |
| 905 | .expect("existing log"); |
| 906 | assert!(loaded.receipts.is_empty()); |
| 907 | assert_eq!(store.load_if_present(id).unwrap(), Some(Vec::new())); |
| 908 | assert_eq!(loaded.valid_bytes, 0); |
| 909 | assert_eq!(loaded.torn_tail.is_some(), !bytes.is_empty()); |
| 910 | assert_eq!(fs::read(path).unwrap(), bytes); |
| 911 | } |
| 912 | } |
| 913 | |
| 914 | #[test] |
| 915 | fn append_preserves_torn_bytes_before_repair_and_never_invents_a_decision() { |
| 916 | let tmp = tempfile::tempdir().unwrap(); |
| 917 | let store = ApprovalReceiptStore::new(tmp.path().join("sessions")); |
| 918 | let ask = ApprovalReceipt::asked("tool-interrupted", "write_file"); |
| 919 | store.append("session-repair", &ask).unwrap(); |
| 920 | let path = store.log_path("session-repair").unwrap(); |
| 921 | let prefix = fs::read(&path).unwrap(); |
| 922 | let tail = b"{\"phase\":\"decided\",\"outcome\":\"approved_once\",\"note\":\"\xf0\x9f"; |
| 923 | OpenOptions::new() |
| 924 | .append(true) |
| 925 | .open(&path) |
| 926 | .unwrap() |
| 927 | .write_all(tail) |
| 928 | .unwrap(); |
| 929 | |
| 930 | let new_ask = ApprovalReceipt::asked("tool-next", "read_file"); |
| 931 | store.append("session-repair", &new_ask).unwrap(); |
| 932 | let replay = store.replay("session-repair").unwrap(); |
| 933 | assert!(replay.completed.is_empty()); |
| 934 | assert_eq!(replay.unmatched_asks, vec![ask, new_ask]); |
| 935 | assert!(fs::read(&path).unwrap().starts_with(&prefix)); |
| 936 | let recovery = fs::read_dir(path.parent().unwrap()) |
| 937 | .unwrap() |
| 938 | .map(|entry| entry.unwrap().path()) |
| 939 | .filter(|path| path.extension().is_some_and(|ext| ext == "recovery")) |
| 940 | .collect::<Vec<_>>(); |
| 941 | assert_eq!(recovery.len(), 1); |
| 942 | assert_eq!(fs::read(&recovery[0]).unwrap(), tail); |
| 943 | #[cfg(unix)] |
| 944 | { |
| 945 | use std::os::unix::fs::PermissionsExt as _; |
| 946 | assert_eq!( |
| 947 | fs::metadata(&recovery[0]).unwrap().permissions().mode() & 0o777, |
| 948 | 0o600 |
| 949 | ); |
| 950 | } |
| 951 | } |
| 952 | |
| 953 | #[test] |
| 954 | fn failed_tail_preservation_keeps_original_log_and_grants_nothing() { |
| 955 | let tmp = tempfile::tempdir().unwrap(); |
| 956 | let store = ApprovalReceiptStore::new(tmp.path().join("sessions")); |
| 957 | let ask = ApprovalReceipt::asked("tool-pending", "exec_shell"); |
| 958 | store.append("session-preserve-error", &ask).unwrap(); |
| 959 | let path = store.log_path("session-preserve-error").unwrap(); |
| 960 | let mut original = fs::read(&path).unwrap(); |
| 961 | original.extend_from_slice(b"{\"phase\":\"decided\""); |
| 962 | fs::write(&path, &original).unwrap(); |
| 963 | let decision = ApprovalReceipt::decided("tool-pending", ApprovalOutcome::ApprovedOnce); |
| 964 | let error = store |
| 965 | .append_with_preservation("session-preserve-error", &decision, |_, _| { |
| 966 | Err(io::Error::other("simulated preservation failure")) |
| 967 | }) |
| 968 | .unwrap_err(); |
| 969 | assert_eq!(error.to_string(), "simulated preservation failure"); |
| 970 | assert_eq!(fs::read(&path).unwrap(), original); |
| 971 | let replay = store.replay("session-preserve-error").unwrap(); |
| 972 | assert!(replay.completed.is_empty()); |
| 973 | assert_eq!(replay.unmatched_asks, vec![ask]); |
| 974 | } |
| 975 | |
| 976 | #[test] |
| 977 | fn invalid_candidate_cannot_trigger_tail_repair() { |
| 978 | let tmp = tempfile::tempdir().unwrap(); |
| 979 | let store = ApprovalReceiptStore::new(tmp.path().join("sessions")); |
| 980 | let ask = ApprovalReceipt::asked("tool-pending", "exec_shell"); |
| 981 | store.append("session-invalid", &ask).unwrap(); |
| 982 | let path = store.log_path("session-invalid").unwrap(); |
| 983 | let mut original = fs::read(&path).unwrap(); |
| 984 | original.extend_from_slice(b"{\"phase\":\"decided\""); |
| 985 | fs::write(&path, &original).unwrap(); |
| 986 | assert!( |
| 987 | store |
| 988 | .append_with_preservation("session-invalid", &ask, |_, _| { |
| 989 | panic!("invalid duplicate ask must fail before preserving or truncating") |
| 990 | }) |
| 991 | .is_err() |
| 992 | ); |
| 993 | assert_eq!(fs::read(path).unwrap(), original); |
| 994 | } |
| 995 | |
| 996 | #[test] |
| 997 | fn complete_unterminated_receipts_survive_and_get_an_append_separator() { |
| 998 | let tmp = tempfile::tempdir().unwrap(); |
| 999 | let store = ApprovalReceiptStore::new(tmp.path().join("sessions")); |
| 1000 | let receipts = completed_receipts(ApprovalOutcome::Denied); |
| 1001 | for count in 1..=receipts.len() { |
| 1002 | let id = format!("session-no-lf-{count}"); |
| 1003 | let path = store.log_path(&id).unwrap(); |
| 1004 | fs::create_dir_all(path.parent().unwrap()).unwrap(); |
| 1005 | let original = receipts[..count] |
| 1006 | .iter() |
| 1007 | .map(|receipt| serde_json::to_string(receipt).unwrap()) |
| 1008 | .collect::<Vec<_>>() |
| 1009 | .join("\n"); |
| 1010 | fs::write(&path, &original).unwrap(); |
| 1011 | assert_eq!(store.load(&id).unwrap(), receipts[..count]); |
| 1012 | let next = ApprovalReceipt::asked("tool-next", "read_file"); |
| 1013 | store.append(&id, &next).unwrap(); |
| 1014 | let mut expected = receipts[..count].to_vec(); |
| 1015 | expected.push(next); |
| 1016 | assert_eq!(store.load(&id).unwrap(), expected); |
| 1017 | assert!( |
| 1018 | fs::read_to_string(path) |
| 1019 | .unwrap() |
| 1020 | .starts_with(&format!("{original}\n")) |
| 1021 | ); |
| 1022 | } |
| 1023 | } |
| 1024 | |
| 1025 | #[test] |
| 1026 | fn malformed_complete_lines_and_invalid_receipts_still_fail_closed() { |
| 1027 | let tmp = tempfile::tempdir().unwrap(); |
| 1028 | let store = ApprovalReceiptStore::new(tmp.path().join("sessions")); |
| 1029 | let ask = ApprovalReceipt::asked("tool-1", "exec_shell"); |
| 1030 | let line = serde_json::to_string(&ask).unwrap(); |
| 1031 | let orphan = ApprovalReceipt::decided("tool-orphan", ApprovalOutcome::ApprovedOnce); |
| 1032 | for (index, original) in [ |
| 1033 | format!("{line}\n{{broken\n"), |
| 1034 | format!("{line}\n{{broken\n{line}\n"), |
| 1035 | format!("{line}\n{line}"), |
| 1036 | "{}".to_string(), |
| 1037 | serde_json::to_string(&ApprovalReceipt::asked("", "exec_shell")).unwrap(), |
| 1038 | serde_json::to_string(&orphan).unwrap(), |
| 1039 | ] |
| 1040 | .into_iter() |
| 1041 | .enumerate() |
| 1042 | { |
| 1043 | let id = format!("session-invalid-{index}"); |
| 1044 | let path = store.log_path(&id).unwrap(); |
| 1045 | fs::create_dir_all(path.parent().unwrap()).unwrap(); |
| 1046 | fs::write(&path, &original).unwrap(); |
| 1047 | assert!(store.load(&id).is_err(), "case {index}"); |
| 1048 | assert!( |
| 1049 | store |
| 1050 | .append(&id, &ApprovalReceipt::asked("tool-new", "read_file")) |
| 1051 | .is_err() |
| 1052 | ); |
| 1053 | assert_eq!(fs::read_to_string(path).unwrap(), original); |
| 1054 | } |
| 1055 | } |
| 1056 | |
| 1057 | #[test] |
| 1058 | fn store_serializes_competing_writers() { |
| 1059 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1060 | let store = ApprovalReceiptStore::new(tmp.path().join("sessions")); |
| 1061 | let barrier = std::sync::Arc::new(std::sync::Barrier::new(8)); |
| 1062 | let mut writers = Vec::new(); |
| 1063 | |
| 1064 | for _ in 0..8 { |
| 1065 | let store = store.clone(); |
| 1066 | let barrier = barrier.clone(); |
| 1067 | writers.push(std::thread::spawn(move || { |
| 1068 | barrier.wait(); |
| 1069 | store.append( |
| 1070 | "session-race", |
| 1071 | &ApprovalReceipt::asked("tool-race", "exec_shell"), |
| 1072 | ) |
| 1073 | })); |
| 1074 | } |
| 1075 | |
| 1076 | let results = writers |
| 1077 | .into_iter() |
| 1078 | .map(|writer| writer.join().expect("writer thread")) |
| 1079 | .collect::<Vec<_>>(); |
| 1080 | assert_eq!(results.iter().filter(|result| result.is_ok()).count(), 1); |
| 1081 | assert_eq!(results.iter().filter(|result| result.is_err()).count(), 7); |
| 1082 | assert_eq!(store.load("session-race").expect("load receipts").len(), 1); |
| 1083 | } |
| 1084 | } |
| 1085 |