1#[allow(unused_imports)]
32use crate::prelude::*;
33
34use serde_json::{Map, Value};
35use sha2::{Digest, Sha256};
36
37use crate::data_integrity::{self, BuildProofOptions};
38use crate::error::{CoreError, Result};
39use crate::jcs;
40use crate::time::{check_clock_skew, parse_protocol_time_ns, seconds_to_ns};
41
42pub const VC_CONTEXT_V2: &str = "https://www.w3.org/ns/credentials/v2";
43pub const VOUCH_CONTEXT_V1: &str = "https://vouch-protocol.com/contexts/v1";
44
45pub const REASONED_ACTION_TYPE: &str = "ReasonedActionCredential";
46pub const ESCROW_RECEIPT_TYPE: &str = "JustificationEscrowReceipt";
47
48pub const JUSTIFICATION_ALGORITHM: &str = "sha-256-jcs";
49
50pub const REASON_INVALID_PROOF: &str = "invalid_proof";
52pub const REASON_NOT_REASONED_ACTION: &str = "not_reasoned_action";
53pub const REASON_MISSING_COMMITMENT: &str = "missing_commitment";
54pub const REASON_MISSING_ESCROW: &str = "missing_escrow";
55pub const REASON_ESCROW_INVALID: &str = "escrow_receipt_invalid";
56pub const REASON_ESCROW_DIGEST_MISMATCH: &str = "escrow_digest_mismatch";
57pub const REASON_ESCROW_AFTER_EXECUTION: &str = "escrow_after_execution";
58pub const REASON_JUSTIFICATION_DIGEST_MISMATCH: &str = "justification_digest_mismatch";
59pub const REASON_EVIDENCE_UNRESOLVED: &str = "evidence_unresolved";
60pub const REASON_EVIDENCE_HASH_MISMATCH: &str = "evidence_hash_mismatch";
61pub const REASON_UNANCHORED_CLAIM: &str = "unanchored_claim";
62
63pub const REASON_INTENT_SEAL_STALE: &str = "intent_seal_stale";
65pub const REASON_INTENT_SEAL_EXPIRED: &str = "intent_seal_expired";
66pub const REASON_INTENT_SEAL_MISSING: &str = "intent_seal_missing";
67pub const REASON_ESCROW_AGENT_MISMATCH: &str = "escrow_agent_mismatch";
69pub const REASON_SEAL_AFTER_DEPOSIT: &str = "seal_after_deposit";
71pub const REASON_SEAL_AFTER_EXECUTION: &str = "seal_after_execution";
73pub const REASON_SEAL_IN_FUTURE: &str = "seal_in_future";
75pub const REASON_MALFORMED_TIME: &str = "malformed_time";
77pub const REASON_INTENT_SEAL_FUTURE: &str = "intent_seal_future";
80pub const REASON_INTENT_EXECUTION_NOT_CURRENT: &str = "intent_execution_not_current";
83
84fn mb64(bytes: &[u8]) -> String {
91 use base64::engine::general_purpose::URL_SAFE_NO_PAD;
92 use base64::Engine;
93 format!("u{}", URL_SAFE_NO_PAD.encode(bytes))
94}
95
96fn artifact_bytes(artifact: &Value) -> Result<Vec<u8>> {
101 match artifact {
102 Value::String(s) => Ok(s.as_bytes().to_vec()),
103 Value::Object(_) => Ok(jcs::canonicalize(artifact)),
104 _ => Err(CoreError::Json(
105 "evidence artifact must be a JSON object or string".into(),
106 )),
107 }
108}
109
110pub fn artifact_digest(artifact: &Value) -> Result<String> {
112 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); artifact);
113 Ok(mb64(&Sha256::digest(&artifact_bytes(artifact)?)))
114}
115
116pub fn artifact_digest_bytes(artifact: &[u8]) -> String {
118 mb64(&Sha256::digest(artifact))
119}
120
121fn type_list(credential: &Value) -> Vec<String> {
122 match credential.get("type") {
123 Some(Value::String(s)) => vec![s.clone()],
124 Some(Value::Array(a)) => a
125 .iter()
126 .filter_map(|v| v.as_str().map(|s| s.to_string()))
127 .collect(),
128 _ => Vec::new(),
129 }
130}
131
132fn attach_proof(
135 credential: &mut Value,
136 seed: Option<&[u8]>,
137 verification_method: &str,
138 created: &str,
139) -> Result<()> {
140 let Some(seed) = seed else {
143 return Ok(());
144 };
145 let opts = BuildProofOptions::new(verification_method, created);
146 let proof = data_integrity::build_proof(credential, seed, &opts)?;
147 credential
148 .as_object_mut()
149 .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
150 .insert("proof".into(), proof);
151 Ok(())
152}
153
154pub fn evidence_anchor(
161 claim: &str,
162 reference: &str,
163 evidence: Option<&Value>,
164 evidence_hash: Option<&str>,
165 anchor_type: &str,
166) -> Result<Value> {
167 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); evidence);
168 if claim.is_empty() || reference.is_empty() {
169 return Err(CoreError::Json(
170 "an evidence anchor needs a claim and a ref".into(),
171 ));
172 }
173 let hash = match evidence_hash {
174 Some(h) => h.to_string(),
175 None => match evidence {
176 Some(e) => artifact_digest(e)?,
177 None => {
178 return Err(CoreError::Json(
179 "supply evidence or evidence_hash for the anchor".into(),
180 ))
181 }
182 },
183 };
184 let mut anchor = Map::new();
185 anchor.insert("type".into(), Value::String(anchor_type.to_string()));
186 anchor.insert("claim".into(), Value::String(claim.to_string()));
187 anchor.insert("ref".into(), Value::String(reference.to_string()));
188 anchor.insert("evidenceHash".into(), Value::String(hash));
189 Ok(Value::Object(anchor))
190}
191
192pub fn build_justification(
195 intent: &Value,
196 anchors: &[Value],
197 commitment_level: Option<i64>,
198) -> Result<Value> {
199 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); intent, anchors);
200 if !intent.is_object()
201 || intent.get("action").and_then(|v| v.as_str()).is_none()
202 || intent.get("target").and_then(|v| v.as_str()).is_none()
203 {
204 return Err(CoreError::Json(
205 "intent must be an object with at least action and target".into(),
206 ));
207 }
208 if anchors.is_empty() {
209 return Err(CoreError::Json(
210 "a justification needs at least one evidence anchor".into(),
211 ));
212 }
213 let mut just = Map::new();
214 just.insert("intent".into(), intent.clone());
215 just.insert("evidenceAnchors".into(), Value::Array(anchors.to_vec()));
216 if let Some(level) = commitment_level {
217 just.insert("commitmentLevel".into(), Value::from(level));
218 }
219 Ok(Value::Object(just))
220}
221
222pub fn justification_digest(justification: &Value) -> Result<String> {
224 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); justification);
225 if !justification.is_object() {
226 return Err(CoreError::Json(
227 "justification must be a JSON object".into(),
228 ));
229 }
230 Ok(mb64(&Sha256::digest(jcs::canonicalize(justification))))
231}
232
233#[allow(clippy::too_many_arguments)]
240pub fn build_escrow_receipt(
241 escrow_seed: &[u8],
242 escrow_did: &str,
243 escrow_verification_method: &str,
244 agent_did: &str,
245 committed_digest: &str,
246 deposited_at: &str,
247 credential_id: &str,
248) -> Result<Value> {
249 build_escrow_receipt_with(
250 Some(escrow_seed),
251 escrow_did,
252 escrow_verification_method,
253 agent_did,
254 committed_digest,
255 deposited_at,
256 credential_id,
257 None,
258 )
259}
260
261#[allow(clippy::too_many_arguments)]
265pub fn build_escrow_receipt_with(
266 escrow_seed: Option<&[u8]>,
267 escrow_did: &str,
268 escrow_verification_method: &str,
269 agent_did: &str,
270 committed_digest: &str,
271 deposited_at: &str,
272 credential_id: &str,
273 created: Option<&str>,
274) -> Result<Value> {
275 let mut subject = Map::new();
276 subject.insert("agent".into(), Value::String(agent_did.to_string()));
277 subject.insert(
278 "committedDigest".into(),
279 Value::String(committed_digest.to_string()),
280 );
281 subject.insert(
282 "depositedAt".into(),
283 Value::String(deposited_at.to_string()),
284 );
285
286 let mut receipt = Map::new();
287 receipt.insert(
288 "@context".into(),
289 Value::Array(vec![
290 Value::String(VC_CONTEXT_V2.into()),
291 Value::String(VOUCH_CONTEXT_V1.into()),
292 ]),
293 );
294 receipt.insert(
295 "type".into(),
296 Value::Array(vec![
297 Value::String("VerifiableCredential".into()),
298 Value::String(ESCROW_RECEIPT_TYPE.into()),
299 ]),
300 );
301 receipt.insert("id".into(), Value::String(credential_id.to_string()));
302 receipt.insert("issuer".into(), Value::String(escrow_did.to_string()));
303 receipt.insert("validFrom".into(), Value::String(deposited_at.to_string()));
304 receipt.insert("credentialSubject".into(), Value::Object(subject));
305
306 let mut receipt = Value::Object(receipt);
307 attach_proof(
308 &mut receipt,
309 escrow_seed,
310 escrow_verification_method,
311 created.unwrap_or(deposited_at),
312 )?;
313 Ok(receipt)
314}
315
316pub fn verify_escrow_receipt(receipt: &Value, escrow_public_key: &[u8]) -> (bool, Option<Value>) {
324 crate::nesting::deep_guard!((false, None); receipt);
325 if !type_list(receipt).iter().any(|t| t == ESCROW_RECEIPT_TYPE) {
326 return (false, None);
327 }
328 let has_context = |item: &Value| {
329 item.as_object()
330 .is_some_and(|proof| proof.contains_key("@context"))
331 };
332 let proof_carries_context = match receipt.get("proof") {
333 Some(Value::Array(items)) => items.iter().any(has_context),
334 Some(item) => has_context(item),
335 None => false,
336 };
337 if proof_carries_context {
338 return (false, None);
339 }
340 let bound = match (
342 crate::credentials::issuer_did(receipt),
343 receipt.get("proof"),
344 ) {
345 (Some(issuer), Some(proof)) => crate::credentials::proof_bound_to_issuer(proof, issuer),
346 _ => false,
347 };
348 if !bound {
349 return (false, None);
350 }
351 match data_integrity::verify_proof(receipt, escrow_public_key) {
352 Ok(true) => {}
353 _ => return (false, None),
354 }
355 let subject = match receipt.get("credentialSubject").and_then(|s| s.as_object()) {
356 Some(s) => s,
357 None => return (false, None),
358 };
359 let has_digest = subject
360 .get("committedDigest")
361 .and_then(|v| v.as_str())
362 .is_some_and(|s| !s.is_empty());
363 let has_agent = subject.get("agent").is_some_and(|v| v.is_string());
364 let has_deposited = subject
365 .get("depositedAt")
366 .and_then(|v| v.as_str())
367 .is_some_and(|s| parse_protocol_time_ns(s).is_ok());
368 if !has_digest || !has_agent || !has_deposited {
369 return (false, None);
370 }
371 (true, Some(Value::Object(subject.clone())))
372}
373
374#[derive(Debug, Clone, Default)]
380pub struct SignReasonedActionOptions {
381 pub include_reasoning: bool,
384 pub escrow_receipt: Option<Value>,
387 pub sealed_at: Option<String>,
391 pub created: Option<String>,
395}
396
397impl SignReasonedActionOptions {
398 pub fn new() -> Self {
399 Self {
400 include_reasoning: true,
401 escrow_receipt: None,
402 sealed_at: None,
403 created: None,
404 }
405 }
406}
407
408#[allow(clippy::too_many_arguments)]
411pub fn sign_reasoned_action(
412 seed: &[u8],
413 issuer_did: &str,
414 verification_method: &str,
415 intent: &Value,
416 justification: &Value,
417 valid_from: &str,
418 credential_id: &str,
419 opts: &SignReasonedActionOptions,
420) -> Result<Value> {
421 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); intent, justification, opts);
422 sign_reasoned_action_with(
423 Some(seed),
424 issuer_did,
425 verification_method,
426 intent,
427 justification,
428 valid_from,
429 credential_id,
430 opts,
431 )
432}
433
434#[allow(clippy::too_many_arguments)]
438pub fn sign_reasoned_action_with(
439 seed: Option<&[u8]>,
440 issuer_did: &str,
441 verification_method: &str,
442 intent: &Value,
443 justification: &Value,
444 valid_from: &str,
445 credential_id: &str,
446 opts: &SignReasonedActionOptions,
447) -> Result<Value> {
448 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); intent, justification, opts);
449 if !intent.is_object()
450 || intent.get("action").and_then(|v| v.as_str()).is_none()
451 || intent.get("target").and_then(|v| v.as_str()).is_none()
452 {
453 return Err(CoreError::Json(
454 "intent must be an object with at least action and target".into(),
455 ));
456 }
457 let digest = justification_digest(justification)?;
458
459 let mut commitment = Map::new();
460 commitment.insert(
461 "algorithm".into(),
462 Value::String(JUSTIFICATION_ALGORITHM.into()),
463 );
464 commitment.insert("digest".into(), Value::String(digest));
465
466 let mut jblock = Map::new();
467 jblock.insert("commitment".into(), Value::Object(commitment));
468 if let Some(sealed) = &opts.sealed_at {
469 jblock.insert("sealedAt".into(), Value::String(sealed.clone()));
470 }
471 if let Some(level) = justification.get("commitmentLevel") {
472 jblock.insert("commitmentLevel".into(), level.clone());
473 }
474 if let Some(receipt) = &opts.escrow_receipt {
475 jblock.insert("escrowReceipt".into(), receipt.clone());
476 }
477 if opts.include_reasoning {
478 let anchors = justification
479 .get("evidenceAnchors")
480 .cloned()
481 .unwrap_or_else(|| Value::Array(Vec::new()));
482 jblock.insert("evidenceAnchors".into(), anchors);
483 }
484
485 let mut subject = Map::new();
486 subject.insert("intent".into(), intent.clone());
487 subject.insert("justification".into(), Value::Object(jblock));
488
489 let mut credential = Map::new();
490 credential.insert(
491 "@context".into(),
492 Value::Array(vec![
493 Value::String(VC_CONTEXT_V2.into()),
494 Value::String(VOUCH_CONTEXT_V1.into()),
495 ]),
496 );
497 credential.insert(
498 "type".into(),
499 Value::Array(vec![
500 Value::String("VerifiableCredential".into()),
501 Value::String(REASONED_ACTION_TYPE.into()),
502 ]),
503 );
504 credential.insert("id".into(), Value::String(credential_id.to_string()));
505 credential.insert("issuer".into(), Value::String(issuer_did.to_string()));
506 credential.insert("validFrom".into(), Value::String(valid_from.to_string()));
507 credential.insert("credentialSubject".into(), Value::Object(subject));
508
509 let mut credential = Value::Object(credential);
510 let created = opts.created.as_deref().unwrap_or(valid_from);
511 attach_proof(&mut credential, seed, verification_method, created)?;
512 Ok(credential)
513}
514
515fn time_of(v: Option<&Value>) -> core::result::Result<i128, ()> {
516 match v.and_then(|v| v.as_str()) {
517 Some(s) => parse_protocol_time_ns(s).map_err(|_| ()),
518 None => Err(()),
519 }
520}
521
522pub fn check_unreadable_reasoned_action(credential: &Value) -> String {
529 crate::nesting::deep_guard!(crate::nesting::TOO_DEEP.into(); credential);
530 if !type_list(credential)
531 .iter()
532 .any(|t| t == REASONED_ACTION_TYPE)
533 {
534 return REASON_NOT_REASONED_ACTION.into();
535 }
536 REASON_INVALID_PROOF.into()
537}
538
539fn check_reasoned_action_inner(
540 credential: &Value,
541 public_key: &[u8],
542 escrow_public_key: Option<&[u8]>,
543 require_escrow: bool,
544 clock: Option<(i128, i128)>,
545) -> Option<String> {
546 if !type_list(credential)
547 .iter()
548 .any(|t| t == REASONED_ACTION_TYPE)
549 {
550 return Some(REASON_NOT_REASONED_ACTION.into());
551 }
552 let bound = match (
553 crate::credentials::issuer_did(credential),
554 credential.get("proof"),
555 ) {
556 (Some(issuer), Some(proof)) => crate::credentials::proof_bound_to_issuer(proof, issuer),
557 _ => false,
558 };
559 if !bound {
560 return Some(REASON_INVALID_PROOF.into());
561 }
562 match data_integrity::verify_proof(credential, public_key) {
563 Ok(true) => {}
564 _ => return Some(REASON_INVALID_PROOF.into()),
565 }
566
567 let jblock = credential
568 .get("credentialSubject")
569 .and_then(|s| s.get("justification"))
570 .filter(|j| j.is_object());
571 let Some(jblock) = jblock else {
572 return Some(REASON_MISSING_COMMITMENT.into());
573 };
574 let commitment_digest = jblock
575 .get("commitment")
576 .and_then(|c| c.get("digest"))
577 .and_then(|d| d.as_str());
578 let commitment_digest = match commitment_digest {
579 Some(d) if !d.is_empty() => d,
580 _ => return Some(REASON_MISSING_COMMITMENT.into()),
581 };
582
583 let Ok(executed) = time_of(credential.get("validFrom")) else {
584 return Some(REASON_MALFORMED_TIME.into());
585 };
586 let sealed = match jblock.get("sealedAt") {
587 None => None,
588 Some(v) => match time_of(Some(v)) {
589 Ok(t) => Some(t),
590 Err(()) => return Some(REASON_MALFORMED_TIME.into()),
591 },
592 };
593 if let Some(t) = sealed {
594 if t > executed {
595 return Some(REASON_SEAL_AFTER_EXECUTION.into());
596 }
597 if let Some((now, skew)) = clock {
598 if t > now + skew {
599 return Some(REASON_SEAL_IN_FUTURE.into());
600 }
601 }
602 }
603
604 let receipt = match jblock.get("escrowReceipt") {
605 None => {
606 return if require_escrow {
607 Some(REASON_MISSING_ESCROW.into())
608 } else {
609 None
610 };
611 }
612 Some(r) => r,
613 };
614 let escrow_key = match escrow_public_key {
615 Some(k) => k,
616 None => return Some(REASON_ESCROW_INVALID.into()),
617 };
618 let (ok, rsubject) = verify_escrow_receipt(receipt, escrow_key);
619 let Some(rsubject) = rsubject.filter(|_| ok) else {
620 return Some(REASON_ESCROW_INVALID.into());
621 };
622 if rsubject.get("agent").and_then(|v| v.as_str()) != crate::credentials::issuer_did(credential)
624 {
625 return Some(REASON_ESCROW_AGENT_MISMATCH.into());
626 }
627 if rsubject.get("committedDigest").and_then(|v| v.as_str()) != Some(commitment_digest) {
628 return Some(REASON_ESCROW_DIGEST_MISMATCH.into());
629 }
630 let Ok(deposited) = time_of(rsubject.get("depositedAt")) else {
631 return Some(REASON_ESCROW_INVALID.into());
632 };
633 if let Some(t) = sealed {
634 if t > deposited {
635 return Some(REASON_SEAL_AFTER_DEPOSIT.into());
636 }
637 }
638 if deposited > executed {
639 return Some(REASON_ESCROW_AFTER_EXECUTION.into());
640 }
641 if let Some((now, skew)) = clock {
642 if deposited > now + skew {
643 return Some(REASON_SEAL_IN_FUTURE.into());
644 }
645 }
646 None
647}
648
649pub fn check_reasoned_action(
667 credential: &Value,
668 public_key: &[u8],
669 escrow_public_key: Option<&[u8]>,
670 require_escrow: bool,
671) -> Option<String> {
672 crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP.into()); credential);
673 check_reasoned_action_inner(
674 credential,
675 public_key,
676 escrow_public_key,
677 require_escrow,
678 None,
679 )
680}
681
682pub fn check_reasoned_action_at(
687 credential: &Value,
688 public_key: &[u8],
689 escrow_public_key: Option<&[u8]>,
690 require_escrow: bool,
691 now_iso: &str,
692 clock_skew_seconds: i64,
693) -> Result<Option<String>> {
694 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
695 let skew = check_clock_skew(clock_skew_seconds)?;
696 let now = parse_protocol_time_ns(now_iso)?;
697 Ok(check_reasoned_action_inner(
698 credential,
699 public_key,
700 escrow_public_key,
701 require_escrow,
702 Some((now, skew)),
703 ))
704}
705
706pub fn verify_reasoned_action(
709 credential: &Value,
710 public_key: &[u8],
711 escrow_public_key: Option<&[u8]>,
712 require_escrow: bool,
713) -> (bool, Option<Value>) {
714 crate::nesting::deep_guard!((false, None); credential);
715 if check_reasoned_action(credential, public_key, escrow_public_key, require_escrow).is_some() {
716 return (false, None);
717 }
718 (true, credential.get("credentialSubject").cloned())
719}
720
721pub fn verify_justification<F>(
726 presented_justification: &Value,
727 credential_subject: &Value,
728 resolver: F,
729) -> (bool, Option<String>)
730where
731 F: Fn(&str) -> Option<Value>,
732{
733 crate::nesting::deep_guard!((false, Some(crate::nesting::TOO_DEEP.into())); presented_justification, credential_subject);
734 let committed = credential_subject
735 .get("justification")
736 .and_then(|j| j.get("commitment"))
737 .and_then(|c| c.get("digest"))
738 .and_then(|d| d.as_str());
739 let committed = match committed {
740 Some(d) if !d.is_empty() => d,
741 _ => return (false, Some(REASON_MISSING_COMMITMENT.into())),
742 };
743
744 match justification_digest(presented_justification) {
745 Ok(d) if d == committed => {}
746 _ => return (false, Some(REASON_JUSTIFICATION_DIGEST_MISMATCH.into())),
747 }
748
749 let anchors = presented_justification
750 .get("evidenceAnchors")
751 .and_then(|a| a.as_array());
752 let anchors = match anchors {
753 Some(a) if !a.is_empty() => a,
754 _ => return (false, Some(REASON_UNANCHORED_CLAIM.into())),
755 };
756 for anchor in anchors {
757 let reference = anchor.get("ref").and_then(|v| v.as_str());
758 let artifact = reference.and_then(&resolver);
759 let artifact = match artifact {
760 Some(a) => a,
761 None => return (false, Some(REASON_EVIDENCE_UNRESOLVED.into())),
762 };
763 let expected = anchor.get("evidenceHash").and_then(|v| v.as_str());
764 match artifact_digest(&artifact) {
765 Ok(actual) if Some(actual.as_str()) == expected => {}
766 _ => return (false, Some(REASON_EVIDENCE_HASH_MISMATCH.into())),
767 }
768 }
769 (true, None)
770}
771
772#[derive(Debug, Clone, Copy, PartialEq, Eq)]
779pub struct PulseWindow {
780 pub in_window: bool,
782 pub in_gap: bool,
784 pub seconds_into_window: i64,
786}
787
788pub fn pulse_window(
792 last_pulse: &str,
793 interval_seconds: i64,
794 exec_time: &str,
795) -> Result<PulseWindow> {
796 let pulse = parse_protocol_time_ns(last_pulse)?;
797 let exec = parse_protocol_time_ns(exec_time)?;
798 let delta = exec - pulse;
799 let interval = seconds_to_ns(interval_seconds);
800 let in_window = delta >= 0 && delta < interval;
801 Ok(PulseWindow {
802 in_window,
803 in_gap: delta >= interval,
804 seconds_into_window: delta.div_euclid(1_000_000_000) as i64,
805 })
806}
807
808#[derive(Debug, Clone, PartialEq, Eq)]
810pub struct FreshnessRequirement {
811 pub require_fresh_seal: bool,
814 pub max_age_seconds: i64,
817 pub max_age: Option<MaxAge>,
821}
822
823#[derive(Debug, Clone, PartialEq, Eq)]
828pub struct MaxAge {
829 pub limit_ns: i128,
830 pub text: String,
831}
832
833impl FreshnessRequirement {
834 pub const NONE: FreshnessRequirement = FreshnessRequirement {
835 require_fresh_seal: false,
836 max_age_seconds: i64::MAX,
837 max_age: None,
838 };
839}
840
841pub const TIER_ROUTINE: i64 = 0;
844pub const TIER_LOW: i64 = 1;
845pub const TIER_MEDIUM: i64 = 2;
846pub const TIER_HIGH: i64 = 3;
847pub const TIER_CRITICAL: i64 = 4;
848
849pub fn default_requirement(tier: i64) -> FreshnessRequirement {
854 match tier {
855 t if t >= TIER_CRITICAL => FreshnessRequirement {
856 require_fresh_seal: true,
857 max_age_seconds: 60,
858 max_age: None,
859 },
860 TIER_HIGH => FreshnessRequirement {
861 require_fresh_seal: true,
862 max_age_seconds: 300,
863 max_age: None,
864 },
865 _ => FreshnessRequirement::NONE,
866 }
867}
868
869pub fn seal_timestamp(credential: &Value) -> Option<String> {
876 crate::nesting::deep_guard!(None; credential);
877 let jblock = credential
878 .get("credentialSubject")
879 .and_then(|s| s.get("justification"))?;
880 if let Some(receipt) = jblock.get("escrowReceipt").filter(|r| r.is_object()) {
883 return receipt
884 .get("credentialSubject")
885 .and_then(|s| s.get("depositedAt"))
886 .and_then(|v| v.as_str())
887 .filter(|d| !d.is_empty())
888 .map(str::to_string);
889 }
890 jblock
891 .get("sealedAt")
892 .and_then(|v| v.as_str())
893 .filter(|s| !s.is_empty())
894 .map(|s| s.to_string())
895}
896
897pub fn check_seal_freshness(
910 sealed_at: &str,
911 exec_time: &str,
912 last_pulse: &str,
913 requirement: FreshnessRequirement,
914) -> Result<Option<String>> {
915 if !requirement.require_fresh_seal {
916 return Ok(None);
917 }
918 let sealed = parse_protocol_time_ns(sealed_at)?;
919 let exec = parse_protocol_time_ns(exec_time)?;
920 let pulse = parse_protocol_time_ns(last_pulse)?;
921 if sealed < pulse {
922 return Ok(Some(format!(
923 "{REASON_INTENT_SEAL_STALE}:sealed_at={sealed_at},last_pulse={last_pulse}"
924 )));
925 }
926 if let Some(limit) = &requirement.max_age {
927 if exec - sealed > limit.limit_ns {
928 return Ok(Some(format!(
929 "{REASON_INTENT_SEAL_EXPIRED}:sealed_at={sealed_at},max_age={}s",
930 limit.text
931 )));
932 }
933 return Ok(None);
934 }
935 if requirement.max_age_seconds != i64::MAX
936 && exec - sealed > seconds_to_ns(requirement.max_age_seconds)
937 {
938 return Ok(Some(format!(
939 "{REASON_INTENT_SEAL_EXPIRED}:sealed_at={sealed_at},max_age={}s",
940 requirement.max_age_seconds
941 )));
942 }
943 Ok(None)
944}
945
946pub fn verify_intent_freshness(
953 credential: &Value,
954 tier: i64,
955 last_pulse: &str,
956 requirement: FreshnessRequirement,
957) -> Result<Option<String>> {
958 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
959 if !requirement.require_fresh_seal {
960 return Ok(None);
961 }
962 parse_protocol_time_ns(last_pulse)?;
963 let receipt = credential
964 .get("credentialSubject")
965 .and_then(|s| s.get("justification"))
966 .and_then(|j| j.get("escrowReceipt"));
967 Ok(Some(match receipt {
968 None => format!("{REASON_INTENT_SEAL_MISSING}:tier={tier}"),
969 Some(_) => REASON_ESCROW_INVALID.to_string(),
970 }))
971}
972
973#[allow(clippy::too_many_arguments)]
999pub fn recheck_intent_freshness(
1000 credential: &Value,
1001 tier: i64,
1002 last_pulse: &str,
1003 requirement: FreshnessRequirement,
1004 now_iso: &str,
1005 clock_skew_seconds: i64,
1006 escrow_public_key: Option<&[u8]>,
1007) -> Result<Option<String>> {
1008 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
1009 recheck_intent_freshness_with(
1010 credential,
1011 tier,
1012 last_pulse,
1013 requirement,
1014 now_iso,
1015 clock_skew_seconds,
1016 escrow_public_key,
1017 false,
1018 )
1019}
1020
1021#[allow(clippy::too_many_arguments)]
1026pub fn recheck_intent_freshness_with(
1027 credential: &Value,
1028 tier: i64,
1029 last_pulse: &str,
1030 requirement: FreshnessRequirement,
1031 now_iso: &str,
1032 clock_skew_seconds: i64,
1033 escrow_public_key: Option<&[u8]>,
1034 receipt_unreadable: bool,
1035) -> Result<Option<String>> {
1036 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
1037 if !requirement.require_fresh_seal {
1038 return Ok(None);
1039 }
1040 let skew = check_clock_skew(clock_skew_seconds)?;
1041 let now = parse_protocol_time_ns(now_iso)?;
1042 parse_protocol_time_ns(last_pulse)?;
1043
1044 let jblock = credential
1045 .get("credentialSubject")
1046 .and_then(|s| s.get("justification"))
1047 .filter(|j| j.is_object());
1048 let Some(receipt) = jblock.and_then(|j| j.get("escrowReceipt")) else {
1049 return Ok(Some(format!("{REASON_INTENT_SEAL_MISSING}:tier={tier}")));
1050 };
1051 let (ok, rsubject) = match escrow_public_key {
1052 Some(_) if receipt_unreadable => (false, None),
1053 Some(k) => verify_escrow_receipt(receipt, k),
1054 None => (false, None),
1055 };
1056 let Some(rsubject) = rsubject.filter(|_| ok) else {
1057 return Ok(Some(REASON_ESCROW_INVALID.into()));
1058 };
1059 if rsubject.get("agent").and_then(|v| v.as_str()) != crate::credentials::issuer_did(credential)
1060 {
1061 return Ok(Some(REASON_ESCROW_AGENT_MISMATCH.into()));
1062 }
1063 let digest = jblock
1064 .and_then(|j| j.get("commitment"))
1065 .and_then(|c| c.get("digest"))
1066 .and_then(|d| d.as_str())
1067 .filter(|d| !d.is_empty());
1068 if digest.is_none() || rsubject.get("committedDigest").and_then(|v| v.as_str()) != digest {
1069 return Ok(Some(REASON_ESCROW_DIGEST_MISMATCH.into()));
1070 }
1071
1072 let exec_str = credential
1073 .get("validFrom")
1074 .and_then(|v| v.as_str())
1075 .unwrap_or_default();
1076 let deposited_str = rsubject
1077 .get("depositedAt")
1078 .and_then(|v| v.as_str())
1079 .unwrap_or_default()
1080 .to_string();
1081 let (Ok(executed), Ok(deposited)) = (
1082 time_of(credential.get("validFrom")),
1083 time_of(rsubject.get("depositedAt")),
1084 ) else {
1085 return Ok(Some(REASON_MALFORMED_TIME.into()));
1086 };
1087 let sealed = match jblock.and_then(|j| j.get("sealedAt")) {
1088 None => None,
1089 Some(v) => match time_of(Some(v)) {
1090 Ok(t) => Some(t),
1091 Err(()) => return Ok(Some(REASON_MALFORMED_TIME.into())),
1092 },
1093 };
1094 if sealed.is_some_and(|t| t > deposited) {
1095 return Ok(Some(REASON_SEAL_AFTER_DEPOSIT.into()));
1096 }
1097 if deposited > executed {
1098 return Ok(Some(REASON_ESCROW_AFTER_EXECUTION.into()));
1099 }
1100 if deposited > now + skew {
1101 return Ok(Some(format!(
1102 "{REASON_INTENT_SEAL_FUTURE}:sealed_at={deposited_str}"
1103 )));
1104 }
1105 if (executed - now).abs() > skew {
1106 return Ok(Some(format!(
1107 "{REASON_INTENT_EXECUTION_NOT_CURRENT}:valid_from={exec_str}"
1108 )));
1109 }
1110 check_seal_freshness(&deposited_str, exec_str, last_pulse, requirement)
1111}
1112
1113#[allow(clippy::too_many_arguments)]
1118pub fn reseal_intent(
1119 seed: &[u8],
1120 issuer_did: &str,
1121 verification_method: &str,
1122 intent: &Value,
1123 anchors: &[Value],
1124 commitment_level: Option<i64>,
1125 now: &str,
1126 credential_id: &str,
1127 include_reasoning: bool,
1128) -> Result<Value> {
1129 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); intent, anchors);
1130 reseal_intent_with(
1131 Some(seed),
1132 issuer_did,
1133 verification_method,
1134 intent,
1135 anchors,
1136 commitment_level,
1137 now,
1138 credential_id,
1139 include_reasoning,
1140 None,
1141 )
1142}
1143
1144#[allow(clippy::too_many_arguments)]
1147pub fn reseal_intent_with(
1148 seed: Option<&[u8]>,
1149 issuer_did: &str,
1150 verification_method: &str,
1151 intent: &Value,
1152 anchors: &[Value],
1153 commitment_level: Option<i64>,
1154 now: &str,
1155 credential_id: &str,
1156 include_reasoning: bool,
1157 created: Option<&str>,
1158) -> Result<Value> {
1159 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); intent, anchors);
1160 let justification = build_justification(intent, anchors, commitment_level)?;
1161 let opts = SignReasonedActionOptions {
1162 include_reasoning,
1163 escrow_receipt: None,
1164 sealed_at: Some(now.to_string()),
1165 created: created.map(str::to_string),
1166 };
1167 sign_reasoned_action_with(
1168 seed,
1169 issuer_did,
1170 verification_method,
1171 intent,
1172 &justification,
1173 now,
1174 credential_id,
1175 &opts,
1176 )
1177}
1178
1179crate::nesting::nested_fields!(SignReasonedActionOptions; escrow_receipt);
1181
1182#[cfg(test)]
1183mod tests {
1184 use super::*;
1185 use crate::keys::Ed25519KeyPair;
1186 use serde_json::json;
1187
1188 fn seed() -> [u8; 32] {
1189 [7u8; 32]
1190 }
1191
1192 fn pubkey() -> [u8; 32] {
1193 Ed25519KeyPair::from_seed_slice(&seed())
1194 .unwrap()
1195 .public_key()
1196 }
1197
1198 fn sample_intent() -> Value {
1199 json!({"action": "transfer_funds", "target": "account:9911", "resource": "https://bank.example/v1/xfer"})
1200 }
1201
1202 fn sample_justification() -> Value {
1203 let anchor = evidence_anchor(
1204 "user approved the transfer",
1205 "urn:msg:42",
1206 Some(&json!({"text": "please move $500 to savings"})),
1207 None,
1208 "user_message",
1209 )
1210 .unwrap();
1211 build_justification(&sample_intent(), &[anchor], Some(TIER_HIGH)).unwrap()
1212 }
1213
1214 #[test]
1215 fn justification_digest_is_multibase_b64url() {
1216 let d = justification_digest(&sample_justification()).unwrap();
1217 assert!(d.starts_with('u'));
1218 }
1219
1220 #[test]
1221 fn sign_then_verify_reasoned_action() {
1222 let cred = sign_reasoned_action(
1223 &seed(),
1224 "did:web:agent.example",
1225 "did:web:agent.example#key-1",
1226 &sample_intent(),
1227 &sample_justification(),
1228 "2026-08-02T10:00:00Z",
1229 "urn:uuid:11111111-1111-1111-1111-111111111111",
1230 &SignReasonedActionOptions::new(),
1231 )
1232 .unwrap();
1233 assert!(check_reasoned_action(&cred, &pubkey(), None, false).is_none());
1234 assert_eq!(
1235 check_reasoned_action(&cred, &pubkey(), None, true),
1236 Some(REASON_MISSING_ESCROW.into())
1237 );
1238 }
1239
1240 #[test]
1241 fn tampered_action_fails() {
1242 let mut cred = sign_reasoned_action(
1243 &seed(),
1244 "did:web:agent.example",
1245 "did:web:agent.example#key-1",
1246 &sample_intent(),
1247 &sample_justification(),
1248 "2026-08-02T10:00:00Z",
1249 "urn:uuid:11111111-1111-1111-1111-111111111111",
1250 &SignReasonedActionOptions::new(),
1251 )
1252 .unwrap();
1253 cred["credentialSubject"]["intent"]["action"] = json!("drain_account");
1254 assert_eq!(
1255 check_reasoned_action(&cred, &pubkey(), None, false),
1256 Some(REASON_INVALID_PROOF.into())
1257 );
1258 }
1259
1260 #[test]
1261 fn pulse_window_classifies_window_and_gap() {
1262 let w = pulse_window("2026-08-02T10:00:00Z", 60, "2026-08-02T10:00:30Z").unwrap();
1264 assert!(w.in_window && !w.in_gap);
1265 let g = pulse_window("2026-08-02T10:00:00Z", 60, "2026-08-02T10:02:00Z").unwrap();
1266 assert!(g.in_gap && !g.in_window);
1267 }
1268
1269 fn reasoned_with_seal(sealed_at: &str, exec: &str, level: i64) -> Value {
1272 let anchor = evidence_anchor(
1273 "user approved",
1274 "urn:msg:42",
1275 Some(&json!({"text": "go"})),
1276 None,
1277 "user_message",
1278 )
1279 .unwrap();
1280 let just = build_justification(&sample_intent(), &[anchor], Some(level)).unwrap();
1281 let opts = SignReasonedActionOptions {
1282 include_reasoning: true,
1283 escrow_receipt: None,
1284 sealed_at: Some(sealed_at.to_string()),
1285 created: None,
1286 };
1287 sign_reasoned_action(
1288 &seed(),
1289 "did:web:agent.example",
1290 "did:web:agent.example#key-1",
1291 &sample_intent(),
1292 &just,
1293 exec,
1294 "urn:uuid:22222222-2222-2222-2222-222222222222",
1295 &opts,
1296 )
1297 .unwrap()
1298 }
1299
1300 #[test]
1301 fn agent_seal_alone_does_not_meet_a_high_tier() {
1302 let cred = reasoned_with_seal("2026-08-02T10:00:10Z", "2026-08-02T10:00:20Z", TIER_HIGH);
1305 let r = recheck_intent_freshness(
1306 &cred,
1307 TIER_HIGH,
1308 "2026-08-02T10:00:00Z",
1309 default_requirement(TIER_HIGH),
1310 "2026-08-02T10:00:20Z",
1311 30,
1312 Some(&pubkey()),
1313 )
1314 .unwrap();
1315 assert_eq!(
1316 r,
1317 Some(format!("{REASON_INTENT_SEAL_MISSING}:tier={TIER_HIGH}"))
1318 );
1319 }
1320
1321 #[test]
1322 fn stale_seal_across_boundary_rejects() {
1323 let r = check_seal_freshness(
1326 "2026-08-02T09:59:50Z",
1327 "2026-08-02T10:00:20Z",
1328 "2026-08-02T10:00:00Z",
1329 default_requirement(TIER_HIGH),
1330 )
1331 .unwrap();
1332 assert_eq!(
1333 r,
1334 Some(
1335 "intent_seal_stale:sealed_at=2026-08-02T09:59:50Z,last_pulse=2026-08-02T10:00:00Z"
1336 .into()
1337 )
1338 );
1339 assert_eq!(
1340 check_seal_freshness(
1341 "2026-08-02T10:00:10Z",
1342 "2026-08-02T10:00:20Z",
1343 "2026-08-02T10:00:00Z",
1344 default_requirement(TIER_HIGH),
1345 )
1346 .unwrap(),
1347 None
1348 );
1349 }
1350
1351 #[test]
1352 fn reseal_in_gap_is_a_valid_action() {
1353 let cred = reseal_intent(
1356 &seed(),
1357 "did:web:agent.example",
1358 "did:web:agent.example#key-1",
1359 &sample_intent(),
1360 &[evidence_anchor(
1361 "user approved",
1362 "urn:msg:42",
1363 Some(&json!({"text": "go"})),
1364 None,
1365 "user_message",
1366 )
1367 .unwrap()],
1368 Some(TIER_HIGH),
1369 "2026-08-02T10:05:00Z",
1370 "urn:uuid:33333333-3333-3333-3333-333333333333",
1371 true,
1372 )
1373 .unwrap();
1374 assert!(check_reasoned_action(&cred, &pubkey(), None, false).is_none());
1377 let r = verify_intent_freshness(
1378 &cred,
1379 TIER_HIGH,
1380 "2026-08-02T10:05:00Z",
1381 default_requirement(TIER_HIGH),
1382 )
1383 .unwrap();
1384 assert_eq!(
1385 r,
1386 Some(format!("{REASON_INTENT_SEAL_MISSING}:tier={TIER_HIGH}"))
1387 );
1388 }
1389
1390 #[test]
1391 fn non_sensitive_tier_ignores_stale_seal() {
1392 let cred = reasoned_with_seal("2026-08-02T09:59:50Z", "2026-08-02T10:00:20Z", TIER_ROUTINE);
1394 let r = verify_intent_freshness(
1395 &cred,
1396 TIER_ROUTINE,
1397 "2026-08-02T10:00:00Z",
1398 default_requirement(TIER_ROUTINE),
1399 )
1400 .unwrap();
1401 assert_eq!(r, None);
1402 }
1403
1404 #[test]
1405 fn sensitive_tier_without_seal_is_missing() {
1406 let cred = sign_reasoned_action(
1408 &seed(),
1409 "did:web:agent.example",
1410 "did:web:agent.example#key-1",
1411 &sample_intent(),
1412 &sample_justification(),
1413 "2026-08-02T10:00:20Z",
1414 "urn:uuid:44444444-4444-4444-4444-444444444444",
1415 &SignReasonedActionOptions::new(),
1416 )
1417 .unwrap();
1418 let r = verify_intent_freshness(
1419 &cred,
1420 TIER_HIGH,
1421 "2026-08-02T10:00:00Z",
1422 default_requirement(TIER_HIGH),
1423 )
1424 .unwrap();
1425 assert_eq!(r, Some("intent_seal_missing:tier=3".into()));
1426 }
1427
1428 #[test]
1429 fn escrow_roundtrip_and_seal_from_deposit() {
1430 let escrow_seed = [3u8; 32];
1431 let escrow_pub = Ed25519KeyPair::from_seed_slice(&escrow_seed)
1432 .unwrap()
1433 .public_key();
1434 let digest = justification_digest(&sample_justification()).unwrap();
1435 let receipt = build_escrow_receipt(
1436 &escrow_seed,
1437 "did:web:escrow.example",
1438 "did:web:escrow.example#key-1",
1439 "did:web:agent.example",
1440 &digest,
1441 "2026-08-02T10:00:05Z",
1442 "urn:uuid:55555555-5555-5555-5555-555555555555",
1443 )
1444 .unwrap();
1445 let (ok, _) = verify_escrow_receipt(&receipt, &escrow_pub);
1446 assert!(ok);
1447
1448 let mut second = receipt.clone();
1452 let context = second["@context"].clone();
1453 second["proof"]["@context"] = context.clone();
1454 assert!(data_integrity::verify_proof(&second, &escrow_pub).unwrap());
1455 assert_eq!(verify_escrow_receipt(&second, &escrow_pub), (false, None));
1456 let mut in_a_list = receipt.clone();
1457 let mut listed = in_a_list["proof"].clone();
1458 listed["@context"] = context;
1459 in_a_list["proof"] = Value::Array(vec![listed]);
1460 assert_eq!(
1461 verify_escrow_receipt(&in_a_list, &escrow_pub),
1462 (false, None)
1463 );
1464
1465 let opts = SignReasonedActionOptions {
1466 include_reasoning: true,
1467 escrow_receipt: Some(receipt),
1468 sealed_at: None,
1469 created: None,
1470 };
1471 let cred = sign_reasoned_action(
1472 &seed(),
1473 "did:web:agent.example",
1474 "did:web:agent.example#key-1",
1475 &sample_intent(),
1476 &sample_justification(),
1477 "2026-08-02T10:00:20Z",
1478 "urn:uuid:66666666-6666-6666-6666-666666666666",
1479 &opts,
1480 )
1481 .unwrap();
1482 assert_eq!(
1484 seal_timestamp(&cred).as_deref(),
1485 Some("2026-08-02T10:00:05Z")
1486 );
1487 assert!(check_reasoned_action(&cred, &pubkey(), Some(&escrow_pub), true).is_none());
1488 }
1489
1490 fn escrow_seed() -> [u8; 32] {
1493 [9u8; 32]
1494 }
1495
1496 fn escrow_pub() -> [u8; 32] {
1497 Ed25519KeyPair::from_seed(&escrow_seed()).public_key()
1498 }
1499
1500 fn escrowed(agent: &str, deposited: &str, exec: &str, sealed: Option<&str>) -> Value {
1504 let just = sample_justification();
1505 let digest = justification_digest(&just).unwrap();
1506 let receipt = build_escrow_receipt(
1507 &escrow_seed(),
1508 "did:web:escrow.example",
1509 "did:web:escrow.example#key-1",
1510 agent,
1511 &digest,
1512 deposited,
1513 "urn:uuid:33333333-3333-3333-3333-333333333333",
1514 )
1515 .unwrap();
1516 let opts = SignReasonedActionOptions {
1517 include_reasoning: true,
1518 escrow_receipt: Some(receipt),
1519 sealed_at: sealed.map(String::from),
1520 created: None,
1521 };
1522 sign_reasoned_action(
1523 &seed(),
1524 "did:web:agent.example",
1525 "did:web:agent.example#key-1",
1526 &sample_intent(),
1527 &just,
1528 exec,
1529 "urn:uuid:44444444-4444-4444-4444-444444444444",
1530 &opts,
1531 )
1532 .unwrap()
1533 }
1534
1535 fn recheck(cred: &Value, now: &str) -> Option<String> {
1536 recheck_intent_freshness(
1537 cred,
1538 TIER_CRITICAL,
1539 "2026-04-26T10:00:00Z",
1540 default_requirement(TIER_CRITICAL),
1541 now,
1542 30,
1543 Some(&escrow_pub()),
1544 )
1545 .unwrap()
1546 }
1547
1548 #[test]
1549 fn recheck_accepts_a_fresh_witnessed_seal() {
1550 let cred = escrowed(
1551 "did:web:agent.example",
1552 "2026-04-26T10:02:30Z",
1553 "2026-04-26T10:03:00Z",
1554 None,
1555 );
1556 assert_eq!(recheck(&cred, "2026-04-26T10:03:05Z"), None);
1557 assert!(check_reasoned_action(&cred, &pubkey(), Some(&escrow_pub()), true).is_none());
1558 }
1559
1560 #[test]
1561 fn recheck_uses_the_escrow_time_not_the_agents_claim() {
1562 let honest = escrowed(
1564 "did:web:agent.example",
1565 "2026-04-26T09:55:00Z",
1566 "2026-04-26T10:03:00Z",
1567 None,
1568 );
1569 assert!(recheck(&honest, "2026-04-26T10:03:00Z")
1570 .unwrap()
1571 .starts_with(REASON_INTENT_SEAL_STALE));
1572 let lying = escrowed(
1573 "did:web:agent.example",
1574 "2026-04-26T09:55:00Z",
1575 "2026-04-26T10:03:00Z",
1576 Some("2026-04-26T10:02:30Z"),
1577 );
1578 assert_eq!(
1579 recheck(&lying, "2026-04-26T10:03:00Z"),
1580 Some(REASON_SEAL_AFTER_DEPOSIT.into())
1581 );
1582 assert_eq!(
1583 check_reasoned_action(&lying, &pubkey(), Some(&escrow_pub()), true),
1584 Some(REASON_SEAL_AFTER_DEPOSIT.into())
1585 );
1586 let old = verify_intent_freshness(
1588 &lying,
1589 TIER_CRITICAL,
1590 "2026-04-26T10:00:00Z",
1591 default_requirement(TIER_CRITICAL),
1592 )
1593 .unwrap();
1594 assert_eq!(old, Some(REASON_ESCROW_INVALID.into()));
1595 }
1596
1597 #[test]
1598 fn recheck_refuses_forward_dated_and_late_seals() {
1599 let future = escrowed(
1600 "did:web:agent.example",
1601 "2099-01-01T00:00:00Z",
1602 "2099-01-01T00:00:00Z",
1603 Some("2099-01-01T00:00:00Z"),
1604 );
1605 assert_eq!(
1606 recheck(&future, "2026-04-26T10:03:00Z"),
1607 Some(format!(
1608 "{REASON_INTENT_SEAL_FUTURE}:sealed_at=2099-01-01T00:00:00Z"
1609 ))
1610 );
1611 assert_eq!(
1612 check_reasoned_action_at(
1613 &future,
1614 &pubkey(),
1615 Some(&escrow_pub()),
1616 true,
1617 "2026-04-26T10:03:00Z",
1618 30
1619 )
1620 .unwrap(),
1621 Some(REASON_SEAL_IN_FUTURE.into())
1622 );
1623 let late = escrowed(
1625 "did:web:agent.example",
1626 "2026-04-26T10:10:00Z",
1627 "2026-04-26T10:03:00Z",
1628 None,
1629 );
1630 assert_eq!(
1631 recheck(&late, "2026-04-26T10:03:00Z"),
1632 Some(REASON_ESCROW_AFTER_EXECUTION.into())
1633 );
1634 let ahead = escrowed(
1636 "did:web:agent.example",
1637 "2026-04-26T10:03:20Z",
1638 "2026-04-26T10:03:20Z",
1639 None,
1640 );
1641 assert_eq!(recheck(&ahead, "2026-04-26T10:03:00Z"), None, "inside skew");
1642 assert!(recheck(&ahead, "2026-04-26T10:02:40Z").is_some());
1643 let after =
1645 reasoned_with_seal("2026-04-26T10:10:00Z", "2026-04-26T10:03:00Z", TIER_ROUTINE);
1646 assert_eq!(
1647 check_reasoned_action(&after, &pubkey(), None, false),
1648 Some(REASON_SEAL_AFTER_EXECUTION.into())
1649 );
1650 let fresh = escrowed(
1652 "did:web:agent.example",
1653 "2026-04-26T10:02:30Z",
1654 "2026-04-26T10:03:00Z",
1655 None,
1656 );
1657 assert_eq!(
1658 recheck(&fresh, "2026-04-26T10:09:00Z"),
1659 Some(format!(
1660 "{REASON_INTENT_EXECUTION_NOT_CURRENT}:valid_from=2026-04-26T10:03:00Z"
1661 ))
1662 );
1663 }
1664
1665 #[test]
1666 fn recheck_binds_the_receipt_to_the_agent_and_key() {
1667 let stolen = escrowed(
1668 "did:web:someone-else.example",
1669 "2026-04-26T10:02:30Z",
1670 "2026-04-26T10:03:00Z",
1671 None,
1672 );
1673 assert_eq!(
1674 recheck(&stolen, "2026-04-26T10:03:00Z"),
1675 Some(REASON_ESCROW_AGENT_MISMATCH.into())
1676 );
1677 assert_eq!(
1678 check_reasoned_action(&stolen, &pubkey(), Some(&escrow_pub()), true),
1679 Some(REASON_ESCROW_AGENT_MISMATCH.into())
1680 );
1681 let good = escrowed(
1682 "did:web:agent.example",
1683 "2026-04-26T10:02:30Z",
1684 "2026-04-26T10:03:00Z",
1685 None,
1686 );
1687 let wrong = recheck_intent_freshness(
1689 &good,
1690 TIER_CRITICAL,
1691 "2026-04-26T10:00:00Z",
1692 default_requirement(TIER_CRITICAL),
1693 "2026-04-26T10:03:00Z",
1694 30,
1695 Some(&pubkey()),
1696 )
1697 .unwrap();
1698 assert_eq!(wrong, Some(REASON_ESCROW_INVALID.into()));
1699 let none = recheck_intent_freshness(
1700 &good,
1701 TIER_CRITICAL,
1702 "2026-04-26T10:00:00Z",
1703 default_requirement(TIER_CRITICAL),
1704 "2026-04-26T10:03:00Z",
1705 30,
1706 None,
1707 )
1708 .unwrap();
1709 assert_eq!(none, Some(REASON_ESCROW_INVALID.into()));
1710 let bare = reasoned_with_seal(
1711 "2026-04-26T10:02:30Z",
1712 "2026-04-26T10:03:00Z",
1713 TIER_CRITICAL,
1714 );
1715 assert_eq!(
1716 recheck(&bare, "2026-04-26T10:03:00Z"),
1717 Some(format!("{REASON_INTENT_SEAL_MISSING}:tier={TIER_CRITICAL}"))
1718 );
1719 assert!(recheck_intent_freshness(
1721 &good,
1722 TIER_CRITICAL,
1723 "2026-04-26T10:00:00Z",
1724 default_requirement(TIER_CRITICAL),
1725 "2026-04-26T10:03:00Z",
1726 121,
1727 Some(&escrow_pub()),
1728 )
1729 .is_err());
1730 }
1731
1732 #[test]
1733 fn proof_bound_to_another_did_is_refused() {
1734 let cred = sign_reasoned_action(
1735 &seed(),
1736 "did:web:agent.example",
1737 "did:web:other.example#key-1",
1738 &sample_intent(),
1739 &sample_justification(),
1740 "2026-08-02T10:00:00Z",
1741 "urn:uuid:11111111-1111-1111-1111-111111111111",
1742 &SignReasonedActionOptions::new(),
1743 )
1744 .unwrap();
1745 assert_eq!(
1746 check_reasoned_action(&cred, &pubkey(), None, false),
1747 Some(REASON_INVALID_PROOF.into())
1748 );
1749 }
1750}