use serde_json::{Map, Value};
use sha2::{Digest, Sha256};
use crate::data_integrity::{self, BuildProofOptions};
use crate::error::{CoreError, Result};
use crate::jcs;
use crate::time::{check_clock_skew, parse_protocol_time_ns, seconds_to_ns};
pub const VC_CONTEXT_V2: &str = "https://www.w3.org/ns/credentials/v2";
pub const VOUCH_CONTEXT_V1: &str = "https://vouch-protocol.com/contexts/v1";
pub const REASONED_ACTION_TYPE: &str = "ReasonedActionCredential";
pub const ESCROW_RECEIPT_TYPE: &str = "JustificationEscrowReceipt";
pub const JUSTIFICATION_ALGORITHM: &str = "sha-256-jcs";
pub const REASON_INVALID_PROOF: &str = "invalid_proof";
pub const REASON_NOT_REASONED_ACTION: &str = "not_reasoned_action";
pub const REASON_MISSING_COMMITMENT: &str = "missing_commitment";
pub const REASON_MISSING_ESCROW: &str = "missing_escrow";
pub const REASON_ESCROW_INVALID: &str = "escrow_receipt_invalid";
pub const REASON_ESCROW_DIGEST_MISMATCH: &str = "escrow_digest_mismatch";
pub const REASON_ESCROW_AFTER_EXECUTION: &str = "escrow_after_execution";
pub const REASON_JUSTIFICATION_DIGEST_MISMATCH: &str = "justification_digest_mismatch";
pub const REASON_EVIDENCE_UNRESOLVED: &str = "evidence_unresolved";
pub const REASON_EVIDENCE_HASH_MISMATCH: &str = "evidence_hash_mismatch";
pub const REASON_UNANCHORED_CLAIM: &str = "unanchored_claim";
pub const REASON_INTENT_SEAL_STALE: &str = "intent_seal_stale";
pub const REASON_INTENT_SEAL_EXPIRED: &str = "intent_seal_expired";
pub const REASON_INTENT_SEAL_MISSING: &str = "intent_seal_missing";
pub const REASON_ESCROW_AGENT_MISMATCH: &str = "escrow_agent_mismatch";
pub const REASON_SEAL_AFTER_DEPOSIT: &str = "seal_after_deposit";
pub const REASON_SEAL_AFTER_EXECUTION: &str = "seal_after_execution";
pub const REASON_SEAL_IN_FUTURE: &str = "seal_in_future";
pub const REASON_MALFORMED_TIME: &str = "malformed_time";
pub const REASON_INTENT_SEAL_FUTURE: &str = "intent_seal_future";
pub const REASON_INTENT_EXECUTION_NOT_CURRENT: &str = "intent_execution_not_current";
fn mb64(bytes: &[u8]) -> String {
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine;
format!("u{}", URL_SAFE_NO_PAD.encode(bytes))
}
fn artifact_bytes(artifact: &Value) -> Result<Vec<u8>> {
match artifact {
Value::String(s) => Ok(s.as_bytes().to_vec()),
Value::Object(_) => Ok(jcs::canonicalize(artifact)),
_ => Err(CoreError::Json(
"evidence artifact must be a JSON object or string".into(),
)),
}
}
pub fn artifact_digest(artifact: &Value) -> Result<String> {
Ok(mb64(&Sha256::digest(&artifact_bytes(artifact)?)))
}
pub fn artifact_digest_bytes(artifact: &[u8]) -> String {
mb64(&Sha256::digest(artifact))
}
fn type_list(credential: &Value) -> Vec<String> {
match credential.get("type") {
Some(Value::String(s)) => vec![s.clone()],
Some(Value::Array(a)) => a
.iter()
.filter_map(|v| v.as_str().map(|s| s.to_string()))
.collect(),
_ => Vec::new(),
}
}
fn attach_proof(
credential: &mut Value,
seed: &[u8],
verification_method: &str,
created: &str,
) -> Result<()> {
let opts = BuildProofOptions::new(verification_method, created);
let proof = data_integrity::build_proof(credential, seed, &opts)?;
credential
.as_object_mut()
.ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
.insert("proof".into(), proof);
Ok(())
}
pub fn evidence_anchor(
claim: &str,
reference: &str,
evidence: Option<&Value>,
evidence_hash: Option<&str>,
anchor_type: &str,
) -> Result<Value> {
if claim.is_empty() || reference.is_empty() {
return Err(CoreError::Json(
"an evidence anchor needs a claim and a ref".into(),
));
}
let hash = match evidence_hash {
Some(h) => h.to_string(),
None => match evidence {
Some(e) => artifact_digest(e)?,
None => {
return Err(CoreError::Json(
"supply evidence or evidence_hash for the anchor".into(),
))
}
},
};
let mut anchor = Map::new();
anchor.insert("type".into(), Value::String(anchor_type.to_string()));
anchor.insert("claim".into(), Value::String(claim.to_string()));
anchor.insert("ref".into(), Value::String(reference.to_string()));
anchor.insert("evidenceHash".into(), Value::String(hash));
Ok(Value::Object(anchor))
}
pub fn build_justification(
intent: &Value,
anchors: &[Value],
commitment_level: Option<i64>,
) -> Result<Value> {
if !intent.is_object()
|| intent.get("action").and_then(|v| v.as_str()).is_none()
|| intent.get("target").and_then(|v| v.as_str()).is_none()
{
return Err(CoreError::Json(
"intent must be an object with at least action and target".into(),
));
}
if anchors.is_empty() {
return Err(CoreError::Json(
"a justification needs at least one evidence anchor".into(),
));
}
let mut just = Map::new();
just.insert("intent".into(), intent.clone());
just.insert("evidenceAnchors".into(), Value::Array(anchors.to_vec()));
if let Some(level) = commitment_level {
just.insert("commitmentLevel".into(), Value::from(level));
}
Ok(Value::Object(just))
}
pub fn justification_digest(justification: &Value) -> Result<String> {
if !justification.is_object() {
return Err(CoreError::Json(
"justification must be a JSON object".into(),
));
}
Ok(mb64(&Sha256::digest(jcs::canonicalize(justification))))
}
#[allow(clippy::too_many_arguments)]
pub fn build_escrow_receipt(
escrow_seed: &[u8],
escrow_did: &str,
escrow_verification_method: &str,
agent_did: &str,
committed_digest: &str,
deposited_at: &str,
credential_id: &str,
) -> Result<Value> {
let mut subject = Map::new();
subject.insert("agent".into(), Value::String(agent_did.to_string()));
subject.insert(
"committedDigest".into(),
Value::String(committed_digest.to_string()),
);
subject.insert(
"depositedAt".into(),
Value::String(deposited_at.to_string()),
);
let mut receipt = Map::new();
receipt.insert(
"@context".into(),
Value::Array(vec![
Value::String(VC_CONTEXT_V2.into()),
Value::String(VOUCH_CONTEXT_V1.into()),
]),
);
receipt.insert(
"type".into(),
Value::Array(vec![
Value::String("VerifiableCredential".into()),
Value::String(ESCROW_RECEIPT_TYPE.into()),
]),
);
receipt.insert("id".into(), Value::String(credential_id.to_string()));
receipt.insert("issuer".into(), Value::String(escrow_did.to_string()));
receipt.insert("validFrom".into(), Value::String(deposited_at.to_string()));
receipt.insert("credentialSubject".into(), Value::Object(subject));
let mut receipt = Value::Object(receipt);
attach_proof(
&mut receipt,
escrow_seed,
escrow_verification_method,
deposited_at,
)?;
Ok(receipt)
}
pub fn verify_escrow_receipt(receipt: &Value, escrow_public_key: &[u8]) -> (bool, Option<Value>) {
if !type_list(receipt).iter().any(|t| t == ESCROW_RECEIPT_TYPE) {
return (false, None);
}
let has_context = |item: &Value| {
item.as_object()
.is_some_and(|proof| proof.contains_key("@context"))
};
let proof_carries_context = match receipt.get("proof") {
Some(Value::Array(items)) => items.iter().any(has_context),
Some(item) => has_context(item),
None => false,
};
if proof_carries_context {
return (false, None);
}
let bound = match (
crate::credentials::issuer_did(receipt),
receipt.get("proof"),
) {
(Some(issuer), Some(proof)) => crate::credentials::proof_bound_to_issuer(proof, issuer),
_ => false,
};
if !bound {
return (false, None);
}
match data_integrity::verify_proof(receipt, escrow_public_key) {
Ok(true) => {}
_ => return (false, None),
}
let subject = match receipt.get("credentialSubject").and_then(|s| s.as_object()) {
Some(s) => s,
None => return (false, None),
};
let has_digest = subject
.get("committedDigest")
.and_then(|v| v.as_str())
.is_some_and(|s| !s.is_empty());
let has_agent = subject.get("agent").is_some_and(|v| v.is_string());
let has_deposited = subject
.get("depositedAt")
.and_then(|v| v.as_str())
.is_some_and(|s| parse_protocol_time_ns(s).is_ok());
if !has_digest || !has_agent || !has_deposited {
return (false, None);
}
(true, Some(Value::Object(subject.clone())))
}
#[derive(Debug, Clone, Default)]
pub struct SignReasonedActionOptions {
pub include_reasoning: bool,
pub escrow_receipt: Option<Value>,
pub sealed_at: Option<String>,
}
impl SignReasonedActionOptions {
pub fn new() -> Self {
Self {
include_reasoning: true,
escrow_receipt: None,
sealed_at: None,
}
}
}
#[allow(clippy::too_many_arguments)]
pub fn sign_reasoned_action(
seed: &[u8],
issuer_did: &str,
verification_method: &str,
intent: &Value,
justification: &Value,
valid_from: &str,
credential_id: &str,
opts: &SignReasonedActionOptions,
) -> Result<Value> {
if !intent.is_object()
|| intent.get("action").and_then(|v| v.as_str()).is_none()
|| intent.get("target").and_then(|v| v.as_str()).is_none()
{
return Err(CoreError::Json(
"intent must be an object with at least action and target".into(),
));
}
let digest = justification_digest(justification)?;
let mut commitment = Map::new();
commitment.insert(
"algorithm".into(),
Value::String(JUSTIFICATION_ALGORITHM.into()),
);
commitment.insert("digest".into(), Value::String(digest));
let mut jblock = Map::new();
jblock.insert("commitment".into(), Value::Object(commitment));
if let Some(sealed) = &opts.sealed_at {
jblock.insert("sealedAt".into(), Value::String(sealed.clone()));
}
if let Some(level) = justification.get("commitmentLevel") {
jblock.insert("commitmentLevel".into(), level.clone());
}
if let Some(receipt) = &opts.escrow_receipt {
jblock.insert("escrowReceipt".into(), receipt.clone());
}
if opts.include_reasoning {
let anchors = justification
.get("evidenceAnchors")
.cloned()
.unwrap_or_else(|| Value::Array(Vec::new()));
jblock.insert("evidenceAnchors".into(), anchors);
}
let mut subject = Map::new();
subject.insert("intent".into(), intent.clone());
subject.insert("justification".into(), Value::Object(jblock));
let mut credential = Map::new();
credential.insert(
"@context".into(),
Value::Array(vec![
Value::String(VC_CONTEXT_V2.into()),
Value::String(VOUCH_CONTEXT_V1.into()),
]),
);
credential.insert(
"type".into(),
Value::Array(vec![
Value::String("VerifiableCredential".into()),
Value::String(REASONED_ACTION_TYPE.into()),
]),
);
credential.insert("id".into(), Value::String(credential_id.to_string()));
credential.insert("issuer".into(), Value::String(issuer_did.to_string()));
credential.insert("validFrom".into(), Value::String(valid_from.to_string()));
credential.insert("credentialSubject".into(), Value::Object(subject));
let mut credential = Value::Object(credential);
attach_proof(&mut credential, seed, verification_method, valid_from)?;
Ok(credential)
}
fn time_of(v: Option<&Value>) -> std::result::Result<i128, ()> {
match v.and_then(|v| v.as_str()) {
Some(s) => parse_protocol_time_ns(s).map_err(|_| ()),
None => Err(()),
}
}
fn check_reasoned_action_inner(
credential: &Value,
public_key: &[u8],
escrow_public_key: Option<&[u8]>,
require_escrow: bool,
clock: Option<(i128, i128)>,
) -> Option<String> {
if !type_list(credential)
.iter()
.any(|t| t == REASONED_ACTION_TYPE)
{
return Some(REASON_NOT_REASONED_ACTION.into());
}
let bound = match (
crate::credentials::issuer_did(credential),
credential.get("proof"),
) {
(Some(issuer), Some(proof)) => crate::credentials::proof_bound_to_issuer(proof, issuer),
_ => false,
};
if !bound {
return Some(REASON_INVALID_PROOF.into());
}
match data_integrity::verify_proof(credential, public_key) {
Ok(true) => {}
_ => return Some(REASON_INVALID_PROOF.into()),
}
let jblock = credential
.get("credentialSubject")
.and_then(|s| s.get("justification"))
.filter(|j| j.is_object());
let Some(jblock) = jblock else {
return Some(REASON_MISSING_COMMITMENT.into());
};
let commitment_digest = jblock
.get("commitment")
.and_then(|c| c.get("digest"))
.and_then(|d| d.as_str());
let commitment_digest = match commitment_digest {
Some(d) if !d.is_empty() => d,
_ => return Some(REASON_MISSING_COMMITMENT.into()),
};
let Ok(executed) = time_of(credential.get("validFrom")) else {
return Some(REASON_MALFORMED_TIME.into());
};
let sealed = match jblock.get("sealedAt") {
None => None,
Some(v) => match time_of(Some(v)) {
Ok(t) => Some(t),
Err(()) => return Some(REASON_MALFORMED_TIME.into()),
},
};
if let Some(t) = sealed {
if t > executed {
return Some(REASON_SEAL_AFTER_EXECUTION.into());
}
if let Some((now, skew)) = clock {
if t > now + skew {
return Some(REASON_SEAL_IN_FUTURE.into());
}
}
}
let receipt = match jblock.get("escrowReceipt") {
None => {
return if require_escrow {
Some(REASON_MISSING_ESCROW.into())
} else {
None
};
}
Some(r) => r,
};
let escrow_key = match escrow_public_key {
Some(k) => k,
None => return Some(REASON_ESCROW_INVALID.into()),
};
let (ok, rsubject) = verify_escrow_receipt(receipt, escrow_key);
let Some(rsubject) = rsubject.filter(|_| ok) else {
return Some(REASON_ESCROW_INVALID.into());
};
if rsubject.get("agent").and_then(|v| v.as_str()) != crate::credentials::issuer_did(credential)
{
return Some(REASON_ESCROW_AGENT_MISMATCH.into());
}
if rsubject.get("committedDigest").and_then(|v| v.as_str()) != Some(commitment_digest) {
return Some(REASON_ESCROW_DIGEST_MISMATCH.into());
}
let Ok(deposited) = time_of(rsubject.get("depositedAt")) else {
return Some(REASON_ESCROW_INVALID.into());
};
if let Some(t) = sealed {
if t > deposited {
return Some(REASON_SEAL_AFTER_DEPOSIT.into());
}
}
if deposited > executed {
return Some(REASON_ESCROW_AFTER_EXECUTION.into());
}
if let Some((now, skew)) = clock {
if deposited > now + skew {
return Some(REASON_SEAL_IN_FUTURE.into());
}
}
None
}
pub fn check_reasoned_action(
credential: &Value,
public_key: &[u8],
escrow_public_key: Option<&[u8]>,
require_escrow: bool,
) -> Option<String> {
check_reasoned_action_inner(
credential,
public_key,
escrow_public_key,
require_escrow,
None,
)
}
pub fn check_reasoned_action_at(
credential: &Value,
public_key: &[u8],
escrow_public_key: Option<&[u8]>,
require_escrow: bool,
now_iso: &str,
clock_skew_seconds: i64,
) -> Result<Option<String>> {
let skew = check_clock_skew(clock_skew_seconds)?;
let now = parse_protocol_time_ns(now_iso)?;
Ok(check_reasoned_action_inner(
credential,
public_key,
escrow_public_key,
require_escrow,
Some((now, skew)),
))
}
pub fn verify_reasoned_action(
credential: &Value,
public_key: &[u8],
escrow_public_key: Option<&[u8]>,
require_escrow: bool,
) -> (bool, Option<Value>) {
if check_reasoned_action(credential, public_key, escrow_public_key, require_escrow).is_some() {
return (false, None);
}
(true, credential.get("credentialSubject").cloned())
}
pub fn verify_justification<F>(
presented_justification: &Value,
credential_subject: &Value,
resolver: F,
) -> (bool, Option<String>)
where
F: Fn(&str) -> Option<Value>,
{
let committed = credential_subject
.get("justification")
.and_then(|j| j.get("commitment"))
.and_then(|c| c.get("digest"))
.and_then(|d| d.as_str());
let committed = match committed {
Some(d) if !d.is_empty() => d,
_ => return (false, Some(REASON_MISSING_COMMITMENT.into())),
};
match justification_digest(presented_justification) {
Ok(d) if d == committed => {}
_ => return (false, Some(REASON_JUSTIFICATION_DIGEST_MISMATCH.into())),
}
let anchors = presented_justification
.get("evidenceAnchors")
.and_then(|a| a.as_array());
let anchors = match anchors {
Some(a) if !a.is_empty() => a,
_ => return (false, Some(REASON_UNANCHORED_CLAIM.into())),
};
for anchor in anchors {
let reference = anchor.get("ref").and_then(|v| v.as_str());
let artifact = reference.and_then(&resolver);
let artifact = match artifact {
Some(a) => a,
None => return (false, Some(REASON_EVIDENCE_UNRESOLVED.into())),
};
let expected = anchor.get("evidenceHash").and_then(|v| v.as_str());
match artifact_digest(&artifact) {
Ok(actual) if Some(actual.as_str()) == expected => {}
_ => return (false, Some(REASON_EVIDENCE_HASH_MISMATCH.into())),
}
}
(true, None)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PulseWindow {
pub in_window: bool,
pub in_gap: bool,
pub seconds_into_window: i64,
}
pub fn pulse_window(
last_pulse: &str,
interval_seconds: i64,
exec_time: &str,
) -> Result<PulseWindow> {
let pulse = parse_protocol_time_ns(last_pulse)?;
let exec = parse_protocol_time_ns(exec_time)?;
let delta = exec - pulse;
let interval = seconds_to_ns(interval_seconds);
let in_window = delta >= 0 && delta < interval;
Ok(PulseWindow {
in_window,
in_gap: delta >= interval,
seconds_into_window: delta.div_euclid(1_000_000_000) as i64,
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FreshnessRequirement {
pub require_fresh_seal: bool,
pub max_age_seconds: i64,
}
impl FreshnessRequirement {
pub const NONE: FreshnessRequirement = FreshnessRequirement {
require_fresh_seal: false,
max_age_seconds: i64::MAX,
};
}
pub const TIER_ROUTINE: i64 = 0;
pub const TIER_LOW: i64 = 1;
pub const TIER_MEDIUM: i64 = 2;
pub const TIER_HIGH: i64 = 3;
pub const TIER_CRITICAL: i64 = 4;
pub fn default_requirement(tier: i64) -> FreshnessRequirement {
match tier {
t if t >= TIER_CRITICAL => FreshnessRequirement {
require_fresh_seal: true,
max_age_seconds: 60,
},
TIER_HIGH => FreshnessRequirement {
require_fresh_seal: true,
max_age_seconds: 300,
},
_ => FreshnessRequirement::NONE,
}
}
pub fn seal_timestamp(credential: &Value) -> Option<String> {
let jblock = credential
.get("credentialSubject")
.and_then(|s| s.get("justification"))?;
let deposited = jblock
.get("escrowReceipt")
.and_then(|r| r.get("credentialSubject"))
.and_then(|s| s.get("depositedAt"))
.and_then(|v| v.as_str());
if let Some(d) = deposited {
return Some(d.to_string());
}
jblock
.get("sealedAt")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
}
pub fn check_seal_freshness(
sealed_at: &str,
exec_time: &str,
last_pulse: &str,
requirement: FreshnessRequirement,
) -> Result<Option<String>> {
if !requirement.require_fresh_seal {
return Ok(None);
}
let sealed = parse_protocol_time_ns(sealed_at)?;
let exec = parse_protocol_time_ns(exec_time)?;
let pulse = parse_protocol_time_ns(last_pulse)?;
if sealed < pulse {
return Ok(Some(format!(
"{REASON_INTENT_SEAL_STALE}:sealed_at={sealed_at},last_pulse={last_pulse}"
)));
}
if requirement.max_age_seconds != i64::MAX
&& exec - sealed > seconds_to_ns(requirement.max_age_seconds)
{
return Ok(Some(format!(
"{REASON_INTENT_SEAL_EXPIRED}:sealed_at={sealed_at},max_age={}s",
requirement.max_age_seconds
)));
}
Ok(None)
}
pub fn verify_intent_freshness(
credential: &Value,
tier: i64,
last_pulse: &str,
requirement: FreshnessRequirement,
) -> Result<Option<String>> {
if !requirement.require_fresh_seal {
return Ok(None);
}
parse_protocol_time_ns(last_pulse)?;
let receipt = credential
.get("credentialSubject")
.and_then(|s| s.get("justification"))
.and_then(|j| j.get("escrowReceipt"));
Ok(Some(match receipt {
None => format!("{REASON_INTENT_SEAL_MISSING}:tier={tier}"),
Some(_) => REASON_ESCROW_INVALID.to_string(),
}))
}
#[allow(clippy::too_many_arguments)]
pub fn recheck_intent_freshness(
credential: &Value,
tier: i64,
last_pulse: &str,
requirement: FreshnessRequirement,
now_iso: &str,
clock_skew_seconds: i64,
escrow_public_key: Option<&[u8]>,
) -> Result<Option<String>> {
if !requirement.require_fresh_seal {
return Ok(None);
}
let skew = check_clock_skew(clock_skew_seconds)?;
let now = parse_protocol_time_ns(now_iso)?;
parse_protocol_time_ns(last_pulse)?;
let jblock = credential
.get("credentialSubject")
.and_then(|s| s.get("justification"))
.filter(|j| j.is_object());
let Some(receipt) = jblock.and_then(|j| j.get("escrowReceipt")) else {
return Ok(Some(format!("{REASON_INTENT_SEAL_MISSING}:tier={tier}")));
};
let (ok, rsubject) = match escrow_public_key {
Some(k) => verify_escrow_receipt(receipt, k),
None => (false, None),
};
let Some(rsubject) = rsubject.filter(|_| ok) else {
return Ok(Some(REASON_ESCROW_INVALID.into()));
};
if rsubject.get("agent").and_then(|v| v.as_str()) != crate::credentials::issuer_did(credential)
{
return Ok(Some(REASON_ESCROW_AGENT_MISMATCH.into()));
}
let digest = jblock
.and_then(|j| j.get("commitment"))
.and_then(|c| c.get("digest"))
.and_then(|d| d.as_str())
.filter(|d| !d.is_empty());
if digest.is_none() || rsubject.get("committedDigest").and_then(|v| v.as_str()) != digest {
return Ok(Some(REASON_ESCROW_DIGEST_MISMATCH.into()));
}
let exec_str = credential
.get("validFrom")
.and_then(|v| v.as_str())
.unwrap_or_default();
let deposited_str = rsubject
.get("depositedAt")
.and_then(|v| v.as_str())
.unwrap_or_default()
.to_string();
let (Ok(executed), Ok(deposited)) = (
time_of(credential.get("validFrom")),
time_of(rsubject.get("depositedAt")),
) else {
return Ok(Some(REASON_MALFORMED_TIME.into()));
};
let sealed = match jblock.and_then(|j| j.get("sealedAt")) {
None => None,
Some(v) => match time_of(Some(v)) {
Ok(t) => Some(t),
Err(()) => return Ok(Some(REASON_MALFORMED_TIME.into())),
},
};
if sealed.is_some_and(|t| t > deposited) {
return Ok(Some(REASON_SEAL_AFTER_DEPOSIT.into()));
}
if deposited > executed {
return Ok(Some(REASON_ESCROW_AFTER_EXECUTION.into()));
}
if deposited > now + skew {
return Ok(Some(format!(
"{REASON_INTENT_SEAL_FUTURE}:sealed_at={deposited_str}"
)));
}
if (executed - now).abs() > skew {
return Ok(Some(format!(
"{REASON_INTENT_EXECUTION_NOT_CURRENT}:valid_from={exec_str}"
)));
}
check_seal_freshness(&deposited_str, exec_str, last_pulse, requirement)
}
#[allow(clippy::too_many_arguments)]
pub fn reseal_intent(
seed: &[u8],
issuer_did: &str,
verification_method: &str,
intent: &Value,
anchors: &[Value],
commitment_level: Option<i64>,
now: &str,
credential_id: &str,
include_reasoning: bool,
) -> Result<Value> {
let justification = build_justification(intent, anchors, commitment_level)?;
let opts = SignReasonedActionOptions {
include_reasoning,
escrow_receipt: None,
sealed_at: Some(now.to_string()),
};
sign_reasoned_action(
seed,
issuer_did,
verification_method,
intent,
&justification,
now,
credential_id,
&opts,
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::keys::Ed25519KeyPair;
use serde_json::json;
fn seed() -> [u8; 32] {
[7u8; 32]
}
fn pubkey() -> [u8; 32] {
Ed25519KeyPair::from_seed_slice(&seed())
.unwrap()
.public_key()
}
fn sample_intent() -> Value {
json!({"action": "transfer_funds", "target": "account:9911", "resource": "https://bank.example/v1/xfer"})
}
fn sample_justification() -> Value {
let anchor = evidence_anchor(
"user approved the transfer",
"urn:msg:42",
Some(&json!({"text": "please move $500 to savings"})),
None,
"user_message",
)
.unwrap();
build_justification(&sample_intent(), &[anchor], Some(TIER_HIGH)).unwrap()
}
#[test]
fn justification_digest_is_multibase_b64url() {
let d = justification_digest(&sample_justification()).unwrap();
assert!(d.starts_with('u'));
}
#[test]
fn sign_then_verify_reasoned_action() {
let cred = sign_reasoned_action(
&seed(),
"did:web:agent.example",
"did:web:agent.example#key-1",
&sample_intent(),
&sample_justification(),
"2026-08-02T10:00:00Z",
"urn:uuid:11111111-1111-1111-1111-111111111111",
&SignReasonedActionOptions::new(),
)
.unwrap();
assert!(check_reasoned_action(&cred, &pubkey(), None, false).is_none());
assert_eq!(
check_reasoned_action(&cred, &pubkey(), None, true),
Some(REASON_MISSING_ESCROW.into())
);
}
#[test]
fn tampered_action_fails() {
let mut cred = sign_reasoned_action(
&seed(),
"did:web:agent.example",
"did:web:agent.example#key-1",
&sample_intent(),
&sample_justification(),
"2026-08-02T10:00:00Z",
"urn:uuid:11111111-1111-1111-1111-111111111111",
&SignReasonedActionOptions::new(),
)
.unwrap();
cred["credentialSubject"]["intent"]["action"] = json!("drain_account");
assert_eq!(
check_reasoned_action(&cred, &pubkey(), None, false),
Some(REASON_INVALID_PROOF.into())
);
}
#[test]
fn pulse_window_classifies_window_and_gap() {
let w = pulse_window("2026-08-02T10:00:00Z", 60, "2026-08-02T10:00:30Z").unwrap();
assert!(w.in_window && !w.in_gap);
let g = pulse_window("2026-08-02T10:00:00Z", 60, "2026-08-02T10:02:00Z").unwrap();
assert!(g.in_gap && !g.in_window);
}
fn reasoned_with_seal(sealed_at: &str, exec: &str, level: i64) -> Value {
let anchor = evidence_anchor(
"user approved",
"urn:msg:42",
Some(&json!({"text": "go"})),
None,
"user_message",
)
.unwrap();
let just = build_justification(&sample_intent(), &[anchor], Some(level)).unwrap();
let opts = SignReasonedActionOptions {
include_reasoning: true,
escrow_receipt: None,
sealed_at: Some(sealed_at.to_string()),
};
sign_reasoned_action(
&seed(),
"did:web:agent.example",
"did:web:agent.example#key-1",
&sample_intent(),
&just,
exec,
"urn:uuid:22222222-2222-2222-2222-222222222222",
&opts,
)
.unwrap()
}
#[test]
fn agent_seal_alone_does_not_meet_a_high_tier() {
let cred = reasoned_with_seal("2026-08-02T10:00:10Z", "2026-08-02T10:00:20Z", TIER_HIGH);
let r = recheck_intent_freshness(
&cred,
TIER_HIGH,
"2026-08-02T10:00:00Z",
default_requirement(TIER_HIGH),
"2026-08-02T10:00:20Z",
30,
Some(&pubkey()),
)
.unwrap();
assert_eq!(
r,
Some(format!("{REASON_INTENT_SEAL_MISSING}:tier={TIER_HIGH}"))
);
}
#[test]
fn stale_seal_across_boundary_rejects() {
let r = check_seal_freshness(
"2026-08-02T09:59:50Z",
"2026-08-02T10:00:20Z",
"2026-08-02T10:00:00Z",
default_requirement(TIER_HIGH),
)
.unwrap();
assert_eq!(
r,
Some(
"intent_seal_stale:sealed_at=2026-08-02T09:59:50Z,last_pulse=2026-08-02T10:00:00Z"
.into()
)
);
assert_eq!(
check_seal_freshness(
"2026-08-02T10:00:10Z",
"2026-08-02T10:00:20Z",
"2026-08-02T10:00:00Z",
default_requirement(TIER_HIGH),
)
.unwrap(),
None
);
}
#[test]
fn reseal_in_gap_is_a_valid_action() {
let cred = reseal_intent(
&seed(),
"did:web:agent.example",
"did:web:agent.example#key-1",
&sample_intent(),
&[evidence_anchor(
"user approved",
"urn:msg:42",
Some(&json!({"text": "go"})),
None,
"user_message",
)
.unwrap()],
Some(TIER_HIGH),
"2026-08-02T10:05:00Z",
"urn:uuid:33333333-3333-3333-3333-333333333333",
true,
)
.unwrap();
assert!(check_reasoned_action(&cred, &pubkey(), None, false).is_none());
let r = verify_intent_freshness(
&cred,
TIER_HIGH,
"2026-08-02T10:05:00Z",
default_requirement(TIER_HIGH),
)
.unwrap();
assert_eq!(
r,
Some(format!("{REASON_INTENT_SEAL_MISSING}:tier={TIER_HIGH}"))
);
}
#[test]
fn non_sensitive_tier_ignores_stale_seal() {
let cred = reasoned_with_seal("2026-08-02T09:59:50Z", "2026-08-02T10:00:20Z", TIER_ROUTINE);
let r = verify_intent_freshness(
&cred,
TIER_ROUTINE,
"2026-08-02T10:00:00Z",
default_requirement(TIER_ROUTINE),
)
.unwrap();
assert_eq!(r, None);
}
#[test]
fn sensitive_tier_without_seal_is_missing() {
let cred = sign_reasoned_action(
&seed(),
"did:web:agent.example",
"did:web:agent.example#key-1",
&sample_intent(),
&sample_justification(),
"2026-08-02T10:00:20Z",
"urn:uuid:44444444-4444-4444-4444-444444444444",
&SignReasonedActionOptions::new(),
)
.unwrap();
let r = verify_intent_freshness(
&cred,
TIER_HIGH,
"2026-08-02T10:00:00Z",
default_requirement(TIER_HIGH),
)
.unwrap();
assert_eq!(r, Some("intent_seal_missing:tier=3".into()));
}
#[test]
fn escrow_roundtrip_and_seal_from_deposit() {
let escrow_seed = [3u8; 32];
let escrow_pub = Ed25519KeyPair::from_seed_slice(&escrow_seed)
.unwrap()
.public_key();
let digest = justification_digest(&sample_justification()).unwrap();
let receipt = build_escrow_receipt(
&escrow_seed,
"did:web:escrow.example",
"did:web:escrow.example#key-1",
"did:web:agent.example",
&digest,
"2026-08-02T10:00:05Z",
"urn:uuid:55555555-5555-5555-5555-555555555555",
)
.unwrap();
let (ok, _) = verify_escrow_receipt(&receipt, &escrow_pub);
assert!(ok);
let mut second = receipt.clone();
let context = second["@context"].clone();
second["proof"]["@context"] = context.clone();
assert!(data_integrity::verify_proof(&second, &escrow_pub).unwrap());
assert_eq!(verify_escrow_receipt(&second, &escrow_pub), (false, None));
let mut in_a_list = receipt.clone();
let mut listed = in_a_list["proof"].clone();
listed["@context"] = context;
in_a_list["proof"] = Value::Array(vec![listed]);
assert_eq!(
verify_escrow_receipt(&in_a_list, &escrow_pub),
(false, None)
);
let opts = SignReasonedActionOptions {
include_reasoning: true,
escrow_receipt: Some(receipt),
sealed_at: None,
};
let cred = sign_reasoned_action(
&seed(),
"did:web:agent.example",
"did:web:agent.example#key-1",
&sample_intent(),
&sample_justification(),
"2026-08-02T10:00:20Z",
"urn:uuid:66666666-6666-6666-6666-666666666666",
&opts,
)
.unwrap();
assert_eq!(
seal_timestamp(&cred).as_deref(),
Some("2026-08-02T10:00:05Z")
);
assert!(check_reasoned_action(&cred, &pubkey(), Some(&escrow_pub), true).is_none());
}
fn escrow_seed() -> [u8; 32] {
[9u8; 32]
}
fn escrow_pub() -> [u8; 32] {
Ed25519KeyPair::from_seed(&escrow_seed()).public_key()
}
fn escrowed(agent: &str, deposited: &str, exec: &str, sealed: Option<&str>) -> Value {
let just = sample_justification();
let digest = justification_digest(&just).unwrap();
let receipt = build_escrow_receipt(
&escrow_seed(),
"did:web:escrow.example",
"did:web:escrow.example#key-1",
agent,
&digest,
deposited,
"urn:uuid:33333333-3333-3333-3333-333333333333",
)
.unwrap();
let opts = SignReasonedActionOptions {
include_reasoning: true,
escrow_receipt: Some(receipt),
sealed_at: sealed.map(String::from),
};
sign_reasoned_action(
&seed(),
"did:web:agent.example",
"did:web:agent.example#key-1",
&sample_intent(),
&just,
exec,
"urn:uuid:44444444-4444-4444-4444-444444444444",
&opts,
)
.unwrap()
}
fn recheck(cred: &Value, now: &str) -> Option<String> {
recheck_intent_freshness(
cred,
TIER_CRITICAL,
"2026-04-26T10:00:00Z",
default_requirement(TIER_CRITICAL),
now,
30,
Some(&escrow_pub()),
)
.unwrap()
}
#[test]
fn recheck_accepts_a_fresh_witnessed_seal() {
let cred = escrowed(
"did:web:agent.example",
"2026-04-26T10:02:30Z",
"2026-04-26T10:03:00Z",
None,
);
assert_eq!(recheck(&cred, "2026-04-26T10:03:05Z"), None);
assert!(check_reasoned_action(&cred, &pubkey(), Some(&escrow_pub()), true).is_none());
}
#[test]
fn recheck_uses_the_escrow_time_not_the_agents_claim() {
let honest = escrowed(
"did:web:agent.example",
"2026-04-26T09:55:00Z",
"2026-04-26T10:03:00Z",
None,
);
assert!(recheck(&honest, "2026-04-26T10:03:00Z")
.unwrap()
.starts_with(REASON_INTENT_SEAL_STALE));
let lying = escrowed(
"did:web:agent.example",
"2026-04-26T09:55:00Z",
"2026-04-26T10:03:00Z",
Some("2026-04-26T10:02:30Z"),
);
assert_eq!(
recheck(&lying, "2026-04-26T10:03:00Z"),
Some(REASON_SEAL_AFTER_DEPOSIT.into())
);
assert_eq!(
check_reasoned_action(&lying, &pubkey(), Some(&escrow_pub()), true),
Some(REASON_SEAL_AFTER_DEPOSIT.into())
);
let old = verify_intent_freshness(
&lying,
TIER_CRITICAL,
"2026-04-26T10:00:00Z",
default_requirement(TIER_CRITICAL),
)
.unwrap();
assert_eq!(old, Some(REASON_ESCROW_INVALID.into()));
}
#[test]
fn recheck_refuses_forward_dated_and_late_seals() {
let future = escrowed(
"did:web:agent.example",
"2099-01-01T00:00:00Z",
"2099-01-01T00:00:00Z",
Some("2099-01-01T00:00:00Z"),
);
assert_eq!(
recheck(&future, "2026-04-26T10:03:00Z"),
Some(format!(
"{REASON_INTENT_SEAL_FUTURE}:sealed_at=2099-01-01T00:00:00Z"
))
);
assert_eq!(
check_reasoned_action_at(
&future,
&pubkey(),
Some(&escrow_pub()),
true,
"2026-04-26T10:03:00Z",
30
)
.unwrap(),
Some(REASON_SEAL_IN_FUTURE.into())
);
let late = escrowed(
"did:web:agent.example",
"2026-04-26T10:10:00Z",
"2026-04-26T10:03:00Z",
None,
);
assert_eq!(
recheck(&late, "2026-04-26T10:03:00Z"),
Some(REASON_ESCROW_AFTER_EXECUTION.into())
);
let ahead = escrowed(
"did:web:agent.example",
"2026-04-26T10:03:20Z",
"2026-04-26T10:03:20Z",
None,
);
assert_eq!(recheck(&ahead, "2026-04-26T10:03:00Z"), None, "inside skew");
assert!(recheck(&ahead, "2026-04-26T10:02:40Z").is_some());
let after =
reasoned_with_seal("2026-04-26T10:10:00Z", "2026-04-26T10:03:00Z", TIER_ROUTINE);
assert_eq!(
check_reasoned_action(&after, &pubkey(), None, false),
Some(REASON_SEAL_AFTER_EXECUTION.into())
);
let fresh = escrowed(
"did:web:agent.example",
"2026-04-26T10:02:30Z",
"2026-04-26T10:03:00Z",
None,
);
assert_eq!(
recheck(&fresh, "2026-04-26T10:09:00Z"),
Some(format!(
"{REASON_INTENT_EXECUTION_NOT_CURRENT}:valid_from=2026-04-26T10:03:00Z"
))
);
}
#[test]
fn recheck_binds_the_receipt_to_the_agent_and_key() {
let stolen = escrowed(
"did:web:someone-else.example",
"2026-04-26T10:02:30Z",
"2026-04-26T10:03:00Z",
None,
);
assert_eq!(
recheck(&stolen, "2026-04-26T10:03:00Z"),
Some(REASON_ESCROW_AGENT_MISMATCH.into())
);
assert_eq!(
check_reasoned_action(&stolen, &pubkey(), Some(&escrow_pub()), true),
Some(REASON_ESCROW_AGENT_MISMATCH.into())
);
let good = escrowed(
"did:web:agent.example",
"2026-04-26T10:02:30Z",
"2026-04-26T10:03:00Z",
None,
);
let wrong = recheck_intent_freshness(
&good,
TIER_CRITICAL,
"2026-04-26T10:00:00Z",
default_requirement(TIER_CRITICAL),
"2026-04-26T10:03:00Z",
30,
Some(&pubkey()),
)
.unwrap();
assert_eq!(wrong, Some(REASON_ESCROW_INVALID.into()));
let none = recheck_intent_freshness(
&good,
TIER_CRITICAL,
"2026-04-26T10:00:00Z",
default_requirement(TIER_CRITICAL),
"2026-04-26T10:03:00Z",
30,
None,
)
.unwrap();
assert_eq!(none, Some(REASON_ESCROW_INVALID.into()));
let bare = reasoned_with_seal(
"2026-04-26T10:02:30Z",
"2026-04-26T10:03:00Z",
TIER_CRITICAL,
);
assert_eq!(
recheck(&bare, "2026-04-26T10:03:00Z"),
Some(format!("{REASON_INTENT_SEAL_MISSING}:tier={TIER_CRITICAL}"))
);
assert!(recheck_intent_freshness(
&good,
TIER_CRITICAL,
"2026-04-26T10:00:00Z",
default_requirement(TIER_CRITICAL),
"2026-04-26T10:03:00Z",
121,
Some(&escrow_pub()),
)
.is_err());
}
#[test]
fn proof_bound_to_another_did_is_refused() {
let cred = sign_reasoned_action(
&seed(),
"did:web:agent.example",
"did:web:other.example#key-1",
&sample_intent(),
&sample_justification(),
"2026-08-02T10:00:00Z",
"urn:uuid:11111111-1111-1111-1111-111111111111",
&SignReasonedActionOptions::new(),
)
.unwrap();
assert_eq!(
check_reasoned_action(&cred, &pubkey(), None, false),
Some(REASON_INVALID_PROOF.into())
);
}
}