#[allow(unused_imports)]
use crate::prelude::*;
use core::fmt;
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use serde_json::{json, Map, Value};
use sha2::{Digest, Sha256};
use crate::attenuation;
use crate::delegation;
use crate::error::CoreError;
use crate::jcs;
pub const REASON_PARENT_MISMATCH: &str = "delegation_parent_mismatch";
pub const REASON_MALFORMED: &str = "malformed_delegation";
pub const REASON_REPLICA_CHAIN_TOO_LONG: &str = "replica_chain_too_long";
pub const REPLICA_OF: &str = "replicaOf";
pub const PARENT_GRANT_DIGEST: &str = "parentGrantDigest";
pub const NAMES_PARENT_GRANT: &str =
"this grant names a parent grant; pass the whole grant chain (a list, root first)";
const MULTIHASH_SHA2_256: [u8; 2] = [0x12, 0x20];
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GrantDigestError(pub String);
impl fmt::Display for GrantDigestError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl core::error::Error for GrantDigestError {}
impl From<GrantDigestError> for CoreError {
fn from(e: GrantDigestError) -> Self {
CoreError::Json(e.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GrantChainError(pub String);
impl fmt::Display for GrantChainError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl core::error::Error for GrantChainError {}
impl From<GrantChainError> for CoreError {
fn from(e: GrantChainError) -> Self {
CoreError::Json(e.0)
}
}
fn refused(msg: impl Into<String>) -> GrantChainError {
GrantChainError(msg.into())
}
pub fn grant_digest(grant: &Value) -> Result<String, GrantDigestError> {
crate::nesting::deep_guard!(Err(GrantDigestError(crate::nesting::TOO_DEEP.into())); grant);
if !grant.is_object() {
return Err(GrantDigestError("a grant must be a JSON object".into()));
}
let mut multihash = Vec::with_capacity(34);
multihash.extend_from_slice(&MULTIHASH_SHA2_256);
multihash.extend_from_slice(&Sha256::digest(jcs::canonicalize(grant)));
Ok(format!("u{}", URL_SAFE_NO_PAD.encode(multihash)))
}
fn subject_of(grant: &Value) -> Option<&Map<String, Value>> {
grant.get("credentialSubject").and_then(Value::as_object)
}
pub fn binding_fields_problem(subject: &Value) -> Option<&'static str> {
crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP); subject);
let subject = subject.as_object()?;
let digest = subject.get(PARENT_GRANT_DIGEST);
if digest.is_some_and(|d| !d.is_string()) {
return Some(REASON_MALFORMED);
}
let chain = subject.get("delegationChain");
if chain.is_some_and(|c| !c.is_array()) {
return Some(REASON_MALFORMED);
}
if digest.is_some()
&& chain
.and_then(Value::as_array)
.is_some_and(|c| !c.is_empty())
{
return Some(REASON_MALFORMED);
}
None
}
fn bindings(cred: &Value) -> (Option<&Value>, &[Value]) {
let subject = subject_of(cred);
let digest = subject.and_then(|s| s.get(PARENT_GRANT_DIGEST));
let embedded = match subject.and_then(|s| s.get("delegationChain")) {
Some(Value::Array(a)) => a.as_slice(),
_ => &[],
};
(digest, embedded)
}
fn binding_failure(chain: &[Value]) -> Option<(usize, &'static str)> {
for (i, link) in chain.iter().enumerate() {
let Some(grant) = link.get("parentCredential").filter(|g| g.is_object()) else {
return Some((i, REASON_MALFORMED));
};
if let Some(malformed) = binding_fields_problem(&grant["credentialSubject"]) {
return Some((i, malformed));
}
let (digest, embedded) = bindings(grant);
let has_embedded = !embedded.is_empty();
if i == 0 {
if digest.is_some() || has_embedded {
return Some((i, REASON_PARENT_MISMATCH));
}
continue;
}
let bound = if let Some(Value::String(d)) = digest {
match grant_digest(&chain[i - 1]["parentCredential"]) {
Ok(expected) => *d == expected,
Err(_) => return Some((i, REASON_MALFORMED)),
}
} else if has_embedded {
embedded.len() == i
&& embedded
.iter()
.zip(&chain[..i])
.all(|(a, b)| jcs::canonicalize(a) == jcs::canonicalize(b))
} else {
false
};
if !bound {
return Some((i, REASON_PARENT_MISMATCH));
}
}
None
}
pub fn chain_binding_problem(chain: &[Value]) -> Option<&'static str> {
crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP); chain);
binding_failure(chain)
.or_else(|| replica_failure(chain))
.map(|(_, reason)| reason)
}
pub fn is_replica_grant(grant: &Value) -> bool {
crate::nesting::deep_guard!(false; grant);
subject_of(grant)
.and_then(|s| s.get("intent"))
.and_then(Value::as_object)
.is_some_and(|i| i.contains_key(REPLICA_OF))
}
fn replica_failure(chain: &[Value]) -> Option<(usize, &'static str)> {
let last = chain.len().saturating_sub(1);
chain[..last]
.iter()
.position(|link| link.get("parentCredential").is_some_and(is_replica_grant))
.map(|i| (i, REASON_REPLICA_CHAIN_TOO_LONG))
}
pub fn presented_chain_problem(credentials: &[Value]) -> Option<(usize, &'static str)> {
crate::nesting::deep_guard!(Some((0, crate::nesting::TOO_DEEP)); credentials);
for (i, cred) in credentials.iter().enumerate() {
if !cred.is_object() {
return Some((i, REASON_MALFORMED));
}
if let Some(malformed) = binding_fields_problem(&cred["credentialSubject"]) {
return Some((i, malformed));
}
let (digest, embedded) = bindings(cred);
if i == 0 {
if digest.is_some() || !embedded.is_empty() {
return Some((i, REASON_PARENT_MISMATCH));
}
continue;
}
let previous = &credentials[i - 1];
let bound = if let Some(digest) = digest {
match grant_digest(previous) {
Ok(expected) => digest.as_str() == Some(expected.as_str()),
Err(_) => return Some((i, REASON_MALFORMED)),
}
} else if let Some(last) = embedded.last() {
last.get("parentCredential")
.filter(|g| g.is_object())
.is_some_and(|g| jcs::canonicalize(g) == jcs::canonicalize(previous))
} else {
continue;
};
if !bound {
return Some((i, REASON_PARENT_MISMATCH));
}
}
None
}
fn embedded_chain(grant: &Value) -> &[Value] {
match subject_of(grant).and_then(|s| s.get("delegationChain")) {
Some(Value::Array(a)) => a.as_slice(),
_ => &[],
}
}
pub fn is_grant_intent(intent: &Value) -> bool {
crate::nesting::deep_guard!(false; intent);
intent
.get("delegatee")
.and_then(Value::as_str)
.is_some_and(|d| !d.is_empty())
}
pub fn parent_grants(parent: &Value) -> Result<Vec<Value>, GrantChainError> {
crate::nesting::deep_guard!(Err(GrantChainError(crate::nesting::TOO_DEEP.into())); parent);
match parent {
Value::Object(_) => {
let subject = subject_of(parent);
if subject.is_some_and(|s| s.contains_key(PARENT_GRANT_DIGEST)) {
return Err(refused(NAMES_PARENT_GRANT));
}
if subject
.and_then(|s| s.get("delegationChain"))
.is_some_and(|c| !c.is_array())
{
return Err(refused(
"Delegation refused: the parent grant's delegationChain is not a list",
));
}
let mut grants = Vec::new();
for link in embedded_chain(parent) {
let Some(grant) = link.get("parentCredential").filter(|g| g.is_object()) else {
return Err(refused(
"Delegation refused: a link in the parent grant's delegationChain \
carries no signed grant",
));
};
grants.push(grant.clone());
}
grants.push(parent.clone());
Ok(grants)
}
Value::Array(items) => {
if items.is_empty() {
return Err(refused("Delegation refused: the grant chain is empty"));
}
if !items.iter().all(Value::is_object) {
return Err(refused(
"Delegation refused: every grant in the grant chain must be an object",
));
}
Ok(items.clone())
}
_ => Err(refused(
"parent_credential must be a grant (a dict) or a grant chain (a list of grants, \
root first)",
)),
}
}
fn intent_of(grant: &Value) -> Result<&Value, GrantChainError> {
subject_of(grant)
.and_then(|s| s.get("intent"))
.filter(|i| i.is_object())
.ok_or_else(|| refused("Delegation refused: the parent grant carries no intent object"))
}
fn link_for(grant: &Value, intent: &Value) -> Result<Value, GrantChainError> {
let mut link = Map::new();
link.insert(
"issuer".into(),
Value::String(
issuer_value(grant)
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
),
);
link.insert(
"subject".into(),
intent_of(grant)?
.get("delegatee")
.cloned()
.unwrap_or(Value::Null),
);
link.insert("intent".into(), intent.clone());
for k in ["validFrom", "validUntil"] {
link.insert(k.into(), grant.get(k).cloned().unwrap_or(Value::Null));
}
let bound: String = delegation::parent_proof_binding_value(grant)
.chars()
.take(64)
.collect();
link.insert("parentProofValue".into(), Value::String(bound));
link.insert("parentCredential".into(), grant.clone());
Ok(Value::Object(link))
}
pub fn chain_links(grants: &[Value], intent: &Value) -> Result<Vec<Value>, GrantChainError> {
crate::nesting::deep_guard!(Err(GrantChainError(crate::nesting::TOO_DEEP.into())); grants, intent);
for grant in grants {
intent_of(grant)?;
}
let mut links: Vec<Value> = Vec::new();
let mut start = 0;
for j in (0..grants.len()).rev() {
let embedded = embedded_chain(&grants[j]);
if embedded.is_empty() {
continue;
}
let same = embedded.len() == j
&& embedded.iter().enumerate().all(|(i, link)| {
link.get("parentCredential")
.filter(|g| g.is_object())
.is_some_and(|g| jcs::canonicalize(g) == jcs::canonicalize(&grants[i]))
});
if !same {
return Err(refused(format!(
"Delegation refused: grant {} of the grant chain embeds a chain that is not \
the grants before it",
j + 1
)));
}
for (i, link) in embedded.iter().enumerate() {
if present(link.get("issuer")) != present(issuer_value(&grants[i])) {
return Err(refused(format!(
"Delegation refused: grant {} of the grant chain embeds a link whose issuer \
is not the issuer of grant {}",
j + 1,
i + 1
)));
}
if present(link.get("subject")) != present(intent_of(&grants[i])?.get("delegatee")) {
return Err(refused(format!(
"Delegation refused: grant {} of the grant chain embeds a link whose subject \
is not the delegatee of grant {}",
j + 1,
i + 1
)));
}
}
links = embedded.to_vec();
start = j;
break;
}
for j in start..grants.len() {
let step_intent = if j + 1 < grants.len() {
intent_of(&grants[j + 1])?
} else {
intent
};
links.push(link_for(&grants[j], step_intent)?);
}
Ok(links)
}
fn issuer_value(grant: &Value) -> Option<&Value> {
match grant.get("issuer") {
Some(Value::Object(o)) => o.get("id"),
other => other,
}
}
fn present(v: Option<&Value>) -> Option<&Value> {
v.filter(|x| !x.is_null())
}
pub(crate) fn truthy(v: Option<&Value>) -> bool {
match v {
None | Some(Value::Null) => false,
Some(Value::Bool(b)) => *b,
Some(Value::Number(n)) => n.as_f64().is_some_and(|f| f != 0.0),
Some(Value::String(s)) => !s.is_empty(),
Some(Value::Array(a)) => !a.is_empty(),
Some(Value::Object(o)) => !o.is_empty(),
}
}
pub(crate) fn py_repr(v: Option<&Value>) -> String {
match v {
None | Some(Value::Null) => "None".into(),
Some(Value::Bool(true)) => "True".into(),
Some(Value::Bool(false)) => "False".into(),
Some(Value::Number(n)) => match n.as_f64() {
Some(f) if n.is_f64() => py_repr_float(f),
_ => n.to_string(),
},
Some(Value::String(s)) => py_repr_str(s),
Some(Value::Array(a)) => {
let items: Vec<String> = a.iter().map(|x| py_repr(Some(x))).collect();
format!("[{}]", items.join(", "))
}
Some(Value::Object(o)) => {
let items: Vec<String> = o
.iter()
.map(|(k, x)| format!("{}: {}", py_repr_str(k), py_repr(Some(x))))
.collect();
format!("{{{}}}", items.join(", "))
}
}
}
fn shortest_digits(f: f64) -> (String, i32) {
let mut buf = ryu_js::Buffer::new();
let text = buf.format(f);
let (number, exp) = match text.split_once('e') {
Some((n, e)) => (n, e.parse::<i32>().unwrap_or(0)),
None => (text, 0),
};
let (whole, fraction) = number.split_once('.').unwrap_or((number, ""));
let all = format!("{whole}{fraction}");
let significant = all.trim_start_matches('0');
let point = whole.len() as i32 + exp - (all.len() - significant.len()) as i32;
let significant = significant.trim_end_matches('0');
if significant.is_empty() {
return ("0".into(), 1);
}
(significant.to_string(), point)
}
pub(crate) fn py_repr_float(f: f64) -> String {
if f.is_nan() {
return "nan".into();
}
if f.is_infinite() {
return if f > 0.0 { "inf" } else { "-inf" }.into();
}
let sign = if f.is_sign_negative() { "-" } else { "" };
let (digits, point) = shortest_digits(f.abs());
let exp = point - 1;
if point <= -4 || point > 16 {
let (first, rest) = digits.split_at(1);
let fraction = if rest.is_empty() {
String::new()
} else {
format!(".{rest}")
};
let exp_sign = if exp < 0 { '-' } else { '+' };
return format!(
"{sign}{first}{fraction}e{exp_sign}{:02}",
exp.unsigned_abs()
);
}
let len = digits.len() as i32;
let body = if point <= 0 {
format!("0.{}{digits}", "0".repeat(point.unsigned_abs() as usize))
} else if point >= len {
format!("{digits}{}.0", "0".repeat((point - len) as usize))
} else {
let (whole, fraction) = digits.split_at(point as usize);
format!("{whole}.{fraction}")
};
format!("{sign}{body}")
}
pub(crate) fn py_repr_str(s: &str) -> String {
let quote = if s.contains('\'') && !s.contains('"') {
'"'
} else {
'\''
};
let mut out = String::with_capacity(s.len() + 2);
out.push(quote);
for c in s.chars() {
match c {
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if c == quote => {
out.push('\\');
out.push(c);
}
c if crate::py_printable::is_printable(c) => out.push(c),
c if (c as u32) <= 0xff => out.push_str(&format!("\\x{:02x}", c as u32)),
c if (c as u32) <= 0xffff => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push_str(&format!("\\U{:08x}", c as u32)),
}
}
out.push(quote);
out
}
pub fn check_grant_chain(grants: &[Value], intent: &Value) -> Result<Vec<Value>, GrantChainError> {
crate::nesting::deep_guard!(Err(GrantChainError(crate::nesting::TOO_DEEP.into())); grants, intent);
for (j, grant) in grants.iter().enumerate() {
intent_of(grant)?;
if !truthy(grant.get("issuer"))
|| !matches!(grant.get("proof"), Some(Value::Object(_) | Value::Array(_)))
{
return Err(refused(
"Delegation refused: the parent grant is not a signed credential",
));
}
if !issuer_value(grant).is_some_and(Value::is_string) {
return Err(refused(format!(
"Delegation refused: grant {} of the grant chain has an issuer that is not a \
string or an object with a string id",
j + 1
)));
}
}
for j in 0..grants.len().saturating_sub(1) {
let delegatee = intent_of(&grants[j])?
.get("delegatee")
.and_then(Value::as_str)
.filter(|d| !d.is_empty());
let Some(delegatee) = delegatee else {
return Err(refused(format!(
"Delegation refused: grant {} of the grant chain names no delegatee",
j + 1
)));
};
let next_issuer = issuer_value(&grants[j + 1]);
if next_issuer.and_then(Value::as_str) != Some(delegatee) {
return Err(refused(format!(
"Delegation refused: grant {} of the grant chain names delegatee {}, but grant \
{} is issued by {}",
j + 1,
py_repr_str(delegatee),
j + 2,
py_repr(next_issuer)
)));
}
}
let links = chain_links(grants, intent)?;
if let Some((index, reason)) = binding_failure(&links) {
return Err(refused(format!(
"Delegation refused: grant {} of the grant chain is not bound to the grant before \
it ({reason})",
index + 1
)));
}
let mut replica = replica_failure(&links).map(|(i, _)| i);
if replica.is_none() && grants.last().is_some_and(is_replica_grant) && is_grant_intent(intent) {
replica = Some(grants.len() - 1);
}
if let Some(index) = replica {
return Err(refused(format!(
"Delegation refused: grant {} of the grant chain is a replica grant, and a replica \
cannot hand its authority on (replica_chain_too_long)",
index + 1
)));
}
if grants.len() > 1 {
let views: Vec<Value> = grants
.iter()
.map(|g| delegation::capability_view(g, true))
.collect();
if let Some(dimension) = attenuation::malformed_dimension(&views[0]) {
return Err(refused(format!(
"Delegation refused: grant 1 of the grant chain has a malformed {}",
py_repr_str(dimension.as_str())
)));
}
if let Err(dimension) = attenuation::first_broader_step(&views) {
return Err(refused(format!(
"Delegation refused: a grant in the grant chain is broader than the grant before \
it on {}",
py_repr_str(dimension.as_str())
)));
}
}
Ok(links)
}
pub fn chain_capability(grants: &[Value], include_time: bool) -> Result<Value, GrantChainError> {
crate::nesting::deep_guard!(Err(GrantChainError(crate::nesting::TOO_DEEP.into())); grants);
let mut effective: Option<Value> = None;
for grant in grants {
let view = delegation::capability_view(grant, include_time);
effective = Some(match effective {
None => view,
Some(e) => attenuation::inherit(&e, &view),
});
}
effective.ok_or_else(|| refused("Delegation refused: the grant chain is empty"))
}
pub fn grant_chain(parent: &Value, grant: &Value) -> Result<Vec<Value>, GrantChainError> {
crate::nesting::deep_guard!(Err(GrantChainError(crate::nesting::TOO_DEEP.into())); parent, grant);
let mut grants = parent_grants(parent)?;
if !grant.is_object() {
return Err(refused("grant must be a signed grant (a dict)"));
}
let intent = intent_of(grant)?;
if !is_grant_intent(intent) {
return Err(refused(
"this credential names no delegatee, so nobody can sign under it",
));
}
grants.push(grant.clone());
check_grant_chain(&grants, intent)?;
Ok(grants)
}
pub fn rules_json(request: &Value) -> crate::error::Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
let arg = |name: &str| request.get(name).unwrap_or(&Value::Null);
let list = |name: &str| -> Vec<Value> { arg(name).as_array().cloned().unwrap_or_default() };
let chain_error = |e: GrantChainError| {
let kind = if e.0.starts_with("parent_credential must be")
|| e.0.starts_with("grant must be a signed grant")
{
"type"
} else {
"refused"
};
json!({ "error": e.0, "kind": kind })
};
let ok = |v: Value| json!({ "ok": v });
let name = request.get("fn").and_then(Value::as_str).unwrap_or("");
Ok(match name {
"grantDigest" => match grant_digest(arg("grant")) {
Ok(d) => ok(json!(d)),
Err(e) => json!({ "error": e.0, "kind": "digest" }),
},
"bindingFieldsProblem" => ok(json!(binding_fields_problem(arg("subject")))),
"chainBindingProblem" => ok(json!(chain_binding_problem(&list("chain")))),
"isReplicaGrant" => ok(json!(is_replica_grant(arg("grant")))),
"isGrantIntent" => ok(json!(is_grant_intent(arg("intent")))),
"presentedChainProblem" => ok(match presented_chain_problem(&list("credentials")) {
Some((i, reason)) => json!([i, reason]),
None => Value::Null,
}),
"parentGrants" => match parent_grants(arg("parent")) {
Ok(g) => ok(Value::Array(g)),
Err(e) => chain_error(e),
},
"chainLinks" => match chain_links(&list("grants"), arg("intent")) {
Ok(l) => ok(Value::Array(l)),
Err(e) => chain_error(e),
},
"checkGrantChain" => match check_grant_chain(&list("grants"), arg("intent")) {
Ok(l) => ok(Value::Array(l)),
Err(e) => chain_error(e),
},
"chainCapability" => {
let include_time = arg("includeTime").as_bool().unwrap_or(true);
match chain_capability(&list("grants"), include_time) {
Ok(c) => ok(c),
Err(e) => chain_error(e),
}
}
"grantChain" => match grant_chain(arg("parent"), arg("grant")) {
Ok(g) => ok(Value::Array(g)),
Err(e) => chain_error(e),
},
other => {
return Err(CoreError::Json(format!(
"unknown grant chain rule {:?}",
other.chars().take(40).collect::<String>()
)))
}
})
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn grant(issuer: &str, delegatee: &str, extra: Value) -> Value {
let mut subject = json!({
"id": issuer,
"intent": {"action": "read", "target": "t", "resource": "https://x/a",
"delegatee": delegatee}
});
for (k, v) in extra.as_object().unwrap() {
subject[k] = v.clone();
}
json!({
"issuer": issuer,
"validFrom": "2026-11-10T00:00:00Z",
"validUntil": "2026-11-11T00:00:00Z",
"credentialSubject": subject,
"proof": {"type": "DataIntegrityProof", "proofValue": format!("z{issuer}")}
})
}
fn link(g: &Value) -> Value {
json!({"issuer": g["issuer"], "subject": g["credentialSubject"]["intent"]["delegatee"],
"parentCredential": g})
}
fn flat3() -> Vec<Value> {
let g1 = grant("did:web:root", "did:web:a", json!({}));
let g2 = grant(
"did:web:a",
"did:web:b",
json!({ "parentGrantDigest": grant_digest(&g1).unwrap() }),
);
let g3 = grant(
"did:web:b",
"did:web:c",
json!({ "parentGrantDigest": grant_digest(&g2).unwrap() }),
);
vec![g1, g2, g3]
}
fn links(grants: &[Value]) -> Vec<Value> {
grants.iter().map(link).collect()
}
#[test]
fn digest_shape_and_exactness() {
let g = grant("did:web:root", "did:web:a", json!({}));
let d = grant_digest(&g).unwrap();
assert!(d.starts_with("uEi"), "{d}");
assert_eq!(d.len(), 47);
assert!(!d.contains('=') && !d.contains('+') && !d.contains('/'));
let reordered: Value = serde_json::from_str(
&serde_json::to_string(&json!({
"proof": g["proof"], "credentialSubject": g["credentialSubject"],
"validUntil": g["validUntil"], "validFrom": g["validFrom"], "issuer": g["issuer"]
}))
.unwrap(),
)
.unwrap();
assert_eq!(grant_digest(&reordered).unwrap(), d);
let mut other = g.clone();
other["proof"]["proofValue"] = json!("zdifferent");
assert_ne!(grant_digest(&other).unwrap(), d);
for bad in [json!([]), json!("x"), Value::Null, json!(1), json!(true)] {
assert_eq!(
grant_digest(&bad),
Err(GrantDigestError("a grant must be a JSON object".into()))
);
}
}
#[test]
fn flat_and_nested_chains_bind() {
assert_eq!(chain_binding_problem(&links(&flat3())), None);
assert_eq!(chain_binding_problem(&[]), None);
let g = flat3();
let ls = links(&g[..2]);
let nested = grant(
"did:web:b",
"did:web:c",
json!({ "delegationChain": ls.clone() }),
);
let mut chain = ls.clone();
chain.push(link(&nested));
assert_eq!(chain_binding_problem(&chain), None);
let g = flat3();
let mut g2 = g[1].clone();
g2["credentialSubject"]["delegationChain"] = json!([]);
assert_eq!(chain_binding_problem(&[link(&g[0]), link(&g2)]), None);
}
#[test]
fn binding_refusals() {
let g = flat3();
let mismatch = Some(REASON_PARENT_MISMATCH);
let malformed = Some(REASON_MALFORMED);
assert_eq!(chain_binding_problem(&links(&g[1..])), mismatch);
let other_root = grant("did:web:root", "did:web:a", json!({"note": "other"}));
assert_eq!(
chain_binding_problem(&[link(&other_root), link(&g[1]), link(&g[2])]),
mismatch
);
let skip = grant(
"did:web:b",
"did:web:c",
json!({ "parentGrantDigest": grant_digest(&g[0]).unwrap() }),
);
assert_eq!(
chain_binding_problem(&[link(&g[0]), link(&g[1]), link(&skip)]),
mismatch
);
let bare = grant("did:web:a", "did:web:b", json!({}));
assert_eq!(chain_binding_problem(&[link(&g[0]), link(&bare)]), mismatch);
let right = grant_digest(&g[0]).unwrap();
for spelled in [
right.to_uppercase(),
format!("{right}="),
format!(" {right}"),
right.replacen('u', "z", 1),
] {
let mut g2 = g[1].clone();
g2["credentialSubject"][PARENT_GRANT_DIGEST] = json!(spelled);
assert_eq!(
chain_binding_problem(&[link(&g[0]), link(&g2)]),
mismatch,
"{spelled}"
);
}
for v in [Value::Null, json!(5), json!({}), json!([right.clone()])] {
let mut g2 = g[1].clone();
g2["credentialSubject"][PARENT_GRANT_DIGEST] = v.clone();
assert_eq!(
chain_binding_problem(&[link(&g[0]), link(&g2)]),
malformed,
"{v}"
);
let mut g1 = g[0].clone();
g1["credentialSubject"][PARENT_GRANT_DIGEST] = v.clone();
assert_eq!(chain_binding_problem(&[link(&g1)]), malformed, "{v}");
}
for v in [Value::Null, json!({}), json!(""), json!(0)] {
let mut g2 = g[1].clone();
g2["credentialSubject"]["delegationChain"] = v.clone();
assert_eq!(
chain_binding_problem(&[link(&g[0]), link(&g2)]),
malformed,
"{v}"
);
}
let mut both = g[1].clone();
both["credentialSubject"]["delegationChain"] = json!([link(&g[0])]);
assert_eq!(
chain_binding_problem(&[link(&g[0]), link(&both)]),
malformed
);
assert_eq!(chain_binding_problem(&[link(&both)]), malformed);
let mut nested_first = g[0].clone();
nested_first["credentialSubject"]["delegationChain"] = json!([link(&g[0])]);
assert_eq!(chain_binding_problem(&[link(&nested_first)]), mismatch);
let mut longer = g[1].clone();
longer["credentialSubject"]
.as_object_mut()
.unwrap()
.remove(PARENT_GRANT_DIGEST);
longer["credentialSubject"]["delegationChain"] = json!([link(&g[0]), link(&g[0])]);
assert_eq!(
chain_binding_problem(&[link(&g[0]), link(&longer)]),
mismatch
);
let mut tampered_link = link(&g[0]);
tampered_link["note"] = json!("x");
longer["credentialSubject"]["delegationChain"] = json!([tampered_link]);
assert_eq!(
chain_binding_problem(&[link(&g[0]), link(&longer)]),
mismatch
);
let mut edited = g[0].clone();
edited["credentialSubject"]["intent"]["resource"] = json!("https://x");
assert_eq!(
chain_binding_problem(&[link(&edited), link(&g[1]), link(&g[2])]),
mismatch
);
assert_eq!(
chain_binding_problem(&[json!({"issuer": "did:web:root"})]),
malformed
);
assert_eq!(
chain_binding_problem(&[link(&g[0]), json!({"parentCredential": "x"})]),
malformed
);
let mut bad_type = g[2].clone();
bad_type["credentialSubject"][PARENT_GRANT_DIGEST] = json!(1);
assert_eq!(
chain_binding_problem(&[link(&g[0]), link(&bare), link(&bad_type)]),
mismatch
);
}
#[test]
fn presented_chain_rule() {
let g = flat3();
assert_eq!(presented_chain_problem(&g), None);
assert_eq!(presented_chain_problem(&[]), None);
assert_eq!(
presented_chain_problem(&g[1..]),
Some((0, REASON_PARENT_MISMATCH))
);
assert_eq!(
presented_chain_problem(&[g[0].clone(), g[2].clone()]),
Some((1, REASON_PARENT_MISMATCH))
);
let mut bad = g[1].clone();
bad["credentialSubject"][PARENT_GRANT_DIGEST] = Value::Null;
assert_eq!(
presented_chain_problem(&[g[0].clone(), bad.clone()]),
Some((1, REASON_MALFORMED))
);
assert_eq!(
presented_chain_problem(core::slice::from_ref(&bad)),
Some((0, REASON_MALFORMED))
);
let plain = grant("did:web:a", "did:web:b", json!({}));
assert_eq!(
presented_chain_problem(&[g[0].clone(), plain.clone()]),
None
);
for (position, value) in [(0, json!("{}")), (1, Value::Null), (2, json!(7))] {
let mut creds = vec![g[0].clone(), plain.clone(), plain.clone()];
creds[position] = value;
assert_eq!(
presented_chain_problem(&creds),
Some((position, REASON_MALFORMED))
);
}
assert_eq!(
presented_chain_problem(&[json!("x"), g[1].clone()]),
Some((0, REASON_MALFORMED))
);
}
fn nested_chain(parent: &Value, intent: &Value) -> Value {
let mut chain = embedded_chain(parent).to_vec();
let mut l = link(parent);
l["intent"] = intent.clone();
chain.push(l);
Value::Array(chain)
}
fn intent_to(delegatee: &str) -> Value {
json!({"action": "read", "target": "t", "resource": "https://x/a", "delegatee": delegatee})
}
fn nested(issuer: &str, delegatee: &str, parent: &Value) -> Value {
grant(
issuer,
delegatee,
json!({ "delegationChain": nested_chain(parent, &intent_to(delegatee)) }),
)
}
fn action(issuer: &str, links: Value) -> Value {
json!({"issuer": issuer, "proof": {"proofValue": "z"},
"credentialSubject": {"intent": {"action": "read"}, "delegationChain": links}})
}
#[test]
fn binding_fields_shape() {
let malformed = Some(REASON_MALFORMED);
let digest = json!("uEiA");
for subject in [
json!({}),
json!({"parentGrantDigest": digest}),
json!({"delegationChain": []}),
json!({"parentGrantDigest": digest, "delegationChain": []}),
json!({"delegationChain": [{"issuer": "x"}]}),
Value::Null,
json!([{"parentGrantDigest": 5}]),
json!("parentGrantDigest"),
] {
assert_eq!(binding_fields_problem(&subject), None, "{subject}");
}
for subject in [
json!({"parentGrantDigest": null}),
json!({"parentGrantDigest": 5}),
json!({"parentGrantDigest": ["u"]}),
json!({"parentGrantDigest": {}}),
json!({"delegationChain": null}),
json!({"delegationChain": {}}),
json!({"delegationChain": ""}),
json!({"delegationChain": 0}),
json!({"delegationChain": false}),
json!({"parentGrantDigest": digest, "delegationChain": [{}]}),
json!({"parentGrantDigest": null, "delegationChain": [{}]}),
] {
assert_eq!(binding_fields_problem(&subject), malformed, "{subject}");
}
}
#[test]
fn presented_chains_with_embedded_chains() {
let mismatch = |i| Some((i, REASON_PARENT_MISMATCH));
let malformed = |i| Some((i, REASON_MALFORMED));
let g = flat3();
let (g1, g2) = (g[0].clone(), g[1].clone());
let g1b = grant("did:web:root2", "did:web:a", json!({}));
let g2b = grant(
"did:web:a",
"did:web:b",
json!({ "parentGrantDigest": grant_digest(&g1b).unwrap() }),
);
let leaf = action("did:web:b", json!([]));
let nested_b = nested("did:web:a", "did:web:b", &g1b);
assert_eq!(
presented_chain_problem(&[g1.clone(), nested_b.clone(), leaf.clone()]),
mismatch(1)
);
assert_eq!(
presented_chain_problem(&[g1b.clone(), nested_b.clone(), leaf.clone()]),
None
);
let nested_a = nested("did:web:a", "did:web:b", &g1);
assert_eq!(
presented_chain_problem(&[nested_a.clone(), leaf.clone()]),
mismatch(0)
);
assert_eq!(
presented_chain_problem(&[g2.clone(), leaf.clone()]),
mismatch(0)
);
let elsewhere = action("did:web:b", json!(links(&[g1b.clone(), g2b])));
assert_eq!(
presented_chain_problem(&[g1.clone(), g2.clone(), elsewhere]),
mismatch(2)
);
let here = action("did:web:b", json!(links(&[g1.clone(), g2.clone()])));
assert_eq!(
presented_chain_problem(&[g1.clone(), g2.clone(), here]),
None
);
for fields in [
json!({ "parentGrantDigest": grant_digest(&g1).unwrap(),
"delegationChain": nested_chain(&g1, &intent_to("did:web:b")) }),
json!({"delegationChain": null}),
json!({"delegationChain": {}}),
json!({"parentGrantDigest": null}),
] {
let sub = grant("did:web:a", "did:web:b", fields.clone());
assert_eq!(
presented_chain_problem(&[g1.clone(), sub, leaf.clone()]),
malformed(1),
"{fields}"
);
}
let g2n = nested("did:web:a", "did:web:b", &g1);
let g3n = nested("did:web:b", "did:web:c", &g2n);
let leaf_c = action("did:web:c", json!([]));
assert_eq!(
presented_chain_problem(&[g1.clone(), g2n.clone(), g3n.clone(), leaf_c.clone()]),
None
);
let nested_leaf = action("did:web:c", nested_chain(&g3n, &json!({"action": "read"})));
assert_eq!(
presented_chain_problem(&[g1.clone(), g2n.clone(), g3n.clone(), nested_leaf]),
None
);
let g3 = grant(
"did:web:b",
"did:web:c",
json!({ "parentGrantDigest": grant_digest(&g2n).unwrap() }),
);
assert_eq!(
presented_chain_problem(&[g1.clone(), g2n.clone(), g3, leaf_c.clone()]),
None
);
assert_eq!(
presented_chain_problem(&[g1.clone(), g2n.clone(), g2n.clone(), g3n, leaf_c]),
mismatch(2)
);
}
#[test]
fn the_last_embedded_link_must_carry_the_previous_credential() {
let g1 = flat3()[0].clone();
let links = nested_chain(&g1, &intent_to("did:web:b"));
let mut no_grant = links.clone();
no_grant[0]
.as_object_mut()
.unwrap()
.remove("parentCredential");
let mut not_an_object = links.clone();
not_an_object[0]["parentCredential"] = json!(g1.to_string());
let mut not_a_link = links.clone();
not_a_link[0] = json!("link");
let mut edited = links.clone();
edited[0]["parentCredential"]["validUntil"] = json!("2026-11-12T00:00:00Z");
for embedded in [no_grant, not_an_object, not_a_link, edited] {
let sub = json!({"issuer": "did:web:a",
"credentialSubject": {"delegationChain": embedded}});
assert_eq!(
presented_chain_problem(&[g1.clone(), sub]),
Some((1, REASON_PARENT_MISMATCH))
);
}
let reordered: Value = serde_json::from_str(&jcs::canonicalize_to_string(&g1)).unwrap();
let sub = json!({"issuer": "did:web:a",
"credentialSubject": {"delegationChain": [{"parentCredential": reordered}]}});
assert_eq!(presented_chain_problem(&[g1, sub]), None);
}
#[test]
#[cfg_attr(
not(feature = "std"),
ignore = "member order follows insertion only with std"
)]
fn grant_chains_for_signing() {
let g = flat3();
let leaf_intent = json!({"action": "read", "target": "t", "resource": "https://x/a"});
let ls = check_grant_chain(&g, &leaf_intent).unwrap();
assert_eq!(ls.len(), 3);
assert_eq!(chain_binding_problem(&ls), None);
assert_eq!(ls[0]["intent"], g[1]["credentialSubject"]["intent"]);
assert_eq!(ls[2]["intent"], leaf_intent);
assert_eq!(ls[1]["subject"], json!("did:web:b"));
assert_eq!(ls[1]["parentProofValue"], json!("zdid:web:a"));
let keys: Vec<&str> = ls[0]
.as_object()
.unwrap()
.keys()
.map(|k| k.as_str())
.collect();
assert_eq!(
keys,
[
"issuer",
"subject",
"intent",
"validFrom",
"validUntil",
"parentProofValue",
"parentCredential"
]
);
let sub = grant(
"did:web:c",
"did:web:d",
json!({ "parentGrantDigest": grant_digest(&g[2]).unwrap() }),
);
let handed = grant_chain(&json!(g.clone()), &sub).unwrap();
assert_eq!(handed.len(), 4);
assert_eq!(handed[3], sub);
assert_eq!(grant_chain(&g[1], &sub).unwrap_err().0, NAMES_PARENT_GRANT);
assert_eq!(parent_grants(&g[2]).unwrap_err().0, NAMES_PARENT_GRANT);
let nested = grant(
"did:web:a",
"did:web:b",
json!({ "delegationChain": [link(&g[0])] }),
);
let pg = parent_grants(&nested).unwrap();
assert_eq!(pg, vec![g[0].clone(), nested.clone()]);
let copied = check_grant_chain(&pg, &leaf_intent).unwrap();
assert_eq!(copied[0], link(&g[0]));
assert_eq!(chain_binding_problem(&copied), None);
let action = json!({"issuer": "did:web:c", "proof": {},
"credentialSubject": {"intent": {"action": "read"}}});
assert_eq!(
grant_chain(&json!(g.clone()), &action).unwrap_err().0,
"this credential names no delegatee, so nobody can sign under it"
);
assert_eq!(
grant_chain(&json!(g.clone()), &json!([])).unwrap_err().0,
"grant must be a signed grant (a dict)"
);
assert!(is_grant_intent(&json!({"delegatee": "did:web:x"})));
for i in [
json!({"delegatee": ""}),
json!({"delegatee": 5}),
json!({}),
json!("x"),
] {
assert!(!is_grant_intent(&i), "{i}");
}
}
#[test]
fn grant_chain_refusals_match_the_reference_text() {
let g = flat3();
let intent = json!({"action": "read", "target": "t", "resource": "https://x/a"});
let err = |grants: &[Value]| check_grant_chain(grants, &intent).unwrap_err().0;
assert_eq!(
parent_grants(&json!([])).unwrap_err().0,
"Delegation refused: the grant chain is empty"
);
assert_eq!(
parent_grants(&json!([g[0].clone(), 5])).unwrap_err().0,
"Delegation refused: every grant in the grant chain must be an object"
);
assert_eq!(
parent_grants(&json!("x")).unwrap_err().0,
"parent_credential must be a grant (a dict) or a grant chain (a list of grants, root first)"
);
let mut bad_chain = g[0].clone();
bad_chain["credentialSubject"]["delegationChain"] = json!({});
assert_eq!(
parent_grants(&bad_chain).unwrap_err().0,
"Delegation refused: the parent grant's delegationChain is not a list"
);
bad_chain["credentialSubject"]["delegationChain"] = json!([{"issuer": "x"}]);
assert_eq!(
parent_grants(&bad_chain).unwrap_err().0,
"Delegation refused: a link in the parent grant's delegationChain carries no signed grant"
);
let mut unsigned = g[0].clone();
unsigned.as_object_mut().unwrap().remove("proof");
assert_eq!(
err(&[unsigned]),
"Delegation refused: the parent grant is not a signed credential"
);
let mut no_issuer = g[0].clone();
no_issuer["issuer"] = json!("");
assert_eq!(
err(&[no_issuer]),
"Delegation refused: the parent grant is not a signed credential"
);
let mut no_intent = g[0].clone();
no_intent["credentialSubject"]["intent"] = json!("read");
assert_eq!(
err(&[no_intent]),
"Delegation refused: the parent grant carries no intent object"
);
assert_eq!(
err(&[g[0].clone(), g[2].clone()]),
"Delegation refused: grant 1 of the grant chain names delegatee 'did:web:a', but grant 2 is issued by 'did:web:b'"
);
let mut no_issuer2 = g[1].clone();
no_issuer2["issuer"] = json!({"name": "x"});
assert_eq!(
err(&[g[0].clone(), no_issuer2]),
"Delegation refused: grant 2 of the grant chain has an issuer that is not a string or an object with a string id"
);
let mut no_delegatee = g[0].clone();
no_delegatee["credentialSubject"]["intent"]
.as_object_mut()
.unwrap()
.remove("delegatee");
assert_eq!(
err(&[no_delegatee, g[1].clone()]),
"Delegation refused: grant 1 of the grant chain names no delegatee"
);
let mut object_issuer = g[1].clone();
object_issuer["issuer"] = json!({"id": "did:web:a"});
assert!(check_grant_chain(&[g[0].clone(), object_issuer], &intent).is_ok());
let bare = grant("did:web:a", "did:web:b", json!({}));
assert_eq!(
err(&[g[0].clone(), bare]),
"Delegation refused: grant 2 of the grant chain is not bound to the grant before it (delegation_parent_mismatch)"
);
let mut bad_digest = g[1].clone();
bad_digest["credentialSubject"][PARENT_GRANT_DIGEST] = json!(7);
assert_eq!(
err(&[g[0].clone(), bad_digest]),
"Delegation refused: grant 2 of the grant chain is not bound to the grant before it (malformed_delegation)"
);
let nested = grant(
"did:web:a",
"did:web:b",
json!({ "delegationChain": [link(&g[0])] }),
);
let other_root = grant("did:web:root", "did:web:a", json!({"note": "other"}));
assert_eq!(
err(&[other_root, nested]),
"Delegation refused: grant 2 of the grant chain embeds a chain that is not the grants before it"
);
assert_eq!(
chain_capability(&[], false).unwrap_err().0,
"Delegation refused: the grant chain is empty"
);
}
const BROADER: &str =
"Delegation refused: a grant in the grant chain is broader than the grant before it on ";
#[test]
fn an_intermediate_grant_broader_than_the_grant_above_it_is_refused() {
let g = flat3();
let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
let digest = json!(grant_digest(&g[0]).unwrap());
let mut broad = g[1].clone();
broad["credentialSubject"]["intent"]["action"] = json!(["read", "write"]);
broad["credentialSubject"][PARENT_GRANT_DIGEST] = digest.clone();
let chain = [g[0].clone(), broad.clone()];
assert_eq!(
check_grant_chain(&chain, &leaf).unwrap_err().0,
format!("{BROADER}'action'")
);
assert_eq!(
grant_chain(&g[0], &broad).unwrap_err().0,
format!("{BROADER}'action'")
);
for (k, v) in [
("validUntil", "2026-11-12T00:00:00Z"),
("validFrom", "2026-11-09T00:00:00Z"),
] {
let mut long = g[1].clone();
long[k] = json!(v);
assert_eq!(
check_grant_chain(&[g[0].clone(), long.clone()], &leaf)
.unwrap_err()
.0,
format!("{BROADER}'time'"),
"{k}"
);
assert_eq!(
grant_chain(&g[0], &long).unwrap_err().0,
format!("{BROADER}'time'")
);
}
let mut wide = g[2].clone();
wide["credentialSubject"]["intent"]["resource"] = json!("https://x");
let mut chain = g.clone();
chain[2] = wide;
assert_eq!(
check_grant_chain(&chain, &leaf).unwrap_err().0,
format!("{BROADER}'resource'")
);
let mut narrow = g[1].clone();
narrow["credentialSubject"]["intent"]["resource"] = json!("https://x/a/b");
narrow["validUntil"] = json!("2026-11-10T12:00:00Z");
assert!(check_grant_chain(&[g[0].clone(), narrow], &leaf).is_ok());
let mut alone = g[0].clone();
alone["credentialSubject"]["intent"]["action"] = json!(["read", "write"]);
assert!(check_grant_chain(&[alone], &leaf).is_ok());
let mut unbound = g[1].clone();
unbound["credentialSubject"]
.as_object_mut()
.unwrap()
.remove(PARENT_GRANT_DIGEST);
unbound["credentialSubject"]["intent"]["action"] = json!("write");
assert_eq!(
check_grant_chain(&[g[0].clone(), unbound], &leaf)
.unwrap_err()
.0,
"Delegation refused: grant 2 of the grant chain is not bound to the grant before it (delegation_parent_mismatch)"
);
}
#[test]
fn a_malformed_first_grant_is_named_as_malformed() {
let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
for (dimension, value) in [
("rate", json!("lots")),
("policy", json!(["not", "an", "object"])),
("action", json!(7)),
("target", json!([1])),
("resource", json!(7)),
("time", json!("soon")),
] {
let mut g1 = grant("did:web:root", "did:web:a", json!({}));
if dimension == "time" {
g1["validUntil"] = value;
} else {
g1["credentialSubject"]["intent"][dimension] = value;
}
let g2 = grant(
"did:web:a",
"did:web:b",
json!({ "parentGrantDigest": grant_digest(&g1).unwrap() }),
);
let message = format!(
"Delegation refused: grant 1 of the grant chain has a malformed '{dimension}'"
);
assert_eq!(
check_grant_chain(&[g1.clone(), g2.clone()], &leaf)
.unwrap_err()
.0,
message
);
assert_eq!(grant_chain(&g1, &g2).unwrap_err().0, message);
assert!(check_grant_chain(&[g1], &leaf).is_ok(), "{dimension}");
}
let g = flat3();
let mut g2 = g[1].clone();
g2["credentialSubject"]["intent"]["rate"] = json!("lots");
assert_eq!(
check_grant_chain(&[g[0].clone(), g2], &leaf).unwrap_err().0,
format!("{BROADER}'rate'")
);
}
#[test]
fn the_helpers_refuse_a_grant_that_is_not_an_object() {
let g = flat3();
let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
let no_intent = "Delegation refused: the parent grant carries no intent object";
let mut no_subject = g[1].clone();
no_subject["credentialSubject"] = json!("subject");
let mut no_intent_member = g[1].clone();
no_intent_member["credentialSubject"]
.as_object_mut()
.unwrap()
.remove("intent");
let nested_after = nested("did:web:a", "did:web:b", &g[0]);
for bad in [
json!("x"),
Value::Null,
json!(5),
json!(["nested"]),
no_subject,
no_intent_member,
] {
for grants in [
vec![bad.clone()],
vec![g[0].clone(), bad.clone()],
vec![bad.clone(), g[0].clone()],
vec![bad.clone(), nested_after.clone()],
] {
assert_eq!(
check_grant_chain(&grants, &leaf).unwrap_err().0,
no_intent,
"{bad}"
);
assert_eq!(
chain_links(&grants, &leaf).unwrap_err().0,
no_intent,
"{bad}"
);
}
}
}
#[test]
fn a_nested_grant_whose_embedded_link_lies_is_refused() {
let g = flat3();
let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
for (field, message) in [
(
"subject",
"Delegation refused: grant 2 of the grant chain embeds a link whose subject is not the delegatee of grant 1",
),
(
"issuer",
"Delegation refused: grant 2 of the grant chain embeds a link whose issuer is not the issuer of grant 1",
),
] {
let mut links = nested_chain(&g[0], &intent_to("did:web:b"));
links[0][field] = json!("did:web:x");
let lying = grant("did:web:a", "did:web:b", json!({ "delegationChain": links }));
let grants = parent_grants(&lying).unwrap();
assert_eq!(check_grant_chain(&grants, &leaf).unwrap_err().0, message);
assert_eq!(
check_grant_chain(&[g[0].clone(), lying.clone()], &leaf)
.unwrap_err()
.0,
message
);
assert_eq!(chain_links(&grants, &leaf).unwrap_err().0, message);
let mut links = nested_chain(&g[0], &intent_to("did:web:b"));
links[0].as_object_mut().unwrap().remove(field);
let missing = grant("did:web:a", "did:web:b", json!({ "delegationChain": links }));
assert_eq!(
check_grant_chain(&[g[0].clone(), missing], &leaf)
.unwrap_err()
.0,
message
);
}
let mut links = nested_chain(&g[0], &intent_to("did:web:b"));
links[0]["issuer"] = json!("did:web:x");
links[0]["subject"] = json!("did:web:x");
let both = grant(
"did:web:a",
"did:web:b",
json!({ "delegationChain": links }),
);
assert!(check_grant_chain(&[g[0].clone(), both.clone()], &leaf)
.unwrap_err()
.0
.contains("whose issuer is not"));
let other_root = grant("did:web:root", "did:web:a", json!({"note": "other"}));
assert_eq!(
check_grant_chain(&[other_root, both], &leaf).unwrap_err().0,
"Delegation refused: grant 2 of the grant chain embeds a chain that is not the grants before it"
);
let honest = nested("did:web:a", "did:web:b", &g[0]);
let out = check_grant_chain(&[g[0].clone(), honest.clone()], &leaf).unwrap();
assert_eq!(out[0], honest["credentialSubject"]["delegationChain"][0]);
assert_eq!(out[1]["parentCredential"], honest);
}
#[test]
fn an_issuer_object_is_carried_as_its_id() {
let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
let mut root = grant("did:web:root", "did:web:a", json!({}));
root["issuer"] = json!({"id": "did:web:root", "name": "Root"});
let links = check_grant_chain(core::slice::from_ref(&root), &leaf).unwrap();
assert_eq!(links[0]["issuer"], json!("did:web:root"));
assert_eq!(links[0]["parentCredential"], root);
assert_eq!(chain_binding_problem(&links), None);
let mut odd = root.clone();
odd["issuer"] = json!(42);
assert_eq!(
chain_links(core::slice::from_ref(&odd), &leaf).unwrap()[0]["issuer"],
json!("")
);
}
#[test]
fn an_issuer_that_is_not_a_did_string_is_refused() {
let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
for issuer in [
json!(42),
json!({"id": 5}),
json!({"name": "Root"}),
json!(["did:key:z"]),
json!(true),
] {
let mut root = grant("did:web:root", "did:web:a", json!({}));
root["issuer"] = issuer.clone();
assert_eq!(
check_grant_chain(&[root], &leaf).unwrap_err().0,
"Delegation refused: grant 1 of the grant chain has an issuer that is not a string or an object with a string id",
"{issuer}"
);
}
for issuer in [json!(""), json!({}), Value::Null, json!(0), json!([])] {
let mut root = grant("did:web:root", "did:web:a", json!({}));
root["issuer"] = issuer.clone();
assert_eq!(
check_grant_chain(&[root], &leaf).unwrap_err().0,
"Delegation refused: the parent grant is not a signed credential",
"{issuer}"
);
}
}
#[test]
fn links_are_copies_of_the_grants() {
let g = flat3();
let before = g.clone();
let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
let mut links = check_grant_chain(&g, &leaf).unwrap();
assert_eq!(links[0]["parentCredential"], g[0]);
assert_eq!(links[0]["intent"], g[1]["credentialSubject"]["intent"]);
links[0]["intent"]["action"] = json!("write");
links[1]["parentCredential"]["credentialSubject"]["intent"]["action"] = json!("write");
assert_eq!(g, before);
}
#[test]
fn chain_capability_inherits_down_the_chain() {
let mut g = flat3();
g[0]["credentialSubject"]["intent"]["rate"] = json!("10/hour");
g[2]["credentialSubject"]["intent"]
.as_object_mut()
.unwrap()
.remove("resource");
let cap = chain_capability(&g, false).unwrap();
assert_eq!(cap["intent"]["resource"], json!("https://x/a"));
assert_eq!(cap["rate"], json!("10/hour"));
assert_eq!(cap["subject"], json!("did:web:c"));
assert!(cap.get("validFrom").is_none());
let timed = chain_capability(&g, true).unwrap();
assert_eq!(timed["validUntil"], json!("2026-11-11T00:00:00Z"));
}
#[test]
fn python_repr_of_quoted_values() {
assert_eq!(py_repr_str("did:web:a"), "'did:web:a'");
assert_eq!(py_repr_str("it's"), "\"it's\"");
assert_eq!(py_repr_str("a'b\"c"), "'a\\'b\"c'");
assert_eq!(py_repr_str("a\\b\n\u{1}"), "'a\\\\b\\n\\x01'");
assert_eq!(py_repr(None), "None");
assert_eq!(py_repr(Some(&json!(["x", 1]))), "['x', 1]");
assert_eq!(
py_repr_str(
"\u{a0}\u{ad}\u{200b}\u{2028}\u{feff}\u{e000}\u{e0001}\u{10ffff} é中😀\u{3000}\u{7f}\u{1b}\u{85}"
),
"'\\xa0\\xad\\u200b\\u2028\\ufeff\\ue000\\U000e0001\\U0010ffff é中😀\\u3000\\x7f\\x1b\\x85'"
);
assert_eq!(py_repr_str("it's \u{2029}"), "\"it's \\u2029\"");
assert_eq!(py_repr_str("a\u{378}b"), "'a\\u0378b'");
assert_eq!(
py_repr(Some(&json!({"k\u{0}": ["\u{2066}"]}))),
"{'k\\x00': ['\\u2066']}"
);
}
#[test]
fn python_repr_of_numbers() {
for (text, expected) in [
("0.0", "0.0"),
("-0.0", "-0.0"),
("1.0", "1.0"),
("-1.5", "-1.5"),
("0.1", "0.1"),
("0.30000000000000004", "0.30000000000000004"),
("100.0", "100.0"),
("1e2", "100.0"),
("0.0001", "0.0001"),
("0.00001", "1e-05"),
("1e-5", "1e-05"),
("0.000123", "0.000123"),
("9.999e-5", "9.999e-05"),
("1e-7", "1e-07"),
("123.456", "123.456"),
("9999999999999998.0", "9999999999999998.0"),
("1e16", "1e+16"),
("12345678901234567.0", "1.2345678901234568e+16"),
("1e21", "1e+21"),
("1e22", "1e+22"),
("1.5e300", "1.5e+300"),
("1.7976931348623157e308", "1.7976931348623157e+308"),
("5e-324", "5e-324"),
("2.2250738585072014e-308", "2.2250738585072014e-308"),
("588197768793114.25", "588197768793114.2"),
("-164193784243384.125", "-164193784243384.12"),
("6.02214076e23", "6.02214076e+23"),
("-2.5e-10", "-2.5e-10"),
("4.35", "4.35"),
("1e100", "1e+100"),
("1E-100", "1e-100"),
("123e-20", "1.23e-18"),
("5", "5"),
("-7", "-7"),
("0", "0"),
("18446744073709551615", "18446744073709551615"),
("-9223372036854775808", "-9223372036854775808"),
(
"{\"maxSpend\": 1e-05, \"ratio\": [0.5, 1e16, 2]}",
"{'maxSpend': 1e-05, 'ratio': [0.5, 1e+16, 2]}",
),
] {
let value: Value = serde_json::from_str(text).unwrap();
assert_eq!(py_repr(Some(&value)), expected, "{text}");
}
assert_eq!(py_repr_float(f64::INFINITY), "inf");
assert_eq!(py_repr_float(f64::NEG_INFINITY), "-inf");
assert_eq!(py_repr_float(f64::NAN), "nan");
}
}