Skip to main content

vouch_core/
reasoning.rs

1//! Reasoned Action Proofs and event-triggered intent recheck.
2//!
3//! A standard credential answers *who* acted and *under what authority*. It says
4//! nothing about *why*. This module adds the missing "why" layer: before acting,
5//! an agent states a structured **justification** (an intent plus a set of
6//! **evidence anchors**, each a claim tied to a real artifact by that artifact's
7//! hash). The justification is committed by digest, optionally deposited with a
8//! neutral **escrow** that timestamps it, and the executed action credential
9//! carries the commitment. Three properties then hold: no fabrication (each
10//! reason names an artifact a verifier re-resolves and hashes), no post-hoc
11//! rewrite (the credential carries the digest), and, with escrow, committed
12//! before execution (the deposit time is not after execution).
13//!
14//! This is the canonical port of the Python reference `vouch/reasoning.py`. The
15//! digest algorithm and every stable reason string match byte for byte, so a
16//! seal built in one language verifies in another. Everything here is an ordinary
17//! `eddsa-jcs-2022` Verifiable Credential.
18//!
19//! ## Intent recheck (event-triggered)
20//!
21//! A heartbeat proves the agent is alive across an interval; it does not prove the
22//! agent's intent is current at the moment of a sensitive action. A justification
23//! sealed early in an interval still passes for an action executed much later in
24//! the same interval, so a sophisticated actor can time a sensitive action to land
25//! after a pulse boundary while reusing an intent sealed before it. The intent
26//! recheck binds seal freshness to the action: for a sensitive consequence tier
27//! the seal must post-date the last pulse boundary and be within a configurable
28//! max age, not merely predate execution. See [`verify_intent_freshness`] and
29//! [`reseal_intent`].
30
31use 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::iso_to_epoch_seconds;
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
47// Structured verification reasons (stable strings, mirrored by every SDK).
48pub 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
60// Intent-recheck reasons (stable prefixes; carry a structured suffix).
61pub 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";
64
65// ---------------------------------------------------------------------------
66// Low-level helpers
67// ---------------------------------------------------------------------------
68
69/// Multibase base64url-no-pad of raw bytes, matching the Python `_mb64` helper
70/// (`"u"` prefix + RFC 4648 base64url without padding).
71fn mb64(bytes: &[u8]) -> String {
72    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
73    use base64::Engine;
74    format!("u{}", URL_SAFE_NO_PAD.encode(bytes))
75}
76
77/// Canonical bytes of an evidence artifact, for content addressing. A JSON string
78/// is hashed as its UTF-8 bytes; a JSON object is JCS-canonicalized. This matches
79/// the `str`/`dict` cases of the Python `_artifact_bytes`. Raw byte artifacts use
80/// [`artifact_digest_bytes`].
81fn artifact_bytes(artifact: &Value) -> Result<Vec<u8>> {
82    match artifact {
83        Value::String(s) => Ok(s.as_bytes().to_vec()),
84        Value::Object(_) => Ok(jcs::canonicalize(artifact)),
85        _ => Err(CoreError::Json(
86            "evidence artifact must be a JSON object or string".into(),
87        )),
88    }
89}
90
91/// Multibase SHA-256 of an evidence artifact (JSON object or string).
92pub fn artifact_digest(artifact: &Value) -> Result<String> {
93    Ok(mb64(&Sha256::digest(&artifact_bytes(artifact)?)))
94}
95
96/// Multibase SHA-256 of a raw-byte evidence artifact.
97pub fn artifact_digest_bytes(artifact: &[u8]) -> String {
98    mb64(&Sha256::digest(artifact))
99}
100
101fn type_list(credential: &Value) -> Vec<String> {
102    match credential.get("type") {
103        Some(Value::String(s)) => vec![s.clone()],
104        Some(Value::Array(a)) => a
105            .iter()
106            .filter_map(|v| v.as_str().map(|s| s.to_string()))
107            .collect(),
108        _ => Vec::new(),
109    }
110}
111
112/// Attach an `eddsa-jcs-2022` proof to `credential` in place, signing with the
113/// raw Ed25519 seed and stamping `created`.
114fn attach_proof(
115    credential: &mut Value,
116    seed: &[u8],
117    verification_method: &str,
118    created: &str,
119) -> Result<()> {
120    let opts = BuildProofOptions::new(verification_method, created);
121    let proof = data_integrity::build_proof(credential, seed, &opts)?;
122    credential
123        .as_object_mut()
124        .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
125        .insert("proof".into(), proof);
126    Ok(())
127}
128
129// ---------------------------------------------------------------------------
130// Justification: the structured "why", anchored to real evidence
131// ---------------------------------------------------------------------------
132
133/// Build one evidence anchor: a claim tied to a verifiable artifact. Supply
134/// `evidence` (its hash is computed) OR a precomputed `evidence_hash`.
135pub fn evidence_anchor(
136    claim: &str,
137    reference: &str,
138    evidence: Option<&Value>,
139    evidence_hash: Option<&str>,
140    anchor_type: &str,
141) -> Result<Value> {
142    if claim.is_empty() || reference.is_empty() {
143        return Err(CoreError::Json(
144            "an evidence anchor needs a claim and a ref".into(),
145        ));
146    }
147    let hash = match evidence_hash {
148        Some(h) => h.to_string(),
149        None => match evidence {
150            Some(e) => artifact_digest(e)?,
151            None => {
152                return Err(CoreError::Json(
153                    "supply evidence or evidence_hash for the anchor".into(),
154                ))
155            }
156        },
157    };
158    let mut anchor = Map::new();
159    anchor.insert("type".into(), Value::String(anchor_type.to_string()));
160    anchor.insert("claim".into(), Value::String(claim.to_string()));
161    anchor.insert("ref".into(), Value::String(reference.to_string()));
162    anchor.insert("evidenceHash".into(), Value::String(hash));
163    Ok(Value::Object(anchor))
164}
165
166/// Assemble a justification: the intent plus its evidence anchors. `intent` must
167/// carry at least `action` and `target`; at least one anchor is required.
168pub fn build_justification(
169    intent: &Value,
170    anchors: &[Value],
171    commitment_level: Option<i64>,
172) -> Result<Value> {
173    if !intent.is_object()
174        || intent.get("action").and_then(|v| v.as_str()).is_none()
175        || intent.get("target").and_then(|v| v.as_str()).is_none()
176    {
177        return Err(CoreError::Json(
178            "intent must be an object with at least action and target".into(),
179        ));
180    }
181    if anchors.is_empty() {
182        return Err(CoreError::Json(
183            "a justification needs at least one evidence anchor".into(),
184        ));
185    }
186    let mut just = Map::new();
187    just.insert("intent".into(), intent.clone());
188    just.insert("evidenceAnchors".into(), Value::Array(anchors.to_vec()));
189    if let Some(level) = commitment_level {
190        just.insert("commitmentLevel".into(), Value::from(level));
191    }
192    Ok(Value::Object(just))
193}
194
195/// Multibase SHA-256 over the JCS-canonical justification.
196pub fn justification_digest(justification: &Value) -> Result<String> {
197    if !justification.is_object() {
198        return Err(CoreError::Json(
199            "justification must be a JSON object".into(),
200        ));
201    }
202    Ok(mb64(&Sha256::digest(&jcs::canonicalize(justification))))
203}
204
205// ---------------------------------------------------------------------------
206// Escrow: a neutral timestamp that fixes the commitment before execution
207// ---------------------------------------------------------------------------
208
209/// Issue a signed `JustificationEscrowReceipt` fixing a commitment in time. The
210/// escrow sees only the digest, never the plaintext justification.
211#[allow(clippy::too_many_arguments)]
212pub fn build_escrow_receipt(
213    escrow_seed: &[u8],
214    escrow_did: &str,
215    escrow_verification_method: &str,
216    agent_did: &str,
217    committed_digest: &str,
218    deposited_at: &str,
219    credential_id: &str,
220) -> Result<Value> {
221    let mut subject = Map::new();
222    subject.insert("agent".into(), Value::String(agent_did.to_string()));
223    subject.insert(
224        "committedDigest".into(),
225        Value::String(committed_digest.to_string()),
226    );
227    subject.insert(
228        "depositedAt".into(),
229        Value::String(deposited_at.to_string()),
230    );
231
232    let mut receipt = Map::new();
233    receipt.insert(
234        "@context".into(),
235        Value::Array(vec![
236            Value::String(VC_CONTEXT_V2.into()),
237            Value::String(VOUCH_CONTEXT_V1.into()),
238        ]),
239    );
240    receipt.insert(
241        "type".into(),
242        Value::Array(vec![
243            Value::String("VerifiableCredential".into()),
244            Value::String(ESCROW_RECEIPT_TYPE.into()),
245        ]),
246    );
247    receipt.insert("id".into(), Value::String(credential_id.to_string()));
248    receipt.insert("issuer".into(), Value::String(escrow_did.to_string()));
249    receipt.insert("validFrom".into(), Value::String(deposited_at.to_string()));
250    receipt.insert("credentialSubject".into(), Value::Object(subject));
251
252    let mut receipt = Value::Object(receipt);
253    attach_proof(
254        &mut receipt,
255        escrow_seed,
256        escrow_verification_method,
257        deposited_at,
258    )?;
259    Ok(receipt)
260}
261
262/// Verify an escrow receipt's proof and structure against the escrow's raw
263/// Ed25519 public key. Returns `(ok, subject)`.
264pub fn verify_escrow_receipt(receipt: &Value, escrow_public_key: &[u8]) -> (bool, Option<Value>) {
265    if !type_list(receipt).iter().any(|t| t == ESCROW_RECEIPT_TYPE) {
266        return (false, None);
267    }
268    match data_integrity::verify_proof(receipt, escrow_public_key) {
269        Ok(true) => {}
270        _ => return (false, None),
271    }
272    let subject = match receipt.get("credentialSubject").and_then(|s| s.as_object()) {
273        Some(s) => s,
274        None => return (false, None),
275    };
276    let has_digest = subject
277        .get("committedDigest")
278        .and_then(|v| v.as_str())
279        .is_some_and(|s| !s.is_empty());
280    let has_deposited = subject
281        .get("depositedAt")
282        .and_then(|v| v.as_str())
283        .is_some_and(|s| !s.is_empty());
284    if !has_digest || !has_deposited {
285        return (false, None);
286    }
287    (true, Some(Value::Object(subject.clone())))
288}
289
290// ---------------------------------------------------------------------------
291// Reasoned action credential: the executed action, carrying its commitment
292// ---------------------------------------------------------------------------
293
294/// Options for [`sign_reasoned_action`].
295#[derive(Debug, Clone, Default)]
296pub struct SignReasonedActionOptions {
297    /// If false, publish only the digest (private reasoning); reveal anchors out
298    /// of band at audit time. Defaults to true.
299    pub include_reasoning: bool,
300    /// Attach an escrow receipt proving the commitment was fixed before this
301    /// action.
302    pub escrow_receipt: Option<Value>,
303    /// The moment the intent was sealed. Read by the intent recheck. When escrow
304    /// is used this SHOULD equal the receipt's `depositedAt`; without escrow the
305    /// signer stamps it. Absent by default (backward compatible).
306    pub sealed_at: Option<String>,
307}
308
309impl SignReasonedActionOptions {
310    pub fn new() -> Self {
311        Self {
312            include_reasoning: true,
313            escrow_receipt: None,
314            sealed_at: None,
315        }
316    }
317}
318
319/// Issue a `ReasonedActionCredential`: the action bound to its justification.
320/// `valid_from` is the execution time and also the proof `created`.
321#[allow(clippy::too_many_arguments)]
322pub fn sign_reasoned_action(
323    seed: &[u8],
324    issuer_did: &str,
325    verification_method: &str,
326    intent: &Value,
327    justification: &Value,
328    valid_from: &str,
329    credential_id: &str,
330    opts: &SignReasonedActionOptions,
331) -> Result<Value> {
332    if !intent.is_object()
333        || intent.get("action").and_then(|v| v.as_str()).is_none()
334        || intent.get("target").and_then(|v| v.as_str()).is_none()
335    {
336        return Err(CoreError::Json(
337            "intent must be an object with at least action and target".into(),
338        ));
339    }
340    let digest = justification_digest(justification)?;
341
342    let mut commitment = Map::new();
343    commitment.insert(
344        "algorithm".into(),
345        Value::String(JUSTIFICATION_ALGORITHM.into()),
346    );
347    commitment.insert("digest".into(), Value::String(digest));
348
349    let mut jblock = Map::new();
350    jblock.insert("commitment".into(), Value::Object(commitment));
351    if let Some(sealed) = &opts.sealed_at {
352        jblock.insert("sealedAt".into(), Value::String(sealed.clone()));
353    }
354    if let Some(level) = justification.get("commitmentLevel") {
355        jblock.insert("commitmentLevel".into(), level.clone());
356    }
357    if let Some(receipt) = &opts.escrow_receipt {
358        jblock.insert("escrowReceipt".into(), receipt.clone());
359    }
360    if opts.include_reasoning {
361        let anchors = justification
362            .get("evidenceAnchors")
363            .cloned()
364            .unwrap_or_else(|| Value::Array(Vec::new()));
365        jblock.insert("evidenceAnchors".into(), anchors);
366    }
367
368    let mut subject = Map::new();
369    subject.insert("intent".into(), intent.clone());
370    subject.insert("justification".into(), Value::Object(jblock));
371
372    let mut credential = Map::new();
373    credential.insert(
374        "@context".into(),
375        Value::Array(vec![
376            Value::String(VC_CONTEXT_V2.into()),
377            Value::String(VOUCH_CONTEXT_V1.into()),
378        ]),
379    );
380    credential.insert(
381        "type".into(),
382        Value::Array(vec![
383            Value::String("VerifiableCredential".into()),
384            Value::String(REASONED_ACTION_TYPE.into()),
385        ]),
386    );
387    credential.insert("id".into(), Value::String(credential_id.to_string()));
388    credential.insert("issuer".into(), Value::String(issuer_did.to_string()));
389    credential.insert("validFrom".into(), Value::String(valid_from.to_string()));
390    credential.insert("credentialSubject".into(), Value::Object(subject));
391
392    let mut credential = Value::Object(credential);
393    attach_proof(&mut credential, seed, verification_method, valid_from)?;
394    Ok(credential)
395}
396
397/// Verify a reasoned-action credential. Returns `None` on success or a structured
398/// reason string on failure. Checks the agent's proof, the commitment, and, when
399/// an escrow receipt is attached, the receipt's proof, digest agreement, and
400/// commit-before-execute. Does not resolve evidence anchors (see
401/// [`verify_justification`]).
402pub fn check_reasoned_action(
403    credential: &Value,
404    public_key: &[u8],
405    escrow_public_key: Option<&[u8]>,
406    require_escrow: bool,
407) -> Option<String> {
408    if !type_list(credential)
409        .iter()
410        .any(|t| t == REASONED_ACTION_TYPE)
411    {
412        return Some(REASON_NOT_REASONED_ACTION.into());
413    }
414    match data_integrity::verify_proof(credential, public_key) {
415        Ok(true) => {}
416        _ => return Some(REASON_INVALID_PROOF.into()),
417    }
418
419    let jblock = credential
420        .get("credentialSubject")
421        .and_then(|s| s.get("justification"));
422    let commitment_digest = jblock
423        .and_then(|j| j.get("commitment"))
424        .and_then(|c| c.get("digest"))
425        .and_then(|d| d.as_str());
426    let commitment_digest = match commitment_digest {
427        Some(d) if !d.is_empty() => d,
428        _ => return Some(REASON_MISSING_COMMITMENT.into()),
429    };
430
431    let receipt = jblock.and_then(|j| j.get("escrowReceipt"));
432    let receipt = match receipt {
433        None | Some(Value::Null) => {
434            return if require_escrow {
435                Some(REASON_MISSING_ESCROW.into())
436            } else {
437                None
438            };
439        }
440        Some(r) => r,
441    };
442
443    let escrow_key = match escrow_public_key {
444        Some(k) => k,
445        None => return Some(REASON_ESCROW_INVALID.into()),
446    };
447    let (ok, rsubject) = verify_escrow_receipt(receipt, escrow_key);
448    if !ok {
449        return Some(REASON_ESCROW_INVALID.into());
450    }
451    let rsubject = rsubject.unwrap();
452    if rsubject.get("committedDigest").and_then(|v| v.as_str()) != Some(commitment_digest) {
453        return Some(REASON_ESCROW_DIGEST_MISMATCH.into());
454    }
455
456    let deposited = rsubject
457        .get("depositedAt")
458        .and_then(|v| v.as_str())
459        .and_then(|s| iso_to_epoch_seconds(s).ok());
460    let executed = credential
461        .get("validFrom")
462        .and_then(|v| v.as_str())
463        .and_then(|s| iso_to_epoch_seconds(s).ok());
464    match (deposited, executed) {
465        (Some(d), Some(e)) if d > e => Some(REASON_ESCROW_AFTER_EXECUTION.into()),
466        (Some(_), Some(_)) => None,
467        _ => Some(REASON_ESCROW_INVALID.into()),
468    }
469}
470
471/// Convenience wrapper over [`check_reasoned_action`] returning
472/// `(ok, credentialSubject)`.
473pub fn verify_reasoned_action(
474    credential: &Value,
475    public_key: &[u8],
476    escrow_public_key: Option<&[u8]>,
477    require_escrow: bool,
478) -> (bool, Option<Value>) {
479    if check_reasoned_action(credential, public_key, escrow_public_key, require_escrow).is_some() {
480        return (false, None);
481    }
482    (true, credential.get("credentialSubject").cloned())
483}
484
485/// Check a revealed justification against a verified credential's commitment: the
486/// justification must recompute to the committed digest, and every anchor must
487/// resolve (via `resolver`) to an artifact whose hash matches. Returns
488/// `(true, None)` on success, else `(false, Some(reason))`.
489pub fn verify_justification<F>(
490    presented_justification: &Value,
491    credential_subject: &Value,
492    resolver: F,
493) -> (bool, Option<String>)
494where
495    F: Fn(&str) -> Option<Value>,
496{
497    let committed = credential_subject
498        .get("justification")
499        .and_then(|j| j.get("commitment"))
500        .and_then(|c| c.get("digest"))
501        .and_then(|d| d.as_str());
502    let committed = match committed {
503        Some(d) if !d.is_empty() => d,
504        _ => return (false, Some(REASON_MISSING_COMMITMENT.into())),
505    };
506
507    match justification_digest(presented_justification) {
508        Ok(d) if d == committed => {}
509        _ => return (false, Some(REASON_JUSTIFICATION_DIGEST_MISMATCH.into())),
510    }
511
512    let anchors = presented_justification
513        .get("evidenceAnchors")
514        .and_then(|a| a.as_array());
515    let anchors = match anchors {
516        Some(a) if !a.is_empty() => a,
517        _ => return (false, Some(REASON_UNANCHORED_CLAIM.into())),
518    };
519    for anchor in anchors {
520        let reference = anchor.get("ref").and_then(|v| v.as_str());
521        let artifact = reference.and_then(&resolver);
522        let artifact = match artifact {
523            Some(a) => a,
524            None => return (false, Some(REASON_EVIDENCE_UNRESOLVED.into())),
525        };
526        let expected = anchor.get("evidenceHash").and_then(|v| v.as_str());
527        match artifact_digest(&artifact) {
528            Ok(actual) if Some(actual.as_str()) == expected => {}
529            _ => return (false, Some(REASON_EVIDENCE_HASH_MISMATCH.into())),
530        }
531    }
532    (true, None)
533}
534
535// ---------------------------------------------------------------------------
536// Intent recheck: bind seal freshness to the action, not the interval alone
537// ---------------------------------------------------------------------------
538
539/// Where an action's execution time falls relative to the current pulse window
540/// `[last_pulse, last_pulse + interval)`.
541#[derive(Debug, Clone, Copy, PartialEq, Eq)]
542pub struct PulseWindow {
543    /// Execution is inside the current window (a pulse is not yet due).
544    pub in_window: bool,
545    /// Execution is in the gap past the window's end (the next pulse is overdue).
546    pub in_gap: bool,
547    /// Seconds from `last_pulse` to execution (negative if execution precedes it).
548    pub seconds_into_window: i64,
549}
550
551/// Classify an action's execution time against the pulse schedule. `last_pulse`
552/// is the issue time of the most recent heartbeat; `interval_seconds` is the
553/// heartbeat period.
554pub fn pulse_window(
555    last_pulse: &str,
556    interval_seconds: i64,
557    exec_time: &str,
558) -> Result<PulseWindow> {
559    let pulse = iso_to_epoch_seconds(last_pulse)?;
560    let exec = iso_to_epoch_seconds(exec_time)?;
561    let delta = exec - pulse;
562    let in_window = delta >= 0 && delta < interval_seconds;
563    Ok(PulseWindow {
564        in_window,
565        in_gap: delta >= interval_seconds,
566        seconds_into_window: delta,
567    })
568}
569
570/// The freshness requirement a consequence tier imposes on an intent seal.
571#[derive(Debug, Clone, Copy, PartialEq, Eq)]
572pub struct FreshnessRequirement {
573    /// The seal must post-date the last pulse boundary (be sealed in the current
574    /// window), not merely predate execution.
575    pub require_fresh_seal: bool,
576    /// The seal must be at most this many seconds older than execution. `i64::MAX`
577    /// means no age bound.
578    pub max_age_seconds: i64,
579}
580
581impl FreshnessRequirement {
582    pub const NONE: FreshnessRequirement = FreshnessRequirement {
583        require_fresh_seal: false,
584        max_age_seconds: i64::MAX,
585    };
586}
587
588/// Consequence tiers, aligned with PAD-017 commitment levels (0..4) and the
589/// trust-entropy stakes bands. Higher tiers demand a fresher seal.
590pub const TIER_ROUTINE: i64 = 0;
591pub const TIER_LOW: i64 = 1;
592pub const TIER_MEDIUM: i64 = 2;
593pub const TIER_HIGH: i64 = 3;
594pub const TIER_CRITICAL: i64 = 4;
595
596/// Reference intent-freshness policy: routine/low/medium tiers inherit the last
597/// pulse's assurance; high and critical tiers require a seal sealed after the
598/// last pulse boundary, within a tightening max age. Deployments substitute their
599/// own thresholds; these are reference values.
600pub fn default_requirement(tier: i64) -> FreshnessRequirement {
601    match tier {
602        t if t >= TIER_CRITICAL => FreshnessRequirement {
603            require_fresh_seal: true,
604            max_age_seconds: 60,
605        },
606        TIER_HIGH => FreshnessRequirement {
607            require_fresh_seal: true,
608            max_age_seconds: 300,
609        },
610        _ => FreshnessRequirement::NONE,
611    }
612}
613
614/// Read the seal timestamp from a reasoned-action credential: the justification's
615/// `sealedAt` if present, else the attached escrow receipt's `depositedAt`.
616pub fn seal_timestamp(credential: &Value) -> Option<String> {
617    let jblock = credential
618        .get("credentialSubject")
619        .and_then(|s| s.get("justification"))?;
620    if let Some(sealed) = jblock.get("sealedAt").and_then(|v| v.as_str()) {
621        return Some(sealed.to_string());
622    }
623    jblock
624        .get("escrowReceipt")
625        .and_then(|r| r.get("credentialSubject"))
626        .and_then(|s| s.get("depositedAt"))
627        .and_then(|v| v.as_str())
628        .map(|s| s.to_string())
629}
630
631/// The core intent-recheck rule. Given a seal time, the action's execution time,
632/// the last pulse boundary, and a tier's freshness requirement, return `None` if
633/// the seal is fresh enough, else a stable reason string.
634///
635/// - `intent_seal_stale:sealed_at=<t>,last_pulse=<t>` — a pulse boundary elapsed
636///   between sealing and execution; the action inherited a prior pulse's
637///   assurance. This is the timing-the-gap case.
638/// - `intent_seal_expired:sealed_at=<t>,max_age=<n>s` — the seal is within the
639///   current window but older than the tier's max age.
640pub fn check_seal_freshness(
641    sealed_at: &str,
642    exec_time: &str,
643    last_pulse: &str,
644    requirement: FreshnessRequirement,
645) -> Result<Option<String>> {
646    if !requirement.require_fresh_seal {
647        return Ok(None);
648    }
649    let sealed = iso_to_epoch_seconds(sealed_at)?;
650    let exec = iso_to_epoch_seconds(exec_time)?;
651    let pulse = iso_to_epoch_seconds(last_pulse)?;
652    if sealed < pulse {
653        return Ok(Some(format!(
654            "{REASON_INTENT_SEAL_STALE}:sealed_at={sealed_at},last_pulse={last_pulse}"
655        )));
656    }
657    if requirement.max_age_seconds != i64::MAX && exec - sealed > requirement.max_age_seconds {
658        return Ok(Some(format!(
659            "{REASON_INTENT_SEAL_EXPIRED}:sealed_at={sealed_at},max_age={}s",
660            requirement.max_age_seconds
661        )));
662    }
663    Ok(None)
664}
665
666/// Verify intent freshness for a reasoned-action credential at a given tier.
667/// Returns `None` when the tier does not require a fresh seal or the seal is
668/// fresh; else a stable reason string. When the tier requires a fresh seal but
669/// the credential carries no seal timestamp, returns `intent_seal_missing`.
670pub fn verify_intent_freshness(
671    credential: &Value,
672    tier: i64,
673    last_pulse: &str,
674    requirement: FreshnessRequirement,
675) -> Result<Option<String>> {
676    if !requirement.require_fresh_seal {
677        return Ok(None);
678    }
679    let exec_time = credential
680        .get("validFrom")
681        .and_then(|v| v.as_str())
682        .ok_or_else(|| CoreError::Json("credential has no validFrom".into()))?;
683    let sealed_at = match seal_timestamp(credential) {
684        Some(s) => s,
685        None => return Ok(Some(format!("{REASON_INTENT_SEAL_MISSING}:tier={tier}"))),
686    };
687    check_seal_freshness(&sealed_at, exec_time, last_pulse, requirement)
688}
689
690/// Execution-time reseal helper: seal the intent right now and issue a fresh
691/// `ReasonedActionCredential` whose `sealedAt` and `validFrom` are both `now`, so
692/// a sensitive action carries a seal made in the current pulse window. Reuses
693/// [`build_justification`] and [`sign_reasoned_action`]; no new cryptography.
694#[allow(clippy::too_many_arguments)]
695pub fn reseal_intent(
696    seed: &[u8],
697    issuer_did: &str,
698    verification_method: &str,
699    intent: &Value,
700    anchors: &[Value],
701    commitment_level: Option<i64>,
702    now: &str,
703    credential_id: &str,
704    include_reasoning: bool,
705) -> Result<Value> {
706    let justification = build_justification(intent, anchors, commitment_level)?;
707    let opts = SignReasonedActionOptions {
708        include_reasoning,
709        escrow_receipt: None,
710        sealed_at: Some(now.to_string()),
711    };
712    sign_reasoned_action(
713        seed,
714        issuer_did,
715        verification_method,
716        intent,
717        &justification,
718        now,
719        credential_id,
720        &opts,
721    )
722}
723
724#[cfg(test)]
725mod tests {
726    use super::*;
727    use crate::keys::Ed25519KeyPair;
728    use serde_json::json;
729
730    fn seed() -> [u8; 32] {
731        [7u8; 32]
732    }
733
734    fn pubkey() -> [u8; 32] {
735        Ed25519KeyPair::from_seed_slice(&seed())
736            .unwrap()
737            .public_key()
738    }
739
740    fn sample_intent() -> Value {
741        json!({"action": "transfer_funds", "target": "account:9911", "resource": "https://bank.example/v1/xfer"})
742    }
743
744    fn sample_justification() -> Value {
745        let anchor = evidence_anchor(
746            "user approved the transfer",
747            "urn:msg:42",
748            Some(&json!({"text": "please move $500 to savings"})),
749            None,
750            "user_message",
751        )
752        .unwrap();
753        build_justification(&sample_intent(), &[anchor], Some(TIER_HIGH)).unwrap()
754    }
755
756    #[test]
757    fn justification_digest_is_multibase_b64url() {
758        let d = justification_digest(&sample_justification()).unwrap();
759        assert!(d.starts_with('u'));
760    }
761
762    #[test]
763    fn sign_then_verify_reasoned_action() {
764        let cred = sign_reasoned_action(
765            &seed(),
766            "did:web:agent.example",
767            "did:web:agent.example#key-1",
768            &sample_intent(),
769            &sample_justification(),
770            "2026-08-02T10:00:00Z",
771            "urn:uuid:11111111-1111-1111-1111-111111111111",
772            &SignReasonedActionOptions::new(),
773        )
774        .unwrap();
775        assert!(check_reasoned_action(&cred, &pubkey(), None, false).is_none());
776        assert_eq!(
777            check_reasoned_action(&cred, &pubkey(), None, true),
778            Some(REASON_MISSING_ESCROW.into())
779        );
780    }
781
782    #[test]
783    fn tampered_action_fails() {
784        let mut cred = sign_reasoned_action(
785            &seed(),
786            "did:web:agent.example",
787            "did:web:agent.example#key-1",
788            &sample_intent(),
789            &sample_justification(),
790            "2026-08-02T10:00:00Z",
791            "urn:uuid:11111111-1111-1111-1111-111111111111",
792            &SignReasonedActionOptions::new(),
793        )
794        .unwrap();
795        cred["credentialSubject"]["intent"]["action"] = json!("drain_account");
796        assert_eq!(
797            check_reasoned_action(&cred, &pubkey(), None, false),
798            Some(REASON_INVALID_PROOF.into())
799        );
800    }
801
802    #[test]
803    fn pulse_window_classifies_window_and_gap() {
804        // interval 60s, last pulse at 10:00:00.
805        let w = pulse_window("2026-08-02T10:00:00Z", 60, "2026-08-02T10:00:30Z").unwrap();
806        assert!(w.in_window && !w.in_gap);
807        let g = pulse_window("2026-08-02T10:00:00Z", 60, "2026-08-02T10:02:00Z").unwrap();
808        assert!(g.in_gap && !g.in_window);
809    }
810
811    // --- Intent recheck acceptance/rejection matrix ---
812
813    fn reasoned_with_seal(sealed_at: &str, exec: &str, level: i64) -> Value {
814        let anchor = evidence_anchor(
815            "user approved",
816            "urn:msg:42",
817            Some(&json!({"text": "go"})),
818            None,
819            "user_message",
820        )
821        .unwrap();
822        let just = build_justification(&sample_intent(), &[anchor], Some(level)).unwrap();
823        let opts = SignReasonedActionOptions {
824            include_reasoning: true,
825            escrow_receipt: None,
826            sealed_at: Some(sealed_at.to_string()),
827        };
828        sign_reasoned_action(
829            &seed(),
830            "did:web:agent.example",
831            "did:web:agent.example#key-1",
832            &sample_intent(),
833            &just,
834            exec,
835            "urn:uuid:22222222-2222-2222-2222-222222222222",
836            &opts,
837        )
838        .unwrap()
839    }
840
841    #[test]
842    fn fresh_seal_in_window_accepts() {
843        // High tier, sealed at 10:00:10, pulse at 10:00:00, exec 10:00:20 (< 300s).
844        let cred = reasoned_with_seal("2026-08-02T10:00:10Z", "2026-08-02T10:00:20Z", TIER_HIGH);
845        let r = verify_intent_freshness(
846            &cred,
847            TIER_HIGH,
848            "2026-08-02T10:00:00Z",
849            default_requirement(TIER_HIGH),
850        )
851        .unwrap();
852        assert_eq!(r, None);
853    }
854
855    #[test]
856    fn stale_seal_across_boundary_rejects() {
857        // Sealed 09:59:50 (before the 10:00:00 pulse), executed at 10:00:20 in the
858        // gap after the boundary. The attacker timed the interval.
859        let cred = reasoned_with_seal("2026-08-02T09:59:50Z", "2026-08-02T10:00:20Z", TIER_HIGH);
860        let r = verify_intent_freshness(
861            &cred,
862            TIER_HIGH,
863            "2026-08-02T10:00:00Z",
864            default_requirement(TIER_HIGH),
865        )
866        .unwrap();
867        assert_eq!(
868            r,
869            Some(
870                "intent_seal_stale:sealed_at=2026-08-02T09:59:50Z,last_pulse=2026-08-02T10:00:00Z"
871                    .into()
872            )
873        );
874    }
875
876    #[test]
877    fn fresh_reseal_in_gap_accepts() {
878        // Even executing at 10:05:00, a reseal at 10:05:00 with a pulse boundary
879        // advanced to 10:05:00 is fresh.
880        let cred = reseal_intent(
881            &seed(),
882            "did:web:agent.example",
883            "did:web:agent.example#key-1",
884            &sample_intent(),
885            &[evidence_anchor(
886                "user approved",
887                "urn:msg:42",
888                Some(&json!({"text": "go"})),
889                None,
890                "user_message",
891            )
892            .unwrap()],
893            Some(TIER_HIGH),
894            "2026-08-02T10:05:00Z",
895            "urn:uuid:33333333-3333-3333-3333-333333333333",
896            true,
897        )
898        .unwrap();
899        let r = verify_intent_freshness(
900            &cred,
901            TIER_HIGH,
902            "2026-08-02T10:05:00Z",
903            default_requirement(TIER_HIGH),
904        )
905        .unwrap();
906        assert_eq!(r, None);
907        assert!(check_reasoned_action(&cred, &pubkey(), None, false).is_none());
908    }
909
910    #[test]
911    fn non_sensitive_tier_ignores_stale_seal() {
912        // Same stale seal, but a routine tier does not require freshness.
913        let cred = reasoned_with_seal("2026-08-02T09:59:50Z", "2026-08-02T10:00:20Z", TIER_ROUTINE);
914        let r = verify_intent_freshness(
915            &cred,
916            TIER_ROUTINE,
917            "2026-08-02T10:00:00Z",
918            default_requirement(TIER_ROUTINE),
919        )
920        .unwrap();
921        assert_eq!(r, None);
922    }
923
924    #[test]
925    fn sensitive_tier_without_seal_is_missing() {
926        // A high-tier action with no seal timestamp at all.
927        let cred = sign_reasoned_action(
928            &seed(),
929            "did:web:agent.example",
930            "did:web:agent.example#key-1",
931            &sample_intent(),
932            &sample_justification(),
933            "2026-08-02T10:00:20Z",
934            "urn:uuid:44444444-4444-4444-4444-444444444444",
935            &SignReasonedActionOptions::new(),
936        )
937        .unwrap();
938        let r = verify_intent_freshness(
939            &cred,
940            TIER_HIGH,
941            "2026-08-02T10:00:00Z",
942            default_requirement(TIER_HIGH),
943        )
944        .unwrap();
945        assert_eq!(r, Some("intent_seal_missing:tier=3".into()));
946    }
947
948    #[test]
949    fn escrow_roundtrip_and_seal_from_deposit() {
950        let escrow_seed = [3u8; 32];
951        let escrow_pub = Ed25519KeyPair::from_seed_slice(&escrow_seed)
952            .unwrap()
953            .public_key();
954        let digest = justification_digest(&sample_justification()).unwrap();
955        let receipt = build_escrow_receipt(
956            &escrow_seed,
957            "did:web:escrow.example",
958            "did:web:escrow.example#key-1",
959            "did:web:agent.example",
960            &digest,
961            "2026-08-02T10:00:05Z",
962            "urn:uuid:55555555-5555-5555-5555-555555555555",
963        )
964        .unwrap();
965        let (ok, _) = verify_escrow_receipt(&receipt, &escrow_pub);
966        assert!(ok);
967
968        let opts = SignReasonedActionOptions {
969            include_reasoning: true,
970            escrow_receipt: Some(receipt),
971            sealed_at: None,
972        };
973        let cred = sign_reasoned_action(
974            &seed(),
975            "did:web:agent.example",
976            "did:web:agent.example#key-1",
977            &sample_intent(),
978            &sample_justification(),
979            "2026-08-02T10:00:20Z",
980            "urn:uuid:66666666-6666-6666-6666-666666666666",
981            &opts,
982        )
983        .unwrap();
984        // Seal timestamp falls back to the escrow depositedAt.
985        assert_eq!(
986            seal_timestamp(&cred).as_deref(),
987            Some("2026-08-02T10:00:05Z")
988        );
989        assert!(check_reasoned_action(&cred, &pubkey(), Some(&escrow_pub), true).is_none());
990    }
991}