1use std::collections::HashMap;
23use std::path::Path;
24
25use chrono::{DateTime, Utc};
26use ed25519_dalek::{Signature, Verifier, VerifyingKey};
27use hmac::{Hmac, Mac};
28use serde::{Deserialize, Serialize};
29use sha2::{Digest, Sha256};
30
31mod sorted_map {
38 use serde::Serialize;
39 use std::collections::BTreeMap;
40
41 pub fn serialize<S, K, V>(
42 value: &std::collections::HashMap<K, V>,
43 serializer: S,
44 ) -> Result<S::Ok, S::Error>
45 where
46 S: serde::Serializer,
47 K: Ord + serde::Serialize,
48 V: serde::Serialize,
49 {
50 let ordered: BTreeMap<&K, &V> = value.iter().collect();
51 ordered.serialize(serializer)
52 }
53}
54
55#[derive(Debug, thiserror::Error)]
57pub enum VerifyError {
58 #[error("envelope parse failed: {0}")]
59 Parse(#[from] serde_json::Error),
60 #[error("schema read failed: {0}")]
61 SchemaRead(String),
62 #[error("schema validation failed: {0}")]
63 Schema(String),
64 #[error("signature field is null")]
65 MissingSignature,
66 #[error("signature mismatch: expected {expected}, got {got}")]
67 SignatureMismatch { expected: String, got: String },
68 #[error("unsigned envelope without evidence_degraded=true (GAP-M-12 violation)")]
69 UnsignedNotDegraded,
70 #[error("HMAC key error: {0}")]
71 HmacKey(String),
72 #[error("audit chain broken: {detail}")]
73 ChainBroken { detail: String },
74 #[error("invalid Ed25519 anchor signature: {0}")]
75 AnchorSignature(String),
76 #[error(
77 "method `{0}` is not declared in the frozen rigorix.* catalog \
78 (ADR-0001 D3 — the namespace is closed; a server implements a subset)"
79 )]
80 UndeclaredMethod(String),
81 #[error("effect record invariant violated: {detail}")]
82 EffectInvariant { detail: String },
83 #[error("settlement evidence has no readback bytes to verify")]
84 ReadbackMissing,
85 #[error("readback digest mismatch: expected {expected}, got {got}")]
86 ReadbackDigestMismatch { expected: String, got: String },
87}
88
89pub type VerifyResult<T> = Result<T, VerifyError>;
90
91type HmacSha256 = Hmac<Sha256>;
92
93#[derive(Debug, Clone, Serialize, Deserialize)]
96pub struct AuditEnvelope {
97 pub execution_id: uuid::Uuid,
98 pub timestamp: DateTime<Utc>,
99 pub template_id: String,
100 pub planning_hash: String,
101 pub source: Option<String>,
102 pub repository: Option<String>,
103 pub author: Option<String>,
104 #[serde(default, skip_serializing_if = "Option::is_none")]
105 pub identity: Option<IdentityRef>,
106 #[serde(default, skip_serializing_if = "Option::is_none")]
111 pub effect_key: Option<String>,
112 pub total_tokens: u32,
113 pub duration_ms: u64,
114 pub git_commit: Option<String>,
115 pub git_branch: Option<String>,
116 pub model_version: Option<String>,
117 pub planning_prompt: Option<String>,
118 #[serde(default, skip_serializing_if = "Vec::is_empty")]
119 pub file_paths: Vec<String>,
120 pub events: Vec<ExecutionEventRef>,
121 #[serde(
122 default,
123 skip_serializing_if = "HashMap::is_empty",
124 serialize_with = "sorted_map::serialize"
125 )]
126 pub scoring_results: HashMap<String, ScoringResultRef>,
127 pub signature: Option<String>,
128 #[serde(default)]
129 pub evidence_degraded: bool,
130 #[serde(default, skip_serializing_if = "Option::is_none")]
135 pub producer_id: Option<String>,
136 #[serde(default, skip_serializing_if = "Option::is_none")]
138 pub sequence: Option<u64>,
139 #[serde(default, skip_serializing_if = "Option::is_none")]
142 pub prev_hash: Option<String>,
143 #[serde(default, skip_serializing_if = "Option::is_none")]
145 pub history_integrity: Option<HistoryIntegrity>,
146 #[serde(default, skip_serializing_if = "Option::is_none")]
149 pub history_policy: Option<HistoryPolicy>,
150 #[serde(default, skip_serializing_if = "Option::is_none")]
156 pub anchor_head: Option<String>,
157 #[serde(default, skip_serializing_if = "Vec::is_empty")]
158 pub approval_events: Vec<ApprovalRecordRef>,
159 #[serde(default, skip_serializing_if = "Vec::is_empty")]
160 pub scope_violations: Vec<ScopeViolationRef>,
161 #[serde(default, skip_serializing_if = "Option::is_none")]
167 pub scope_check: Option<ScopeCheckStatus>,
168 #[serde(default, skip_serializing_if = "Vec::is_empty")]
169 pub sequence_policy_findings: Vec<SequencePolicyFindingRef>,
170 #[serde(default, skip_serializing_if = "Vec::is_empty")]
173 pub requirement_findings: Vec<RequirementFindingRef>,
174 #[serde(default, skip_serializing_if = "Vec::is_empty")]
177 pub precondition_findings: Vec<PreconditionFindingRef>,
178 #[serde(default, skip_serializing_if = "Option::is_none")]
179 pub decision_context_ref: Option<String>,
180}
181
182#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
184#[serde(rename_all = "snake_case")]
185pub enum ScopeCheckStatus {
186 Checked,
187 NotDeclared,
188 Unavailable,
189}
190
191#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
193#[serde(rename_all = "snake_case")]
194pub enum HistoryIntegrity {
195 LocalUnanchored,
197 Anchored,
199 AnchoredPending,
202}
203
204#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
206#[serde(rename_all = "snake_case")]
207pub enum HistoryPolicy {
208 AllowUnanchored,
210}
211
212#[derive(Debug, Clone, Serialize, Deserialize)]
213pub struct IdentityRef {
214 pub subject: String,
215 pub issuer: String,
216 pub source: IdentitySource,
217 pub authority: Option<String>,
218 pub expires_at: Option<DateTime<Utc>>,
219}
220
221#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
222#[serde(rename_all = "snake_case")]
223pub enum IdentitySource {
224 IdpToken,
225 LocalPrincipal,
226 Unverified,
227}
228
229#[derive(Debug, Clone, Serialize, Deserialize)]
230pub struct ExecutionEventRef {
231 pub event_type: String,
232 pub summary: String,
233 pub occurred_at: DateTime<Utc>,
234 pub correlation_id: Option<uuid::Uuid>,
235 pub status: EventStatus,
236 #[serde(default, skip_serializing_if = "Option::is_none")]
237 pub payload: Option<serde_json::Value>,
238}
239
240#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
244pub enum EventStatus {
245 Success,
246 Failure,
247 Skipped,
248 Cancelled,
249}
250
251#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
253#[serde(rename_all = "snake_case")]
254pub enum IntentHashProvenance {
255 Derived,
257 Asserted,
259}
260
261#[derive(Debug, Clone, Serialize, Deserialize)]
262pub struct ApprovalRecordRef {
263 pub node_id: uuid::Uuid,
264 pub step_name: String,
265 pub intent_hash: String,
266 pub intent_hash_provenance: IntentHashProvenance,
269 pub approver_id: String,
270 pub authority: Option<String>,
271 pub decided_at: DateTime<Utc>,
272}
273
274#[derive(Debug, Clone, Serialize, Deserialize)]
275pub struct ScopeViolationRef {
276 pub node_id: uuid::Uuid,
277 pub step_name: String,
278 pub out_of_scope: Vec<String>,
279 pub detected_at: DateTime<Utc>,
280}
281
282#[derive(Debug, Clone, Serialize, Deserialize)]
283pub struct SequencePolicyFindingRef {
284 pub rule_id: String,
285 pub action: String,
286 pub later_step: String,
287 pub matched_indices: Vec<usize>,
288 pub summary: String,
289}
290
291#[derive(Debug, Clone, Serialize, Deserialize)]
294pub struct RequirementFindingRef {
295 pub requirement_id: String,
296 pub step: String,
297 pub action: String,
298 pub unmet: Vec<String>,
299 pub summary: String,
300}
301
302#[derive(Debug, Clone, Serialize, Deserialize)]
307pub struct PreconditionFindingRef {
308 pub precondition_id: String,
309 pub step: String,
310 pub outcome: String,
311 pub exit_code: Option<i32>,
312 pub inputs_hash: String,
313 pub checked_at: DateTime<Utc>,
314 pub summary: String,
315 #[serde(default, skip_serializing_if = "Option::is_none")]
318 pub check_digest: Option<String>,
319 #[serde(default, skip_serializing_if = "Option::is_none")]
322 pub authority_digest: Option<String>,
323 #[serde(default, skip_serializing_if = "Option::is_none")]
325 pub check_writable: Option<bool>,
326 #[serde(default, skip_serializing_if = "Option::is_none")]
331 pub attribution: Option<String>,
332}
333
334#[derive(Debug, Clone, Serialize, Deserialize)]
335pub struct ScoringResultRef {
336 pub passed: bool,
337 pub backend: String,
338 #[serde(serialize_with = "sorted_map::serialize")]
339 pub dimensions: HashMap<String, ScoreDimensionRef>,
340 pub duration_ms: u64,
341}
342
343#[derive(Debug, Clone, Serialize, Deserialize)]
344pub struct ScoreDimensionRef {
345 pub score: f64,
346 pub max: f64,
347 pub label: String,
348 pub passed: bool,
349}
350
351pub fn canonical_bytes(json: &str) -> VerifyResult<Vec<u8>> {
356 let envelope: AuditEnvelope = serde_json::from_str(json)?;
357 canonical_bytes_of(&envelope)
358}
359
360pub fn canonical_bytes_of(envelope: &AuditEnvelope) -> VerifyResult<Vec<u8>> {
364 let mut canonical = envelope.clone();
365 canonical.signature = None;
366 Ok(serde_json::to_vec(&canonical)?)
367}
368
369pub fn envelope_hash(json: &str) -> VerifyResult<String> {
372 let envelope: AuditEnvelope = serde_json::from_str(json)?;
373 envelope_hash_of(&envelope)
374}
375
376pub fn envelope_hash_of(envelope: &AuditEnvelope) -> VerifyResult<String> {
378 Ok(sha256_hex(&canonical_bytes_of(envelope)?))
379}
380
381fn sha256_hex(bytes: &[u8]) -> String {
382 let mut hasher = Sha256::new();
383 hasher.update(bytes);
384 hasher
385 .finalize()
386 .iter()
387 .map(|b| format!("{b:02x}"))
388 .collect()
389}
390
391fn truncate8(s: &str) -> &str {
392 &s[..s.len().min(8)]
393}
394
395fn chains_by_producer(envelopes: &[AuditEnvelope]) -> Vec<(String, Vec<&AuditEnvelope>)> {
399 let mut by_producer: HashMap<String, Vec<&AuditEnvelope>> = HashMap::new();
400 for envelope in envelopes {
401 if let (Some(producer), Some(_)) = (envelope.producer_id.as_deref(), envelope.sequence) {
402 by_producer
403 .entry(producer.to_string())
404 .or_default()
405 .push(envelope);
406 }
407 }
408 let mut producers: Vec<String> = by_producer.keys().cloned().collect();
409 producers.sort();
410 producers
411 .into_iter()
412 .map(|producer| {
413 let mut chain = by_producer.remove(&producer).unwrap_or_default();
414 chain.sort_by_key(|e| e.sequence.expect("filtered on Some(sequence)"));
415 (producer, chain)
416 })
417 .collect()
418}
419
420pub fn verify_chain(envelopes: &[AuditEnvelope]) -> VerifyResult<()> {
432 verify_chain_with_checkpoints(envelopes, &[], "")
433}
434
435pub fn verify_chain_with_checkpoints(
441 envelopes: &[AuditEnvelope],
442 checkpoints: &[CompactionCheckpoint],
443 anchor_public_key_hex: &str,
444) -> VerifyResult<()> {
445 for checkpoint in checkpoints {
447 verify_compaction_checkpoint(checkpoint, anchor_public_key_hex)?;
448 }
449
450 for (producer, chain) in chains_by_producer(envelopes) {
451 if chain.is_empty() {
452 continue;
453 }
454 let base = chain[0].sequence.expect("chained");
455 if base != 0 {
456 return Err(VerifyError::ChainBroken {
457 detail: format!(
458 "producer '{producer}': chain starts at sequence {base}, not genesis 0 — \
459 the earliest envelope(s) were deleted"
460 ),
461 });
462 }
463 if chain[0].prev_hash.is_some() {
464 return Err(VerifyError::ChainBroken {
465 detail: format!(
466 "producer '{producer}': genesis envelope carries a prev_hash — \
467 content was reordered into the genesis slot"
468 ),
469 });
470 }
471
472 for pair in chain.windows(2) {
473 let prev = pair[0];
474 let next = pair[1];
475 let prev_seq = prev.sequence.expect("chained");
476 let next_seq = next.sequence.expect("chained");
477 if next_seq <= prev_seq {
478 return Err(VerifyError::ChainBroken {
479 detail: format!(
480 "producer '{producer}': sequence not strictly increasing \
481 ({prev_seq} -> {next_seq}) — insertion/reorder"
482 ),
483 });
484 }
485 let prev_hash = envelope_hash_of(prev)?;
486 if next_seq == prev_seq + 1 {
487 match next.prev_hash.as_deref() {
488 Some(actual) if actual == prev_hash => {}
489 Some(actual) => {
490 return Err(VerifyError::ChainBroken {
491 detail: format!(
492 "producer '{producer}': prev_hash mismatch at sequence \
493 {next_seq} (expected {}…, got {}…)",
494 truncate8(&prev_hash),
495 truncate8(actual),
496 ),
497 });
498 }
499 None => {
500 return Err(VerifyError::ChainBroken {
501 detail: format!(
502 "producer '{producer}': missing prev_hash at sequence {next_seq}"
503 ),
504 });
505 }
506 }
507 continue;
508 }
509
510 let next_link = next
514 .prev_hash
515 .as_deref()
516 .ok_or_else(|| VerifyError::ChainBroken {
517 detail: format!(
518 "producer '{producer}': missing prev_hash after gap at sequence {next_seq}"
519 ),
520 })?;
521 let covered = checkpoints.iter().any(|c| {
522 c.sequence_from == prev_seq + 1
523 && c.sequence_to == next_seq - 1
524 && c.prior_head == prev_hash
525 && c.new_head == next_link
526 });
527 if !covered {
528 return Err(VerifyError::ChainBroken {
529 detail: format!(
530 "producer '{producer}': uncovered gap sequences {}..={} \
531 (missing envelopes with no valid compaction checkpoint)",
532 prev_seq + 1,
533 next_seq - 1,
534 ),
535 });
536 }
537 }
538 }
539 Ok(())
540}
541
542#[derive(Debug, Clone, Serialize, Deserialize)]
546pub struct LedgerReceipt {
547 pub ledger_id: String,
548 pub envelope_hash: String,
549 pub sequence: u64,
550 pub recorded_at: DateTime<Utc>,
551 pub sig: Option<String>,
553}
554
555#[derive(Debug, Clone, Serialize, Deserialize)]
558pub struct HistoryActionRef {
559 pub node: String,
560 pub principal: Option<String>,
561 pub at: DateTime<Utc>,
562 #[serde(default, skip_serializing_if = "Option::is_none")]
563 pub effect_key: Option<String>,
564}
565
566#[derive(Debug, Clone, Serialize, Deserialize)]
568pub struct HistorySlice {
569 pub scope: String,
570 pub since: DateTime<Utc>,
571 pub actions: Vec<HistoryActionRef>,
572 pub head_hash: String,
573 pub sig: Option<String>,
574}
575
576#[derive(Debug, Clone, Serialize, Deserialize)]
578pub struct CompactionCheckpoint {
579 pub sequence_from: u64,
580 pub sequence_to: u64,
581 pub reason: String,
582 pub prior_head: String,
583 pub new_head: String,
584 pub sig: Option<String>,
585}
586
587#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
597#[serde(rename_all = "snake_case")]
598pub enum EffectState {
599 Dispatched,
601 Committed,
603 NotCommitted,
605 Ambiguous,
608}
609
610impl EffectState {
611 pub fn is_terminal(&self) -> bool {
613 matches!(self, Self::Committed | Self::NotCommitted)
614 }
615
616 pub fn as_str(&self) -> &'static str {
618 match self {
619 Self::Dispatched => "dispatched",
620 Self::Committed => "committed",
621 Self::NotCommitted => "not_committed",
622 Self::Ambiguous => "ambiguous",
623 }
624 }
625}
626
627impl std::fmt::Display for EffectState {
628 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
629 f.write_str(self.as_str())
630 }
631}
632
633#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
635#[serde(rename_all = "snake_case")]
636pub enum OutcomeVerdict {
637 Committed,
638 NotCommitted,
639}
640
641impl OutcomeVerdict {
642 pub fn terminal_state(&self) -> EffectState {
644 match self {
645 Self::Committed => EffectState::Committed,
646 Self::NotCommitted => EffectState::NotCommitted,
647 }
648 }
649
650 pub fn as_str(&self) -> &'static str {
652 match self {
653 Self::Committed => "committed",
654 Self::NotCommitted => "not_committed",
655 }
656 }
657}
658
659#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
661#[serde(rename_all = "snake_case")]
662pub enum ResolverKind {
663 Operator,
664 Reconciler,
665 BreakGlass,
666}
667
668#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
670pub struct ResolverIdentity {
671 pub actor: String,
672 pub kind: ResolverKind,
673}
674
675#[derive(Debug, Clone, Serialize, Deserialize)]
677pub struct EffectRecord {
678 pub id: uuid::Uuid,
679 pub intent_key: String,
680 pub dag_id: String,
681 pub node_id: String,
682 pub attempt: u32,
683 pub state: EffectState,
684 pub dispatched_by: String,
685 pub deadline: Option<DateTime<Utc>>,
686 pub reason: Option<String>,
687 pub created_at: DateTime<Utc>,
688}
689
690#[derive(Debug, Clone, Serialize, Deserialize)]
693pub struct SettlementEvidence {
694 pub receipt_id: String,
695 pub readback_digest: String,
696 pub observed_at: DateTime<Utc>,
697 pub source: String,
698 pub verdict: OutcomeVerdict,
699 #[serde(default, skip_serializing_if = "Option::is_none")]
702 pub readback: Option<String>,
703 #[serde(default, skip_serializing_if = "Option::is_none")]
705 pub resolver: Option<ResolverIdentity>,
706}
707
708#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
710#[serde(rename_all = "lowercase")]
711pub enum Durability {
712 L1,
714 L2,
716}
717
718#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
720#[serde(rename_all = "lowercase")]
721pub enum SettlementLevel {
722 None,
724 L3,
726}
727
728#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
733pub struct ClaimLevels {
734 pub durability: Durability,
735 pub settlement: SettlementLevel,
736}
737
738#[derive(Debug, Clone, Serialize, Deserialize)]
740pub struct EffectRecordArtifact {
741 pub record: EffectRecord,
742 #[serde(default, skip_serializing_if = "Option::is_none")]
745 pub settlement: Option<SettlementEvidence>,
746 pub levels: ClaimLevels,
747}
748
749pub fn ledger_receipt_signing_bytes(receipt: &LedgerReceipt) -> VerifyResult<Vec<u8>> {
751 let mut unsigned = receipt.clone();
752 unsigned.sig = None;
753 Ok(serde_json::to_vec(&unsigned)?)
754}
755
756pub fn history_slice_signing_bytes(slice: &HistorySlice) -> VerifyResult<Vec<u8>> {
758 let mut unsigned = slice.clone();
759 unsigned.sig = None;
760 Ok(serde_json::to_vec(&unsigned)?)
761}
762
763pub fn compaction_checkpoint_signing_bytes(
765 checkpoint: &CompactionCheckpoint,
766) -> VerifyResult<Vec<u8>> {
767 let mut unsigned = checkpoint.clone();
768 unsigned.sig = None;
769 Ok(serde_json::to_vec(&unsigned)?)
770}
771
772fn public_key_from_hex(public_key_hex: &str) -> VerifyResult<VerifyingKey> {
773 let bytes = hex::decode(public_key_hex)
774 .map_err(|e| VerifyError::AnchorSignature(format!("public key hex: {e}")))?;
775 let arr: [u8; 32] = bytes
776 .as_slice()
777 .try_into()
778 .map_err(|_| VerifyError::AnchorSignature("public key must be 32 bytes".to_string()))?;
779 VerifyingKey::from_bytes(&arr).map_err(|e| VerifyError::AnchorSignature(e.to_string()))
780}
781
782pub fn verify_ed25519(canonical: &[u8], sig_hex: &str, public_key_hex: &str) -> VerifyResult<()> {
785 let key = public_key_from_hex(public_key_hex)?;
786 let sig_bytes = hex::decode(sig_hex)
787 .map_err(|e| VerifyError::AnchorSignature(format!("signature hex: {e}")))?;
788 let arr: [u8; 64] = sig_bytes
789 .as_slice()
790 .try_into()
791 .map_err(|_| VerifyError::AnchorSignature("signature must be 64 bytes".to_string()))?;
792 let signature = Signature::from_bytes(&arr);
793 key.verify(canonical, &signature)
794 .map_err(|e| VerifyError::AnchorSignature(e.to_string()))
795}
796
797pub fn verify_ledger_receipt(receipt: &LedgerReceipt, public_key_hex: &str) -> VerifyResult<()> {
799 let sig = receipt.sig.clone().unwrap_or_default();
800 verify_ed25519(
801 &ledger_receipt_signing_bytes(receipt)?,
802 &sig,
803 public_key_hex,
804 )
805}
806
807pub fn verify_history_slice(slice: &HistorySlice, public_key_hex: &str) -> VerifyResult<()> {
809 let sig = slice.sig.clone().unwrap_or_default();
810 verify_ed25519(&history_slice_signing_bytes(slice)?, &sig, public_key_hex)
811}
812
813pub fn verify_compaction_checkpoint(
815 checkpoint: &CompactionCheckpoint,
816 public_key_hex: &str,
817) -> VerifyResult<()> {
818 let sig = checkpoint.sig.clone().unwrap_or_default();
819 verify_ed25519(
820 &compaction_checkpoint_signing_bytes(checkpoint)?,
821 &sig,
822 public_key_hex,
823 )
824}
825
826pub fn verify_effect_record(artifact: &EffectRecordArtifact) -> VerifyResult<()> {
839 let record = &artifact.record;
840
841 if record.state == EffectState::Dispatched && record.deadline.is_none() {
842 return Err(VerifyError::EffectInvariant {
843 detail: "dispatched record must carry a deadline".to_string(),
844 });
845 }
846
847 match (record.state.is_terminal(), artifact.settlement.as_ref()) {
848 (true, None) => {
849 return Err(VerifyError::EffectInvariant {
850 detail: format!(
851 "terminal state `{}` must carry settlement evidence (EvidenceMissing)",
852 record.state
853 ),
854 });
855 }
856 (false, Some(_)) => {
857 return Err(VerifyError::EffectInvariant {
858 detail: format!(
859 "non-terminal state `{}` must not carry settlement evidence (Contended)",
860 record.state
861 ),
862 });
863 }
864 _ => {}
865 }
866
867 if let Some(settlement) = artifact.settlement.as_ref() {
868 let authorised = settlement.verdict.terminal_state();
869 if authorised != record.state {
870 return Err(VerifyError::EffectInvariant {
871 detail: format!(
872 "settlement verdict `{}` authorises `{}`, but the record is `{}`",
873 settlement.verdict.as_str(),
874 authorised,
875 record.state
876 ),
877 });
878 }
879 if artifact.levels.settlement != SettlementLevel::L3 {
880 return Err(VerifyError::EffectInvariant {
881 detail: "settlement evidence is present but levels.settlement is `none`"
882 .to_string(),
883 });
884 }
885 }
886
887 Ok(())
888}
889
890pub fn verify_settlement_evidence(artifact: &EffectRecordArtifact) -> VerifyResult<()> {
897 verify_effect_record(artifact)?;
898 let settlement = artifact
899 .settlement
900 .as_ref()
901 .ok_or_else(|| VerifyError::EffectInvariant {
902 detail: "no settlement evidence to verify".to_string(),
903 })?;
904 let readback = settlement
905 .readback
906 .as_ref()
907 .ok_or(VerifyError::ReadbackMissing)?;
908 let got = hex::encode(Sha256::digest(readback.as_bytes()));
909 if got != settlement.readback_digest {
910 return Err(VerifyError::ReadbackDigestMismatch {
911 expected: settlement.readback_digest.clone(),
912 got,
913 });
914 }
915 Ok(())
916}
917
918pub fn sign(json: &str, key: &str) -> VerifyResult<String> {
920 let mut mac = HmacSha256::new_from_slice(key.as_bytes())
921 .map_err(|e| VerifyError::HmacKey(e.to_string()))?;
922 mac.update(&canonical_bytes(json)?);
923 Ok(hex::encode(mac.finalize().into_bytes()))
924}
925
926pub fn verify_signature(json: &str, key: &str) -> VerifyResult<()> {
932 let envelope: AuditEnvelope = serde_json::from_str(json)?;
933 let Some(expected) = envelope.signature.as_ref() else {
934 if envelope.evidence_degraded {
935 return Ok(()); }
937 return Err(VerifyError::UnsignedNotDegraded);
938 };
939 let got = sign(json, key)?;
940 if constant_time_eq(expected, &got) {
941 Ok(())
942 } else {
943 Err(VerifyError::SignatureMismatch {
944 expected: expected.clone(),
945 got,
946 })
947 }
948}
949
950pub fn validate_schema(json: &str) -> VerifyResult<()> {
955 validate_schema_file("envelope.json", json)
956}
957
958fn validate_schema_file(file: &str, json: &str) -> VerifyResult<()> {
960 let schema_text = schema_text(file)?;
961 let schema = serde_json::from_str(&schema_text)?;
962 let instance: serde_json::Value = serde_json::from_str(json)?;
963 let compiled = build_validator(file, &schema)?;
964 let errors: Vec<String> = compiled
965 .iter_errors(&instance)
966 .map(|e| e.to_string())
967 .collect();
968 if !errors.is_empty() {
969 return Err(VerifyError::Schema(errors.join("; ")));
970 }
971 Ok(())
972}
973
974fn schema_text(file: &str) -> VerifyResult<String> {
982 if let Ok(dir) = std::env::var("RIGORIX_SDK_SCHEMAS") {
983 let path = Path::new(&dir).join(file);
984 if !path.exists() {
985 return Err(VerifyError::SchemaRead(format!(
986 "RIGORIX_SDK_SCHEMAS set but {} missing",
987 path.display()
988 )));
989 }
990 return std::fs::read_to_string(&path)
991 .map_err(|e| VerifyError::SchemaRead(format!("{}: {e}", path.display())));
992 }
993 rigorix_schemas::schema(file)
994 .map(str::to_string)
995 .ok_or_else(|| {
996 VerifyError::SchemaRead(format!(
997 "schema `{file}` not found — set RIGORIX_SDK_SCHEMAS or use the embedded \
998 rigorix-schemas corpus"
999 ))
1000 })
1001}
1002
1003pub fn verify_catalog_subset(candidate: &[&str]) -> VerifyResult<()> {
1011 let text = schema_text("api/catalog.json")?;
1012 let catalog: serde_json::Value = serde_json::from_str(&text)?;
1013 let declared: std::collections::HashSet<&str> = catalog["methods"]
1014 .as_array()
1015 .ok_or_else(|| VerifyError::Schema("catalog.json: methods is not an array".to_string()))?
1016 .iter()
1017 .filter_map(|method| method["name"].as_str())
1018 .collect();
1019 for method in candidate {
1020 if !declared.contains(method) {
1021 return Err(VerifyError::UndeclaredMethod((*method).to_string()));
1022 }
1023 }
1024 Ok(())
1025}
1026
1027const ENVELOPE_SCHEMA_ID: &str = "https://rigorix.eu/schemas/envelope-v2.json";
1030
1031const CLAIMS_SCHEMA_ID: &str = "https://rigorix.eu/schemas/claims.json";
1035
1036const HISTORY_SLICE_SCHEMA_ID: &str = "https://rigorix.eu/schemas/api/history-slice-v1.json";
1039
1040const AUTHORITY_FACT_BUNDLE_SCHEMA_ID: &str =
1044 "https://rigorix.eu/schemas/api/authority-fact-bundle-v1.json";
1045
1046fn build_validator(file: &str, schema: &serde_json::Value) -> VerifyResult<jsonschema::Validator> {
1052 let mut options = jsonschema::options();
1053 for (sibling, id) in [
1054 ("envelope.json", ENVELOPE_SCHEMA_ID),
1055 ("claims.json", CLAIMS_SCHEMA_ID),
1056 ("api/history-slice.json", HISTORY_SLICE_SCHEMA_ID),
1057 (
1058 "api/authority-fact-bundle.json",
1059 AUTHORITY_FACT_BUNDLE_SCHEMA_ID,
1060 ),
1061 ] {
1062 if file == sibling {
1063 continue;
1064 }
1065 let text = schema_text(sibling)?;
1066 let value: serde_json::Value = serde_json::from_str(&text)?;
1067 let resource = jsonschema::Resource::from_contents(value)
1068 .map_err(|e| VerifyError::Schema(e.to_string()))?;
1069 options.with_resource(id, resource);
1070 }
1071 options
1072 .build(schema)
1073 .map_err(|e| VerifyError::Schema(e.to_string()))
1074}
1075
1076fn constant_time_eq(a: &str, b: &str) -> bool {
1078 if a.len() != b.len() {
1079 return false;
1080 }
1081 a.bytes()
1082 .zip(b.bytes())
1083 .fold(0u8, |acc, (x, y)| acc | (x ^ y))
1084 == 0
1085}
1086
1087#[cfg(test)]
1088mod tests {
1089 use super::*;
1090
1091 fn fixture_text(rel: &str) -> String {
1098 if let Ok(dir) = std::env::var("RIGORIX_SDK_SCHEMAS") {
1099 let path = Path::new(&dir).join("fixtures").join(rel);
1100 return std::fs::read_to_string(&path)
1101 .unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
1102 }
1103 rigorix_schemas::fixture(rel)
1104 .map(str::to_string)
1105 .unwrap_or_else(|| panic!("fixture `{rel}` is not embedded in rigorix-schemas"))
1106 }
1107
1108 fn fixture_json_names(prefix: &str) -> Vec<String> {
1110 if let Ok(dir) = std::env::var("RIGORIX_SDK_SCHEMAS") {
1111 let root = Path::new(&dir).join("fixtures").join(prefix);
1112 let mut out = Vec::new();
1113 collect_json(&root, &root, &mut out);
1114 out.sort();
1115 return out;
1116 }
1117 let needle = format!("fixtures/{prefix}/");
1118 let mut out: Vec<String> = rigorix_schemas::schema_names()
1119 .iter()
1120 .filter_map(|name| name.strip_prefix(&needle))
1121 .filter(|rel| rel.ends_with(".json"))
1122 .map(str::to_string)
1123 .collect();
1124 out.sort();
1125 out
1126 }
1127
1128 fn collect_json(root: &Path, dir: &Path, out: &mut Vec<String>) {
1129 let entries =
1130 std::fs::read_dir(dir).unwrap_or_else(|e| panic!("read {}: {e}", dir.display()));
1131 for entry in entries {
1132 let path = entry.expect("dir entry").path();
1133 if path.is_dir() {
1134 collect_json(root, &path, out);
1135 } else if path.extension().and_then(|e| e.to_str()) == Some("json") {
1136 out.push(
1137 path.strip_prefix(root)
1138 .expect("under fixture root")
1139 .to_string_lossy()
1140 .replace('\\', "/"),
1141 );
1142 }
1143 }
1144 }
1145
1146 const KEY: &str = "test-hmac-key";
1147
1148 fn minimal_envelope() -> String {
1149 serde_json::json!({
1150 "execution_id": "c24a5a7e-1f4d-4f0e-9b3a-8e0d3a1b2c3d",
1151 "timestamp": "2026-09-07T10:00:00Z",
1152 "template_id": "conference-registration",
1153 "planning_hash": "abc123",
1154 "total_tokens": 1000,
1155 "duration_ms": 5000,
1156 "events": [
1157 {
1158 "event_type": "tool_executed",
1159 "summary": "removed alice",
1160 "occurred_at": "2026-09-07T09:59:59Z",
1161 "status": "Success"
1162 }
1163 ],
1164 "signature": null,
1165 "evidence_degraded": false
1166 })
1167 .to_string()
1168 }
1169
1170 fn signed_envelope() -> String {
1171 let json = minimal_envelope();
1172 let sig = sign(&json, KEY).unwrap();
1173 let mut v: serde_json::Value = serde_json::from_str(&json).unwrap();
1174 v["signature"] = serde_json::Value::String(sig);
1175 v.to_string()
1176 }
1177
1178 #[test]
1179 fn sign_and_verify_roundtrip() {
1180 let envelope = signed_envelope();
1181 assert!(verify_signature(&envelope, KEY).is_ok());
1182 }
1183
1184 #[test]
1185 fn tampering_detected() {
1186 let mut v: serde_json::Value = serde_json::from_str(&signed_envelope()).unwrap();
1187 v["total_tokens"] = serde_json::json!(9999); let err = verify_signature(&v.to_string(), KEY).unwrap_err();
1189 assert!(matches!(err, VerifyError::SignatureMismatch { .. }));
1190 }
1191
1192 #[test]
1193 fn unsigned_must_be_degraded() {
1194 let err = verify_signature(&minimal_envelope(), KEY).unwrap_err();
1196 assert!(matches!(err, VerifyError::UnsignedNotDegraded));
1197 }
1198
1199 #[test]
1200 fn unsigned_marked_degraded_is_ok() {
1201 let mut v: serde_json::Value = serde_json::from_str(&minimal_envelope()).unwrap();
1202 v["evidence_degraded"] = serde_json::json!(true);
1203 assert!(verify_signature(&v.to_string(), KEY).is_ok());
1204 }
1205
1206 #[test]
1207 fn wrong_key_fails() {
1208 let envelope = signed_envelope();
1209 let err = verify_signature(&envelope, "wrong-key").unwrap_err();
1210 assert!(matches!(err, VerifyError::SignatureMismatch { .. }));
1211 }
1212
1213 #[test]
1214 fn canonical_stability() {
1215 let a = canonical_bytes(&minimal_envelope()).unwrap();
1217 let b = canonical_bytes(&minimal_envelope()).unwrap();
1218 assert_eq!(a, b);
1219 }
1220
1221 #[test]
1222 fn schema_conformance_of_minimal() {
1223 assert!(validate_schema(&minimal_envelope()).is_ok());
1227 }
1228
1229 #[test]
1230 fn schema_rejects_wrong_status_case() {
1231 let mut v: serde_json::Value = serde_json::from_str(&minimal_envelope()).unwrap();
1234 v["events"][0]["status"] = serde_json::json!("success");
1235 let err = validate_schema(&v.to_string()).unwrap_err();
1236 assert!(matches!(err, VerifyError::Schema(_)));
1237 }
1238
1239 #[test]
1244 fn policy_schema_round_trips_step_requirement() {
1245 let policy = serde_json::json!({
1246 "fail_closed": true,
1247 "rules": [],
1248 "requirements": [{
1249 "id": "payout-guard",
1250 "name": "Payout commands must be attested and carry effect data",
1251 "description": "d",
1252 "match": {
1253 "tool": "run_command",
1254 "params": [{
1255 "pointer": "/command",
1256 "kind": "glob",
1257 "value": "*execute_payout.sh*"
1258 }]
1259 },
1260 "require_identity": true,
1261 "require_params": ["/beneficiary", "/effect_key"],
1262 "action": "deny"
1263 }]
1264 });
1265 assert!(validate_schema_file("policy.json", &policy.to_string()).is_ok());
1266
1267 let mut defaulted = policy.clone();
1269 defaulted["requirements"][0]
1270 .as_object_mut()
1271 .unwrap()
1272 .remove("action");
1273 assert!(validate_schema_file("policy.json", &defaulted.to_string()).is_ok());
1274
1275 let mut missing_name = policy.clone();
1277 missing_name["requirements"][0]
1278 .as_object_mut()
1279 .unwrap()
1280 .remove("name");
1281 assert!(validate_schema_file("policy.json", &missing_name.to_string()).is_err());
1282
1283 let mut bad_pointer = policy.clone();
1285 bad_pointer["requirements"][0]["require_params"] = serde_json::json!(["beneficiary"]);
1286 assert!(validate_schema_file("policy.json", &bad_pointer.to_string()).is_err());
1287 }
1288
1289 #[test]
1290 fn envelope_schema_accepts_requirement_findings() {
1291 let mut v: serde_json::Value = serde_json::from_str(&minimal_envelope()).unwrap();
1292 v["requirement_findings"] = serde_json::json!([{
1293 "requirement_id": "payout-guard",
1294 "step": "pay",
1295 "action": "deny",
1296 "unmet": ["identity", "/beneficiary"],
1297 "summary": "operator requirement 'payout-guard' denied step 'pay'"
1298 }]);
1299 assert!(validate_schema(&v.to_string()).is_ok());
1300
1301 let mut bad = v.clone();
1303 bad["requirement_findings"][0]
1304 .as_object_mut()
1305 .unwrap()
1306 .remove("unmet");
1307 assert!(validate_schema(&bad.to_string()).is_err());
1308
1309 let mut wrong_action = v.clone();
1311 wrong_action["requirement_findings"][0]["action"] = serde_json::json!("DENY");
1312 assert!(validate_schema(&wrong_action.to_string()).is_err());
1313 }
1314
1315 #[test]
1323 fn engine_signed_fixtures_verify_byte_exact() {
1324 let key = "fixture-hmac-key-2026";
1325 let names = fixture_json_names("envelope");
1326 let mut found = 0;
1327 for name in &names {
1328 let json = fixture_text(&format!("envelope/{name}"));
1329 verify_signature(&json, key).unwrap_or_else(|e| panic!("{name}: {e}"));
1331 validate_schema(&json).unwrap_or_else(|e| panic!("{name}: {e}"));
1333 found += 1;
1334 }
1335 assert!(
1336 found >= 3,
1337 "expected ≥3 committed engine fixtures, found {found}"
1338 );
1339 }
1340
1341 #[test]
1345 fn approval_ref_provenance_is_required_and_signed() {
1346 let json = fixture_text("envelope/envelope-rich-signed.json");
1347 let envelope: AuditEnvelope = serde_json::from_str(&json).expect("fixture parses");
1348 let approval = envelope
1349 .approval_events
1350 .first()
1351 .expect("rich fixture carries an approval");
1352 assert_eq!(
1353 approval.intent_hash_provenance,
1354 IntentHashProvenance::Derived,
1355 "the OSS engine emits derived intent hashes"
1356 );
1357
1358 let mut value: serde_json::Value = serde_json::from_str(&json).expect("json");
1359 let refs = value["approval_events"]
1360 .as_array_mut()
1361 .expect("approval_events");
1362 refs[0]["intent_hash_provenance"] = serde_json::json!("asserted");
1363 let asserted = serde_json::to_string(&value).expect("serialize");
1364 validate_schema(&asserted).expect("asserted is a valid, weaker kind");
1365 let asserted_envelope: AuditEnvelope =
1366 serde_json::from_value(value.clone()).expect("asserted parses");
1367 assert_eq!(
1368 asserted_envelope.approval_events[0].intent_hash_provenance,
1369 IntentHashProvenance::Asserted
1370 );
1371
1372 value["approval_events"][0]
1373 .as_object_mut()
1374 .expect("approval ref")
1375 .remove("intent_hash_provenance");
1376 let missing = serde_json::to_string(&value).expect("serialize");
1377 assert!(
1378 validate_schema(&missing).is_err(),
1379 "schema must reject an approval ref that does not state provenance"
1380 );
1381 assert!(
1382 serde_json::from_value::<AuditEnvelope>(value).is_err(),
1383 "deserialization must reject a missing provenance, not default it"
1384 );
1385 }
1386
1387 #[test]
1392 fn anchored_envelope_binds_anchor_head_at_engine_position() {
1393 const HEAD: &str = "3f2a9c1e7b4d5f6081a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f708";
1394 let json = fixture_text("envelope/envelope-anchored-signed.json");
1395 let envelope: AuditEnvelope = serde_json::from_str(&json).expect("anchored fixture parses");
1396 assert_eq!(envelope.history_integrity, Some(HistoryIntegrity::Anchored));
1397 assert_eq!(envelope.anchor_head.as_deref(), Some(HEAD));
1398 assert!(
1399 !envelope.approval_events.is_empty(),
1400 "fixture must carry approval_events (position proof)"
1401 );
1402
1403 verify_signature(&json, "fixture-hmac-key-2026")
1405 .expect("anchored fixture verifies byte-exact");
1406 validate_schema(&json).expect("anchored fixture conforms to envelope.json");
1407
1408 let bytes = canonical_bytes_of(&envelope).expect("canonical bytes");
1410 let canonical = String::from_utf8(bytes).expect("utf8");
1411 let head_at = canonical
1412 .find("\"anchor_head\"")
1413 .expect("anchor_head is part of the signed bytes");
1414 let approvals_at = canonical
1415 .find("\"approval_events\"")
1416 .expect("approval_events present");
1417 assert!(
1418 head_at < approvals_at,
1419 "anchor_head must precede approval_events"
1420 );
1421
1422 let tampered = json.replacen(HEAD, &"0".repeat(64), 1);
1424 assert!(matches!(
1425 verify_signature(&tampered, "fixture-hmac-key-2026"),
1426 Err(VerifyError::SignatureMismatch { .. })
1427 ));
1428
1429 let local = fixture_text("envelope/envelope-minimal-signed.json");
1432 assert!(!local.contains("\"anchor_head\""));
1433 verify_signature(&local, "fixture-hmac-key-2026").expect("local fixture unchanged");
1434 }
1435
1436 #[test]
1442 #[ignore = "writes the ADR-017 precondition fixture (contract-first)"]
1443 fn generate_precondition_fixture() {
1444 let base = fixture_text("envelope/envelope-minimal-signed.json");
1445 let mut value: serde_json::Value =
1446 serde_json::from_str(&base).expect("minimal fixture parses");
1447 let obj = value.as_object_mut().expect("object");
1448 let _ = obj.remove("signature");
1449 obj.insert(
1450 "precondition_findings".to_string(),
1451 serde_json::json!([
1452 {
1453 "precondition_id": "beneficiary-eligible",
1454 "step": "risky_step",
1455 "outcome": "failed",
1456 "exit_code": 3,
1457 "inputs_hash": "5f2a9c1e7b4d5f6081a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f708",
1458 "checked_at": "2026-10-01T12:00:00Z",
1459 "summary": "authority check denied dispatch (exit 3)",
1460 "check_digest": "sha256:1111111111111111111111111111111111111111111111111111111111111111",
1461 "authority_digest": "sha256:2222222222222222222222222222222222222222222222222222222222222222",
1462 "check_writable": false,
1463 "attribution": "recorded"
1464 },
1465 {
1466 "precondition_id": "account-open",
1467 "step": "run_command",
1468 "outcome": "passed",
1469 "exit_code": 0,
1470 "inputs_hash": "1c2b3a495867798a0b1c2d3e4f5061728394a5b6c7d8e9f0a1b2c3d4e5f60718",
1471 "checked_at": "2026-10-01T12:00:01Z",
1472 "summary": "authority stands",
1473 "check_digest": "sha256:1111111111111111111111111111111111111111111111111111111111111111",
1474 "check_writable": true,
1475 "attribution": "recorded"
1476 },
1477 {
1478 "precondition_id": "network-eligible",
1479 "step": "run_command",
1480 "outcome": "error",
1481 "exit_code": null,
1482 "inputs_hash": "9e8d7c6b5a4938271605f4e3d2c1b0a99887766554433221100ffeeddccbbaa",
1483 "checked_at": "2026-10-01T12:00:02Z",
1484 "summary": "check refused before it ran",
1485 "attribution": "refused_before_check"
1486 },
1487 {
1488 "precondition_id": "payout-authority",
1489 "step": "run_command",
1490 "outcome": "failed",
1491 "exit_code": 5,
1492 "inputs_hash": "0a1b2c3d4e5f60718293a4b5c6d7e8f90123456789abcdef0123456789abcdef",
1493 "checked_at": "2026-10-01T12:00:03Z",
1494 "summary": "authority check denied dispatch (exit 5)",
1495 "check_digest": "sha256:1111111111111111111111111111111111111111111111111111111111111111",
1496 "attribution": "artifact_unreadable"
1497 }
1498 ]),
1499 );
1500 let signature = sign(&value.to_string(), FIXTURE_KEY).expect("sign fixture");
1501 let mut envelope: AuditEnvelope =
1502 serde_json::from_value(value).expect("fixture parses into AuditEnvelope");
1503 envelope.signature = Some(signature);
1504 let json = serde_json::to_string_pretty(&envelope).expect("serialize fixture");
1505 let path = Path::new(env!("CARGO_MANIFEST_DIR"))
1506 .join("../../schemas/fixtures/envelope/envelope-precondition-signed.json");
1507 std::fs::write(&path, format!("{json}\n")).expect("write fixture");
1508 eprintln!("wrote {}", path.display());
1509 }
1510
1511 #[test]
1519 #[ignore = "writes the anchored_pending fixture (contract-first)"]
1520 fn generate_anchored_pending_fixture() {
1521 let base = fixture_text("envelope/envelope-anchored-signed.json");
1522 let mut value: serde_json::Value =
1523 serde_json::from_str(&base).expect("anchored fixture parses");
1524 let obj = value.as_object_mut().expect("object");
1525 let _ = obj.remove("signature");
1526 let _ = obj.remove("anchor_head");
1528 obj.insert(
1529 "history_integrity".to_string(),
1530 serde_json::json!("anchored_pending"),
1531 );
1532 let signature = sign(&value.to_string(), FIXTURE_KEY).expect("sign fixture");
1533 let mut envelope: AuditEnvelope =
1534 serde_json::from_value(value).expect("fixture parses into AuditEnvelope");
1535 assert_eq!(
1536 envelope.history_integrity,
1537 Some(HistoryIntegrity::AnchoredPending)
1538 );
1539 assert!(envelope.anchor_head.is_none());
1540 envelope.signature = Some(signature);
1541 let json = serde_json::to_string_pretty(&envelope).expect("serialize fixture");
1542 let path = Path::new(env!("CARGO_MANIFEST_DIR"))
1543 .join("../../schemas/fixtures/envelope/envelope-anchored-pending-signed.json");
1544 std::fs::write(&path, format!("{json}\n")).expect("write fixture");
1545 eprintln!("wrote {}", path.display());
1546 }
1547
1548 #[test]
1551 fn anchored_pending_fixture_verifies() {
1552 let json = fixture_text("envelope/envelope-anchored-pending-signed.json");
1553 let envelope: AuditEnvelope = serde_json::from_str(&json).expect("fixture parses");
1554 assert_eq!(
1555 envelope.history_integrity,
1556 Some(HistoryIntegrity::AnchoredPending)
1557 );
1558 assert!(envelope.anchor_head.is_none(), "nothing was verified");
1559 assert_ne!(
1560 envelope.history_integrity,
1561 Some(HistoryIntegrity::Anchored),
1562 "anchored_pending must not be treated as authenticated"
1563 );
1564 verify_signature(&json, FIXTURE_KEY).expect("fixture verifies byte-exact");
1565 validate_schema(&json).expect("fixture conforms to envelope.json");
1566
1567 let tampered = json.replacen("anchored_pending", "anchored", 1);
1569 assert!(matches!(
1570 verify_signature(&tampered, FIXTURE_KEY),
1571 Err(VerifyError::SignatureMismatch { .. })
1572 ));
1573 }
1574
1575 #[test]
1578 fn precondition_findings_fixture_verifies() {
1579 let json = fixture_text("envelope/envelope-precondition-signed.json");
1580 let envelope: AuditEnvelope = serde_json::from_str(&json).expect("fixture parses");
1581 assert_eq!(envelope.precondition_findings.len(), 4);
1582 assert_eq!(envelope.precondition_findings[0].outcome, "failed");
1583 assert_eq!(envelope.precondition_findings[0].exit_code, Some(3));
1584 assert_eq!(envelope.precondition_findings[1].outcome, "passed");
1585 assert_eq!(envelope.precondition_findings[1].exit_code, Some(0));
1586 assert_eq!(envelope.precondition_findings[2].outcome, "error");
1587 assert_eq!(envelope.precondition_findings[2].exit_code, None);
1588 assert_eq!(envelope.precondition_findings[3].outcome, "failed");
1589 assert_eq!(envelope.precondition_findings[3].exit_code, Some(5));
1590 assert_eq!(
1592 envelope.precondition_findings[0].check_digest.as_deref(),
1593 Some("sha256:1111111111111111111111111111111111111111111111111111111111111111")
1594 );
1595 assert_eq!(
1596 envelope.precondition_findings[0]
1597 .authority_digest
1598 .as_deref(),
1599 Some("sha256:2222222222222222222222222222222222222222222222222222222222222222")
1600 );
1601 assert_eq!(
1602 envelope.precondition_findings[0].check_writable,
1603 Some(false)
1604 );
1605 assert_eq!(
1607 envelope.precondition_findings[0].attribution.as_deref(),
1608 Some("recorded")
1609 );
1610 assert_eq!(
1611 envelope.precondition_findings[1].attribution.as_deref(),
1612 Some("recorded")
1613 );
1614 assert_eq!(
1615 envelope.precondition_findings[2].attribution.as_deref(),
1616 Some("refused_before_check")
1617 );
1618 assert_eq!(
1619 envelope.precondition_findings[3].attribution.as_deref(),
1620 Some("artifact_unreadable")
1621 );
1622 assert_eq!(envelope.precondition_findings[2].check_digest, None);
1624 assert_eq!(envelope.precondition_findings[2].authority_digest, None);
1625 assert_eq!(
1627 envelope.precondition_findings[3].check_digest.as_deref(),
1628 Some("sha256:1111111111111111111111111111111111111111111111111111111111111111")
1629 );
1630 assert_eq!(envelope.precondition_findings[3].authority_digest, None);
1631
1632 verify_signature(&json, "fixture-hmac-key-2026").expect("byte-exact");
1633 validate_schema(&json).expect("schema conformance");
1634
1635 let tampered = json.replacen("\"exit_code\": 3", "\"exit_code\": 0", 1);
1636 assert!(matches!(
1637 verify_signature(&tampered, "fixture-hmac-key-2026"),
1638 Err(VerifyError::SignatureMismatch { .. })
1639 ));
1640
1641 let forged = json.replacen(
1643 "sha256:2222222222222222222222222222222222222222222222222222222222222222",
1644 "sha256:3333333333333333333333333333333333333333333333333333333333333333",
1645 1,
1646 );
1647 assert!(matches!(
1648 verify_signature(&forged, "fixture-hmac-key-2026"),
1649 Err(VerifyError::SignatureMismatch { .. })
1650 ));
1651
1652 let legacy = fixture_text("envelope/envelope-minimal-signed.json");
1653 assert!(!legacy.contains("precondition_findings"));
1654 verify_signature(&legacy, "fixture-hmac-key-2026").expect("legacy unchanged");
1655 }
1656
1657 #[test]
1663 fn all_schemas_compile() {
1664 for name in [
1665 "envelope.json",
1666 "claims.json",
1667 "policy.json",
1668 "api/catalog.schema.json",
1669 "api/errors.json",
1670 "api/events.json",
1671 "api/ledger-receipt.json",
1672 "api/history-slice.json",
1673 "api/compaction-checkpoint.json",
1674 "api/authority-fact-bundle.json",
1675 "api/effect-record.json",
1676 ] {
1677 let text = schema_text(name).unwrap_or_else(|e| panic!("{name}: {e}"));
1678 let schema: serde_json::Value =
1679 serde_json::from_str(&text).unwrap_or_else(|e| panic!("{name}: {e}"));
1680 build_validator(name, &schema)
1681 .unwrap_or_else(|e| panic!("{name}: not a valid schema: {e}"));
1682 }
1683 }
1684
1685 #[test]
1694 fn events_fixtures_validate() {
1695 let mut found = 0;
1696 for name in fixture_json_names("events") {
1697 let json = fixture_text(&format!("events/{name}"));
1698 validate_schema_file("api/events.json", &json)
1699 .unwrap_or_else(|e| panic!("{name}: {e}"));
1700 found += 1;
1701 }
1702 assert!(
1703 found >= 3,
1704 "expected ≥3 committed SSE event fixtures, found {found}"
1705 );
1706 }
1707
1708 #[test]
1709 fn events_mapping_complete() {
1710 let text = schema_text("api/events.json").expect("events schema");
1711 let events: serde_json::Value = serde_json::from_str(&text).expect("events parses");
1712
1713 let mapping = events["x-engine-event-mapping"]
1716 .as_object()
1717 .expect("x-engine-event-mapping object");
1718 assert_eq!(
1719 mapping.len(),
1720 24,
1721 "engine→SSE mapping must cover all 24 engine event variants"
1722 );
1723
1724 let frozen = ["approval_required", "run_progress", "policy_changed"];
1725 for (event_type, target) in mapping {
1726 match target.as_str() {
1727 Some(name) => assert!(
1728 frozen.contains(&name),
1729 "{event_type} maps to unknown SSE event {name}"
1730 ),
1731 None => assert!(target.is_null(), "{event_type}: bad mapping value"),
1732 }
1733 }
1734 for name in frozen {
1735 assert!(
1736 mapping.values().any(|v| v.as_str() == Some(name)),
1737 "SSE event {name} has no engine event assigned"
1738 );
1739 }
1740
1741 let mut consts: Vec<String> = Vec::new();
1743 for variant in events["oneOf"].as_array().expect("events oneOf") {
1744 let key = variant["$ref"]
1745 .as_str()
1746 .expect("variant $ref")
1747 .rsplit('/')
1748 .next()
1749 .expect("$defs key");
1750 for part in events["$defs"][key]["allOf"].as_array().expect("allOf") {
1751 if let Some(c) = part["properties"]["event"]["const"].as_str() {
1752 consts.push(c.to_string());
1753 }
1754 }
1755 }
1756 consts.sort();
1757 let mut expected: Vec<String> = frozen.iter().map(|s| s.to_string()).collect();
1758 expected.sort();
1759 assert_eq!(consts, expected, "oneOf discriminant set drifted");
1760 }
1761
1762 #[test]
1772 fn catalog_references_claims_shapes_instead_of_duplicating_them() {
1773 let text = schema_text("api/catalog.json").expect("catalog.json");
1774 let catalog: serde_json::Value = serde_json::from_str(&text).expect("catalog parses");
1775
1776 let defs = catalog["$defs"].as_object().expect("$defs object");
1777 assert!(
1778 !defs.contains_key("identityRef"),
1779 "identityRef must not be duplicated in catalog.json — it lives in claims.json"
1780 );
1781 assert!(
1782 !defs.contains_key("identityClaim"),
1783 "identityClaim must not be duplicated in catalog.json — it lives in claims.json"
1784 );
1785
1786 assert_eq!(
1787 catalog["$defs"]["validatePlanParams"]["properties"]["identity"]["$ref"],
1788 "https://rigorix.eu/schemas/claims.json#/$defs/identityRef"
1789 );
1790 assert_eq!(
1791 catalog["$defs"]["authVerifyResult"]["properties"]["claim"]["$ref"],
1792 "https://rigorix.eu/schemas/claims.json#/$defs/identityClaim"
1793 );
1794
1795 build_validator("api/catalog.json", &catalog)
1798 .expect("catalog compiles with claims.json registered");
1799 }
1800
1801 #[test]
1802 fn catalog_integrity() {
1803 let text = schema_text("api/catalog.json").expect("catalog.json");
1804 let catalog: serde_json::Value = serde_json::from_str(&text).expect("catalog parses");
1805
1806 let catalog_schema_text =
1808 schema_text("api/catalog.schema.json").expect("catalog.schema.json");
1809 let schema: serde_json::Value =
1810 serde_json::from_str(&catalog_schema_text).expect("schema parses");
1811 let compiled = jsonschema::validator_for(&schema).expect("catalog schema compiles");
1812 let errors: Vec<String> = compiled
1813 .iter_errors(&catalog)
1814 .map(|e| e.to_string())
1815 .collect();
1816 assert!(errors.is_empty(), "catalog violates its schema: {errors:?}");
1817
1818 let api_version = catalog["apiVersion"].as_str().expect("apiVersion");
1819 assert!(
1820 semver_ok(api_version),
1821 "apiVersion must be semver, got {api_version}"
1822 );
1823 assert_eq!(catalog["jsonrpc"], "2.0");
1824
1825 let defs = catalog["$defs"].as_object().expect("$defs object");
1826 let methods = catalog["methods"].as_array().expect("methods array");
1827 assert!(
1828 methods.len() >= 23,
1829 "catalog should list the frozen surface (>= 23 methods)"
1830 );
1831
1832 let mut seen = std::collections::HashSet::new();
1833 for m in methods {
1834 let name = m["name"].as_str().expect("method name");
1835 assert!(name.starts_with("rigorix."), "bad namespace: {name}");
1836 assert!(seen.insert(name.to_string()), "duplicate method: {name}");
1837
1838 assert!(
1839 matches!(m["kind"].as_str(), Some("query" | "command")),
1840 "{name}: bad kind"
1841 );
1842 assert!(
1843 matches!(m["auth"].as_str(), Some("public" | "session" | "admin")),
1844 "{name}: bad auth level"
1845 );
1846 assert!(
1847 matches!(
1848 m["stability"].as_str(),
1849 Some("frozen" | "draft" | "deprecated")
1850 ),
1851 "{name}: bad stability"
1852 );
1853 let since = m["since"].as_str().expect("since");
1854 assert!(semver_ok(since), "{name}: since not semver: {since}");
1855
1856 for slot in ["params", "result"] {
1857 let reference = m[slot]["$ref"]
1858 .as_str()
1859 .unwrap_or_else(|| panic!("{name}: missing {slot}.$ref"));
1860 let key = reference.rsplit('/').next().unwrap_or_default();
1861 assert!(
1862 defs.contains_key(key),
1863 "{name}: {slot} $ref '{reference}' does not resolve in $defs"
1864 );
1865 }
1866 }
1867
1868 let push = &catalog["transport"]["push"];
1872 assert_eq!(push["kind"], "sse", "push kind");
1873 assert_eq!(push["endpoint"], "/events", "push endpoint");
1874 let push_schema = push["schema"].as_str().expect("transport.push.schema");
1875 let push_text = schema_text(push_schema).expect("push schema");
1876 let push_events: serde_json::Value =
1877 serde_json::from_str(&push_text).expect("events schema parses");
1878 build_validator(push_schema, &push_events).unwrap_or_else(|e| panic!("{push_schema}: {e}"));
1879 let mut declared: Vec<&str> = push["events"]
1880 .as_array()
1881 .expect("push.events")
1882 .iter()
1883 .map(|v| v.as_str().expect("event name"))
1884 .collect();
1885 declared.sort_unstable();
1886 let mut known: Vec<&str> = Vec::new();
1887 for variant in push_events["oneOf"].as_array().expect("events oneOf") {
1888 let key = variant["$ref"]
1889 .as_str()
1890 .expect("variant $ref")
1891 .rsplit('/')
1892 .next()
1893 .expect("$defs key");
1894 for part in push_events["$defs"][key]["allOf"]
1895 .as_array()
1896 .expect("allOf")
1897 {
1898 if let Some(c) = part["properties"]["event"]["const"].as_str() {
1899 known.push(c);
1900 }
1901 }
1902 }
1903 known.sort_unstable();
1904 assert_eq!(
1905 declared, known,
1906 "catalog transport.push.events must match events.json discriminants"
1907 );
1908
1909 assert!(
1912 catalog["description"]
1913 .as_str()
1914 .is_some_and(|d| d.contains("CLOSED")),
1915 "catalog.json must document the closed `rigorix.*` namespace"
1916 );
1917 let auth_verify = methods
1918 .iter()
1919 .find(|m| m["name"] == "rigorix.auth.verify")
1920 .expect("rigorix.auth.verify must be declared in the frozen catalog");
1921 assert_eq!(auth_verify["kind"], "query");
1922 assert_eq!(auth_verify["auth"], "session");
1923 assert!(
1924 auth_verify["mcpTool"].is_null(),
1925 "auth.verify is server-only"
1926 );
1927 for slot in ["params", "result"] {
1928 let reference = auth_verify[slot]["$ref"]
1929 .as_str()
1930 .unwrap_or_else(|| panic!("auth.verify: missing {slot}.$ref"));
1931 let key = reference.rsplit('/').next().unwrap_or_default();
1932 assert!(
1933 defs.contains_key(key),
1934 "auth.verify {slot} $ref '{reference}' does not resolve in $defs"
1935 );
1936 }
1937
1938 for name in [
1941 "rigorix.audit.head",
1942 "rigorix.audit.history",
1943 "rigorix.audit.overdue",
1944 ] {
1945 let method = methods
1946 .iter()
1947 .find(|m| m["name"] == name)
1948 .unwrap_or_else(|| panic!("{name} must be declared in the frozen catalog"));
1949 assert_eq!(method["kind"], "query", "{name}: kind");
1950 assert_eq!(method["auth"], "session", "{name}: auth");
1951 assert!(method["mcpTool"].is_null(), "{name} is server-only");
1952 for slot in ["params", "result"] {
1953 let reference = method[slot]["$ref"]
1954 .as_str()
1955 .unwrap_or_else(|| panic!("{name}: missing {slot}.$ref"));
1956 let key = reference.rsplit('/').next().unwrap_or_default();
1957 assert!(
1958 defs.contains_key(key),
1959 "{name}: {slot} $ref '{reference}' does not resolve in $defs"
1960 );
1961 }
1962 }
1963 assert_eq!(
1965 defs["auditHistoryResult"]["$ref"], HISTORY_SLICE_SCHEMA_ID,
1966 "rigorix.audit.history must reuse api/history-slice.json"
1967 );
1968 }
1969
1970 #[test]
1973 fn error_taxonomy_codes_consistent() {
1974 let text = schema_text("api/errors.json").expect("errors.json");
1975 let errors: serde_json::Value = serde_json::from_str(&text).expect("errors parses");
1976
1977 let types: Vec<&str> = errors["$defs"]["errorType"]["enum"]
1978 .as_array()
1979 .expect("errorType enum")
1980 .iter()
1981 .map(|v| v.as_str().expect("string"))
1982 .collect();
1983 let codes = errors["x-error-codes"].as_object().expect("x-error-codes");
1984
1985 for t in &types {
1986 assert!(codes.contains_key(*t), "error type '{t}' has no code");
1987 }
1988 for key in codes.keys() {
1989 assert!(
1990 types.contains(&key.as_str()),
1991 "code mapping '{key}' is not a declared error type"
1992 );
1993 }
1994 }
1995
1996 const FIXTURE_KEY: &str = "fixture-hmac-key-2026";
2004 const ANCHOR_SECRET: [u8; 32] = [7u8; 32];
2006
2007 fn anchor_signing_key() -> ed25519_dalek::SigningKey {
2008 ed25519_dalek::SigningKey::from_bytes(&ANCHOR_SECRET)
2009 }
2010
2011 fn anchor_public_hex() -> String {
2012 hex::encode(anchor_signing_key().verifying_key().to_bytes())
2013 }
2014
2015 fn integrity_dir() -> std::path::PathBuf {
2017 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../schemas/fixtures/integrity")
2018 }
2019
2020 fn read_envelopes(name: &str) -> Vec<AuditEnvelope> {
2022 let text = read_json(name);
2023 serde_json::from_str(&text).unwrap_or_else(|e| panic!("{name}: {e}"))
2024 }
2025
2026 fn read_json(name: &str) -> String {
2027 fixture_text(&format!("integrity/{name}"))
2028 }
2029
2030 #[test]
2034 fn embedded_corpus_smoke() {
2035 let json = fixture_text("envelope/envelope-minimal-signed.json");
2036 verify_signature(&json, FIXTURE_KEY).expect("embedded engine fixture verifies");
2037 verify_catalog_subset(&["rigorix.plan", "rigorix.auth.verify"])
2038 .expect("embedded catalog contains the declared subset");
2039 let chain = read_envelopes("chain.json");
2040 verify_chain(&chain).expect("embedded chain verifies");
2041 }
2042
2043 #[test]
2044 fn integrity_chain_fixtures_verify() {
2045 let envelopes = read_envelopes("chain.json");
2046 assert!(envelopes.len() >= 3, "expected a >=3-envelope chain");
2047
2048 let values: Vec<serde_json::Value> =
2051 serde_json::from_str(&read_json("chain.json")).expect("chain array parses");
2052 for value in &values {
2053 let one = value.to_string();
2054 verify_signature(&one, FIXTURE_KEY).unwrap_or_else(|e| panic!("fixture hmac: {e}"));
2055 validate_schema(&one).unwrap_or_else(|e| panic!("envelope schema: {e}"));
2056 }
2057
2058 verify_chain(&envelopes).expect("valid chain must verify");
2060 assert!(envelopes
2061 .iter()
2062 .all(|e| e.history_integrity == Some(HistoryIntegrity::LocalUnanchored)));
2063 for pair in envelopes.windows(2) {
2064 assert_eq!(
2065 Some(envelope_hash_of(&pair[0]).unwrap()),
2066 pair[1].prev_hash,
2067 "prev_hash must be the predecessor's canonical hash"
2068 );
2069 }
2070 assert_eq!(envelopes[0].sequence, Some(0));
2071 assert!(envelopes[0].prev_hash.is_none(), "genesis has no prev_hash");
2072 }
2073
2074 #[test]
2075 fn integrity_broken_chain_is_rejected() {
2076 let envelopes = read_envelopes("broken-chain.json");
2077 let err = verify_chain(&envelopes).expect_err("an uncovered gap must fail");
2078 assert!(matches!(err, VerifyError::ChainBroken { .. }), "{err:?}");
2079 }
2080
2081 #[test]
2082 fn chain_detects_altered_predecessor_and_duplicate_sequence() {
2083 let mut envelopes = read_envelopes("chain.json");
2085 envelopes[2].prev_hash = Some("0".repeat(64));
2086 let err = verify_chain(&envelopes).expect_err("altered prev_hash must fail");
2087 assert!(matches!(err, VerifyError::ChainBroken { .. }), "{err:?}");
2088
2089 let mut envelopes = read_envelopes("chain.json");
2091 envelopes[2].sequence = Some(1);
2092 let err = verify_chain(&envelopes).expect_err("duplicate sequence must fail");
2093 assert!(matches!(err, VerifyError::ChainBroken { .. }), "{err:?}");
2094 }
2095
2096 #[test]
2097 fn checkpoint_covers_broken_chain_gap() {
2098 let envelopes = read_envelopes("broken-chain.json");
2099 let text = read_json("compaction-checkpoint.json");
2100 let checkpoint: CompactionCheckpoint = serde_json::from_str(&text).expect("checkpoint");
2101
2102 assert!(verify_chain(&envelopes).is_err());
2104 verify_chain_with_checkpoints(
2105 &envelopes,
2106 std::slice::from_ref(&checkpoint),
2107 &anchor_public_hex(),
2108 )
2109 .expect("a checkpoint-covered gap must verify");
2110 validate_schema_file("api/compaction-checkpoint.json", &text).expect("checkpoint schema");
2111
2112 let mut forged = checkpoint.clone();
2115 forged.new_head = "0".repeat(64);
2116 assert!(verify_chain_with_checkpoints(
2117 &envelopes,
2118 std::slice::from_ref(&forged),
2119 &anchor_public_hex()
2120 )
2121 .is_err());
2122 }
2123
2124 #[test]
2125 fn history_slice_fixture_verifies() {
2126 let text = read_json("history-slice.json");
2127 let slice: HistorySlice = serde_json::from_str(&text).expect("slice parses");
2128 verify_history_slice(&slice, &anchor_public_hex()).expect("anchor signature");
2129 validate_schema_file("api/history-slice.json", &text).expect("history-slice schema");
2130 assert!(!slice.actions.is_empty(), "slice carries prior actions");
2131
2132 let mut forged = slice.clone();
2134 forged.actions[0].node = "forged_node".to_string();
2135 assert!(verify_history_slice(&forged, &anchor_public_hex()).is_err());
2136 }
2137
2138 #[test]
2139 fn ledger_receipt_fixture_verifies() {
2140 let text = read_json("ledger-receipt.json");
2141 let receipt: LedgerReceipt = serde_json::from_str(&text).expect("receipt parses");
2142 verify_ledger_receipt(&receipt, &anchor_public_hex()).expect("anchor signature");
2143 validate_schema_file("api/ledger-receipt.json", &text).expect("ledger-receipt schema");
2144
2145 let mut forged = receipt.clone();
2146 forged.envelope_hash = "0".repeat(64);
2147 assert!(verify_ledger_receipt(&forged, &anchor_public_hex()).is_err());
2148 }
2149
2150 fn read_effect(name: &str) -> (String, EffectRecordArtifact) {
2157 let text = fixture_text(&format!("effect/{name}"));
2158 let artifact: EffectRecordArtifact =
2159 serde_json::from_str(&text).unwrap_or_else(|e| panic!("{name}: {e}"));
2160 (text, artifact)
2161 }
2162
2163 const ACCEPTED_EFFECT_FIXTURES: &[&str] = &[
2167 "ambiguous-unsettled.json",
2168 "committed-l1-l3.json",
2169 "dispatched-with-deadline.json",
2170 "not-committed-l2-l3.json",
2171 "resolved-ambiguous.json",
2172 ];
2173
2174 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
2178 enum RejectionLayer {
2179 Schema,
2180 Structural,
2181 ReadbackDigestMismatch,
2182 ReadbackMissing,
2183 }
2184
2185 const REJECTED_EFFECT_FIXTURES: &[(&str, RejectionLayer)] = &[
2189 (
2190 "rejected-terminal-without-evidence.json",
2191 RejectionLayer::Schema,
2192 ),
2193 (
2194 "rejected-nonterminal-with-settlement.json",
2195 RejectionLayer::Schema,
2196 ),
2197 (
2198 "rejected-dispatched-without-deadline.json",
2199 RejectionLayer::Schema,
2200 ),
2201 ("rejected-verdict-mismatch.json", RejectionLayer::Schema),
2202 (
2203 "rejected-readback-mismatch.json",
2204 RejectionLayer::ReadbackDigestMismatch,
2205 ),
2206 (
2207 "rejected-readback-missing.json",
2208 RejectionLayer::ReadbackMissing,
2209 ),
2210 (
2211 "rejected-settlement-with-none-level.json",
2212 RejectionLayer::Structural,
2213 ),
2214 ];
2215
2216 fn accepted_fixture_names() -> Vec<String> {
2217 fixture_json_names("effect")
2218 .into_iter()
2219 .filter(|name| !name.starts_with("rejected-"))
2220 .collect()
2221 }
2222
2223 fn rejected_fixture_names() -> Vec<String> {
2224 fixture_json_names("effect")
2225 .into_iter()
2226 .filter(|name| name.starts_with("rejected-"))
2227 .collect()
2228 }
2229
2230 fn sorted(mut names: Vec<String>) -> Vec<String> {
2231 names.sort();
2232 names
2233 }
2234
2235 #[test]
2238 fn effect_record_fixtures_verify() {
2239 let on_disk = sorted(accepted_fixture_names());
2240 let pinned: Vec<String> = ACCEPTED_EFFECT_FIXTURES
2241 .iter()
2242 .map(|name| (*name).to_string())
2243 .collect();
2244 assert_eq!(
2245 on_disk,
2246 sorted(pinned),
2247 "every accepted fixture must be pinned and every pinned fixture must exist"
2248 );
2249
2250 for name in ACCEPTED_EFFECT_FIXTURES {
2251 let (text, artifact) = read_effect(name);
2252 validate_schema_file("api/effect-record.json", &text)
2253 .unwrap_or_else(|e| panic!("{name}: schema: {e}"));
2254 verify_effect_record(&artifact).unwrap_or_else(|e| panic!("{name}: structural: {e}"));
2255 if artifact
2256 .settlement
2257 .as_ref()
2258 .is_some_and(|s| s.readback.is_some())
2259 {
2260 verify_settlement_evidence(&artifact)
2261 .unwrap_or_else(|e| panic!("{name}: readback: {e}"));
2262 }
2263 }
2264 }
2265
2266 #[test]
2269 fn effect_record_keeps_durability_and_settlement_orthogonal() {
2270 let (_, artifact) = read_effect("committed-l1-l3.json");
2271 assert_eq!(artifact.levels.durability, Durability::L1);
2272 assert_eq!(artifact.levels.settlement, SettlementLevel::L3);
2273 verify_settlement_evidence(&artifact).expect("valid l1 + l3 artifact");
2274 }
2275
2276 #[test]
2280 fn effect_record_rejected_fixtures_are_pinned_and_rejected() {
2281 let on_disk = sorted(rejected_fixture_names());
2282 let pinned: Vec<String> = REJECTED_EFFECT_FIXTURES
2283 .iter()
2284 .map(|(name, _)| (*name).to_string())
2285 .collect();
2286 assert_eq!(
2287 on_disk,
2288 sorted(pinned),
2289 "every rejected fixture must have a case and every case must have a fixture"
2290 );
2291
2292 for (name, layer) in REJECTED_EFFECT_FIXTURES {
2293 let (text, artifact) = read_effect(name);
2294
2295 let schema = validate_schema_file("api/effect-record.json", &text);
2296 let structural = verify_effect_record(&artifact);
2297
2298 match layer {
2299 RejectionLayer::Schema => {
2300 assert!(schema.is_err(), "{name}: schema must reject");
2301 let err = structural.expect_err("structural must also reject");
2302 assert!(
2303 matches!(err, VerifyError::EffectInvariant { .. }),
2304 "{name}: {err:?}"
2305 );
2306 }
2307 RejectionLayer::Structural => {
2308 schema.unwrap_or_else(|e| panic!("{name}: schema should accept: {e}"));
2309 let err = structural.expect_err("structural must reject");
2310 assert!(
2311 matches!(err, VerifyError::EffectInvariant { .. }),
2312 "{name}: {err:?}"
2313 );
2314 }
2315 RejectionLayer::ReadbackDigestMismatch => {
2316 schema.unwrap_or_else(|e| panic!("{name}: schema should accept: {e}"));
2317 structural.unwrap_or_else(|e| panic!("{name}: structural should accept: {e}"));
2318 let err = verify_settlement_evidence(&artifact)
2319 .expect_err("readback digest must not match");
2320 assert!(
2321 matches!(err, VerifyError::ReadbackDigestMismatch { .. }),
2322 "{name}: {err:?}"
2323 );
2324 }
2325 RejectionLayer::ReadbackMissing => {
2326 schema.unwrap_or_else(|e| panic!("{name}: schema should accept: {e}"));
2327 structural.unwrap_or_else(|e| panic!("{name}: structural should accept: {e}"));
2328 let err = verify_settlement_evidence(&artifact)
2329 .expect_err("readback bytes must be required");
2330 assert!(
2331 matches!(err, VerifyError::ReadbackMissing),
2332 "{name}: {err:?}"
2333 );
2334 }
2335 }
2336 }
2337 }
2338
2339 #[test]
2342 #[ignore = "fixture generator — run with --ignored to regenerate anchor fixtures"]
2343 fn generate_anchor_fixtures() {
2344 use ed25519_dalek::Signer;
2345
2346 let key = anchor_signing_key();
2347 let dir = integrity_dir();
2348 let chain = read_envelopes("chain.json");
2349 let head = chain.last().expect("chain non-empty");
2350
2351 let mut slice = HistorySlice {
2353 scope: "local".to_string(),
2354 since: chain[0].timestamp,
2355 actions: chain
2356 .iter()
2357 .flat_map(|envelope| {
2358 envelope.events.iter().filter_map(|event| {
2359 let node = event
2360 .payload
2361 .as_ref()?
2362 .get("step_name")?
2363 .as_str()?
2364 .to_string();
2365 Some(HistoryActionRef {
2366 node,
2367 principal: envelope.author.clone(),
2368 at: event.occurred_at,
2369 effect_key: envelope.effect_key.clone(),
2370 })
2371 })
2372 })
2373 .collect(),
2374 head_hash: envelope_hash_of(head).expect("head hash"),
2375 sig: None,
2376 };
2377 let bytes = history_slice_signing_bytes(&slice).expect("slice bytes");
2378 slice.sig = Some(hex::encode(key.sign(&bytes).to_bytes()));
2379 std::fs::write(
2380 dir.join("history-slice.json"),
2381 format!("{}\n", serde_json::to_string_pretty(&slice).unwrap()),
2382 )
2383 .expect("write history slice");
2384
2385 let mut receipt = LedgerReceipt {
2387 ledger_id: "local-ledger".to_string(),
2388 envelope_hash: envelope_hash_of(head).expect("head hash"),
2389 sequence: head.sequence.expect("head sequence"),
2390 recorded_at: head.timestamp,
2391 sig: None,
2392 };
2393 let bytes = ledger_receipt_signing_bytes(&receipt).expect("receipt bytes");
2394 receipt.sig = Some(hex::encode(key.sign(&bytes).to_bytes()));
2395 std::fs::write(
2396 dir.join("ledger-receipt.json"),
2397 format!("{}\n", serde_json::to_string_pretty(&receipt).unwrap()),
2398 )
2399 .expect("write ledger receipt");
2400
2401 let broken = read_envelopes("broken-chain.json");
2403 let after = &broken[1];
2404 let mut checkpoint = CompactionCheckpoint {
2405 sequence_from: 1,
2406 sequence_to: 1,
2407 reason: "gdpr-erasure".to_string(),
2408 prior_head: envelope_hash_of(&broken[0]).expect("prior hash"),
2409 new_head: after.prev_hash.clone().expect("successor link"),
2410 sig: None,
2411 };
2412 let bytes = compaction_checkpoint_signing_bytes(&checkpoint).expect("checkpoint bytes");
2413 checkpoint.sig = Some(hex::encode(key.sign(&bytes).to_bytes()));
2414 std::fs::write(
2415 dir.join("compaction-checkpoint.json"),
2416 format!("{}\n", serde_json::to_string_pretty(&checkpoint).unwrap()),
2417 )
2418 .expect("write compaction checkpoint");
2419 }
2420
2421 #[test]
2428 fn catalog_subset_guard_rejects_undeclared_method() {
2429 let enterprise = [
2430 "rigorix.plan",
2431 "rigorix.validatePlan",
2432 "rigorix.run",
2433 "rigorix.approve",
2434 "rigorix.auth.verify",
2435 "rigorix.policy.bundle",
2436 "rigorix.audit.read",
2437 "rigorix.audit.list",
2438 "rigorix.audit.summary",
2439 "rigorix.audit.head",
2440 "rigorix.audit.history",
2441 "rigorix.audit.overdue",
2442 "rigorix.system.version",
2443 ];
2444 verify_catalog_subset(&enterprise).expect("a declared subset must pass");
2445
2446 let err = verify_catalog_subset(&["rigorix.auth.bogus"]).unwrap_err();
2447 assert!(
2448 matches!(err, VerifyError::UndeclaredMethod(ref m) if m == "rigorix.auth.bogus"),
2449 "{err:?}"
2450 );
2451 }
2452
2453 #[test]
2458 fn catalog_declares_authority_fact_projection_additively() {
2459 let text = schema_text("api/catalog.json").expect("catalog.json");
2460 let catalog: serde_json::Value = serde_json::from_str(&text).expect("catalog parses");
2461 let method = catalog["methods"]
2462 .as_array()
2463 .expect("methods")
2464 .iter()
2465 .find(|m| m["name"] == "rigorix.audit.authorityFacts")
2466 .expect("rigorix.audit.authorityFacts must be declared");
2467 assert_eq!(method["kind"], "query");
2468 assert_eq!(
2469 method["auth"], "session",
2470 "an OSS capability is a session method, not an enterprise (admin) scope"
2471 );
2472 assert_eq!(method["mcpTool"], "rigorix_audit_authority_facts");
2473 assert_eq!(method["params"]["$ref"], "#/$defs/authorityFactsParams");
2474 assert_eq!(method["result"]["$ref"], "#/$defs/authorityFactsResult");
2475
2476 assert_eq!(
2480 catalog["$defs"]["authorityFactsResult"]["$ref"],
2481 AUTHORITY_FACT_BUNDLE_SCHEMA_ID
2482 );
2483
2484 let bundle_text = schema_text("api/authority-fact-bundle.json").expect("bundle schema");
2486 let bundle: serde_json::Value = serde_json::from_str(&bundle_text).expect("bundle parses");
2487 assert_eq!(
2488 bundle["properties"]["envelopes"]["items"]["$ref"], ENVELOPE_SCHEMA_ID,
2489 "the bundle must $ref envelope.json (no second envelope dialect)"
2490 );
2491
2492 verify_catalog_subset(&["rigorix.audit.authorityFacts"])
2494 .expect("the projection method must be a declared subset member");
2495 }
2496
2497 fn semver_ok(s: &str) -> bool {
2498 let parts: Vec<&str> = s.split('.').collect();
2499 parts.len() == 3 && parts.iter().all(|p| p.parse::<u64>().is_ok())
2500 }
2501
2502 #[test]
2506 fn scope_check_survives_canonicalization() {
2507 let raw = r#"{
2508 "execution_id": "8c1d5eac-8935-4960-82cf-199df61d2539",
2509 "timestamp": "2026-10-30T12:00:00Z",
2510 "template_id": "t",
2511 "planning_hash": "h",
2512 "total_tokens": 0,
2513 "duration_ms": 0,
2514 "events": [],
2515 "signature": null,
2516 "evidence_degraded": false,
2517 "scope_check": "checked"
2518 }"#;
2519 let envelope: AuditEnvelope = serde_json::from_str(raw).expect("parse");
2520 assert_eq!(envelope.scope_check, Some(ScopeCheckStatus::Checked));
2521 let canonical = String::from_utf8(canonical_bytes(raw).expect("canonical")).expect("utf8");
2522 assert!(
2523 canonical.contains(r#""scope_check":"checked""#),
2524 "the field must be in the signed bytes: {canonical}"
2525 );
2526 }
2527}