1use serde_json::{Map, Value};
32use sha2::{Digest, Sha256};
33
34use crate::data_integrity::{self, BuildProofOptions};
35use crate::error::{CoreError, Result};
36use crate::jcs;
37use crate::time::{check_clock_skew, parse_protocol_time_ns, seconds_to_ns};
38
39pub const VC_CONTEXT_V2: &str = "https://www.w3.org/ns/credentials/v2";
40pub const VOUCH_CONTEXT_V1: &str = "https://vouch-protocol.com/contexts/v1";
41
42pub const REASONED_ACTION_TYPE: &str = "ReasonedActionCredential";
43pub const ESCROW_RECEIPT_TYPE: &str = "JustificationEscrowReceipt";
44
45pub const JUSTIFICATION_ALGORITHM: &str = "sha-256-jcs";
46
47pub const REASON_INVALID_PROOF: &str = "invalid_proof";
49pub const REASON_NOT_REASONED_ACTION: &str = "not_reasoned_action";
50pub const REASON_MISSING_COMMITMENT: &str = "missing_commitment";
51pub const REASON_MISSING_ESCROW: &str = "missing_escrow";
52pub const REASON_ESCROW_INVALID: &str = "escrow_receipt_invalid";
53pub const REASON_ESCROW_DIGEST_MISMATCH: &str = "escrow_digest_mismatch";
54pub const REASON_ESCROW_AFTER_EXECUTION: &str = "escrow_after_execution";
55pub const REASON_JUSTIFICATION_DIGEST_MISMATCH: &str = "justification_digest_mismatch";
56pub const REASON_EVIDENCE_UNRESOLVED: &str = "evidence_unresolved";
57pub const REASON_EVIDENCE_HASH_MISMATCH: &str = "evidence_hash_mismatch";
58pub const REASON_UNANCHORED_CLAIM: &str = "unanchored_claim";
59
60pub const REASON_INTENT_SEAL_STALE: &str = "intent_seal_stale";
62pub const REASON_INTENT_SEAL_EXPIRED: &str = "intent_seal_expired";
63pub const REASON_INTENT_SEAL_MISSING: &str = "intent_seal_missing";
64pub const REASON_ESCROW_AGENT_MISMATCH: &str = "escrow_agent_mismatch";
66pub const REASON_SEAL_AFTER_DEPOSIT: &str = "seal_after_deposit";
68pub const REASON_SEAL_AFTER_EXECUTION: &str = "seal_after_execution";
70pub const REASON_SEAL_IN_FUTURE: &str = "seal_in_future";
72pub const REASON_MALFORMED_TIME: &str = "malformed_time";
74pub const REASON_INTENT_SEAL_FUTURE: &str = "intent_seal_future";
77pub const REASON_INTENT_EXECUTION_NOT_CURRENT: &str = "intent_execution_not_current";
80
81fn mb64(bytes: &[u8]) -> String {
88 use base64::engine::general_purpose::URL_SAFE_NO_PAD;
89 use base64::Engine;
90 format!("u{}", URL_SAFE_NO_PAD.encode(bytes))
91}
92
93fn artifact_bytes(artifact: &Value) -> Result<Vec<u8>> {
98 match artifact {
99 Value::String(s) => Ok(s.as_bytes().to_vec()),
100 Value::Object(_) => Ok(jcs::canonicalize(artifact)),
101 _ => Err(CoreError::Json(
102 "evidence artifact must be a JSON object or string".into(),
103 )),
104 }
105}
106
107pub fn artifact_digest(artifact: &Value) -> Result<String> {
109 Ok(mb64(&Sha256::digest(&artifact_bytes(artifact)?)))
110}
111
112pub fn artifact_digest_bytes(artifact: &[u8]) -> String {
114 mb64(&Sha256::digest(artifact))
115}
116
117fn type_list(credential: &Value) -> Vec<String> {
118 match credential.get("type") {
119 Some(Value::String(s)) => vec![s.clone()],
120 Some(Value::Array(a)) => a
121 .iter()
122 .filter_map(|v| v.as_str().map(|s| s.to_string()))
123 .collect(),
124 _ => Vec::new(),
125 }
126}
127
128fn attach_proof(
131 credential: &mut Value,
132 seed: &[u8],
133 verification_method: &str,
134 created: &str,
135) -> Result<()> {
136 let opts = BuildProofOptions::new(verification_method, created);
137 let proof = data_integrity::build_proof(credential, seed, &opts)?;
138 credential
139 .as_object_mut()
140 .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
141 .insert("proof".into(), proof);
142 Ok(())
143}
144
145pub fn evidence_anchor(
152 claim: &str,
153 reference: &str,
154 evidence: Option<&Value>,
155 evidence_hash: Option<&str>,
156 anchor_type: &str,
157) -> Result<Value> {
158 if claim.is_empty() || reference.is_empty() {
159 return Err(CoreError::Json(
160 "an evidence anchor needs a claim and a ref".into(),
161 ));
162 }
163 let hash = match evidence_hash {
164 Some(h) => h.to_string(),
165 None => match evidence {
166 Some(e) => artifact_digest(e)?,
167 None => {
168 return Err(CoreError::Json(
169 "supply evidence or evidence_hash for the anchor".into(),
170 ))
171 }
172 },
173 };
174 let mut anchor = Map::new();
175 anchor.insert("type".into(), Value::String(anchor_type.to_string()));
176 anchor.insert("claim".into(), Value::String(claim.to_string()));
177 anchor.insert("ref".into(), Value::String(reference.to_string()));
178 anchor.insert("evidenceHash".into(), Value::String(hash));
179 Ok(Value::Object(anchor))
180}
181
182pub fn build_justification(
185 intent: &Value,
186 anchors: &[Value],
187 commitment_level: Option<i64>,
188) -> Result<Value> {
189 if !intent.is_object()
190 || intent.get("action").and_then(|v| v.as_str()).is_none()
191 || intent.get("target").and_then(|v| v.as_str()).is_none()
192 {
193 return Err(CoreError::Json(
194 "intent must be an object with at least action and target".into(),
195 ));
196 }
197 if anchors.is_empty() {
198 return Err(CoreError::Json(
199 "a justification needs at least one evidence anchor".into(),
200 ));
201 }
202 let mut just = Map::new();
203 just.insert("intent".into(), intent.clone());
204 just.insert("evidenceAnchors".into(), Value::Array(anchors.to_vec()));
205 if let Some(level) = commitment_level {
206 just.insert("commitmentLevel".into(), Value::from(level));
207 }
208 Ok(Value::Object(just))
209}
210
211pub fn justification_digest(justification: &Value) -> Result<String> {
213 if !justification.is_object() {
214 return Err(CoreError::Json(
215 "justification must be a JSON object".into(),
216 ));
217 }
218 Ok(mb64(&Sha256::digest(jcs::canonicalize(justification))))
219}
220
221#[allow(clippy::too_many_arguments)]
228pub fn build_escrow_receipt(
229 escrow_seed: &[u8],
230 escrow_did: &str,
231 escrow_verification_method: &str,
232 agent_did: &str,
233 committed_digest: &str,
234 deposited_at: &str,
235 credential_id: &str,
236) -> Result<Value> {
237 let mut subject = Map::new();
238 subject.insert("agent".into(), Value::String(agent_did.to_string()));
239 subject.insert(
240 "committedDigest".into(),
241 Value::String(committed_digest.to_string()),
242 );
243 subject.insert(
244 "depositedAt".into(),
245 Value::String(deposited_at.to_string()),
246 );
247
248 let mut receipt = Map::new();
249 receipt.insert(
250 "@context".into(),
251 Value::Array(vec![
252 Value::String(VC_CONTEXT_V2.into()),
253 Value::String(VOUCH_CONTEXT_V1.into()),
254 ]),
255 );
256 receipt.insert(
257 "type".into(),
258 Value::Array(vec![
259 Value::String("VerifiableCredential".into()),
260 Value::String(ESCROW_RECEIPT_TYPE.into()),
261 ]),
262 );
263 receipt.insert("id".into(), Value::String(credential_id.to_string()));
264 receipt.insert("issuer".into(), Value::String(escrow_did.to_string()));
265 receipt.insert("validFrom".into(), Value::String(deposited_at.to_string()));
266 receipt.insert("credentialSubject".into(), Value::Object(subject));
267
268 let mut receipt = Value::Object(receipt);
269 attach_proof(
270 &mut receipt,
271 escrow_seed,
272 escrow_verification_method,
273 deposited_at,
274 )?;
275 Ok(receipt)
276}
277
278pub fn verify_escrow_receipt(receipt: &Value, escrow_public_key: &[u8]) -> (bool, Option<Value>) {
286 if !type_list(receipt).iter().any(|t| t == ESCROW_RECEIPT_TYPE) {
287 return (false, None);
288 }
289 let has_context = |item: &Value| {
290 item.as_object()
291 .is_some_and(|proof| proof.contains_key("@context"))
292 };
293 let proof_carries_context = match receipt.get("proof") {
294 Some(Value::Array(items)) => items.iter().any(has_context),
295 Some(item) => has_context(item),
296 None => false,
297 };
298 if proof_carries_context {
299 return (false, None);
300 }
301 let bound = match (
303 crate::credentials::issuer_did(receipt),
304 receipt.get("proof"),
305 ) {
306 (Some(issuer), Some(proof)) => crate::credentials::proof_bound_to_issuer(proof, issuer),
307 _ => false,
308 };
309 if !bound {
310 return (false, None);
311 }
312 match data_integrity::verify_proof(receipt, escrow_public_key) {
313 Ok(true) => {}
314 _ => return (false, None),
315 }
316 let subject = match receipt.get("credentialSubject").and_then(|s| s.as_object()) {
317 Some(s) => s,
318 None => return (false, None),
319 };
320 let has_digest = subject
321 .get("committedDigest")
322 .and_then(|v| v.as_str())
323 .is_some_and(|s| !s.is_empty());
324 let has_agent = subject.get("agent").is_some_and(|v| v.is_string());
325 let has_deposited = subject
326 .get("depositedAt")
327 .and_then(|v| v.as_str())
328 .is_some_and(|s| parse_protocol_time_ns(s).is_ok());
329 if !has_digest || !has_agent || !has_deposited {
330 return (false, None);
331 }
332 (true, Some(Value::Object(subject.clone())))
333}
334
335#[derive(Debug, Clone, Default)]
341pub struct SignReasonedActionOptions {
342 pub include_reasoning: bool,
345 pub escrow_receipt: Option<Value>,
348 pub sealed_at: Option<String>,
352}
353
354impl SignReasonedActionOptions {
355 pub fn new() -> Self {
356 Self {
357 include_reasoning: true,
358 escrow_receipt: None,
359 sealed_at: None,
360 }
361 }
362}
363
364#[allow(clippy::too_many_arguments)]
367pub fn sign_reasoned_action(
368 seed: &[u8],
369 issuer_did: &str,
370 verification_method: &str,
371 intent: &Value,
372 justification: &Value,
373 valid_from: &str,
374 credential_id: &str,
375 opts: &SignReasonedActionOptions,
376) -> Result<Value> {
377 if !intent.is_object()
378 || intent.get("action").and_then(|v| v.as_str()).is_none()
379 || intent.get("target").and_then(|v| v.as_str()).is_none()
380 {
381 return Err(CoreError::Json(
382 "intent must be an object with at least action and target".into(),
383 ));
384 }
385 let digest = justification_digest(justification)?;
386
387 let mut commitment = Map::new();
388 commitment.insert(
389 "algorithm".into(),
390 Value::String(JUSTIFICATION_ALGORITHM.into()),
391 );
392 commitment.insert("digest".into(), Value::String(digest));
393
394 let mut jblock = Map::new();
395 jblock.insert("commitment".into(), Value::Object(commitment));
396 if let Some(sealed) = &opts.sealed_at {
397 jblock.insert("sealedAt".into(), Value::String(sealed.clone()));
398 }
399 if let Some(level) = justification.get("commitmentLevel") {
400 jblock.insert("commitmentLevel".into(), level.clone());
401 }
402 if let Some(receipt) = &opts.escrow_receipt {
403 jblock.insert("escrowReceipt".into(), receipt.clone());
404 }
405 if opts.include_reasoning {
406 let anchors = justification
407 .get("evidenceAnchors")
408 .cloned()
409 .unwrap_or_else(|| Value::Array(Vec::new()));
410 jblock.insert("evidenceAnchors".into(), anchors);
411 }
412
413 let mut subject = Map::new();
414 subject.insert("intent".into(), intent.clone());
415 subject.insert("justification".into(), Value::Object(jblock));
416
417 let mut credential = Map::new();
418 credential.insert(
419 "@context".into(),
420 Value::Array(vec![
421 Value::String(VC_CONTEXT_V2.into()),
422 Value::String(VOUCH_CONTEXT_V1.into()),
423 ]),
424 );
425 credential.insert(
426 "type".into(),
427 Value::Array(vec![
428 Value::String("VerifiableCredential".into()),
429 Value::String(REASONED_ACTION_TYPE.into()),
430 ]),
431 );
432 credential.insert("id".into(), Value::String(credential_id.to_string()));
433 credential.insert("issuer".into(), Value::String(issuer_did.to_string()));
434 credential.insert("validFrom".into(), Value::String(valid_from.to_string()));
435 credential.insert("credentialSubject".into(), Value::Object(subject));
436
437 let mut credential = Value::Object(credential);
438 attach_proof(&mut credential, seed, verification_method, valid_from)?;
439 Ok(credential)
440}
441
442fn time_of(v: Option<&Value>) -> std::result::Result<i128, ()> {
443 match v.and_then(|v| v.as_str()) {
444 Some(s) => parse_protocol_time_ns(s).map_err(|_| ()),
445 None => Err(()),
446 }
447}
448
449fn check_reasoned_action_inner(
452 credential: &Value,
453 public_key: &[u8],
454 escrow_public_key: Option<&[u8]>,
455 require_escrow: bool,
456 clock: Option<(i128, i128)>,
457) -> Option<String> {
458 if !type_list(credential)
459 .iter()
460 .any(|t| t == REASONED_ACTION_TYPE)
461 {
462 return Some(REASON_NOT_REASONED_ACTION.into());
463 }
464 let bound = match (
465 crate::credentials::issuer_did(credential),
466 credential.get("proof"),
467 ) {
468 (Some(issuer), Some(proof)) => crate::credentials::proof_bound_to_issuer(proof, issuer),
469 _ => false,
470 };
471 if !bound {
472 return Some(REASON_INVALID_PROOF.into());
473 }
474 match data_integrity::verify_proof(credential, public_key) {
475 Ok(true) => {}
476 _ => return Some(REASON_INVALID_PROOF.into()),
477 }
478
479 let jblock = credential
480 .get("credentialSubject")
481 .and_then(|s| s.get("justification"))
482 .filter(|j| j.is_object());
483 let Some(jblock) = jblock else {
484 return Some(REASON_MISSING_COMMITMENT.into());
485 };
486 let commitment_digest = jblock
487 .get("commitment")
488 .and_then(|c| c.get("digest"))
489 .and_then(|d| d.as_str());
490 let commitment_digest = match commitment_digest {
491 Some(d) if !d.is_empty() => d,
492 _ => return Some(REASON_MISSING_COMMITMENT.into()),
493 };
494
495 let Ok(executed) = time_of(credential.get("validFrom")) else {
496 return Some(REASON_MALFORMED_TIME.into());
497 };
498 let sealed = match jblock.get("sealedAt") {
499 None => None,
500 Some(v) => match time_of(Some(v)) {
501 Ok(t) => Some(t),
502 Err(()) => return Some(REASON_MALFORMED_TIME.into()),
503 },
504 };
505 if let Some(t) = sealed {
506 if t > executed {
507 return Some(REASON_SEAL_AFTER_EXECUTION.into());
508 }
509 if let Some((now, skew)) = clock {
510 if t > now + skew {
511 return Some(REASON_SEAL_IN_FUTURE.into());
512 }
513 }
514 }
515
516 let receipt = match jblock.get("escrowReceipt") {
517 None => {
518 return if require_escrow {
519 Some(REASON_MISSING_ESCROW.into())
520 } else {
521 None
522 };
523 }
524 Some(r) => r,
525 };
526 let escrow_key = match escrow_public_key {
527 Some(k) => k,
528 None => return Some(REASON_ESCROW_INVALID.into()),
529 };
530 let (ok, rsubject) = verify_escrow_receipt(receipt, escrow_key);
531 let Some(rsubject) = rsubject.filter(|_| ok) else {
532 return Some(REASON_ESCROW_INVALID.into());
533 };
534 if rsubject.get("agent").and_then(|v| v.as_str()) != crate::credentials::issuer_did(credential)
536 {
537 return Some(REASON_ESCROW_AGENT_MISMATCH.into());
538 }
539 if rsubject.get("committedDigest").and_then(|v| v.as_str()) != Some(commitment_digest) {
540 return Some(REASON_ESCROW_DIGEST_MISMATCH.into());
541 }
542 let Ok(deposited) = time_of(rsubject.get("depositedAt")) else {
543 return Some(REASON_ESCROW_INVALID.into());
544 };
545 if let Some(t) = sealed {
546 if t > deposited {
547 return Some(REASON_SEAL_AFTER_DEPOSIT.into());
548 }
549 }
550 if deposited > executed {
551 return Some(REASON_ESCROW_AFTER_EXECUTION.into());
552 }
553 if let Some((now, skew)) = clock {
554 if deposited > now + skew {
555 return Some(REASON_SEAL_IN_FUTURE.into());
556 }
557 }
558 None
559}
560
561pub fn check_reasoned_action(
579 credential: &Value,
580 public_key: &[u8],
581 escrow_public_key: Option<&[u8]>,
582 require_escrow: bool,
583) -> Option<String> {
584 check_reasoned_action_inner(
585 credential,
586 public_key,
587 escrow_public_key,
588 require_escrow,
589 None,
590 )
591}
592
593pub fn check_reasoned_action_at(
598 credential: &Value,
599 public_key: &[u8],
600 escrow_public_key: Option<&[u8]>,
601 require_escrow: bool,
602 now_iso: &str,
603 clock_skew_seconds: i64,
604) -> Result<Option<String>> {
605 let skew = check_clock_skew(clock_skew_seconds)?;
606 let now = parse_protocol_time_ns(now_iso)?;
607 Ok(check_reasoned_action_inner(
608 credential,
609 public_key,
610 escrow_public_key,
611 require_escrow,
612 Some((now, skew)),
613 ))
614}
615
616pub fn verify_reasoned_action(
619 credential: &Value,
620 public_key: &[u8],
621 escrow_public_key: Option<&[u8]>,
622 require_escrow: bool,
623) -> (bool, Option<Value>) {
624 if check_reasoned_action(credential, public_key, escrow_public_key, require_escrow).is_some() {
625 return (false, None);
626 }
627 (true, credential.get("credentialSubject").cloned())
628}
629
630pub fn verify_justification<F>(
635 presented_justification: &Value,
636 credential_subject: &Value,
637 resolver: F,
638) -> (bool, Option<String>)
639where
640 F: Fn(&str) -> Option<Value>,
641{
642 let committed = credential_subject
643 .get("justification")
644 .and_then(|j| j.get("commitment"))
645 .and_then(|c| c.get("digest"))
646 .and_then(|d| d.as_str());
647 let committed = match committed {
648 Some(d) if !d.is_empty() => d,
649 _ => return (false, Some(REASON_MISSING_COMMITMENT.into())),
650 };
651
652 match justification_digest(presented_justification) {
653 Ok(d) if d == committed => {}
654 _ => return (false, Some(REASON_JUSTIFICATION_DIGEST_MISMATCH.into())),
655 }
656
657 let anchors = presented_justification
658 .get("evidenceAnchors")
659 .and_then(|a| a.as_array());
660 let anchors = match anchors {
661 Some(a) if !a.is_empty() => a,
662 _ => return (false, Some(REASON_UNANCHORED_CLAIM.into())),
663 };
664 for anchor in anchors {
665 let reference = anchor.get("ref").and_then(|v| v.as_str());
666 let artifact = reference.and_then(&resolver);
667 let artifact = match artifact {
668 Some(a) => a,
669 None => return (false, Some(REASON_EVIDENCE_UNRESOLVED.into())),
670 };
671 let expected = anchor.get("evidenceHash").and_then(|v| v.as_str());
672 match artifact_digest(&artifact) {
673 Ok(actual) if Some(actual.as_str()) == expected => {}
674 _ => return (false, Some(REASON_EVIDENCE_HASH_MISMATCH.into())),
675 }
676 }
677 (true, None)
678}
679
680#[derive(Debug, Clone, Copy, PartialEq, Eq)]
687pub struct PulseWindow {
688 pub in_window: bool,
690 pub in_gap: bool,
692 pub seconds_into_window: i64,
694}
695
696pub fn pulse_window(
700 last_pulse: &str,
701 interval_seconds: i64,
702 exec_time: &str,
703) -> Result<PulseWindow> {
704 let pulse = parse_protocol_time_ns(last_pulse)?;
705 let exec = parse_protocol_time_ns(exec_time)?;
706 let delta = exec - pulse;
707 let interval = seconds_to_ns(interval_seconds);
708 let in_window = delta >= 0 && delta < interval;
709 Ok(PulseWindow {
710 in_window,
711 in_gap: delta >= interval,
712 seconds_into_window: delta.div_euclid(1_000_000_000) as i64,
713 })
714}
715
716#[derive(Debug, Clone, Copy, PartialEq, Eq)]
718pub struct FreshnessRequirement {
719 pub require_fresh_seal: bool,
722 pub max_age_seconds: i64,
725}
726
727impl FreshnessRequirement {
728 pub const NONE: FreshnessRequirement = FreshnessRequirement {
729 require_fresh_seal: false,
730 max_age_seconds: i64::MAX,
731 };
732}
733
734pub const TIER_ROUTINE: i64 = 0;
737pub const TIER_LOW: i64 = 1;
738pub const TIER_MEDIUM: i64 = 2;
739pub const TIER_HIGH: i64 = 3;
740pub const TIER_CRITICAL: i64 = 4;
741
742pub fn default_requirement(tier: i64) -> FreshnessRequirement {
747 match tier {
748 t if t >= TIER_CRITICAL => FreshnessRequirement {
749 require_fresh_seal: true,
750 max_age_seconds: 60,
751 },
752 TIER_HIGH => FreshnessRequirement {
753 require_fresh_seal: true,
754 max_age_seconds: 300,
755 },
756 _ => FreshnessRequirement::NONE,
757 }
758}
759
760pub fn seal_timestamp(credential: &Value) -> Option<String> {
767 let jblock = credential
768 .get("credentialSubject")
769 .and_then(|s| s.get("justification"))?;
770 let deposited = jblock
771 .get("escrowReceipt")
772 .and_then(|r| r.get("credentialSubject"))
773 .and_then(|s| s.get("depositedAt"))
774 .and_then(|v| v.as_str());
775 if let Some(d) = deposited {
776 return Some(d.to_string());
777 }
778 jblock
779 .get("sealedAt")
780 .and_then(|v| v.as_str())
781 .map(|s| s.to_string())
782}
783
784pub fn check_seal_freshness(
797 sealed_at: &str,
798 exec_time: &str,
799 last_pulse: &str,
800 requirement: FreshnessRequirement,
801) -> Result<Option<String>> {
802 if !requirement.require_fresh_seal {
803 return Ok(None);
804 }
805 let sealed = parse_protocol_time_ns(sealed_at)?;
806 let exec = parse_protocol_time_ns(exec_time)?;
807 let pulse = parse_protocol_time_ns(last_pulse)?;
808 if sealed < pulse {
809 return Ok(Some(format!(
810 "{REASON_INTENT_SEAL_STALE}:sealed_at={sealed_at},last_pulse={last_pulse}"
811 )));
812 }
813 if requirement.max_age_seconds != i64::MAX
814 && exec - sealed > seconds_to_ns(requirement.max_age_seconds)
815 {
816 return Ok(Some(format!(
817 "{REASON_INTENT_SEAL_EXPIRED}:sealed_at={sealed_at},max_age={}s",
818 requirement.max_age_seconds
819 )));
820 }
821 Ok(None)
822}
823
824pub fn verify_intent_freshness(
831 credential: &Value,
832 tier: i64,
833 last_pulse: &str,
834 requirement: FreshnessRequirement,
835) -> Result<Option<String>> {
836 if !requirement.require_fresh_seal {
837 return Ok(None);
838 }
839 parse_protocol_time_ns(last_pulse)?;
840 let receipt = credential
841 .get("credentialSubject")
842 .and_then(|s| s.get("justification"))
843 .and_then(|j| j.get("escrowReceipt"));
844 Ok(Some(match receipt {
845 None => format!("{REASON_INTENT_SEAL_MISSING}:tier={tier}"),
846 Some(_) => REASON_ESCROW_INVALID.to_string(),
847 }))
848}
849
850#[allow(clippy::too_many_arguments)]
876pub fn recheck_intent_freshness(
877 credential: &Value,
878 tier: i64,
879 last_pulse: &str,
880 requirement: FreshnessRequirement,
881 now_iso: &str,
882 clock_skew_seconds: i64,
883 escrow_public_key: Option<&[u8]>,
884) -> Result<Option<String>> {
885 if !requirement.require_fresh_seal {
886 return Ok(None);
887 }
888 let skew = check_clock_skew(clock_skew_seconds)?;
889 let now = parse_protocol_time_ns(now_iso)?;
890 parse_protocol_time_ns(last_pulse)?;
891
892 let jblock = credential
893 .get("credentialSubject")
894 .and_then(|s| s.get("justification"))
895 .filter(|j| j.is_object());
896 let Some(receipt) = jblock.and_then(|j| j.get("escrowReceipt")) else {
897 return Ok(Some(format!("{REASON_INTENT_SEAL_MISSING}:tier={tier}")));
898 };
899 let (ok, rsubject) = match escrow_public_key {
900 Some(k) => verify_escrow_receipt(receipt, k),
901 None => (false, None),
902 };
903 let Some(rsubject) = rsubject.filter(|_| ok) else {
904 return Ok(Some(REASON_ESCROW_INVALID.into()));
905 };
906 if rsubject.get("agent").and_then(|v| v.as_str()) != crate::credentials::issuer_did(credential)
907 {
908 return Ok(Some(REASON_ESCROW_AGENT_MISMATCH.into()));
909 }
910 let digest = jblock
911 .and_then(|j| j.get("commitment"))
912 .and_then(|c| c.get("digest"))
913 .and_then(|d| d.as_str())
914 .filter(|d| !d.is_empty());
915 if digest.is_none() || rsubject.get("committedDigest").and_then(|v| v.as_str()) != digest {
916 return Ok(Some(REASON_ESCROW_DIGEST_MISMATCH.into()));
917 }
918
919 let exec_str = credential
920 .get("validFrom")
921 .and_then(|v| v.as_str())
922 .unwrap_or_default();
923 let deposited_str = rsubject
924 .get("depositedAt")
925 .and_then(|v| v.as_str())
926 .unwrap_or_default()
927 .to_string();
928 let (Ok(executed), Ok(deposited)) = (
929 time_of(credential.get("validFrom")),
930 time_of(rsubject.get("depositedAt")),
931 ) else {
932 return Ok(Some(REASON_MALFORMED_TIME.into()));
933 };
934 let sealed = match jblock.and_then(|j| j.get("sealedAt")) {
935 None => None,
936 Some(v) => match time_of(Some(v)) {
937 Ok(t) => Some(t),
938 Err(()) => return Ok(Some(REASON_MALFORMED_TIME.into())),
939 },
940 };
941 if sealed.is_some_and(|t| t > deposited) {
942 return Ok(Some(REASON_SEAL_AFTER_DEPOSIT.into()));
943 }
944 if deposited > executed {
945 return Ok(Some(REASON_ESCROW_AFTER_EXECUTION.into()));
946 }
947 if deposited > now + skew {
948 return Ok(Some(format!(
949 "{REASON_INTENT_SEAL_FUTURE}:sealed_at={deposited_str}"
950 )));
951 }
952 if (executed - now).abs() > skew {
953 return Ok(Some(format!(
954 "{REASON_INTENT_EXECUTION_NOT_CURRENT}:valid_from={exec_str}"
955 )));
956 }
957 check_seal_freshness(&deposited_str, exec_str, last_pulse, requirement)
958}
959
960#[allow(clippy::too_many_arguments)]
965pub fn reseal_intent(
966 seed: &[u8],
967 issuer_did: &str,
968 verification_method: &str,
969 intent: &Value,
970 anchors: &[Value],
971 commitment_level: Option<i64>,
972 now: &str,
973 credential_id: &str,
974 include_reasoning: bool,
975) -> Result<Value> {
976 let justification = build_justification(intent, anchors, commitment_level)?;
977 let opts = SignReasonedActionOptions {
978 include_reasoning,
979 escrow_receipt: None,
980 sealed_at: Some(now.to_string()),
981 };
982 sign_reasoned_action(
983 seed,
984 issuer_did,
985 verification_method,
986 intent,
987 &justification,
988 now,
989 credential_id,
990 &opts,
991 )
992}
993
994#[cfg(test)]
995mod tests {
996 use super::*;
997 use crate::keys::Ed25519KeyPair;
998 use serde_json::json;
999
1000 fn seed() -> [u8; 32] {
1001 [7u8; 32]
1002 }
1003
1004 fn pubkey() -> [u8; 32] {
1005 Ed25519KeyPair::from_seed_slice(&seed())
1006 .unwrap()
1007 .public_key()
1008 }
1009
1010 fn sample_intent() -> Value {
1011 json!({"action": "transfer_funds", "target": "account:9911", "resource": "https://bank.example/v1/xfer"})
1012 }
1013
1014 fn sample_justification() -> Value {
1015 let anchor = evidence_anchor(
1016 "user approved the transfer",
1017 "urn:msg:42",
1018 Some(&json!({"text": "please move $500 to savings"})),
1019 None,
1020 "user_message",
1021 )
1022 .unwrap();
1023 build_justification(&sample_intent(), &[anchor], Some(TIER_HIGH)).unwrap()
1024 }
1025
1026 #[test]
1027 fn justification_digest_is_multibase_b64url() {
1028 let d = justification_digest(&sample_justification()).unwrap();
1029 assert!(d.starts_with('u'));
1030 }
1031
1032 #[test]
1033 fn sign_then_verify_reasoned_action() {
1034 let cred = sign_reasoned_action(
1035 &seed(),
1036 "did:web:agent.example",
1037 "did:web:agent.example#key-1",
1038 &sample_intent(),
1039 &sample_justification(),
1040 "2026-08-02T10:00:00Z",
1041 "urn:uuid:11111111-1111-1111-1111-111111111111",
1042 &SignReasonedActionOptions::new(),
1043 )
1044 .unwrap();
1045 assert!(check_reasoned_action(&cred, &pubkey(), None, false).is_none());
1046 assert_eq!(
1047 check_reasoned_action(&cred, &pubkey(), None, true),
1048 Some(REASON_MISSING_ESCROW.into())
1049 );
1050 }
1051
1052 #[test]
1053 fn tampered_action_fails() {
1054 let mut cred = sign_reasoned_action(
1055 &seed(),
1056 "did:web:agent.example",
1057 "did:web:agent.example#key-1",
1058 &sample_intent(),
1059 &sample_justification(),
1060 "2026-08-02T10:00:00Z",
1061 "urn:uuid:11111111-1111-1111-1111-111111111111",
1062 &SignReasonedActionOptions::new(),
1063 )
1064 .unwrap();
1065 cred["credentialSubject"]["intent"]["action"] = json!("drain_account");
1066 assert_eq!(
1067 check_reasoned_action(&cred, &pubkey(), None, false),
1068 Some(REASON_INVALID_PROOF.into())
1069 );
1070 }
1071
1072 #[test]
1073 fn pulse_window_classifies_window_and_gap() {
1074 let w = pulse_window("2026-08-02T10:00:00Z", 60, "2026-08-02T10:00:30Z").unwrap();
1076 assert!(w.in_window && !w.in_gap);
1077 let g = pulse_window("2026-08-02T10:00:00Z", 60, "2026-08-02T10:02:00Z").unwrap();
1078 assert!(g.in_gap && !g.in_window);
1079 }
1080
1081 fn reasoned_with_seal(sealed_at: &str, exec: &str, level: i64) -> Value {
1084 let anchor = evidence_anchor(
1085 "user approved",
1086 "urn:msg:42",
1087 Some(&json!({"text": "go"})),
1088 None,
1089 "user_message",
1090 )
1091 .unwrap();
1092 let just = build_justification(&sample_intent(), &[anchor], Some(level)).unwrap();
1093 let opts = SignReasonedActionOptions {
1094 include_reasoning: true,
1095 escrow_receipt: None,
1096 sealed_at: Some(sealed_at.to_string()),
1097 };
1098 sign_reasoned_action(
1099 &seed(),
1100 "did:web:agent.example",
1101 "did:web:agent.example#key-1",
1102 &sample_intent(),
1103 &just,
1104 exec,
1105 "urn:uuid:22222222-2222-2222-2222-222222222222",
1106 &opts,
1107 )
1108 .unwrap()
1109 }
1110
1111 #[test]
1112 fn agent_seal_alone_does_not_meet_a_high_tier() {
1113 let cred = reasoned_with_seal("2026-08-02T10:00:10Z", "2026-08-02T10:00:20Z", TIER_HIGH);
1116 let r = recheck_intent_freshness(
1117 &cred,
1118 TIER_HIGH,
1119 "2026-08-02T10:00:00Z",
1120 default_requirement(TIER_HIGH),
1121 "2026-08-02T10:00:20Z",
1122 30,
1123 Some(&pubkey()),
1124 )
1125 .unwrap();
1126 assert_eq!(
1127 r,
1128 Some(format!("{REASON_INTENT_SEAL_MISSING}:tier={TIER_HIGH}"))
1129 );
1130 }
1131
1132 #[test]
1133 fn stale_seal_across_boundary_rejects() {
1134 let r = check_seal_freshness(
1137 "2026-08-02T09:59:50Z",
1138 "2026-08-02T10:00:20Z",
1139 "2026-08-02T10:00:00Z",
1140 default_requirement(TIER_HIGH),
1141 )
1142 .unwrap();
1143 assert_eq!(
1144 r,
1145 Some(
1146 "intent_seal_stale:sealed_at=2026-08-02T09:59:50Z,last_pulse=2026-08-02T10:00:00Z"
1147 .into()
1148 )
1149 );
1150 assert_eq!(
1151 check_seal_freshness(
1152 "2026-08-02T10:00:10Z",
1153 "2026-08-02T10:00:20Z",
1154 "2026-08-02T10:00:00Z",
1155 default_requirement(TIER_HIGH),
1156 )
1157 .unwrap(),
1158 None
1159 );
1160 }
1161
1162 #[test]
1163 fn reseal_in_gap_is_a_valid_action() {
1164 let cred = reseal_intent(
1167 &seed(),
1168 "did:web:agent.example",
1169 "did:web:agent.example#key-1",
1170 &sample_intent(),
1171 &[evidence_anchor(
1172 "user approved",
1173 "urn:msg:42",
1174 Some(&json!({"text": "go"})),
1175 None,
1176 "user_message",
1177 )
1178 .unwrap()],
1179 Some(TIER_HIGH),
1180 "2026-08-02T10:05:00Z",
1181 "urn:uuid:33333333-3333-3333-3333-333333333333",
1182 true,
1183 )
1184 .unwrap();
1185 assert!(check_reasoned_action(&cred, &pubkey(), None, false).is_none());
1188 let r = verify_intent_freshness(
1189 &cred,
1190 TIER_HIGH,
1191 "2026-08-02T10:05:00Z",
1192 default_requirement(TIER_HIGH),
1193 )
1194 .unwrap();
1195 assert_eq!(
1196 r,
1197 Some(format!("{REASON_INTENT_SEAL_MISSING}:tier={TIER_HIGH}"))
1198 );
1199 }
1200
1201 #[test]
1202 fn non_sensitive_tier_ignores_stale_seal() {
1203 let cred = reasoned_with_seal("2026-08-02T09:59:50Z", "2026-08-02T10:00:20Z", TIER_ROUTINE);
1205 let r = verify_intent_freshness(
1206 &cred,
1207 TIER_ROUTINE,
1208 "2026-08-02T10:00:00Z",
1209 default_requirement(TIER_ROUTINE),
1210 )
1211 .unwrap();
1212 assert_eq!(r, None);
1213 }
1214
1215 #[test]
1216 fn sensitive_tier_without_seal_is_missing() {
1217 let cred = sign_reasoned_action(
1219 &seed(),
1220 "did:web:agent.example",
1221 "did:web:agent.example#key-1",
1222 &sample_intent(),
1223 &sample_justification(),
1224 "2026-08-02T10:00:20Z",
1225 "urn:uuid:44444444-4444-4444-4444-444444444444",
1226 &SignReasonedActionOptions::new(),
1227 )
1228 .unwrap();
1229 let r = verify_intent_freshness(
1230 &cred,
1231 TIER_HIGH,
1232 "2026-08-02T10:00:00Z",
1233 default_requirement(TIER_HIGH),
1234 )
1235 .unwrap();
1236 assert_eq!(r, Some("intent_seal_missing:tier=3".into()));
1237 }
1238
1239 #[test]
1240 fn escrow_roundtrip_and_seal_from_deposit() {
1241 let escrow_seed = [3u8; 32];
1242 let escrow_pub = Ed25519KeyPair::from_seed_slice(&escrow_seed)
1243 .unwrap()
1244 .public_key();
1245 let digest = justification_digest(&sample_justification()).unwrap();
1246 let receipt = build_escrow_receipt(
1247 &escrow_seed,
1248 "did:web:escrow.example",
1249 "did:web:escrow.example#key-1",
1250 "did:web:agent.example",
1251 &digest,
1252 "2026-08-02T10:00:05Z",
1253 "urn:uuid:55555555-5555-5555-5555-555555555555",
1254 )
1255 .unwrap();
1256 let (ok, _) = verify_escrow_receipt(&receipt, &escrow_pub);
1257 assert!(ok);
1258
1259 let mut second = receipt.clone();
1263 let context = second["@context"].clone();
1264 second["proof"]["@context"] = context.clone();
1265 assert!(data_integrity::verify_proof(&second, &escrow_pub).unwrap());
1266 assert_eq!(verify_escrow_receipt(&second, &escrow_pub), (false, None));
1267 let mut in_a_list = receipt.clone();
1268 let mut listed = in_a_list["proof"].clone();
1269 listed["@context"] = context;
1270 in_a_list["proof"] = Value::Array(vec![listed]);
1271 assert_eq!(
1272 verify_escrow_receipt(&in_a_list, &escrow_pub),
1273 (false, None)
1274 );
1275
1276 let opts = SignReasonedActionOptions {
1277 include_reasoning: true,
1278 escrow_receipt: Some(receipt),
1279 sealed_at: None,
1280 };
1281 let cred = sign_reasoned_action(
1282 &seed(),
1283 "did:web:agent.example",
1284 "did:web:agent.example#key-1",
1285 &sample_intent(),
1286 &sample_justification(),
1287 "2026-08-02T10:00:20Z",
1288 "urn:uuid:66666666-6666-6666-6666-666666666666",
1289 &opts,
1290 )
1291 .unwrap();
1292 assert_eq!(
1294 seal_timestamp(&cred).as_deref(),
1295 Some("2026-08-02T10:00:05Z")
1296 );
1297 assert!(check_reasoned_action(&cred, &pubkey(), Some(&escrow_pub), true).is_none());
1298 }
1299
1300 fn escrow_seed() -> [u8; 32] {
1303 [9u8; 32]
1304 }
1305
1306 fn escrow_pub() -> [u8; 32] {
1307 Ed25519KeyPair::from_seed(&escrow_seed()).public_key()
1308 }
1309
1310 fn escrowed(agent: &str, deposited: &str, exec: &str, sealed: Option<&str>) -> Value {
1314 let just = sample_justification();
1315 let digest = justification_digest(&just).unwrap();
1316 let receipt = build_escrow_receipt(
1317 &escrow_seed(),
1318 "did:web:escrow.example",
1319 "did:web:escrow.example#key-1",
1320 agent,
1321 &digest,
1322 deposited,
1323 "urn:uuid:33333333-3333-3333-3333-333333333333",
1324 )
1325 .unwrap();
1326 let opts = SignReasonedActionOptions {
1327 include_reasoning: true,
1328 escrow_receipt: Some(receipt),
1329 sealed_at: sealed.map(String::from),
1330 };
1331 sign_reasoned_action(
1332 &seed(),
1333 "did:web:agent.example",
1334 "did:web:agent.example#key-1",
1335 &sample_intent(),
1336 &just,
1337 exec,
1338 "urn:uuid:44444444-4444-4444-4444-444444444444",
1339 &opts,
1340 )
1341 .unwrap()
1342 }
1343
1344 fn recheck(cred: &Value, now: &str) -> Option<String> {
1345 recheck_intent_freshness(
1346 cred,
1347 TIER_CRITICAL,
1348 "2026-04-26T10:00:00Z",
1349 default_requirement(TIER_CRITICAL),
1350 now,
1351 30,
1352 Some(&escrow_pub()),
1353 )
1354 .unwrap()
1355 }
1356
1357 #[test]
1358 fn recheck_accepts_a_fresh_witnessed_seal() {
1359 let cred = escrowed(
1360 "did:web:agent.example",
1361 "2026-04-26T10:02:30Z",
1362 "2026-04-26T10:03:00Z",
1363 None,
1364 );
1365 assert_eq!(recheck(&cred, "2026-04-26T10:03:05Z"), None);
1366 assert!(check_reasoned_action(&cred, &pubkey(), Some(&escrow_pub()), true).is_none());
1367 }
1368
1369 #[test]
1370 fn recheck_uses_the_escrow_time_not_the_agents_claim() {
1371 let honest = escrowed(
1373 "did:web:agent.example",
1374 "2026-04-26T09:55:00Z",
1375 "2026-04-26T10:03:00Z",
1376 None,
1377 );
1378 assert!(recheck(&honest, "2026-04-26T10:03:00Z")
1379 .unwrap()
1380 .starts_with(REASON_INTENT_SEAL_STALE));
1381 let lying = escrowed(
1382 "did:web:agent.example",
1383 "2026-04-26T09:55:00Z",
1384 "2026-04-26T10:03:00Z",
1385 Some("2026-04-26T10:02:30Z"),
1386 );
1387 assert_eq!(
1388 recheck(&lying, "2026-04-26T10:03:00Z"),
1389 Some(REASON_SEAL_AFTER_DEPOSIT.into())
1390 );
1391 assert_eq!(
1392 check_reasoned_action(&lying, &pubkey(), Some(&escrow_pub()), true),
1393 Some(REASON_SEAL_AFTER_DEPOSIT.into())
1394 );
1395 let old = verify_intent_freshness(
1397 &lying,
1398 TIER_CRITICAL,
1399 "2026-04-26T10:00:00Z",
1400 default_requirement(TIER_CRITICAL),
1401 )
1402 .unwrap();
1403 assert_eq!(old, Some(REASON_ESCROW_INVALID.into()));
1404 }
1405
1406 #[test]
1407 fn recheck_refuses_forward_dated_and_late_seals() {
1408 let future = escrowed(
1409 "did:web:agent.example",
1410 "2099-01-01T00:00:00Z",
1411 "2099-01-01T00:00:00Z",
1412 Some("2099-01-01T00:00:00Z"),
1413 );
1414 assert_eq!(
1415 recheck(&future, "2026-04-26T10:03:00Z"),
1416 Some(format!(
1417 "{REASON_INTENT_SEAL_FUTURE}:sealed_at=2099-01-01T00:00:00Z"
1418 ))
1419 );
1420 assert_eq!(
1421 check_reasoned_action_at(
1422 &future,
1423 &pubkey(),
1424 Some(&escrow_pub()),
1425 true,
1426 "2026-04-26T10:03:00Z",
1427 30
1428 )
1429 .unwrap(),
1430 Some(REASON_SEAL_IN_FUTURE.into())
1431 );
1432 let late = escrowed(
1434 "did:web:agent.example",
1435 "2026-04-26T10:10:00Z",
1436 "2026-04-26T10:03:00Z",
1437 None,
1438 );
1439 assert_eq!(
1440 recheck(&late, "2026-04-26T10:03:00Z"),
1441 Some(REASON_ESCROW_AFTER_EXECUTION.into())
1442 );
1443 let ahead = escrowed(
1445 "did:web:agent.example",
1446 "2026-04-26T10:03:20Z",
1447 "2026-04-26T10:03:20Z",
1448 None,
1449 );
1450 assert_eq!(recheck(&ahead, "2026-04-26T10:03:00Z"), None, "inside skew");
1451 assert!(recheck(&ahead, "2026-04-26T10:02:40Z").is_some());
1452 let after =
1454 reasoned_with_seal("2026-04-26T10:10:00Z", "2026-04-26T10:03:00Z", TIER_ROUTINE);
1455 assert_eq!(
1456 check_reasoned_action(&after, &pubkey(), None, false),
1457 Some(REASON_SEAL_AFTER_EXECUTION.into())
1458 );
1459 let fresh = escrowed(
1461 "did:web:agent.example",
1462 "2026-04-26T10:02:30Z",
1463 "2026-04-26T10:03:00Z",
1464 None,
1465 );
1466 assert_eq!(
1467 recheck(&fresh, "2026-04-26T10:09:00Z"),
1468 Some(format!(
1469 "{REASON_INTENT_EXECUTION_NOT_CURRENT}:valid_from=2026-04-26T10:03:00Z"
1470 ))
1471 );
1472 }
1473
1474 #[test]
1475 fn recheck_binds_the_receipt_to_the_agent_and_key() {
1476 let stolen = escrowed(
1477 "did:web:someone-else.example",
1478 "2026-04-26T10:02:30Z",
1479 "2026-04-26T10:03:00Z",
1480 None,
1481 );
1482 assert_eq!(
1483 recheck(&stolen, "2026-04-26T10:03:00Z"),
1484 Some(REASON_ESCROW_AGENT_MISMATCH.into())
1485 );
1486 assert_eq!(
1487 check_reasoned_action(&stolen, &pubkey(), Some(&escrow_pub()), true),
1488 Some(REASON_ESCROW_AGENT_MISMATCH.into())
1489 );
1490 let good = escrowed(
1491 "did:web:agent.example",
1492 "2026-04-26T10:02:30Z",
1493 "2026-04-26T10:03:00Z",
1494 None,
1495 );
1496 let wrong = recheck_intent_freshness(
1498 &good,
1499 TIER_CRITICAL,
1500 "2026-04-26T10:00:00Z",
1501 default_requirement(TIER_CRITICAL),
1502 "2026-04-26T10:03:00Z",
1503 30,
1504 Some(&pubkey()),
1505 )
1506 .unwrap();
1507 assert_eq!(wrong, Some(REASON_ESCROW_INVALID.into()));
1508 let none = recheck_intent_freshness(
1509 &good,
1510 TIER_CRITICAL,
1511 "2026-04-26T10:00:00Z",
1512 default_requirement(TIER_CRITICAL),
1513 "2026-04-26T10:03:00Z",
1514 30,
1515 None,
1516 )
1517 .unwrap();
1518 assert_eq!(none, Some(REASON_ESCROW_INVALID.into()));
1519 let bare = reasoned_with_seal(
1520 "2026-04-26T10:02:30Z",
1521 "2026-04-26T10:03:00Z",
1522 TIER_CRITICAL,
1523 );
1524 assert_eq!(
1525 recheck(&bare, "2026-04-26T10:03:00Z"),
1526 Some(format!("{REASON_INTENT_SEAL_MISSING}:tier={TIER_CRITICAL}"))
1527 );
1528 assert!(recheck_intent_freshness(
1530 &good,
1531 TIER_CRITICAL,
1532 "2026-04-26T10:00:00Z",
1533 default_requirement(TIER_CRITICAL),
1534 "2026-04-26T10:03:00Z",
1535 121,
1536 Some(&escrow_pub()),
1537 )
1538 .is_err());
1539 }
1540
1541 #[test]
1542 fn proof_bound_to_another_did_is_refused() {
1543 let cred = sign_reasoned_action(
1544 &seed(),
1545 "did:web:agent.example",
1546 "did:web:other.example#key-1",
1547 &sample_intent(),
1548 &sample_justification(),
1549 "2026-08-02T10:00:00Z",
1550 "urn:uuid:11111111-1111-1111-1111-111111111111",
1551 &SignReasonedActionOptions::new(),
1552 )
1553 .unwrap();
1554 assert_eq!(
1555 check_reasoned_action(&cred, &pubkey(), None, false),
1556 Some(REASON_INVALID_PROOF.into())
1557 );
1558 }
1559}