#[allow(unused_imports)]
use crate::prelude::*;
use alloc::collections::BTreeMap;
use serde_json::{json, Map, Value};
use crate::attenuation;
use crate::data_integrity;
use crate::error::{CoreError, Result};
use crate::grant_chain;
use crate::hybrid;
use crate::multikey;
use crate::time::{check_clock_skew, parse_protocol_time_ns, window_state_ns, WindowState};
#[derive(Debug, Clone)]
pub struct DelegationLinkInput {
pub issuer: String,
pub subject: String,
pub intent: Value,
pub valid_from: Option<String>,
pub valid_until: Option<String>,
pub parent_proof_value: Option<String>,
}
pub fn build_delegation_link(input: &DelegationLinkInput) -> Value {
crate::nesting::deep_guard!(Value::Null; input);
let mut link = Map::new();
link.insert("issuer".into(), json!(input.issuer));
link.insert("subject".into(), json!(input.subject));
link.insert("intent".into(), input.intent.clone());
if let Some(vf) = &input.valid_from {
link.insert("validFrom".into(), json!(vf));
}
if let Some(vu) = &input.valid_until {
link.insert("validUntil".into(), json!(vu));
}
if let Some(pp) = &input.parent_proof_value {
link.insert("parentProofValue".into(), json!(pp));
}
Value::Object(link)
}
fn link_bound(obj: &Map<String, Value>, key: &str) -> Result<Option<i128>> {
match obj.get(key) {
None => Ok(None),
Some(Value::String(s)) => Ok(Some(parse_protocol_time_ns(s)?)),
Some(_) => Err(CoreError::Json(format!(
"delegation link {key} must be a time string"
))),
}
}
fn link_window(link: &Value) -> Result<(Option<i128>, Option<i128>)> {
let obj = link
.as_object()
.ok_or_else(|| CoreError::Json("delegation link must be an object".into()))?;
Ok((
link_bound(obj, "validFrom")?,
link_bound(obj, "validUntil")?,
))
}
pub fn verify_chain_time_bound(
chain: &[Value],
now_iso: &str,
clock_skew_seconds: i64,
) -> Result<bool> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); chain);
let skew = check_clock_skew(clock_skew_seconds)?;
let now = parse_protocol_time_ns(now_iso)?;
let mut eff_from: Option<i128> = None;
let mut eff_until: Option<i128> = None;
for link in chain {
let (vf, vu) = link_window(link)?;
if let (Some(f), Some(u)) = (vf, vu) {
if f > u {
return Ok(false); }
}
if let (Some(f), Some(ef)) = (vf, eff_from) {
if f < ef {
return Ok(false); }
}
if let (Some(u), Some(eu)) = (vu, eff_until) {
if u > eu {
return Ok(false); }
}
if let Some(f) = vf {
eff_from = Some(eff_from.map_or(f, |cur| cur.max(f)));
}
if let Some(u) = vu {
eff_until = Some(eff_until.map_or(u, |cur| cur.min(u)));
}
}
Ok(window_state_ns(now, eff_from, eff_until, skew) == WindowState::Ok)
}
pub fn capability_view(credential: &Value, include_time: bool) -> Value {
crate::nesting::deep_guard!(Value::Null; credential);
let intent = credential
.get("credentialSubject")
.and_then(|s| s.get("intent"))
.and_then(|i| i.as_object())
.cloned()
.unwrap_or_default();
let mut view = Map::new();
view.insert(
"issuer".into(),
issuer_did(credential)
.map(Value::String)
.unwrap_or(Value::Null),
);
view.insert(
"subject".into(),
intent.get("delegatee").cloned().unwrap_or(Value::Null),
);
let mut dims = Map::new();
for k in ["action", "target", "resource", "amount"] {
if let Some(v) = intent.get(k) {
dims.insert(k.into(), v.clone());
}
}
view.insert("intent".into(), Value::Object(dims));
if include_time {
for k in ["validFrom", "validUntil"] {
if let Some(v) = credential.get(k) {
view.insert(k.into(), v.clone());
}
}
}
for k in ["rate", "policy"] {
if let Some(v) = intent.get(k) {
view.insert(k.into(), v.clone());
}
}
Value::Object(view)
}
fn issuer_did(credential: &Value) -> Option<String> {
crate::credentials::issuer_did(credential).map(String::from)
}
fn resolve_chain_key(did: &str, root_keys: &BTreeMap<String, Vec<u8>>) -> Option<Vec<u8>> {
let from_did = match did.strip_prefix("did:key:") {
Some(mk) => {
let decoded = multikey::decode(mk).ok()?;
if decoded.algorithm != "Ed25519" {
return None;
}
Some(decoded.raw_key)
}
None => None,
};
let given = root_keys.get(did);
if given.is_some_and(|k| crate::keys::strict_verifying_key(k).is_err()) {
return None;
}
match (given, from_did) {
(Some(k), Some(d)) => (k == &d).then_some(d),
(Some(k), None) => Some(k.clone()),
(None, d) => d,
}
}
struct GrantIssuerKeys {
ed25519: Vec<u8>,
mldsa44: Option<Vec<u8>>,
slhdsa128: Option<Vec<u8>>,
requires: hybrid::Required,
}
fn grant_issuer_keys(
issuer: &str,
grant: &Value,
grant_keys: &BTreeMap<String, Vec<u8>>,
opts: &ChainOptions,
) -> Option<GrantIssuerKeys> {
let given_requires = hybrid::Required {
post_quantum: false,
mldsa44: opts.mldsa_keys.is_some_and(|m| m.contains_key(issuer)),
slhdsa128: opts.slhdsa_keys.is_some_and(|m| m.contains_key(issuer)),
};
let given_mldsa = opts
.mldsa_keys
.and_then(|m| m.get(issuer))
.filter(|k| !k.is_empty())
.cloned();
let given_slhdsa = opts
.slhdsa_keys
.and_then(|m| m.get(issuer))
.filter(|k| !k.is_empty())
.cloned();
if let Some(ed25519) = resolve_chain_key(issuer, grant_keys) {
return Some(GrantIssuerKeys {
ed25519,
mldsa44: given_mldsa,
slhdsa128: given_slhdsa,
requires: given_requires,
});
}
if grant_keys.contains_key(issuer) {
return None;
}
let fetched = opts
.grant_documents
.filter(|_| issuer.starts_with("did:web:") || crate::did_webvh::is_did_webvh(issuer))
.and_then(|docs| docs.get(issuer));
let state = match fetched {
Some(document) => document.clone(),
None if crate::did_webvh::is_did_webvh(issuer) => {
opts.grant_logs?.resolve(issuer)?.ok()?.document
}
None => return None,
};
let methods = crate::credentials::proof_methods(grant);
let keys = crate::did_document::proof_keys_for(
&state,
issuer,
crate::did_document::ProofMethodRefs {
ed25519: methods.ed25519.as_deref(),
mldsa44: methods.mldsa44.as_deref(),
slhdsa128: methods.slhdsa128.as_deref(),
},
);
let published = keys.required();
let requires = hybrid::Required {
post_quantum: published.post_quantum,
mldsa44: published.mldsa44 || given_requires.mldsa44,
slhdsa128: published.slhdsa128 || given_requires.slhdsa128,
};
Some(GrantIssuerKeys {
ed25519: keys.ed25519?,
mldsa44: given_mldsa.or(keys.mldsa44),
slhdsa128: given_slhdsa.or(keys.slhdsa128),
requires,
})
}
pub(crate) fn parent_proof_binding_value(grant: &Value) -> String {
match grant.get("proof") {
Some(Value::Array(items)) => {
for p in items {
if p.get("cryptosuite").and_then(|v| v.as_str())
== Some(data_integrity::CRYPTOSUITE_ID)
{
return p
.get("proofValue")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
}
}
for p in items {
if let Some(v) = p.get("proofValue").and_then(|v| v.as_str()) {
if !v.is_empty() {
return v.to_string();
}
}
}
String::new()
}
Some(Value::Object(p)) => p
.get("proofValue")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string(),
_ => String::new(),
}
}
#[allow(clippy::too_many_arguments)]
fn verify_grant_proof(
grant: &Value,
issuer: &str,
key: &[u8],
mldsa_key: Option<&[u8]>,
slhdsa_key: Option<&[u8]>,
required: hybrid::Required,
now: i128,
skew: i128,
) -> bool {
if !grant_proof_well_formed(grant, issuer, now, skew) {
return false;
}
match grant.get("proof") {
Some(Value::Object(_)) => {
!required.any() && matches!(data_integrity::verify_proof(grant, key), Ok(true))
}
Some(Value::Array(items)) => {
let Some(members) = hybrid::set_members(items) else {
return false;
};
if !required.met_by(&members.suites()) {
return false;
}
let verdict = if required.any() {
hybrid::verify_set(grant, key, mldsa_key, slhdsa_key)
} else {
hybrid::verify_set_known_keys(grant, key, mldsa_key, slhdsa_key)
};
matches!(verdict, Ok(true))
}
_ => false,
}
}
fn grant_proof_well_formed(grant: &Value, issuer: &str, now: i128, skew: i128) -> bool {
let Some(proof) = grant.get("proof") else {
return false;
};
let members: Vec<&Value> = match proof {
Value::Array(items) => items.iter().collect(),
other => vec![other],
};
if members.is_empty()
|| !members
.iter()
.all(|m| crate::credentials::proof_member_ok(m, issuer, now, skew))
{
return false;
}
match proof {
Value::Object(_) => hybrid::Suite::of_proof(proof) == Some(hybrid::Suite::Eddsa),
Value::Array(items) => hybrid::set_members(items).is_some(),
_ => false,
}
}
fn first_64(s: &str) -> String {
s.chars().take(64).collect()
}
pub const REASON_TRUSTED_ROOTS_REQUIRED: &str =
"the chain's starting point is not trusted: pass trusted roots";
pub const REASON_BUDGET_EXCEEDED: &str = "verifier_budget_exceeded";
pub const MAX_CHAIN_BYTES: usize = attenuation::MAX_CHAIN_BYTES;
pub fn root_did(root: &str) -> Option<String> {
crate::did_web::normalize_root(root).ok()
}
pub fn root_matches(root: &str, issuer: &str) -> bool {
root_did(root).as_deref() == Some(issuer)
}
#[derive(Debug, Clone, Copy, Default)]
pub struct ChainOptions<'a> {
pub trusted_roots: Option<&'a [String]>,
pub grant_keys: Option<&'a BTreeMap<String, Vec<u8>>>,
pub mldsa_keys: Option<&'a BTreeMap<String, Vec<u8>>>,
pub slhdsa_keys: Option<&'a BTreeMap<String, Vec<u8>>>,
pub slhdsa128_key: Option<&'a [u8]>,
pub grant_logs: Option<&'a crate::did_webvh::LogSet>,
pub grant_documents: Option<&'a BTreeMap<String, Value>>,
pub require_pq: bool,
pub require_suites: &'a [hybrid::Suite],
pub max_depth: Option<usize>,
pub through_link: Option<usize>,
}
pub fn verify_delegation_chain(
credential: &Value,
now_iso: &str,
clock_skew_seconds: i64,
root_keys: &BTreeMap<String, Vec<u8>>,
root_dids: Option<&[String]>,
) -> Option<String> {
crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP.into()); credential);
let opts = ChainOptions {
trusted_roots: root_dids,
grant_keys: Some(root_keys),
..Default::default()
};
verify_delegation_chain_with(credential, now_iso, clock_skew_seconds, &opts)
}
pub fn chain_links_problem(
credential: &Value,
now_iso: &str,
clock_skew_seconds: i64,
opts: &ChainOptions,
) -> Option<String> {
crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP.into()); credential, opts);
let malformed = || Some("malformed_delegation".to_string());
if !credential.is_object() {
return malformed();
}
if let Some(reason) = grant_chain::binding_fields_problem(&credential["credentialSubject"]) {
return Some(reason.into());
}
let chain_value = match credential
.get("credentialSubject")
.and_then(|s| s.get("delegationChain"))
{
None => return None,
Some(Value::Array(a)) if a.is_empty() => return None,
Some(v @ Value::Array(_)) => v,
Some(_) => return malformed(),
};
let chain = chain_value.as_array().expect("checked above");
match attenuation::chain_budget_exceeded(chain_value, opts.max_depth) {
Ok(None) => {}
Ok(Some(_)) => return Some(REASON_BUDGET_EXCEEDED.into()),
Err(_) => return malformed(),
}
let Some(roots) = opts.trusted_roots else {
return Some(REASON_TRUSTED_ROOTS_REQUIRED.into());
};
if check_clock_skew(clock_skew_seconds).is_err() || parse_protocol_time_ns(now_iso).is_err() {
return malformed();
}
for link in chain {
let shape_ok = link.get("issuer").is_some_and(|v| v.is_string())
&& link.get("subject").is_some_and(|v| v.is_string());
if !shape_ok {
return malformed();
}
}
for i in 1..chain.len() {
if chain[i - 1].get("subject") != chain[i].get("issuer") {
return Some("delegation_subject_issuer_mismatch".into());
}
}
let last_subject = chain[chain.len() - 1]
.get("subject")
.and_then(|v| v.as_str());
if last_subject.map(String::from) != issuer_did(credential) {
return Some("delegation_subject_issuer_mismatch".into());
}
let root = chain[0]
.get("issuer")
.and_then(|v| v.as_str())
.unwrap_or("");
if !roots.iter().any(|d| root_matches(d, root)) {
return Some("untrusted_principal".into());
}
if chain
.iter()
.all(|link| matches!(link.get("parentCredential"), Some(Value::Object(_))))
{
if let Some(reason) = grant_chain::chain_binding_problem(chain) {
return Some(reason.into());
}
}
None
}
pub fn verify_delegation_chain_with(
credential: &Value,
now_iso: &str,
clock_skew_seconds: i64,
opts: &ChainOptions,
) -> Option<String> {
crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP.into()); credential, opts);
let malformed = || Some("malformed_delegation".to_string());
if let Some(reason) = chain_links_problem(credential, now_iso, clock_skew_seconds, opts) {
return Some(reason);
}
let chain = credential
.get("credentialSubject")
.and_then(|s| s.get("delegationChain"))
.and_then(Value::as_array)
.filter(|c| !c.is_empty())?;
let (Ok(skew), Ok(now)) = (
check_clock_skew(clock_skew_seconds),
parse_protocol_time_ns(now_iso),
) else {
return malformed();
};
let empty = BTreeMap::new();
let grant_keys = opts.grant_keys.unwrap_or(&empty);
let mut grants: Vec<&Value> = Vec::with_capacity(chain.len());
for (index, link) in chain.iter().enumerate() {
if opts.through_link == Some(index) {
return None;
}
let link_issuer = link["issuer"].as_str().unwrap_or_default();
let link_subject = link["subject"].as_str().unwrap_or_default();
let Some(grant) = link.get("parentCredential").filter(|g| g.is_object()) else {
return Some("delegation_link_unsigned".into());
};
if !matches!(
grant.get("proof"),
Some(Value::Object(_)) | Some(Value::Array(_))
) {
return Some("delegation_link_unsigned".into());
}
let grant_issuer = issuer_did(grant);
if grant_issuer.as_deref() != Some(link_issuer) {
return Some("delegation_link_issuer_mismatch".into());
}
if !grant_proof_well_formed(grant, link_issuer, now, skew) {
return Some("delegation_signature_invalid".into());
}
if !opts.require_suites.is_empty() {
let carried = hybrid::proof_suites(grant);
if opts.require_suites.iter().any(|s| !carried.contains(s)) {
return Some("delegation_signature_invalid".into());
}
}
let Some(keys) = grant_issuer_keys(link_issuer, grant, grant_keys, opts) else {
return Some("delegation_issuer_key_unresolved".into());
};
if !verify_grant_proof(
grant,
link_issuer,
&keys.ed25519,
keys.mldsa44.as_deref(),
keys.slhdsa128.as_deref(),
hybrid::Required {
post_quantum: opts.require_pq
|| keys.requires.post_quantum
|| opts
.require_suites
.iter()
.any(|s| *s != hybrid::Suite::Eddsa),
mldsa44: keys.requires.mldsa44
|| opts.require_suites.contains(&hybrid::Suite::Mldsa44),
slhdsa128: keys.requires.slhdsa128
|| opts.require_suites.contains(&hybrid::Suite::Slhdsa128),
},
now,
skew,
) {
return Some("delegation_signature_invalid".into());
}
if let Some(bound) = link.get("parentProofValue") {
let Some(bound) = bound.as_str() else {
return malformed();
};
if bound != first_64(&parent_proof_binding_value(grant)) {
return Some("delegation_link_tampered".into());
}
}
let delegatee = grant
.get("credentialSubject")
.and_then(|s| s.get("intent"))
.and_then(|i| i.get("delegatee"))
.and_then(|d| d.as_str())
.filter(|d| !d.is_empty());
let Some(delegatee) = delegatee else {
return Some("delegation_no_delegatee".into());
};
if delegatee != link_subject {
return Some("delegation_subject_mismatch".into());
}
let window = (
grant
.get("validFrom")
.and_then(|v| v.as_str())
.map(parse_protocol_time_ns),
grant
.get("validUntil")
.and_then(|v| v.as_str())
.map(parse_protocol_time_ns),
);
let (Some(Ok(from)), Some(Ok(until))) = window else {
return malformed();
};
match window_state_ns(now, Some(from), Some(until), skew) {
WindowState::Ok => {}
WindowState::Expired => return Some("delegation_expired".into()),
WindowState::NotYetValid => return Some("delegation_not_yet_valid".into()),
WindowState::Inverted => return malformed(),
}
grants.push(grant);
}
let last_subject = chain[chain.len() - 1]
.get("subject")
.and_then(|v| v.as_str());
if last_subject.map(String::from) != issuer_did(credential) {
return Some("delegation_subject_issuer_mismatch".into());
}
let mut views: Vec<Value> = grants.iter().map(|g| capability_view(g, true)).collect();
views.push(capability_view(credential, true));
if let Err(dim) = attenuation::first_broader_step(&views) {
return Some(format!("scope_exceeds_parent:{}", dim.as_str()));
}
None
}
crate::nesting::nested_fields!(DelegationLinkInput; intent);
crate::nesting::nested_fields!(ChainOptions<'_>; grant_documents);
#[cfg(test)]
mod tests {
use super::*;
fn link(vf: &str, vu: &str) -> Value {
build_delegation_link(&DelegationLinkInput {
issuer: "did:web:a".into(),
subject: "did:web:b".into(),
intent: json!({"action":"read","target":"t","resource":"https://x/y"}),
valid_from: Some(vf.into()),
valid_until: Some(vu.into()),
parent_proof_value: None,
})
}
#[test]
fn nested_windows_pass() {
let chain = vec![
link("2026-04-26T09:00:00Z", "2026-04-26T12:00:00Z"),
link("2026-04-26T10:00:00Z", "2026-04-26T11:00:00Z"),
];
assert!(verify_chain_time_bound(&chain, "2026-04-26T10:30:00Z", 30).unwrap());
}
#[test]
fn child_wider_than_parent_fails() {
let chain = vec![
link("2026-04-26T10:00:00Z", "2026-04-26T11:00:00Z"),
link("2026-04-26T09:00:00Z", "2026-04-26T12:00:00Z"), ];
assert!(!verify_chain_time_bound(&chain, "2026-04-26T10:30:00Z", 30).unwrap());
}
#[test]
fn now_outside_leaf_window_fails() {
let chain = vec![link("2026-04-26T10:00:00Z", "2026-04-26T11:00:00Z")];
assert!(!verify_chain_time_bound(&chain, "2026-04-26T12:00:00Z", 30).unwrap());
}
#[test]
fn a_window_less_middle_link_stays_bounded_by_the_root() {
let root = json!({"issuer":"did:web:root","subject":"did:web:a","intent":{},
"validFrom":"2026-04-26T09:00:00Z","validUntil":"2026-04-26T11:00:00Z"});
let mid = json!({"issuer":"did:web:a","subject":"did:web:b","intent":{}});
let leaf = json!({"issuer":"did:web:b","subject":"did:web:c","intent":{},
"validFrom":"2026-04-26T09:00:00Z","validUntil":"2099-01-01T00:00:00Z"});
let chain = vec![root.clone(), mid, leaf];
assert!(!verify_chain_time_bound(&chain, "2030-01-01T00:00:00Z", 30).unwrap());
assert!(!verify_chain_time_bound(&chain, "2026-04-26T10:00:00Z", 30).unwrap());
let bad = json!({"issuer":"did:web:a","subject":"did:web:b","intent":{},
"validFrom":"2026-04-26T09:00:00Z","validUntil":0});
assert!(verify_chain_time_bound(&[root.clone(), bad], "2026-04-26T10:00:00Z", 30).is_err());
let inv = link("2026-04-26T11:00:00Z", "2026-04-26T10:00:00Z");
assert!(!verify_chain_time_bound(&[inv], "2026-04-26T10:30:00Z", 120).unwrap());
assert!(verify_chain_time_bound(&[root], "2026-04-26T10:00:00Z", 121).is_err());
}
struct Party {
seed: [u8; 32],
did: String,
}
fn party(n: u8) -> Party {
let seed = [n; 32];
let did = crate::keys::Ed25519KeyPair::from_seed(&seed).did_key();
Party { seed, did }
}
fn vm(p: &Party) -> String {
format!("{}#{}", p.did, p.did.trim_start_matches("did:key:"))
}
fn grant_body(from: &Party, to: &Party) -> Value {
json!({
"@context": ["https://www.w3.org/ns/credentials/v2"],
"type": ["VerifiableCredential", "VouchCredential"],
"issuer": from.did,
"validFrom": "2026-04-26T09:00:00Z",
"validUntil": "2026-04-26T12:00:00Z",
"credentialSubject": {"id": from.did, "vouchVersion": "1.0", "intent": {
"action": "read", "target": "t", "resource": "https://x/a", "delegatee": to.did}}
})
}
fn leaf_credential(leaf: &Party, link: Value) -> Value {
json!({
"@context": ["https://www.w3.org/ns/credentials/v2"],
"type": ["VerifiableCredential", "VouchCredential"],
"issuer": leaf.did,
"validFrom": "2026-04-26T10:00:00Z",
"validUntil": "2026-04-26T10:05:00Z",
"credentialSubject": {"id": leaf.did, "vouchVersion": "1.0",
"intent": {"action": "read", "target": "t", "resource": "https://x/a/b"},
"delegationChain": [link]}
})
}
const NOW: &str = "2026-04-26T10:01:00Z";
fn opts_with<'a>(roots: &'a [String]) -> ChainOptions<'a> {
ChainOptions {
trusted_roots: Some(roots),
..Default::default()
}
}
#[test]
fn signed_chain_needs_roots_and_respects_the_size_guard() {
let (root, leaf) = (party(1), party(2));
let grant = data_integrity::sign(
&grant_body(&root, &leaf),
&root.seed,
&data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
)
.unwrap();
let link = json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant});
let cred = leaf_credential(&leaf, link.clone());
let roots = vec![root.did.clone()];
assert_eq!(
verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&roots)),
None
);
assert_eq!(
verify_delegation_chain_with(&cred, NOW, 30, &ChainOptions::default()),
Some(REASON_TRUSTED_ROOTS_REQUIRED.into())
);
assert_eq!(
verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&[])),
Some("untrusted_principal".into())
);
let bare = vec![root.did.trim_start_matches("did:key:").to_string()];
assert_eq!(
verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&bare)),
Some("untrusted_principal".into())
);
assert!(root_matches("yourcompany.com", "did:web:yourcompany.com"));
assert!(!root_matches(
"yourcompany.com",
"did:web:yourcompany.com.evil"
));
assert!(!root_matches("yourcompany.com", "did:key:yourcompany.com"));
assert_eq!(
root_did("yourcompany.com").as_deref(),
Some("did:web:yourcompany.com")
);
assert_eq!(
root_did("yourcompany.com:8443").as_deref(),
Some("did:web:yourcompany.com%3A8443")
);
assert!(root_did("127.0.0.1").is_none());
let other = vec!["did:web:someone-else".to_string()];
assert_eq!(
verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&other)),
Some("untrusted_principal".into())
);
let budget = ChainOptions {
max_depth: Some(0),
..opts_with(&roots)
};
assert_eq!(
verify_delegation_chain_with(&cred, NOW, 30, &budget),
Some(REASON_BUDGET_EXCEEDED.into())
);
let mut big = link;
big["note"] = json!("a".repeat(MAX_CHAIN_BYTES));
let cred = leaf_credential(&leaf, big);
assert_eq!(
verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&roots)),
Some(REASON_BUDGET_EXCEEDED.into())
);
}
#[test]
#[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
fn post_quantum_profile_requires_a_valid_dual_proof_on_every_grant() {
let (root, leaf) = (party(3), party(4));
let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
let body = grant_body(&root, &leaf);
let dual = hybrid::sign_dual(
&body,
&root.seed,
&ml,
&vm(&root),
&format!("{}#mldsa", root.did),
"2026-04-26T09:00:00Z",
)
.unwrap();
let single = data_integrity::sign(
&body,
&root.seed,
&data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
)
.unwrap();
let roots = vec![root.did.clone()];
let mut mldsa_keys = BTreeMap::new();
mldsa_keys.insert(root.did.clone(), ml.public_key().to_vec());
let pq = ChainOptions {
trusted_roots: Some(&roots),
mldsa_keys: Some(&mldsa_keys),
require_pq: true,
..Default::default()
};
let chain_of = |grant: &Value| {
leaf_credential(
&leaf,
json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
)
};
assert_eq!(
verify_delegation_chain_with(&chain_of(&dual), NOW, 30, &pq),
None
);
assert_eq!(
verify_delegation_chain_with(&chain_of(&single), NOW, 30, &pq),
Some("delegation_signature_invalid".into())
);
let mut broken = dual.clone();
broken["proof"][1]["proofValue"] = dual["proof"][0]["proofValue"].clone();
assert_eq!(
verify_delegation_chain_with(&chain_of(&broken), NOW, 30, &pq),
Some("delegation_signature_invalid".into())
);
let none = ChainOptions {
mldsa_keys: None,
..pq
};
assert_eq!(
verify_delegation_chain_with(&chain_of(&dual), NOW, 30, &none),
Some("delegation_signature_invalid".into())
);
assert_eq!(
verify_delegation_chain_with(&chain_of(&dual), NOW, 30, &opts_with(&roots)),
None
);
let mut foreign = dual.clone();
foreign["proof"][1]["verificationMethod"] = json!("did:web:someone-else#k");
assert_eq!(
verify_delegation_chain_with(&chain_of(&foreign), NOW, 30, &opts_with(&roots)),
Some("delegation_signature_invalid".into())
);
}
fn chain_with_proof(root: &Party, leaf: &Party, proof: Value) -> Value {
let mut grant = grant_body(root, leaf);
grant["proof"] = proof;
leaf_credential(
leaf,
json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
)
}
fn eddsa_proof(root: &Party, leaf: &Party, opts: data_integrity::BuildProofOptions) -> Value {
data_integrity::build_proof(&grant_body(root, leaf), &root.seed, &opts).unwrap()
}
#[test]
fn grant_proofs_follow_the_top_level_rules() {
let (root, leaf) = (party(5), party(6));
let roots = vec![root.did.clone()];
let o = opts_with(&roots);
let base = || data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z");
let good = eddsa_proof(&root, &leaf, base());
let check = |proof: Value| {
verify_delegation_chain_with(&chain_with_proof(&root, &leaf, proof), NOW, 30, &o)
};
assert_eq!(check(good.clone()), None);
let invalid = Some("delegation_signature_invalid".to_string());
for expires in [json!("2026-04-26T09:30:00Z"), Value::Null, json!(5)] {
let mut p = good.clone();
p["expires"] = expires.clone();
let mut unsigned = p.clone();
unsigned.as_object_mut().unwrap().remove("proofValue");
let input =
data_integrity::hash_data(&grant_body(&root, &leaf), unsigned.as_object().unwrap())
.unwrap();
let sig = crate::keys::Ed25519KeyPair::from_seed(&root.seed).sign(&input);
p["proofValue"] = json!(format!("z{}", bs58::encode(sig).into_string()));
assert_eq!(check(p), invalid, "expires {expires}");
}
let mut opts = base();
opts.created = "yesterday".into();
assert_eq!(check(eddsa_proof(&root, &leaf, opts)), invalid);
let mut p = good.clone();
p["cryptosuite"] = json!("some-unregistered-suite-2030");
assert_eq!(check(p), invalid);
let mut p = good.clone();
p.as_object_mut().unwrap().remove("proofValue");
assert_eq!(check(p), invalid);
assert_eq!(check(json!([good.clone(), 7])), invalid);
assert_eq!(check(json!([good.clone()])), invalid);
assert_eq!(check(json!([good.clone(), good.clone()])), invalid);
}
#[test]
fn grant_issuer_is_a_did_string_or_id() {
let (root, leaf) = (party(7), party(8));
let roots = vec![root.did.clone()];
let mut body = grant_body(&root, &leaf);
body["issuer"] = json!([root.did.clone()]);
let grant = data_integrity::sign(
&body,
&root.seed,
&data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
)
.unwrap();
let cred = leaf_credential(
&leaf,
json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
);
assert_eq!(
verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&roots)),
Some("delegation_link_issuer_mismatch".into())
);
}
#[test]
#[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
fn a_known_mldsa_key_checks_the_grant_member() {
let (root, leaf) = (party(9), party(10));
let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
let body = grant_body(&root, &leaf);
let dual = hybrid::sign_dual(
&body,
&root.seed,
&ml,
&vm(&root),
&format!("{}#mldsa", root.did),
"2026-04-26T09:00:00Z",
)
.unwrap();
let roots = vec![root.did.clone()];
let mut keys = BTreeMap::new();
keys.insert(root.did.clone(), ml.public_key().to_vec());
let known = ChainOptions {
trusted_roots: Some(&roots),
mldsa_keys: Some(&keys),
..Default::default()
};
let link = |g: &Value| {
leaf_credential(
&leaf,
json!({"issuer": root.did, "subject": leaf.did, "parentCredential": g}),
)
};
assert_eq!(
verify_delegation_chain_with(&link(&dual), NOW, 30, &known),
None
);
let mut broken = dual.clone();
broken["proof"][1]["proofValue"] = dual["proof"][0]["proofValue"].clone();
assert_eq!(
verify_delegation_chain_with(&link(&broken), NOW, 30, &known),
Some("delegation_signature_invalid".into())
);
let composite =
hybrid::composite_for_tests(&body, &root.seed, &ml, &vm(&root), "2026-04-26T09:00:00Z");
assert_eq!(
verify_delegation_chain_with(&link(&composite), NOW, 30, &known),
Some("delegation_signature_invalid".into())
);
assert_eq!(
verify_delegation_chain_with(&link(&composite), NOW, 30, &opts_with(&roots)),
Some("delegation_signature_invalid".into())
);
}
#[test]
#[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
fn a_grant_may_carry_an_slhdsa_proof() {
let (root, leaf) = (party(21), party(22));
let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
let slh = crate::slh::SlhDsa128KeyPair::generate().unwrap();
let body = grant_body(&root, &leaf);
let ed_vm = vm(&root);
let sign = |with_ml: bool| {
hybrid::sign_set(
&body,
&root.seed,
&ed_vm,
with_ml.then_some(hybrid::PqSigner {
key: &ml,
verification_method: &crate::issuance::mldsa44_verification_method(&ed_vm),
}),
Some(hybrid::PqSigner {
key: &slh,
verification_method: &crate::issuance::slhdsa128_verification_method(&ed_vm),
}),
"2026-04-26T09:00:00Z",
)
.unwrap()
};
let roots = vec![root.did.clone()];
let ml_keys = BTreeMap::from([(root.did.clone(), ml.public_key().to_vec())]);
let slh_keys = BTreeMap::from([(root.did.clone(), slh.public_key().to_vec())]);
let link = |g: &Value| {
leaf_credential(
&leaf,
json!({"issuer": root.did, "subject": leaf.did, "parentCredential": g}),
)
};
let all = ChainOptions {
trusted_roots: Some(&roots),
mldsa_keys: Some(&ml_keys),
slhdsa_keys: Some(&slh_keys),
..Default::default()
};
let slh_only = ChainOptions {
mldsa_keys: None,
..all
};
let invalid = Some("delegation_signature_invalid".to_string());
for with_ml in [true, false] {
let grant = sign(with_ml);
if !with_ml {
assert_eq!(
verify_delegation_chain_with(&link(&grant), NOW, 30, &all),
invalid
);
}
let all = if with_ml { all } else { slh_only };
assert_eq!(
verify_delegation_chain_with(&link(&grant), NOW, 30, &all),
None
);
let required = ChainOptions {
require_pq: true,
..all
};
assert_eq!(
verify_delegation_chain_with(&link(&grant), NOW, 30, &required),
None
);
let no_slh = ChainOptions {
slhdsa_keys: None,
..required
};
assert_eq!(
verify_delegation_chain_with(&link(&grant), NOW, 30, &no_slh),
invalid
);
let mut broken = grant.clone();
let last = broken["proof"].as_array().unwrap().len() - 1;
let value = broken["proof"][last]["proofValue"]
.as_str()
.unwrap()
.to_string();
let flipped = if value.ends_with('A') { "Q" } else { "A" };
broken["proof"][last]["proofValue"] =
json!(format!("{}{flipped}", &value[..value.len() - 1]));
assert_eq!(
verify_delegation_chain_with(&link(&broken), NOW, 30, &all),
invalid
);
}
}
#[test]
fn a_did_key_grant_issuer_keeps_its_own_key() {
let (root, leaf, other) = (party(11), party(12), party(13));
let grant = data_integrity::sign(
&grant_body(&root, &leaf),
&root.seed,
&data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
)
.unwrap();
let cred = leaf_credential(
&leaf,
json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
);
let roots = vec![root.did.clone()];
let mut keys = BTreeMap::new();
keys.insert(
root.did.clone(),
crate::keys::Ed25519KeyPair::from_seed(&other.seed)
.public_key()
.to_vec(),
);
let pinned = ChainOptions {
trusted_roots: Some(&roots),
grant_keys: Some(&keys),
..Default::default()
};
assert_eq!(
verify_delegation_chain_with(&cred, NOW, 30, &pinned),
Some("delegation_issuer_key_unresolved".into())
);
}
#[test]
fn link_fields_are_checked_before_any_key() {
let link = |iss: &str, sub: &str| {
json!({"issuer": iss, "subject": sub,
"parentCredential": {"issuer": iss, "proof": {"type": "DataIntegrityProof"}}})
};
let cred = |chain: Value| json!({"issuer": "did:web:c", "credentialSubject": {"delegationChain": chain}});
let roots = vec!["did:web:root".to_string()];
assert_eq!(
verify_delegation_chain_with(
&cred(json!([link("did:web:other", "did:web:c")])),
NOW,
30,
&opts_with(&roots)
),
Some("untrusted_principal".into())
);
assert_eq!(
verify_delegation_chain_with(
&cred(json!([
link("did:web:root", "did:web:a"),
link("did:web:b", "did:web:c")
])),
NOW,
30,
&opts_with(&roots)
),
Some("delegation_subject_issuer_mismatch".into())
);
assert_eq!(
verify_delegation_chain_with(
&cred(json!([link("did:web:root", "did:web:other")])),
NOW,
30,
&opts_with(&roots)
),
Some("delegation_subject_issuer_mismatch".into())
);
assert_eq!(
verify_delegation_chain_with(
&cred(json!([link("did:web:root", "did:web:c")])),
NOW,
30,
&opts_with(&roots)
),
Some("delegation_signature_invalid".into())
);
for chain in [Value::Null, json!({}), json!(""), json!(0), json!(false)] {
assert_eq!(
verify_delegation_chain_with(&cred(chain.clone()), NOW, 30, &opts_with(&roots)),
Some("malformed_delegation".into()),
"{chain}"
);
}
let big =
cred(json!([{"issuer": "x", "subject": "y", "pad": "a".repeat(MAX_CHAIN_BYTES)}]));
assert_eq!(
verify_delegation_chain_with(&big, NOW, 30, &ChainOptions::default()),
Some(REASON_BUDGET_EXCEEDED.into())
);
}
#[test]
fn grant_binding_is_checked_before_any_key() {
let grant = |iss: &str, sub: &str, extra: Value| {
let mut g = json!({"issuer": iss, "proof": {"type": "DataIntegrityProof"},
"credentialSubject": {"intent": {"delegatee": sub}}});
for (k, v) in extra.as_object().unwrap() {
g["credentialSubject"][k] = v.clone();
}
g
};
let link = |g: &Value| {
json!({"issuer": g["issuer"], "subject": g["credentialSubject"]["intent"]["delegatee"],
"parentCredential": g})
};
let cred = |chain: Vec<Value>| json!({"issuer": "did:web:c", "credentialSubject": {"delegationChain": chain}});
let roots = vec!["did:web:root".to_string()];
let check = |chain: Vec<Value>| {
verify_delegation_chain_with(&cred(chain), NOW, 30, &opts_with(&roots))
};
let g1 = grant("did:web:root", "did:web:a", json!({}));
let digest = grant_chain::grant_digest(&g1).unwrap();
let bound = grant(
"did:web:a",
"did:web:c",
json!({ "parentGrantDigest": digest }),
);
let unbound = grant("did:web:a", "did:web:c", json!({}));
assert_eq!(
check(vec![link(&g1), link(&bound)]),
Some("delegation_signature_invalid".into())
);
assert_eq!(
check(vec![link(&g1), link(&unbound)]),
Some("delegation_parent_mismatch".into())
);
let cut = grant(
"did:web:root",
"did:web:c",
json!({ "parentGrantDigest": "uEiAAAA" }),
);
assert_eq!(
check(vec![link(&cut)]),
Some("delegation_parent_mismatch".into())
);
for extra in [
json!({ "parentGrantDigest": null }),
json!({ "delegationChain": null }),
json!({ "parentGrantDigest": digest, "delegationChain": [link(&g1)] }),
] {
let g2 = grant("did:web:a", "did:web:c", extra.clone());
assert_eq!(
check(vec![link(&g1), link(&g2)]),
Some("malformed_delegation".into()),
"{extra}"
);
}
assert_eq!(
verify_delegation_chain_with(
&cred(vec![link(&g1), link(&unbound)]),
NOW,
30,
&opts_with(&["did:web:other".to_string()])
),
Some("untrusted_principal".into())
);
for missing in [None, Some(json!("grant")), Some(Value::Null)] {
let mut first = link(&g1);
match &missing {
None => {
first.as_object_mut().unwrap().remove("parentCredential");
}
Some(v) => first["parentCredential"] = v.clone(),
}
assert_eq!(
check(vec![first, link(&unbound)]),
Some("delegation_link_unsigned".into()),
"{missing:?}"
);
}
}
}