| 319 | /// `--no-verify`). |
| 320 | #[allow(clippy::too_many_arguments)] |
| 321 | pub fn verify_capture( |
| 322 | sessions_dir: &Path, |
| 323 | session: &AgentSession, |
| 324 | turn: u32, |
| 325 | expected_working_copy: &str, |
| 326 | expected_parent_oid: Option<&str>, |
| 327 | expected_committed_tree: Option<&str>, |
| 328 | turn_started_at: i64, |
| 329 | ) -> AgentResult<Option<ManagedCommitCapture>> { |
| 330 | // Verify the LATEST attempt (the last commit attempt of the turn); |
| 331 | // earlier attempts stay on disk as durable evidence. |
| 332 | let Some(path) = latest_capture_file(sessions_dir, &session.session_id, turn)? else { |
| 333 | return Ok(None); |
| 334 | }; |
| 335 | let bytes = std::fs::read(&path).map_err(|error| crate::error::AgentError::CaptureInvalid { |
| 336 | reason: format!("cannot read capture {}: {}", path.display(), error), |
| 337 | })?; |
| 338 | let capture = ManagedCommitCapture::from_json(&bytes)?; |
| 339 | if capture.version != CAPTURE_VERSION { |
| 340 | return Err(crate::error::AgentError::CaptureInvalid { |
| 341 | reason: format!( |
| 342 | "capture schema version {} is not supported (expected {CAPTURE_VERSION})", |
| 343 | capture.version |
| 344 | ), |
| 345 | }); |
| 346 | } |
| 347 | |
| 348 | // The durable session JSON is the MAC-key authority: the pre-commit hook |
| 349 | // persisted the key it signed with. Fall back to the in-memory session |
| 350 | // for freshly-created keys not yet saved. |
| 351 | let key = { |
| 352 | let store = crate::turn::session::SessionStore::new(sessions_dir)?; |
| 353 | store |
| 354 | .load(&session.session_id)? |
| 355 | .and_then(|stored| stored.mac_key) |
| 356 | .or_else(|| session.mac_key.clone()) |
| 357 | }; |
| 358 | let key = key.ok_or_else(|| crate::error::AgentError::CaptureInvalid { |
| 359 | reason: "session has no MAC key; capture cannot authenticate".to_string(), |
| 360 | })?; |
| 361 | if !capture.verify(&key) { |
| 362 | return Err(crate::error::AgentError::CaptureInvalid { |
| 363 | reason: "capture MAC verification failed (tampered or forged)".to_string(), |
| 364 | }); |
| 365 | } |
| 366 | if capture.session_id != session.session_id { |
| 367 | return Err(crate::error::AgentError::CaptureInvalid { |
| 368 | reason: format!( |
| 369 | "capture binds session '{}' not '{}'", |
| 370 | capture.session_id, session.session_id |
| 371 | ), |
| 372 | }); |
| 373 | } |
| 374 | if capture.turn != turn { |
| 375 | return Err(crate::error::AgentError::CaptureInvalid { |
| 376 | reason: format!( |
| 377 | "capture binds turn {} not {} (replayed or stale)", |
| 378 | capture.turn, turn |