1pub mod artifact;
64pub mod backend;
65mod exec;
66pub mod hashing;
67mod proc;
68pub mod result;
69mod scratch;
70
71use std::path::{Path, PathBuf};
72use std::time::Instant;
73
74pub use artifact::{
75 load_artifact, Obligation, ObligationArtifact, ObligationChecker, ObligationsError, Signal,
76};
77pub use backend::*;
78pub use exec::attestation::{
79 attestation_sidecar_path, load_attestation_sidecar, AttestationClaim, AttestationError,
80 AttestationRecord, AttestationSidecar, ATTESTATIONS_RELATIVE_PATH,
81 STALE_ATTESTATION_CLASSIFICATION,
82};
83pub use result::*;
84
85pub const ACTION_RECEIPT_WIRING: &str = "action_receipt";
89
90#[derive(Debug, Clone)]
95pub struct ReceiptSubject {
96 pub display_path: String,
100 pub sha256: String,
103 pub value: serde_json::Value,
105}
106
107#[derive(Debug, thiserror::Error)]
112pub enum ReceiptSubjectError {
113 #[error("cannot hash receipt file {path}: {source}")]
114 Hash {
115 path: PathBuf,
116 #[source]
117 source: hashing::HashingError,
118 },
119 #[error("cannot read receipt file {path}: {source}")]
120 Read {
121 path: PathBuf,
122 #[source]
123 source: std::io::Error,
124 },
125 #[error("receipt file {path} is not valid JSON (sha256 {sha256}): {source}")]
126 Json {
127 path: PathBuf,
128 sha256: String,
129 #[source]
130 source: serde_json::Error,
131 },
132}
133
134impl ReceiptSubjectError {
135 pub fn sha256(&self) -> Option<&str> {
137 match self {
138 ReceiptSubjectError::Json { sha256, .. } => Some(sha256),
139 ReceiptSubjectError::Hash { .. } | ReceiptSubjectError::Read { .. } => None,
140 }
141 }
142}
143
144pub fn load_receipt_subject(path: &Path) -> Result<ReceiptSubject, ReceiptSubjectError> {
148 let sha256 = hashing::sha256_file(path).map_err(|source| ReceiptSubjectError::Hash {
149 path: path.to_path_buf(),
150 source,
151 })?;
152 let text = std::fs::read_to_string(path).map_err(|source| ReceiptSubjectError::Read {
153 path: path.to_path_buf(),
154 source,
155 })?;
156 let value: serde_json::Value =
157 serde_json::from_str(&text).map_err(|source| ReceiptSubjectError::Json {
158 path: path.to_path_buf(),
159 sha256: sha256.clone(),
160 source,
161 })?;
162 Ok(ReceiptSubject {
163 display_path: path.display().to_string(),
164 sha256,
165 value,
166 })
167}
168
169#[tracing::instrument(skip(artifact, workspace_root, receipt), fields(obligations_count = artifact.obligations.len()))]
186pub fn run_obligations(
187 artifact: &ObligationArtifact,
188 workspace_root: &Path,
189 receipt: Option<&ReceiptSubject>,
190) -> Vec<ObligationResult> {
191 let run_start = Instant::now();
192 let attestations = exec::attestation::load_for_run(workspace_root);
193 let results: Vec<ObligationResult> = artifact
194 .obligations
195 .iter()
196 .filter_map(|o| run_one_scoped(o, workspace_root, &attestations, receipt))
197 .collect();
198 tracing::debug!(
199 duration_ms = run_start.elapsed().as_millis() as u64,
200 "obligations.run_all"
201 );
202 results
203}
204
205fn run_one_scoped(
212 obligation: &Obligation,
213 workspace_root: &Path,
214 attestations: &exec::attestation::LoadedAttestations,
215 receipt: Option<&ReceiptSubject>,
216) -> Option<ObligationResult> {
217 let wiring_is_receipt = obligation
218 .signal
219 .as_ref()
220 .map(|signal| signal.wiring == ACTION_RECEIPT_WIRING)
221 .unwrap_or(false);
222
223 match (receipt, wiring_is_receipt) {
224 (None, true) => Some(receipt_scoped_unknown_result(&obligation.id)),
226 (None, false) => Some(run_one(
228 obligation,
229 workspace_root,
230 attestations,
231 false,
232 None,
233 )),
234 (Some(subject), true) => Some(run_one(
236 obligation,
237 workspace_root,
238 attestations,
239 true,
240 Some(subject),
241 )),
242 (Some(_), false) => None,
244 }
245}
246
247fn receipt_scoped_unknown_result(id: &str) -> ObligationResult {
252 ObligationResult {
253 id: id.to_string(),
254 status: ObligationStatus::Unknown,
255 trust: None,
256 evidence: Evidence {
257 backend: "none".to_string(),
258 summary: "receipt-wired obligation; run `g8 check --receipt <path>` to evaluate"
259 .to_string(),
260 detail: serde_json::json!({ "scope": ACTION_RECEIPT_WIRING }),
261 duration_ms: 0,
262 checks_run: vec![],
263 },
264 }
265}
266
267fn run_one(
268 obligation: &Obligation,
269 workspace_root: &Path,
270 attestations: &exec::attestation::LoadedAttestations,
271 wiring_is_receipt: bool,
272 receipt: Option<&ReceiptSubject>,
273) -> ObligationResult {
274 match &obligation.checker {
275 None => unknown_result(&obligation.id, "no checker configured for this obligation"),
276 Some(ObligationChecker::ProseOnly) => {
277 unknown_result(&obligation.id, "checker.mode = prose_only")
278 }
279 Some(ObligationChecker::Attestation { attestation_id }) => {
280 exec::attestation::run(&obligation.id, attestation_id, attestations, workspace_root)
281 }
282 Some(ObligationChecker::Typed { checks }) => run_typed(
283 &obligation.id,
284 checks,
285 workspace_root,
286 attestations,
287 wiring_is_receipt,
288 receipt,
289 ),
290 }
291}
292
293fn unknown_result(id: &str, reason: &str) -> ObligationResult {
294 ObligationResult {
295 id: id.to_string(),
296 status: ObligationStatus::Unknown,
297 trust: None,
298 evidence: Evidence {
299 backend: "none".to_string(),
300 summary: reason.to_string(),
301 detail: serde_json::json!({}),
302 duration_ms: 0,
303 checks_run: vec![],
304 },
305 }
306}
307
308fn run_typed(
309 id: &str,
310 checks: &[CheckerBackend],
311 workspace_root: &Path,
312 attestations: &exec::attestation::LoadedAttestations,
313 wiring_is_receipt: bool,
314 receipt: Option<&ReceiptSubject>,
315) -> ObligationResult {
316 let start = Instant::now();
317
318 if let Some(message) = subject_binding_violation(checks, wiring_is_receipt) {
324 return ObligationResult {
325 id: id.to_string(),
326 status: ObligationStatus::Error,
327 trust: Some(TrustLevel::Checked),
328 evidence: Evidence {
329 backend: "none".to_string(),
330 summary: message.clone(),
331 detail: serde_json::json!({ "error": message }),
332 duration_ms: start.elapsed().as_millis() as u64,
333 checks_run: vec![],
334 },
335 };
336 }
337
338 let mut checks_run: Vec<SubCheckResult> = checks
339 .iter()
340 .map(|backend| exec::dispatch(backend, workspace_root, receipt))
341 .collect();
342
343 if let exec::attestation::AttestationEvaluation::Evaluated(attestation) =
347 exec::attestation::evaluate(attestations, id, None, workspace_root)
348 {
349 checks_run.push(attestation);
350 }
351
352 let (status, trust) = result::aggregate(&checks_run);
353
354 let representative = checks_run
358 .iter()
359 .find(|c| c.status == ObligationStatus::Error)
360 .or_else(|| {
361 checks_run
362 .iter()
363 .find(|c| c.status == ObligationStatus::Failed)
364 })
365 .or_else(|| {
366 checks_run
367 .iter()
368 .find(|c| c.status == ObligationStatus::Unknown)
369 })
370 .or_else(|| {
371 checks_run
372 .iter()
373 .max_by_key(|check| result::backend_tier_rank(&check.backend))
374 });
375
376 let (backend, summary, detail) = match representative {
377 Some(r) => (
378 r.backend.clone(),
379 format!("{:?}: {}", r.status, summarize_detail(&r.detail)),
380 r.detail.clone(),
381 ),
382 None => (
383 "none".to_string(),
384 "no checks configured".to_string(),
385 serde_json::json!({}),
386 ),
387 };
388
389 ObligationResult {
390 id: id.to_string(),
391 status,
392 trust,
393 evidence: Evidence {
394 backend,
395 summary,
396 detail,
397 duration_ms: start.elapsed().as_millis() as u64,
398 checks_run,
399 },
400 }
401}
402
403fn summarize_detail(detail: &serde_json::Value) -> String {
404 if let Some(s) = detail.get("summary").and_then(|v| v.as_str()) {
405 s.to_string()
406 } else {
407 detail.to_string()
408 }
409}
410
411fn subject_binding_violation(checks: &[CheckerBackend], wiring_is_receipt: bool) -> Option<String> {
415 checks.iter().find_map(|backend| {
416 let is_receipt_backend = backend.name() == "receipt_query";
417 if is_receipt_backend == wiring_is_receipt {
418 return None;
419 }
420 Some(if wiring_is_receipt {
421 format!(
422 "subject-binding violation: obligation is wired to '{ACTION_RECEIPT_WIRING}' but \
423 its checks include non-receipt backend '{}'; a receipt-wired obligation may only \
424 use receipt_query",
425 backend.name()
426 )
427 } else {
428 "subject-binding violation: 'receipt_query' backend used in an obligation not wired \
429 to 'action_receipt'; receipt_query may only appear in an action_receipt-wired \
430 obligation"
431 .to_string()
432 })
433 })
434}
435
436#[cfg(test)]
437mod receipt_scope_tests {
438 use super::*;
439
440 fn receipt_wired_obligation(id: &str, checks: Vec<CheckerBackend>) -> Obligation {
441 serde_json::from_value(serde_json::json!({
442 "id": id,
443 "checker": { "mode": "typed", "checks": checks },
444 "signal": { "wiring": "action_receipt", "advisory": false },
445 }))
446 .expect("must deserialize a hand-built obligation")
447 }
448
449 fn repo_wired_obligation(id: &str, checks: Vec<CheckerBackend>) -> Obligation {
450 serde_json::from_value(serde_json::json!({
451 "id": id,
452 "checker": { "mode": "typed", "checks": checks },
453 "signal": { "wiring": "compiled_intent_extension", "advisory": false },
454 }))
455 .expect("must deserialize a hand-built obligation")
456 }
457
458 fn receipt_query_backend() -> CheckerBackend {
459 CheckerBackend::ReceiptQuery(ReceiptQueryArgs {
460 select: "$.actions[*]".to_string(),
461 where_clauses: vec![],
462 aggregate: ReceiptAggregate::Count,
463 expected: ReceiptExpectation::Zero,
464 })
465 }
466
467 fn repo_backend() -> CheckerBackend {
468 CheckerBackend::RgMatchCount(RgArgs {
469 pattern: "ZZZ_NEVER_PRESENT_ZZZ".to_string(),
470 glob: vec!["Cargo.toml".to_string()],
471 expected: CountExpectation::Zero,
472 })
473 }
474
475 fn workspace_root() -> std::path::PathBuf {
476 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
477 .parent()
478 .unwrap()
479 .parent()
480 .unwrap()
481 .to_path_buf()
482 }
483
484 fn subject() -> ReceiptSubject {
485 ReceiptSubject {
486 display_path: "receipts/test.json".to_string(),
487 sha256: "sha256:test".to_string(),
488 value: serde_json::json!({ "actions": [] }),
489 }
490 }
491
492 #[test]
493 fn repo_mode_receipt_wired_obligation_is_unknown_and_scoped_not_executed() {
494 let obligation = receipt_wired_obligation("OBL-RCPT-01", vec![receipt_query_backend()]);
495 let attestations = exec::attestation::load_for_run(&workspace_root());
496 let result = run_one_scoped(&obligation, &workspace_root(), &attestations, None)
497 .expect("repo mode always produces a result for every obligation");
498 assert_eq!(result.status, ObligationStatus::Unknown);
499 assert_eq!(result.trust, None);
500 assert_eq!(
501 result.evidence.detail.get("scope").and_then(|v| v.as_str()),
502 Some(ACTION_RECEIPT_WIRING)
503 );
504 }
505
506 #[test]
507 fn repo_mode_repo_wired_obligation_runs_unaffected() {
508 let obligation = repo_wired_obligation("OBL-REPO-01", vec![repo_backend()]);
509 let attestations = exec::attestation::load_for_run(&workspace_root());
510 let result = run_one_scoped(&obligation, &workspace_root(), &attestations, None)
511 .expect("repo mode always produces a result for every obligation");
512 assert_eq!(result.status, ObligationStatus::Passed);
513 }
514
515 #[test]
516 fn receipt_mode_repo_wired_obligation_is_excluded_entirely() {
517 let obligation = repo_wired_obligation("OBL-REPO-01", vec![repo_backend()]);
518 let attestations = exec::attestation::load_for_run(&workspace_root());
519 let subject = subject();
520 let result = run_one_scoped(
521 &obligation,
522 &workspace_root(),
523 &attestations,
524 Some(&subject),
525 );
526 assert!(result.is_none());
527 }
528
529 #[test]
530 fn receipt_mode_receipt_wired_obligation_runs_against_the_subject() {
531 let obligation = receipt_wired_obligation("OBL-RCPT-01", vec![receipt_query_backend()]);
532 let attestations = exec::attestation::load_for_run(&workspace_root());
533 let subject = subject();
534 let result = run_one_scoped(
535 &obligation,
536 &workspace_root(),
537 &attestations,
538 Some(&subject),
539 )
540 .expect("receipt mode runs receipt-wired obligations");
541 assert_eq!(result.status, ObligationStatus::Passed); }
543
544 #[test]
545 fn receipt_query_in_a_repo_wired_obligation_is_a_binding_error() {
546 let obligation = repo_wired_obligation("OBL-BAD-01", vec![receipt_query_backend()]);
547 let attestations = exec::attestation::load_for_run(&workspace_root());
548 let result = run_one_scoped(&obligation, &workspace_root(), &attestations, None)
549 .expect("repo mode always produces a result for every obligation");
550 assert_eq!(result.status, ObligationStatus::Error);
551 assert_eq!(result.trust, Some(TrustLevel::Checked));
552 }
553
554 #[test]
555 fn repo_backend_in_a_receipt_wired_obligation_is_a_binding_error() {
556 let obligation = receipt_wired_obligation("OBL-BAD-02", vec![repo_backend()]);
557 let attestations = exec::attestation::load_for_run(&workspace_root());
558 let subject = subject();
559 let result = run_one_scoped(
560 &obligation,
561 &workspace_root(),
562 &attestations,
563 Some(&subject),
564 )
565 .expect("receipt mode runs receipt-wired obligations, including a broken one");
566 assert_eq!(result.status, ObligationStatus::Error);
567 }
568
569 #[test]
570 fn load_receipt_subject_hashes_and_parses_a_real_file() {
571 let dir = tempfile::tempdir().unwrap();
572 let path = dir.path().join("receipt.json");
573 std::fs::write(&path, r#"{"actions": []}"#).unwrap();
574 let subject = load_receipt_subject(&path).expect("must load");
575 assert!(subject.sha256.starts_with("sha256:"));
576 assert_eq!(subject.value, serde_json::json!({"actions": []}));
577 }
578
579 #[test]
580 fn load_receipt_subject_missing_file_has_no_sha256() {
581 let error = load_receipt_subject(std::path::Path::new("/nonexistent/receipt.json"))
582 .expect_err("missing file must error");
583 assert_eq!(error.sha256(), None);
584 }
585
586 #[test]
587 fn load_receipt_subject_malformed_json_still_reports_a_sha256() {
588 let dir = tempfile::tempdir().unwrap();
589 let path = dir.path().join("receipt.json");
590 std::fs::write(&path, "{ not json").unwrap();
591 let error = load_receipt_subject(&path).expect_err("malformed JSON must error");
592 assert!(error.sha256().is_some());
593 }
594}