Skip to main content

vouch_core/
grant_chain.rs

1//! Flat delegation chains: grant digests, grant chains, and the rule that binds
2//! every grant to the grant above it.
3//!
4//! A port of `vouch/grant_chain.py` (Python is the reference). A grant made by
5//! a delegatee (a sub-grant) does not copy the chain above it. It names its
6//! direct parent grant by digest instead, in
7//! `credentialSubject.parentGrantDigest`. The delegatee of a sub-grant is
8//! handed a grant chain: a JSON array of grants, root first. A credential
9//! signed under a grant chain carries one delegation link per grant
10//! (`delegationChain`), so its size grows by one grant per hop and its JSON
11//! nesting depth stays the same.
12//!
13//! The rules, the same in every language:
14//!
15//! * [`grant_digest`] is `"u"` followed by the base64url (no padding) encoding
16//!   of the bytes `0x12 0x20` and the SHA-256 of the JCS form of the whole
17//!   grant, proof included: a multibase, multihash SHA-256 value, the shape of
18//!   VC 2.0 `digestMultibase`. Digests compare as exact strings.
19//! * Binding fields ([`binding_fields_problem`]): a `parentGrantDigest` that is
20//!   present must be a string, a `delegationChain` that is present must be a
21//!   list, and one credential never carries a digest together with a non-empty
22//!   `delegationChain`. Anything else is `malformed_delegation`. This holds for
23//!   every grant in a chain, for every credential in a fleet chain, and for the
24//!   credential being verified itself.
25//! * Binding ([`chain_binding_problem`], checked by verifiers for every
26//!   embedded chain and by [`check_grant_chain`] before signing): the first
27//!   link's grant is a root grant (no digest, no embedded chain). Every later
28//!   link's grant either carries the digest of the grant before it, or (the
29//!   older nested form) embeds a chain that is JCS-equal to the links before it
30//!   in the credential.
31//! * Fleet chains ([`presented_chain_problem`], credentials presented one by
32//!   one, root first): credential 0 names no parent. A later credential with a
33//!   digest carries the digest of the credential before it; one with a
34//!   non-empty `delegationChain` ends that chain with a link whose grant is
35//!   JCS-equal to the credential before it.
36//! * Signing ([`check_grant_chain`]): before a signer signs under a grant chain
37//!   it checks the chain from its link fields: every grant signed and issued by
38//!   a DID, each delegatee the next grant's issuer, every grant bound to the one
39//!   before it, no grant broader than the one before it (time included), and
40//!   every link copied from an older nested grant naming that grant's issuer
41//!   and delegatee.
42//!
43//! The core has no signer, so the signing side is a set of pure functions. To
44//! sign under a parent (a grant, or a grant chain): take
45//! `grants = parent_grants(parent)`, check them with
46//! `links = check_grant_chain(&grants, &intent)`, and check that the new intent
47//! stays inside `chain_capability(&grants, false)`. A new grant (its intent
48//! names a delegatee, [`is_grant_intent`]) is a bare sub-grant:
49//! [`crate::credentials::build_sub_grant`] with the digest of the last grant.
50//! Anything else carries `links` as its `delegationChain`. Hand the delegatee
51//! of a new sub-grant [`grant_chain`]`(parent, sub_grant)`.
52
53#[allow(unused_imports)]
54use crate::prelude::*;
55
56use core::fmt;
57
58use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
59use serde_json::{json, Map, Value};
60use sha2::{Digest, Sha256};
61
62use crate::attenuation;
63use crate::delegation;
64use crate::error::CoreError;
65use crate::jcs;
66
67/// The reason a grant in a chain is not bound to the grant before it.
68pub const REASON_PARENT_MISMATCH: &str = "delegation_parent_mismatch";
69/// The reason a binding field is present but malformed, or cannot be hashed.
70pub const REASON_MALFORMED: &str = "malformed_delegation";
71/// A chain that goes on past a replica grant: a replica cannot hand its
72/// authority on.
73pub const REASON_REPLICA_CHAIN_TOO_LONG: &str = "replica_chain_too_long";
74/// The intent field that marks a replica grant.
75pub const REPLICA_OF: &str = "replicaOf";
76
77/// The credentialSubject field where a sub-grant names its direct parent grant.
78pub const PARENT_GRANT_DIGEST: &str = "parentGrantDigest";
79
80/// The refusal when a single grant that names a parent grant is passed alone.
81pub const NAMES_PARENT_GRANT: &str =
82    "this grant names a parent grant; pass the whole grant chain (a list, root first)";
83
84/// The multihash prefix of a SHA-256 digest: code 0x12, length 0x20 (32 bytes).
85const MULTIHASH_SHA2_256: [u8; 2] = [0x12, 0x20];
86
87/// A grant has no digest: it is not a JSON object. Verifiers report it as
88/// `malformed_delegation`. (A `serde_json::Value` always has a JCS form, so
89/// the reference's other cause, a value that is not plain JSON, cannot reach
90/// this point: such input is refused when the JSON is parsed.)
91#[derive(Debug, Clone, PartialEq, Eq)]
92pub struct GrantDigestError(pub String);
93
94impl fmt::Display for GrantDigestError {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        f.write_str(&self.0)
97    }
98}
99
100impl core::error::Error for GrantDigestError {}
101
102impl From<GrantDigestError> for CoreError {
103    fn from(e: GrantDigestError) -> Self {
104        CoreError::Json(e.0)
105    }
106}
107
108/// A grant chain refused before signing. The message is the reference's
109/// refusal text, byte for byte.
110#[derive(Debug, Clone, PartialEq, Eq)]
111pub struct GrantChainError(pub String);
112
113impl fmt::Display for GrantChainError {
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        f.write_str(&self.0)
116    }
117}
118
119impl core::error::Error for GrantChainError {}
120
121impl From<GrantChainError> for CoreError {
122    fn from(e: GrantChainError) -> Self {
123        CoreError::Json(e.0)
124    }
125}
126
127fn refused(msg: impl Into<String>) -> GrantChainError {
128    GrantChainError(msg.into())
129}
130
131/// The digest of a grant, the value a sub-grant puts in
132/// `credentialSubject.parentGrantDigest`:
133/// `"u" + base64url_nopad(0x12 0x20 || SHA-256(JCS(grant)))`, over the whole
134/// grant object, its proof (or proof set) included. The result is "u" and 46
135/// base64url characters.
136///
137/// Errors when the grant is not a JSON object.
138pub fn grant_digest(grant: &Value) -> Result<String, GrantDigestError> {
139    crate::nesting::deep_guard!(Err(GrantDigestError(crate::nesting::TOO_DEEP.into())); grant);
140    if !grant.is_object() {
141        return Err(GrantDigestError("a grant must be a JSON object".into()));
142    }
143    let mut multihash = Vec::with_capacity(34);
144    multihash.extend_from_slice(&MULTIHASH_SHA2_256);
145    multihash.extend_from_slice(&Sha256::digest(jcs::canonicalize(grant)));
146    Ok(format!("u{}", URL_SAFE_NO_PAD.encode(multihash)))
147}
148
149/// `credentialSubject` when it is an object, else nothing (the reference reads
150/// a missing or non-object subject as an empty one).
151fn subject_of(grant: &Value) -> Option<&Map<String, Value>> {
152    grant.get("credentialSubject").and_then(Value::as_object)
153}
154
155/// The shape of a credential's own binding fields, read from its
156/// `credentialSubject`: None when they are well formed, otherwise
157/// `malformed_delegation`.
158///
159/// - `parentGrantDigest` present and not a string: `malformed_delegation`;
160/// - `delegationChain` present and not a list: `malformed_delegation`;
161/// - a digest together with a non-empty `delegationChain`:
162///   `malformed_delegation`.
163///
164/// A present null, number or object is malformed, never absent (D29). An
165/// empty `delegationChain` is no chain. The verifiers apply this to the
166/// credential they verify ([`crate::delegation::verify_delegation_chain_with`]
167/// runs it first, on every verify path), to every grant in an embedded chain
168/// and to every credential in a fleet chain.
169///
170/// `subject` is the credential's `credentialSubject`; anything that is not an
171/// object carries no binding fields.
172pub fn binding_fields_problem(subject: &Value) -> Option<&'static str> {
173    crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP); subject);
174    // Anything that is not an object carries no binding fields.
175    let subject = subject.as_object()?;
176    let digest = subject.get(PARENT_GRANT_DIGEST);
177    if digest.is_some_and(|d| !d.is_string()) {
178        return Some(REASON_MALFORMED);
179    }
180    let chain = subject.get("delegationChain");
181    if chain.is_some_and(|c| !c.is_array()) {
182        return Some(REASON_MALFORMED);
183    }
184    if digest.is_some()
185        && chain
186            .and_then(Value::as_array)
187            .is_some_and(|c| !c.is_empty())
188    {
189        return Some(REASON_MALFORMED);
190    }
191    None
192}
193
194/// A credential's `parentGrantDigest` and its `delegationChain` (empty when
195/// absent), read once [`binding_fields_problem`] has passed.
196fn bindings(cred: &Value) -> (Option<&Value>, &[Value]) {
197    let subject = subject_of(cred);
198    let digest = subject.and_then(|s| s.get(PARENT_GRANT_DIGEST));
199    let embedded = match subject.and_then(|s| s.get("delegationChain")) {
200        Some(Value::Array(a)) => a.as_slice(),
201        _ => &[],
202    };
203    (digest, embedded)
204}
205
206/// (index of the link, reason) for the first link whose grant is not bound to
207/// the grant before it, or None. Links are checked in order; for each one: the
208/// binding fields' shape ([`binding_fields_problem`]), then the binding.
209fn binding_failure(chain: &[Value]) -> Option<(usize, &'static str)> {
210    for (i, link) in chain.iter().enumerate() {
211        let Some(grant) = link.get("parentCredential").filter(|g| g.is_object()) else {
212            return Some((i, REASON_MALFORMED));
213        };
214        if let Some(malformed) = binding_fields_problem(&grant["credentialSubject"]) {
215            return Some((i, malformed));
216        }
217        let (digest, embedded) = bindings(grant);
218        // An empty embedded chain counts as no embedded chain.
219        let has_embedded = !embedded.is_empty();
220        if i == 0 {
221            // The first grant is a root grant: it names no grant above it.
222            if digest.is_some() || has_embedded {
223                return Some((i, REASON_PARENT_MISMATCH));
224            }
225            continue;
226        }
227        let bound = if let Some(Value::String(d)) = digest {
228            match grant_digest(&chain[i - 1]["parentCredential"]) {
229                Ok(expected) => *d == expected,
230                Err(_) => return Some((i, REASON_MALFORMED)),
231            }
232        } else if has_embedded {
233            // The older nested form: the grant's own copy of the chain above
234            // it must be exactly the links before it (JCS-equal).
235            embedded.len() == i
236                && embedded
237                    .iter()
238                    .zip(&chain[..i])
239                    .all(|(a, b)| jcs::canonicalize(a) == jcs::canonicalize(b))
240        } else {
241            false
242        };
243        if !bound {
244            return Some((i, REASON_PARENT_MISMATCH));
245        }
246    }
247    None
248}
249
250/// The binding rule for an embedded delegation chain: None when every link's
251/// grant is bound to the grant before it, otherwise the reason.
252///
253/// For each link, in order (first failure wins):
254///
255/// - the link carries no grant object: `malformed_delegation`;
256/// - `parentGrantDigest` present but not a string, or `delegationChain`
257///   present but not a list: `malformed_delegation`;
258/// - the grant carries a digest and a non-empty embedded chain
259///   ([`binding_fields_problem`]): `malformed_delegation`;
260/// - first link: the grant carries a digest or a non-empty embedded chain (it
261///   is not a root grant): `delegation_parent_mismatch`;
262/// - later links: the digest is the digest of the previous link's grant, or
263///   the embedded chain is JCS-equal to the links before this one; neither:
264///   `delegation_parent_mismatch`.
265///
266/// Verifiers run it at the end of the pre-filter, before any key is resolved,
267/// and only when every link's `parentCredential` is an object. A link without
268/// one is malformed here.
269///
270/// Then, once every link is bound: a replica grant (its intent carries
271/// `replicaOf`) anywhere but in the last link is `replica_chain_too_long` (a
272/// replica cannot hand its authority on).
273pub fn chain_binding_problem(chain: &[Value]) -> Option<&'static str> {
274    crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP); chain);
275    binding_failure(chain)
276        .or_else(|| replica_failure(chain))
277        .map(|(_, reason)| reason)
278}
279
280/// True when a grant's intent marks it as a replica grant (`replicaOf`).
281pub fn is_replica_grant(grant: &Value) -> bool {
282    crate::nesting::deep_guard!(false; grant);
283    subject_of(grant)
284        .and_then(|s| s.get("intent"))
285        .and_then(Value::as_object)
286        .is_some_and(|i| i.contains_key(REPLICA_OF))
287}
288
289/// (index, `replica_chain_too_long`) for the first link before the last
290/// whose grant is a replica grant, or None.
291fn replica_failure(chain: &[Value]) -> Option<(usize, &'static str)> {
292    let last = chain.len().saturating_sub(1);
293    chain[..last]
294        .iter()
295        .position(|link| link.get("parentCredential").is_some_and(is_replica_grant))
296        .map(|i| (i, REASON_REPLICA_CHAIN_TOO_LONG))
297}
298
299/// The binding rule for credentials presented one by one, root first (a fleet
300/// chain): (index, reason) for the first credential that breaks it, or None.
301///
302/// For each credential, in order (first failure wins):
303///
304/// - the credential is not an object: `malformed_delegation` (the fleet
305///   verifier refuses it before this runs: `"credential {i} is not a JSON
306///   object"`);
307/// - `parentGrantDigest` present and not a string, `delegationChain` present
308///   and not a list, or a digest together with a non-empty `delegationChain`
309///   ([`binding_fields_problem`]): `malformed_delegation`;
310/// - credential 0 carries a digest or a non-empty `delegationChain` (it is not
311///   a root grant): `delegation_parent_mismatch`;
312/// - credential i >= 1 carries a digest that is not the digest of credential
313///   i-1: `delegation_parent_mismatch`;
314/// - credential i >= 1 carries a non-empty `delegationChain` (an older nested
315///   sub-grant, or a credential that embeds its chain) whose last link's
316///   `parentCredential` is not an object JCS-equal to credential i-1:
317///   `delegation_parent_mismatch`.
318///
319/// A credential with neither binding is read as before (its place in the chain
320/// is checked by the issuer and delegatee walk). A fleet verifier runs this
321/// before any credential is verified and refuses with
322/// `"credential {i}: {reason}"`. (The reference's last rule, a credential with
323/// no JCS form, cannot arise here: every `serde_json::Value` has one.)
324pub fn presented_chain_problem(credentials: &[Value]) -> Option<(usize, &'static str)> {
325    crate::nesting::deep_guard!(Some((0, crate::nesting::TOO_DEEP)); credentials);
326    for (i, cred) in credentials.iter().enumerate() {
327        if !cred.is_object() {
328            return Some((i, REASON_MALFORMED));
329        }
330        if let Some(malformed) = binding_fields_problem(&cred["credentialSubject"]) {
331            return Some((i, malformed));
332        }
333        let (digest, embedded) = bindings(cred);
334        if i == 0 {
335            // The first credential is a root grant: it names nothing above it.
336            if digest.is_some() || !embedded.is_empty() {
337                return Some((i, REASON_PARENT_MISMATCH));
338            }
339            continue;
340        }
341        let previous = &credentials[i - 1];
342        let bound = if let Some(digest) = digest {
343            match grant_digest(previous) {
344                Ok(expected) => digest.as_str() == Some(expected.as_str()),
345                Err(_) => return Some((i, REASON_MALFORMED)),
346            }
347        } else if let Some(last) = embedded.last() {
348            // The older nested form, or a credential that embeds its chain:
349            // the chain it carries ends at the credential before it.
350            last.get("parentCredential")
351                .filter(|g| g.is_object())
352                .is_some_and(|g| jcs::canonicalize(g) == jcs::canonicalize(previous))
353        } else {
354            continue;
355        };
356        if !bound {
357            return Some((i, REASON_PARENT_MISMATCH));
358        }
359    }
360    None
361}
362
363// ---------------------------------------------------------------------------
364// Grant chains (the signing side)
365// ---------------------------------------------------------------------------
366
367/// A grant's own embedded chain when it is a list, else none.
368fn embedded_chain(grant: &Value) -> &[Value] {
369    match subject_of(grant).and_then(|s| s.get("delegationChain")) {
370        Some(Value::Array(a)) => a.as_slice(),
371        _ => &[],
372    }
373}
374
375/// True when an intent names a delegatee (a non-empty string), so what is
376/// signed with it is a grant.
377pub fn is_grant_intent(intent: &Value) -> bool {
378    crate::nesting::deep_guard!(false; intent);
379    intent
380        .get("delegatee")
381        .and_then(Value::as_str)
382        .is_some_and(|d| !d.is_empty())
383}
384
385/// The grants a parent stands for, root first.
386///
387/// A grant chain (an array) is taken as it is. A single grant (an object) is
388/// a root grant, or an older grant that embeds the chain above it, whose
389/// embedded grants come first. A single grant that names a parent grant by
390/// digest is refused ([`NAMES_PARENT_GRANT`]), because the grants above it are
391/// missing.
392///
393/// Errors: the parent is an empty array, holds something other than grants,
394/// names a parent grant without its ancestors, embeds a chain that is not a
395/// list of links carrying grants, or is neither an object nor an array.
396pub fn parent_grants(parent: &Value) -> Result<Vec<Value>, GrantChainError> {
397    crate::nesting::deep_guard!(Err(GrantChainError(crate::nesting::TOO_DEEP.into())); parent);
398    match parent {
399        Value::Object(_) => {
400            let subject = subject_of(parent);
401            if subject.is_some_and(|s| s.contains_key(PARENT_GRANT_DIGEST)) {
402                return Err(refused(NAMES_PARENT_GRANT));
403            }
404            if subject
405                .and_then(|s| s.get("delegationChain"))
406                .is_some_and(|c| !c.is_array())
407            {
408                return Err(refused(
409                    "Delegation refused: the parent grant's delegationChain is not a list",
410                ));
411            }
412            let mut grants = Vec::new();
413            for link in embedded_chain(parent) {
414                let Some(grant) = link.get("parentCredential").filter(|g| g.is_object()) else {
415                    return Err(refused(
416                        "Delegation refused: a link in the parent grant's delegationChain \
417                         carries no signed grant",
418                    ));
419                };
420                grants.push(grant.clone());
421            }
422            grants.push(parent.clone());
423            Ok(grants)
424        }
425        Value::Array(items) => {
426            if items.is_empty() {
427                return Err(refused("Delegation refused: the grant chain is empty"));
428            }
429            if !items.iter().all(Value::is_object) {
430                return Err(refused(
431                    "Delegation refused: every grant in the grant chain must be an object",
432                ));
433            }
434            Ok(items.clone())
435        }
436        _ => Err(refused(
437            "parent_credential must be a grant (a dict) or a grant chain (a list of grants, \
438             root first)",
439        )),
440    }
441}
442
443/// The grant's intent object, or the reference's refusal.
444fn intent_of(grant: &Value) -> Result<&Value, GrantChainError> {
445    subject_of(grant)
446        .and_then(|s| s.get("intent"))
447        .filter(|i| i.is_object())
448        .ok_or_else(|| refused("Delegation refused: the parent grant carries no intent object"))
449}
450
451/// The delegation link for one grant (Specification 9.2), in the shape every
452/// verifier reads: the intent is the one signed at the next step.
453///
454/// The link's issuer is the grant's issuer as a string (the `id` of an issuer
455/// object), or "" when it is not one. The intent and the grant are copies, so
456/// the link shares nothing with the caller's values.
457fn link_for(grant: &Value, intent: &Value) -> Result<Value, GrantChainError> {
458    let mut link = Map::new();
459    link.insert(
460        "issuer".into(),
461        Value::String(
462            issuer_value(grant)
463                .and_then(Value::as_str)
464                .unwrap_or_default()
465                .to_string(),
466        ),
467    );
468    link.insert(
469        "subject".into(),
470        intent_of(grant)?
471            .get("delegatee")
472            .cloned()
473            .unwrap_or(Value::Null),
474    );
475    link.insert("intent".into(), intent.clone());
476    for k in ["validFrom", "validUntil"] {
477        link.insert(k.into(), grant.get(k).cloned().unwrap_or(Value::Null));
478    }
479    let bound: String = delegation::parent_proof_binding_value(grant)
480        .chars()
481        .take(64)
482        .collect();
483    link.insert("parentProofValue".into(), Value::String(bound));
484    link.insert("parentCredential".into(), grant.clone());
485    Ok(Value::Object(link))
486}
487
488/// The delegation links for a credential signed under `grants` (root first)
489/// with `intent`: one link per grant. Link j's intent is the intent of grant
490/// j+1, and the last link's is `intent`.
491///
492/// When a grant embeds the chain above it (the older nested form), the links
493/// before it are copied from it verbatim, so they stay JCS-equal to what that
494/// grant signed. Each copied link must carry grant i of the chain, name grant
495/// i's issuer as its issuer, and name grant i's delegatee as its subject.
496///
497/// Every link is a copy: the result shares no value with `grants`, `intent`
498/// or the links a nested grant embeds.
499///
500/// Errors: a grant is not an object or carries no intent object
501/// ("Delegation refused: the parent grant carries no intent object", checked
502/// for every grant first), the grants before an older nested grant are not
503/// the ones it embeds, or a link it embeds names another issuer or subject
504/// than its grant.
505pub fn chain_links(grants: &[Value], intent: &Value) -> Result<Vec<Value>, GrantChainError> {
506    crate::nesting::deep_guard!(Err(GrantChainError(crate::nesting::TOO_DEEP.into())); grants, intent);
507    for grant in grants {
508        intent_of(grant)?;
509    }
510    let mut links: Vec<Value> = Vec::new();
511    let mut start = 0;
512    for j in (0..grants.len()).rev() {
513        let embedded = embedded_chain(&grants[j]);
514        if embedded.is_empty() {
515            continue;
516        }
517        let same = embedded.len() == j
518            && embedded.iter().enumerate().all(|(i, link)| {
519                link.get("parentCredential")
520                    .filter(|g| g.is_object())
521                    .is_some_and(|g| jcs::canonicalize(g) == jcs::canonicalize(&grants[i]))
522            });
523        if !same {
524            return Err(refused(format!(
525                "Delegation refused: grant {} of the grant chain embeds a chain that is not \
526                 the grants before it",
527                j + 1
528            )));
529        }
530        for (i, link) in embedded.iter().enumerate() {
531            if present(link.get("issuer")) != present(issuer_value(&grants[i])) {
532                return Err(refused(format!(
533                    "Delegation refused: grant {} of the grant chain embeds a link whose issuer \
534                     is not the issuer of grant {}",
535                    j + 1,
536                    i + 1
537                )));
538            }
539            if present(link.get("subject")) != present(intent_of(&grants[i])?.get("delegatee")) {
540                return Err(refused(format!(
541                    "Delegation refused: grant {} of the grant chain embeds a link whose subject \
542                     is not the delegatee of grant {}",
543                    j + 1,
544                    i + 1
545                )));
546            }
547        }
548        links = embedded.to_vec();
549        start = j;
550        break;
551    }
552    for j in start..grants.len() {
553        let step_intent = if j + 1 < grants.len() {
554            intent_of(&grants[j + 1])?
555        } else {
556            intent
557        };
558        links.push(link_for(&grants[j], step_intent)?);
559    }
560    Ok(links)
561}
562
563/// The issuer of a grant: the `issuer` value, or the `id` of an issuer object.
564fn issuer_value(grant: &Value) -> Option<&Value> {
565    match grant.get("issuer") {
566        Some(Value::Object(o)) => o.get("id"),
567        other => other,
568    }
569}
570
571/// A field as the reference's `dict.get` reads it: absent and null are both
572/// "no value".
573fn present(v: Option<&Value>) -> Option<&Value> {
574    v.filter(|x| !x.is_null())
575}
576
577/// Python truthiness of a JSON value (absent and null are false).
578pub(crate) fn truthy(v: Option<&Value>) -> bool {
579    match v {
580        None | Some(Value::Null) => false,
581        Some(Value::Bool(b)) => *b,
582        Some(Value::Number(n)) => n.as_f64().is_some_and(|f| f != 0.0),
583        Some(Value::String(s)) => !s.is_empty(),
584        Some(Value::Array(a)) => !a.is_empty(),
585        Some(Value::Object(o)) => !o.is_empty(),
586    }
587}
588
589/// Python's `repr` of a JSON value, for refusal text that quotes a value the
590/// way the reference does (`'did:web:a'`, `None`, `1e-05`).
591pub(crate) fn py_repr(v: Option<&Value>) -> String {
592    match v {
593        None | Some(Value::Null) => "None".into(),
594        Some(Value::Bool(true)) => "True".into(),
595        Some(Value::Bool(false)) => "False".into(),
596        // An integer is written as its digits, a float the way Python does.
597        Some(Value::Number(n)) => match n.as_f64() {
598            Some(f) if n.is_f64() => py_repr_float(f),
599            _ => n.to_string(),
600        },
601        Some(Value::String(s)) => py_repr_str(s),
602        Some(Value::Array(a)) => {
603            let items: Vec<String> = a.iter().map(|x| py_repr(Some(x))).collect();
604            format!("[{}]", items.join(", "))
605        }
606        Some(Value::Object(o)) => {
607            let items: Vec<String> = o
608                .iter()
609                .map(|(k, x)| format!("{}: {}", py_repr_str(k), py_repr(Some(x))))
610                .collect();
611            format!("{{{}}}", items.join(", "))
612        }
613    }
614}
615
616/// The shortest digits that read back as `f` (finite, not negative) and where
617/// the decimal point goes: `f` is 0.DIGITS times 10 to the power of the
618/// second value. Zero is ("0", 1).
619///
620/// The digits come from ECMAScript's number to string (ryu-js), which picks
621/// the closest of the shortest candidates and, on an exact tie, the even last
622/// digit, the same as Python's `repr`. (Rust's own `{:e}` breaks a tie
623/// upward, so 588197768793114.25 would end in 3 instead of Python's 2.)
624fn shortest_digits(f: f64) -> (String, i32) {
625    let mut buf = ryu_js::Buffer::new();
626    let text = buf.format(f);
627    let (number, exp) = match text.split_once('e') {
628        Some((n, e)) => (n, e.parse::<i32>().unwrap_or(0)),
629        None => (text, 0),
630    };
631    let (whole, fraction) = number.split_once('.').unwrap_or((number, ""));
632    let all = format!("{whole}{fraction}");
633    let significant = all.trim_start_matches('0');
634    let point = whole.len() as i32 + exp - (all.len() - significant.len()) as i32;
635    let significant = significant.trim_end_matches('0');
636    if significant.is_empty() {
637        return ("0".into(), 1);
638    }
639    (significant.to_string(), point)
640}
641
642/// Python's `repr` of a float. The digits are the shortest that read back as
643/// the same value ([`shortest_digits`]). With the value written as 0.DIGITS
644/// times 10 to the power `point`, a `point` from -3 to 16 is written out in
645/// full (`0.0001`, `1.5`, `1234.0`, a whole number keeping its `.0`); anything
646/// else is written with an exponent that has a sign and at least two digits
647/// (`1e-05`, `1e+16`, `1.5e+300`). The sign of `-0.0` is kept. A JSON number
648/// is never infinite or NaN, but they are written as Python writes them too.
649pub(crate) fn py_repr_float(f: f64) -> String {
650    if f.is_nan() {
651        return "nan".into();
652    }
653    if f.is_infinite() {
654        return if f > 0.0 { "inf" } else { "-inf" }.into();
655    }
656    let sign = if f.is_sign_negative() { "-" } else { "" };
657    let (digits, point) = shortest_digits(f.abs());
658    let exp = point - 1;
659    if point <= -4 || point > 16 {
660        let (first, rest) = digits.split_at(1);
661        let fraction = if rest.is_empty() {
662            String::new()
663        } else {
664            format!(".{rest}")
665        };
666        let exp_sign = if exp < 0 { '-' } else { '+' };
667        return format!(
668            "{sign}{first}{fraction}e{exp_sign}{:02}",
669            exp.unsigned_abs()
670        );
671    }
672    let len = digits.len() as i32;
673    let body = if point <= 0 {
674        format!("0.{}{digits}", "0".repeat(point.unsigned_abs() as usize))
675    } else if point >= len {
676        format!("{digits}{}.0", "0".repeat((point - len) as usize))
677    } else {
678        let (whole, fraction) = digits.split_at(point as usize);
679        format!("{whole}.{fraction}")
680    };
681    format!("{sign}{body}")
682}
683
684/// Python's `repr` of a string: single quotes unless the string holds a single
685/// quote and no double quote; backslash and the quote escaped; tab, newline
686/// and carriage return as `\t`, `\n`, `\r`; every other character that
687/// Python's `str.isprintable()` rejects as `\xhh`, `\uhhhh` or `\Uhhhhhhhh`
688/// (lowercase hex, the shortest form that holds it).
689pub(crate) fn py_repr_str(s: &str) -> String {
690    let quote = if s.contains('\'') && !s.contains('"') {
691        '"'
692    } else {
693        '\''
694    };
695    let mut out = String::with_capacity(s.len() + 2);
696    out.push(quote);
697    for c in s.chars() {
698        match c {
699            '\\' => out.push_str("\\\\"),
700            '\n' => out.push_str("\\n"),
701            '\r' => out.push_str("\\r"),
702            '\t' => out.push_str("\\t"),
703            c if c == quote => {
704                out.push('\\');
705                out.push(c);
706            }
707            c if crate::py_printable::is_printable(c) => out.push(c),
708            c if (c as u32) <= 0xff => out.push_str(&format!("\\x{:02x}", c as u32)),
709            c if (c as u32) <= 0xffff => out.push_str(&format!("\\u{:04x}", c as u32)),
710            c => out.push_str(&format!("\\U{:08x}", c as u32)),
711        }
712    }
713    out.push(quote);
714    out
715}
716
717/// Check a grant chain from its link fields and build the links for `intent`
718/// signed under it (see [`chain_links`]).
719///
720/// The rules, in order (first failure wins):
721///
722/// - each grant is an object whose subject carries an intent object
723///   ("Delegation refused: the parent grant carries no intent object"), is
724///   signed, and is issued by a DID string (an issuer object's string `id`
725///   counts, and the link carries the string);
726/// - each grant's delegatee is the next grant's issuer;
727/// - a link copied from an older nested grant names that grant's issuer and
728///   delegatee ([`chain_links`]);
729/// - every grant is bound to the grant before it ([`chain_binding_problem`]);
730/// - no grant but the last is a replica grant, and a replica grant is never
731///   used to sign another grant ("... a replica cannot hand its authority on
732///   (replica_chain_too_long)");
733/// - with two grants or more: the first grant writes down every dimension in
734///   a form that can be compared, time included ("Delegation refused: grant 1
735///   of the grant chain has a malformed '{dimension}'",
736///   [`attenuation::malformed_dimension`]), and no grant is broader than the
737///   grants before it on any dimension, time included
738///   ([`attenuation::first_broader_step`] over the grants), so a window
739///   clamped to the last grant sits inside every grant above it.
740///
741/// Who the last delegatee is, and whether `intent` stays inside the chain, are
742/// the signer's checks. No signature is checked here: the verifier checks
743/// every grant's proof.
744///
745/// Errors: the first rule the chain breaks.
746pub fn check_grant_chain(grants: &[Value], intent: &Value) -> Result<Vec<Value>, GrantChainError> {
747    crate::nesting::deep_guard!(Err(GrantChainError(crate::nesting::TOO_DEEP.into())); grants, intent);
748    for (j, grant) in grants.iter().enumerate() {
749        intent_of(grant)?;
750        if !truthy(grant.get("issuer"))
751            || !matches!(grant.get("proof"), Some(Value::Object(_) | Value::Array(_)))
752        {
753            return Err(refused(
754                "Delegation refused: the parent grant is not a signed credential",
755            ));
756        }
757        if !issuer_value(grant).is_some_and(Value::is_string) {
758            return Err(refused(format!(
759                "Delegation refused: grant {} of the grant chain has an issuer that is not a \
760                 string or an object with a string id",
761                j + 1
762            )));
763        }
764    }
765    for j in 0..grants.len().saturating_sub(1) {
766        let delegatee = intent_of(&grants[j])?
767            .get("delegatee")
768            .and_then(Value::as_str)
769            .filter(|d| !d.is_empty());
770        let Some(delegatee) = delegatee else {
771            return Err(refused(format!(
772                "Delegation refused: grant {} of the grant chain names no delegatee",
773                j + 1
774            )));
775        };
776        let next_issuer = issuer_value(&grants[j + 1]);
777        if next_issuer.and_then(Value::as_str) != Some(delegatee) {
778            return Err(refused(format!(
779                "Delegation refused: grant {} of the grant chain names delegatee {}, but grant \
780                 {} is issued by {}",
781                j + 1,
782                py_repr_str(delegatee),
783                j + 2,
784                py_repr(next_issuer)
785            )));
786        }
787    }
788    let links = chain_links(grants, intent)?;
789    if let Some((index, reason)) = binding_failure(&links) {
790        return Err(refused(format!(
791            "Delegation refused: grant {} of the grant chain is not bound to the grant before \
792             it ({reason})",
793            index + 1
794        )));
795    }
796    let mut replica = replica_failure(&links).map(|(i, _)| i);
797    if replica.is_none() && grants.last().is_some_and(is_replica_grant) && is_grant_intent(intent) {
798        replica = Some(grants.len() - 1);
799    }
800    if let Some(index) = replica {
801        return Err(refused(format!(
802            "Delegation refused: grant {} of the grant chain is a replica grant, and a replica \
803             cannot hand its authority on (replica_chain_too_long)",
804            index + 1
805        )));
806    }
807    // A single grant has no grant before it; the signer checks the new intent
808    // against it.
809    if grants.len() > 1 {
810        let views: Vec<Value> = grants
811            .iter()
812            .map(|g| delegation::capability_view(g, true))
813            .collect();
814        // A malformed bound on the first grant is named as such: nothing in
815        // the chain can be shown to sit inside it.
816        if let Some(dimension) = attenuation::malformed_dimension(&views[0]) {
817            return Err(refused(format!(
818                "Delegation refused: grant 1 of the grant chain has a malformed {}",
819                py_repr_str(dimension.as_str())
820            )));
821        }
822        if let Err(dimension) = attenuation::first_broader_step(&views) {
823            return Err(refused(format!(
824                "Delegation refused: a grant in the grant chain is broader than the grant before \
825                 it on {}",
826                py_repr_str(dimension.as_str())
827            )));
828        }
829    }
830    Ok(links)
831}
832
833/// The effective capability at the end of a grant chain: the last grant's
834/// view, with every dimension it omits inherited from the grants above it (the
835/// same fold the verifier does over an embedded chain).
836///
837/// Errors when `grants` is empty.
838pub fn chain_capability(grants: &[Value], include_time: bool) -> Result<Value, GrantChainError> {
839    crate::nesting::deep_guard!(Err(GrantChainError(crate::nesting::TOO_DEEP.into())); grants);
840    let mut effective: Option<Value> = None;
841    for grant in grants {
842        let view = delegation::capability_view(grant, include_time);
843        effective = Some(match effective {
844            None => view,
845            Some(e) => attenuation::inherit(&e, &view),
846        });
847    }
848    effective.ok_or_else(|| refused("Delegation refused: the grant chain is empty"))
849}
850
851/// The grant chain to hand the delegatee of `grant`: the grants above it, root
852/// first, then `grant` itself.
853///
854/// `parent` is what `grant` was signed under: a root grant, an older grant
855/// that embeds its chain, or a grant chain. The delegatee signs with the
856/// result as its parent. Every grant in the result is a copy, so it shares
857/// nothing with `parent` or `grant`.
858///
859/// Errors: `grant` is not an object, names no delegatee, is not issued by the
860/// delegatee of the last parent grant, or is not bound to it, or the chain
861/// itself breaks a rule of [`check_grant_chain`].
862pub fn grant_chain(parent: &Value, grant: &Value) -> Result<Vec<Value>, GrantChainError> {
863    crate::nesting::deep_guard!(Err(GrantChainError(crate::nesting::TOO_DEEP.into())); parent, grant);
864    let mut grants = parent_grants(parent)?;
865    if !grant.is_object() {
866        return Err(refused("grant must be a signed grant (a dict)"));
867    }
868    let intent = intent_of(grant)?;
869    if !is_grant_intent(intent) {
870        return Err(refused(
871            "this credential names no delegatee, so nobody can sign under it",
872        ));
873    }
874    grants.push(grant.clone());
875    check_grant_chain(&grants, intent)?;
876    Ok(grants)
877}
878
879/// The grant chain rules as one JSON entry point, for the bindings:
880/// `{"fn": name, ...arguments}` to `{"ok": value}` or `{"error": text,
881/// "kind": "digest" | "type" | "refused"}`. The names and arguments:
882///
883/// - `grantDigest` (`grant`) -> the digest;
884/// - `bindingFieldsProblem` (`subject`), `chainBindingProblem` (`chain`) ->
885///   the reason or null;
886/// - `isReplicaGrant` (`grant`), `isGrantIntent` (`intent`) -> true or false;
887/// - `presentedChainProblem` (`credentials`) -> `[index, reason]` or null;
888/// - `parentGrants` (`parent`), `chainLinks` and `checkGrantChain`
889///   (`grants`, `intent`), `chainCapability` (`grants`, `includeTime`),
890///   `grantChain` (`parent`, `grant`) -> the result.
891///
892/// "type" marks the refusals the reference raises as a TypeError (a value of
893/// the wrong kind).
894pub fn rules_json(request: &Value) -> crate::error::Result<Value> {
895    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
896    let arg = |name: &str| request.get(name).unwrap_or(&Value::Null);
897    let list = |name: &str| -> Vec<Value> { arg(name).as_array().cloned().unwrap_or_default() };
898    let chain_error = |e: GrantChainError| {
899        let kind = if e.0.starts_with("parent_credential must be")
900            || e.0.starts_with("grant must be a signed grant")
901        {
902            "type"
903        } else {
904            "refused"
905        };
906        json!({ "error": e.0, "kind": kind })
907    };
908    let ok = |v: Value| json!({ "ok": v });
909    let name = request.get("fn").and_then(Value::as_str).unwrap_or("");
910    Ok(match name {
911        "grantDigest" => match grant_digest(arg("grant")) {
912            Ok(d) => ok(json!(d)),
913            Err(e) => json!({ "error": e.0, "kind": "digest" }),
914        },
915        "bindingFieldsProblem" => ok(json!(binding_fields_problem(arg("subject")))),
916        "chainBindingProblem" => ok(json!(chain_binding_problem(&list("chain")))),
917        "isReplicaGrant" => ok(json!(is_replica_grant(arg("grant")))),
918        "isGrantIntent" => ok(json!(is_grant_intent(arg("intent")))),
919        "presentedChainProblem" => ok(match presented_chain_problem(&list("credentials")) {
920            Some((i, reason)) => json!([i, reason]),
921            None => Value::Null,
922        }),
923        "parentGrants" => match parent_grants(arg("parent")) {
924            Ok(g) => ok(Value::Array(g)),
925            Err(e) => chain_error(e),
926        },
927        "chainLinks" => match chain_links(&list("grants"), arg("intent")) {
928            Ok(l) => ok(Value::Array(l)),
929            Err(e) => chain_error(e),
930        },
931        "checkGrantChain" => match check_grant_chain(&list("grants"), arg("intent")) {
932            Ok(l) => ok(Value::Array(l)),
933            Err(e) => chain_error(e),
934        },
935        "chainCapability" => {
936            let include_time = arg("includeTime").as_bool().unwrap_or(true);
937            match chain_capability(&list("grants"), include_time) {
938                Ok(c) => ok(c),
939                Err(e) => chain_error(e),
940            }
941        }
942        "grantChain" => match grant_chain(arg("parent"), arg("grant")) {
943            Ok(g) => ok(Value::Array(g)),
944            Err(e) => chain_error(e),
945        },
946        other => {
947            return Err(CoreError::Json(format!(
948                "unknown grant chain rule {:?}",
949                other.chars().take(40).collect::<String>()
950            )))
951        }
952    })
953}
954
955#[cfg(test)]
956mod tests {
957    use super::*;
958    use serde_json::json;
959
960    fn grant(issuer: &str, delegatee: &str, extra: Value) -> Value {
961        let mut subject = json!({
962            "id": issuer,
963            "intent": {"action": "read", "target": "t", "resource": "https://x/a",
964                       "delegatee": delegatee}
965        });
966        for (k, v) in extra.as_object().unwrap() {
967            subject[k] = v.clone();
968        }
969        json!({
970            "issuer": issuer,
971            "validFrom": "2026-11-10T00:00:00Z",
972            "validUntil": "2026-11-11T00:00:00Z",
973            "credentialSubject": subject,
974            "proof": {"type": "DataIntegrityProof", "proofValue": format!("z{issuer}")}
975        })
976    }
977
978    fn link(g: &Value) -> Value {
979        json!({"issuer": g["issuer"], "subject": g["credentialSubject"]["intent"]["delegatee"],
980               "parentCredential": g})
981    }
982
983    /// root -> a -> b, flat: b's grant names a's by digest, a's names root's.
984    fn flat3() -> Vec<Value> {
985        let g1 = grant("did:web:root", "did:web:a", json!({}));
986        let g2 = grant(
987            "did:web:a",
988            "did:web:b",
989            json!({ "parentGrantDigest": grant_digest(&g1).unwrap() }),
990        );
991        let g3 = grant(
992            "did:web:b",
993            "did:web:c",
994            json!({ "parentGrantDigest": grant_digest(&g2).unwrap() }),
995        );
996        vec![g1, g2, g3]
997    }
998
999    fn links(grants: &[Value]) -> Vec<Value> {
1000        grants.iter().map(link).collect()
1001    }
1002
1003    #[test]
1004    fn digest_shape_and_exactness() {
1005        let g = grant("did:web:root", "did:web:a", json!({}));
1006        let d = grant_digest(&g).unwrap();
1007        assert!(d.starts_with("uEi"), "{d}");
1008        assert_eq!(d.len(), 47);
1009        assert!(!d.contains('=') && !d.contains('+') && !d.contains('/'));
1010        // Key order does not matter (JCS), any change of content does.
1011        let reordered: Value = serde_json::from_str(
1012            &serde_json::to_string(&json!({
1013                "proof": g["proof"], "credentialSubject": g["credentialSubject"],
1014                "validUntil": g["validUntil"], "validFrom": g["validFrom"], "issuer": g["issuer"]
1015            }))
1016            .unwrap(),
1017        )
1018        .unwrap();
1019        assert_eq!(grant_digest(&reordered).unwrap(), d);
1020        let mut other = g.clone();
1021        other["proof"]["proofValue"] = json!("zdifferent");
1022        assert_ne!(grant_digest(&other).unwrap(), d);
1023        for bad in [json!([]), json!("x"), Value::Null, json!(1), json!(true)] {
1024            assert_eq!(
1025                grant_digest(&bad),
1026                Err(GrantDigestError("a grant must be a JSON object".into()))
1027            );
1028        }
1029    }
1030
1031    #[test]
1032    fn flat_and_nested_chains_bind() {
1033        assert_eq!(chain_binding_problem(&links(&flat3())), None);
1034        assert_eq!(chain_binding_problem(&[]), None);
1035        // The older nested form: the third grant embeds the two links above it.
1036        let g = flat3();
1037        let ls = links(&g[..2]);
1038        let nested = grant(
1039            "did:web:b",
1040            "did:web:c",
1041            json!({ "delegationChain": ls.clone() }),
1042        );
1043        let mut chain = ls.clone();
1044        chain.push(link(&nested));
1045        assert_eq!(chain_binding_problem(&chain), None);
1046        // An empty embedded chain is no chain: the digest binds.
1047        let g = flat3();
1048        let mut g2 = g[1].clone();
1049        g2["credentialSubject"]["delegationChain"] = json!([]);
1050        assert_eq!(chain_binding_problem(&[link(&g[0]), link(&g2)]), None);
1051    }
1052
1053    #[test]
1054    fn binding_refusals() {
1055        let g = flat3();
1056        let mismatch = Some(REASON_PARENT_MISMATCH);
1057        let malformed = Some(REASON_MALFORMED);
1058        // Truncated: the first grant names a parent.
1059        assert_eq!(chain_binding_problem(&links(&g[1..])), mismatch);
1060        // Splice: a's grant presented under a different root grant.
1061        let other_root = grant("did:web:root", "did:web:a", json!({"note": "other"}));
1062        assert_eq!(
1063            chain_binding_problem(&[link(&other_root), link(&g[1]), link(&g[2])]),
1064            mismatch
1065        );
1066        // The digest of the grandparent.
1067        let skip = grant(
1068            "did:web:b",
1069            "did:web:c",
1070            json!({ "parentGrantDigest": grant_digest(&g[0]).unwrap() }),
1071        );
1072        assert_eq!(
1073            chain_binding_problem(&[link(&g[0]), link(&g[1]), link(&skip)]),
1074            mismatch
1075        );
1076        // No binding at all on a later grant.
1077        let bare = grant("did:web:a", "did:web:b", json!({}));
1078        assert_eq!(chain_binding_problem(&[link(&g[0]), link(&bare)]), mismatch);
1079        // Spelling games: same hash, different text.
1080        let right = grant_digest(&g[0]).unwrap();
1081        for spelled in [
1082            right.to_uppercase(),
1083            format!("{right}="),
1084            format!(" {right}"),
1085            right.replacen('u', "z", 1),
1086        ] {
1087            let mut g2 = g[1].clone();
1088            g2["credentialSubject"][PARENT_GRANT_DIGEST] = json!(spelled);
1089            assert_eq!(
1090                chain_binding_problem(&[link(&g[0]), link(&g2)]),
1091                mismatch,
1092                "{spelled}"
1093            );
1094        }
1095        // null, a number, an object, an array: present and not a string.
1096        for v in [Value::Null, json!(5), json!({}), json!([right.clone()])] {
1097            let mut g2 = g[1].clone();
1098            g2["credentialSubject"][PARENT_GRANT_DIGEST] = v.clone();
1099            assert_eq!(
1100                chain_binding_problem(&[link(&g[0]), link(&g2)]),
1101                malformed,
1102                "{v}"
1103            );
1104            // On the first link the type check comes first too.
1105            let mut g1 = g[0].clone();
1106            g1["credentialSubject"][PARENT_GRANT_DIGEST] = v.clone();
1107            assert_eq!(chain_binding_problem(&[link(&g1)]), malformed, "{v}");
1108        }
1109        // A delegationChain that is not a list.
1110        for v in [Value::Null, json!({}), json!(""), json!(0)] {
1111            let mut g2 = g[1].clone();
1112            g2["credentialSubject"]["delegationChain"] = v.clone();
1113            assert_eq!(
1114                chain_binding_problem(&[link(&g[0]), link(&g2)]),
1115                malformed,
1116                "{v}"
1117            );
1118        }
1119        // Both bindings on one grant, even when each would hold.
1120        let mut both = g[1].clone();
1121        both["credentialSubject"]["delegationChain"] = json!([link(&g[0])]);
1122        assert_eq!(
1123            chain_binding_problem(&[link(&g[0]), link(&both)]),
1124            malformed
1125        );
1126        // The first grant embeds a chain.
1127        assert_eq!(chain_binding_problem(&[link(&both)]), malformed);
1128        let mut nested_first = g[0].clone();
1129        nested_first["credentialSubject"]["delegationChain"] = json!([link(&g[0])]);
1130        assert_eq!(chain_binding_problem(&[link(&nested_first)]), mismatch);
1131        // An embedded chain that is not the links before it.
1132        let mut longer = g[1].clone();
1133        longer["credentialSubject"]
1134            .as_object_mut()
1135            .unwrap()
1136            .remove(PARENT_GRANT_DIGEST);
1137        longer["credentialSubject"]["delegationChain"] = json!([link(&g[0]), link(&g[0])]);
1138        assert_eq!(
1139            chain_binding_problem(&[link(&g[0]), link(&longer)]),
1140            mismatch
1141        );
1142        let mut tampered_link = link(&g[0]);
1143        tampered_link["note"] = json!("x");
1144        longer["credentialSubject"]["delegationChain"] = json!([tampered_link]);
1145        assert_eq!(
1146            chain_binding_problem(&[link(&g[0]), link(&longer)]),
1147            mismatch
1148        );
1149        // A grant edited after its child named it.
1150        let mut edited = g[0].clone();
1151        edited["credentialSubject"]["intent"]["resource"] = json!("https://x");
1152        assert_eq!(
1153            chain_binding_problem(&[link(&edited), link(&g[1]), link(&g[2])]),
1154            mismatch
1155        );
1156        // Called directly, a link without its grant is malformed.
1157        assert_eq!(
1158            chain_binding_problem(&[json!({"issuer": "did:web:root"})]),
1159            malformed
1160        );
1161        assert_eq!(
1162            chain_binding_problem(&[link(&g[0]), json!({"parentCredential": "x"})]),
1163            malformed
1164        );
1165        // The first failure wins.
1166        let mut bad_type = g[2].clone();
1167        bad_type["credentialSubject"][PARENT_GRANT_DIGEST] = json!(1);
1168        assert_eq!(
1169            chain_binding_problem(&[link(&g[0]), link(&bare), link(&bad_type)]),
1170            mismatch
1171        );
1172    }
1173
1174    #[test]
1175    fn presented_chain_rule() {
1176        let g = flat3();
1177        assert_eq!(presented_chain_problem(&g), None);
1178        assert_eq!(presented_chain_problem(&[]), None);
1179        // Credential 0 with a digest.
1180        assert_eq!(
1181            presented_chain_problem(&g[1..]),
1182            Some((0, REASON_PARENT_MISMATCH))
1183        );
1184        // A wrong digest further down.
1185        assert_eq!(
1186            presented_chain_problem(&[g[0].clone(), g[2].clone()]),
1187            Some((1, REASON_PARENT_MISMATCH))
1188        );
1189        // Not a string, on credential 0 too (the type is checked first).
1190        let mut bad = g[1].clone();
1191        bad["credentialSubject"][PARENT_GRANT_DIGEST] = Value::Null;
1192        assert_eq!(
1193            presented_chain_problem(&[g[0].clone(), bad.clone()]),
1194            Some((1, REASON_MALFORMED))
1195        );
1196        assert_eq!(
1197            presented_chain_problem(core::slice::from_ref(&bad)),
1198            Some((0, REASON_MALFORMED))
1199        );
1200        // Credentials without a binding are read as before.
1201        let plain = grant("did:web:a", "did:web:b", json!({}));
1202        assert_eq!(
1203            presented_chain_problem(&[g[0].clone(), plain.clone()]),
1204            None
1205        );
1206        // A credential that is not an object is malformed, wherever it sits
1207        // (the fleet verifier refuses it before this runs).
1208        for (position, value) in [(0, json!("{}")), (1, Value::Null), (2, json!(7))] {
1209            let mut creds = vec![g[0].clone(), plain.clone(), plain.clone()];
1210            creds[position] = value;
1211            assert_eq!(
1212                presented_chain_problem(&creds),
1213                Some((position, REASON_MALFORMED))
1214            );
1215        }
1216        assert_eq!(
1217            presented_chain_problem(&[json!("x"), g[1].clone()]),
1218            Some((0, REASON_MALFORMED))
1219        );
1220    }
1221
1222    /// The older nested chain a delegatee of `parent` embeds when it signs
1223    /// `intent`: the parent's own embedded links, then a link for the parent.
1224    fn nested_chain(parent: &Value, intent: &Value) -> Value {
1225        let mut chain = embedded_chain(parent).to_vec();
1226        let mut l = link(parent);
1227        l["intent"] = intent.clone();
1228        chain.push(l);
1229        Value::Array(chain)
1230    }
1231
1232    fn intent_to(delegatee: &str) -> Value {
1233        json!({"action": "read", "target": "t", "resource": "https://x/a", "delegatee": delegatee})
1234    }
1235
1236    /// An older nested sub-grant by `issuer` to `delegatee` under `parent`.
1237    fn nested(issuer: &str, delegatee: &str, parent: &Value) -> Value {
1238        grant(
1239            issuer,
1240            delegatee,
1241            json!({ "delegationChain": nested_chain(parent, &intent_to(delegatee)) }),
1242        )
1243    }
1244
1245    /// An action by `issuer` that embeds `links`.
1246    fn action(issuer: &str, links: Value) -> Value {
1247        json!({"issuer": issuer, "proof": {"proofValue": "z"},
1248               "credentialSubject": {"intent": {"action": "read"}, "delegationChain": links}})
1249    }
1250
1251    #[test]
1252    fn binding_fields_shape() {
1253        let malformed = Some(REASON_MALFORMED);
1254        let digest = json!("uEiA");
1255        for subject in [
1256            json!({}),
1257            json!({"parentGrantDigest": digest}),
1258            json!({"delegationChain": []}),
1259            json!({"parentGrantDigest": digest, "delegationChain": []}),
1260            json!({"delegationChain": [{"issuer": "x"}]}),
1261            // Anything that is not an object carries no binding fields.
1262            Value::Null,
1263            json!([{"parentGrantDigest": 5}]),
1264            json!("parentGrantDigest"),
1265        ] {
1266            assert_eq!(binding_fields_problem(&subject), None, "{subject}");
1267        }
1268        for subject in [
1269            json!({"parentGrantDigest": null}),
1270            json!({"parentGrantDigest": 5}),
1271            json!({"parentGrantDigest": ["u"]}),
1272            json!({"parentGrantDigest": {}}),
1273            json!({"delegationChain": null}),
1274            json!({"delegationChain": {}}),
1275            json!({"delegationChain": ""}),
1276            json!({"delegationChain": 0}),
1277            json!({"delegationChain": false}),
1278            json!({"parentGrantDigest": digest, "delegationChain": [{}]}),
1279            json!({"parentGrantDigest": null, "delegationChain": [{}]}),
1280        ] {
1281            assert_eq!(binding_fields_problem(&subject), malformed, "{subject}");
1282        }
1283    }
1284
1285    #[test]
1286    fn presented_chains_with_embedded_chains() {
1287        let mismatch = |i| Some((i, REASON_PARENT_MISMATCH));
1288        let malformed = |i| Some((i, REASON_MALFORMED));
1289        let g = flat3();
1290        let (g1, g2) = (g[0].clone(), g[1].clone());
1291        let g1b = grant("did:web:root2", "did:web:a", json!({}));
1292        let g2b = grant(
1293            "did:web:a",
1294            "did:web:b",
1295            json!({ "parentGrantDigest": grant_digest(&g1b).unwrap() }),
1296        );
1297        let leaf = action("did:web:b", json!([]));
1298        // a holds grants from two roots: its older nested sub-grant made under
1299        // root2's grant cannot follow root's grant, only root2's.
1300        let nested_b = nested("did:web:a", "did:web:b", &g1b);
1301        assert_eq!(
1302            presented_chain_problem(&[g1.clone(), nested_b.clone(), leaf.clone()]),
1303            mismatch(1)
1304        );
1305        assert_eq!(
1306            presented_chain_problem(&[g1b.clone(), nested_b.clone(), leaf.clone()]),
1307            None
1308        );
1309        // An older nested sub-grant (or a flat one) as credential 0.
1310        let nested_a = nested("did:web:a", "did:web:b", &g1);
1311        assert_eq!(
1312            presented_chain_problem(&[nested_a.clone(), leaf.clone()]),
1313            mismatch(0)
1314        );
1315        assert_eq!(
1316            presented_chain_problem(&[g2.clone(), leaf.clone()]),
1317            mismatch(0)
1318        );
1319        // An action that embeds another chain from the same root.
1320        let elsewhere = action("did:web:b", json!(links(&[g1b.clone(), g2b])));
1321        assert_eq!(
1322            presented_chain_problem(&[g1.clone(), g2.clone(), elsewhere]),
1323            mismatch(2)
1324        );
1325        let here = action("did:web:b", json!(links(&[g1.clone(), g2.clone()])));
1326        assert_eq!(
1327            presented_chain_problem(&[g1.clone(), g2.clone(), here]),
1328            None
1329        );
1330        // Binding fields of the wrong shape on credential 1.
1331        for fields in [
1332            json!({ "parentGrantDigest": grant_digest(&g1).unwrap(),
1333                    "delegationChain": nested_chain(&g1, &intent_to("did:web:b")) }),
1334            json!({"delegationChain": null}),
1335            json!({"delegationChain": {}}),
1336            json!({"parentGrantDigest": null}),
1337        ] {
1338            let sub = grant("did:web:a", "did:web:b", fields.clone());
1339            assert_eq!(
1340                presented_chain_problem(&[g1.clone(), sub, leaf.clone()]),
1341                malformed(1),
1342                "{fields}"
1343            );
1344        }
1345        // Older nested chains, and mixed chains, follow on.
1346        let g2n = nested("did:web:a", "did:web:b", &g1);
1347        let g3n = nested("did:web:b", "did:web:c", &g2n);
1348        let leaf_c = action("did:web:c", json!([]));
1349        assert_eq!(
1350            presented_chain_problem(&[g1.clone(), g2n.clone(), g3n.clone(), leaf_c.clone()]),
1351            None
1352        );
1353        let nested_leaf = action("did:web:c", nested_chain(&g3n, &json!({"action": "read"})));
1354        assert_eq!(
1355            presented_chain_problem(&[g1.clone(), g2n.clone(), g3n.clone(), nested_leaf]),
1356            None
1357        );
1358        let g3 = grant(
1359            "did:web:b",
1360            "did:web:c",
1361            json!({ "parentGrantDigest": grant_digest(&g2n).unwrap() }),
1362        );
1363        assert_eq!(
1364            presented_chain_problem(&[g1.clone(), g2n.clone(), g3, leaf_c.clone()]),
1365            None
1366        );
1367        // The same nested sub-grant one place later does not follow on.
1368        assert_eq!(
1369            presented_chain_problem(&[g1.clone(), g2n.clone(), g2n.clone(), g3n, leaf_c]),
1370            mismatch(2)
1371        );
1372    }
1373
1374    #[test]
1375    fn the_last_embedded_link_must_carry_the_previous_credential() {
1376        let g1 = flat3()[0].clone();
1377        let links = nested_chain(&g1, &intent_to("did:web:b"));
1378        let mut no_grant = links.clone();
1379        no_grant[0]
1380            .as_object_mut()
1381            .unwrap()
1382            .remove("parentCredential");
1383        let mut not_an_object = links.clone();
1384        not_an_object[0]["parentCredential"] = json!(g1.to_string());
1385        let mut not_a_link = links.clone();
1386        not_a_link[0] = json!("link");
1387        // A link whose grant differs from credential 0 by one field.
1388        let mut edited = links.clone();
1389        edited[0]["parentCredential"]["validUntil"] = json!("2026-11-12T00:00:00Z");
1390        for embedded in [no_grant, not_an_object, not_a_link, edited] {
1391            let sub = json!({"issuer": "did:web:a",
1392                             "credentialSubject": {"delegationChain": embedded}});
1393            assert_eq!(
1394                presented_chain_problem(&[g1.clone(), sub]),
1395                Some((1, REASON_PARENT_MISMATCH))
1396            );
1397        }
1398        // JCS-equal is enough: key order does not matter.
1399        let reordered: Value = serde_json::from_str(&jcs::canonicalize_to_string(&g1)).unwrap();
1400        let sub = json!({"issuer": "did:web:a",
1401                         "credentialSubject": {"delegationChain": [{"parentCredential": reordered}]}});
1402        assert_eq!(presented_chain_problem(&[g1, sub]), None);
1403    }
1404
1405    #[test]
1406    #[cfg_attr(
1407        not(feature = "std"),
1408        ignore = "member order follows insertion only with std"
1409    )]
1410    fn grant_chains_for_signing() {
1411        let g = flat3();
1412        let leaf_intent = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1413        let ls = check_grant_chain(&g, &leaf_intent).unwrap();
1414        assert_eq!(ls.len(), 3);
1415        assert_eq!(chain_binding_problem(&ls), None);
1416        // Link j carries grant j+1's intent, and the last the new intent.
1417        assert_eq!(ls[0]["intent"], g[1]["credentialSubject"]["intent"]);
1418        assert_eq!(ls[2]["intent"], leaf_intent);
1419        assert_eq!(ls[1]["subject"], json!("did:web:b"));
1420        assert_eq!(ls[1]["parentProofValue"], json!("zdid:web:a"));
1421        let keys: Vec<&str> = ls[0]
1422            .as_object()
1423            .unwrap()
1424            .keys()
1425            .map(|k| k.as_str())
1426            .collect();
1427        assert_eq!(
1428            keys,
1429            [
1430                "issuer",
1431                "subject",
1432                "intent",
1433                "validFrom",
1434                "validUntil",
1435                "parentProofValue",
1436                "parentCredential"
1437            ]
1438        );
1439        // grant_chain: what to hand the delegatee of a new sub-grant.
1440        let sub = grant(
1441            "did:web:c",
1442            "did:web:d",
1443            json!({ "parentGrantDigest": grant_digest(&g[2]).unwrap() }),
1444        );
1445        let handed = grant_chain(&json!(g.clone()), &sub).unwrap();
1446        assert_eq!(handed.len(), 4);
1447        assert_eq!(handed[3], sub);
1448        // A single grant that names a parent is refused alone.
1449        assert_eq!(grant_chain(&g[1], &sub).unwrap_err().0, NAMES_PARENT_GRANT);
1450        assert_eq!(parent_grants(&g[2]).unwrap_err().0, NAMES_PARENT_GRANT);
1451        // An older nested grant stands for its embedded grants and itself.
1452        let nested = grant(
1453            "did:web:a",
1454            "did:web:b",
1455            json!({ "delegationChain": [link(&g[0])] }),
1456        );
1457        let pg = parent_grants(&nested).unwrap();
1458        assert_eq!(pg, vec![g[0].clone(), nested.clone()]);
1459        // Its embedded link is copied verbatim.
1460        let copied = check_grant_chain(&pg, &leaf_intent).unwrap();
1461        assert_eq!(copied[0], link(&g[0]));
1462        assert_eq!(chain_binding_problem(&copied), None);
1463        // A credential (no delegatee) cannot be signed under.
1464        let action = json!({"issuer": "did:web:c", "proof": {},
1465            "credentialSubject": {"intent": {"action": "read"}}});
1466        assert_eq!(
1467            grant_chain(&json!(g.clone()), &action).unwrap_err().0,
1468            "this credential names no delegatee, so nobody can sign under it"
1469        );
1470        assert_eq!(
1471            grant_chain(&json!(g.clone()), &json!([])).unwrap_err().0,
1472            "grant must be a signed grant (a dict)"
1473        );
1474        assert!(is_grant_intent(&json!({"delegatee": "did:web:x"})));
1475        for i in [
1476            json!({"delegatee": ""}),
1477            json!({"delegatee": 5}),
1478            json!({}),
1479            json!("x"),
1480        ] {
1481            assert!(!is_grant_intent(&i), "{i}");
1482        }
1483    }
1484
1485    #[test]
1486    fn grant_chain_refusals_match_the_reference_text() {
1487        let g = flat3();
1488        let intent = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1489        let err = |grants: &[Value]| check_grant_chain(grants, &intent).unwrap_err().0;
1490        assert_eq!(
1491            parent_grants(&json!([])).unwrap_err().0,
1492            "Delegation refused: the grant chain is empty"
1493        );
1494        assert_eq!(
1495            parent_grants(&json!([g[0].clone(), 5])).unwrap_err().0,
1496            "Delegation refused: every grant in the grant chain must be an object"
1497        );
1498        assert_eq!(
1499            parent_grants(&json!("x")).unwrap_err().0,
1500            "parent_credential must be a grant (a dict) or a grant chain (a list of grants, root first)"
1501        );
1502        let mut bad_chain = g[0].clone();
1503        bad_chain["credentialSubject"]["delegationChain"] = json!({});
1504        assert_eq!(
1505            parent_grants(&bad_chain).unwrap_err().0,
1506            "Delegation refused: the parent grant's delegationChain is not a list"
1507        );
1508        bad_chain["credentialSubject"]["delegationChain"] = json!([{"issuer": "x"}]);
1509        assert_eq!(
1510            parent_grants(&bad_chain).unwrap_err().0,
1511            "Delegation refused: a link in the parent grant's delegationChain carries no signed grant"
1512        );
1513        // Unsigned, no intent, a gap, no delegatee.
1514        let mut unsigned = g[0].clone();
1515        unsigned.as_object_mut().unwrap().remove("proof");
1516        assert_eq!(
1517            err(&[unsigned]),
1518            "Delegation refused: the parent grant is not a signed credential"
1519        );
1520        let mut no_issuer = g[0].clone();
1521        no_issuer["issuer"] = json!("");
1522        assert_eq!(
1523            err(&[no_issuer]),
1524            "Delegation refused: the parent grant is not a signed credential"
1525        );
1526        let mut no_intent = g[0].clone();
1527        no_intent["credentialSubject"]["intent"] = json!("read");
1528        assert_eq!(
1529            err(&[no_intent]),
1530            "Delegation refused: the parent grant carries no intent object"
1531        );
1532        assert_eq!(
1533            err(&[g[0].clone(), g[2].clone()]),
1534            "Delegation refused: grant 1 of the grant chain names delegatee 'did:web:a', but grant 2 is issued by 'did:web:b'"
1535        );
1536        // An issuer that is not a DID string is refused before the walk.
1537        let mut no_issuer2 = g[1].clone();
1538        no_issuer2["issuer"] = json!({"name": "x"});
1539        assert_eq!(
1540            err(&[g[0].clone(), no_issuer2]),
1541            "Delegation refused: grant 2 of the grant chain has an issuer that is not a string or an object with a string id"
1542        );
1543        let mut no_delegatee = g[0].clone();
1544        no_delegatee["credentialSubject"]["intent"]
1545            .as_object_mut()
1546            .unwrap()
1547            .remove("delegatee");
1548        assert_eq!(
1549            err(&[no_delegatee, g[1].clone()]),
1550            "Delegation refused: grant 1 of the grant chain names no delegatee"
1551        );
1552        // An issuer object with the right id follows on.
1553        let mut object_issuer = g[1].clone();
1554        object_issuer["issuer"] = json!({"id": "did:web:a"});
1555        assert!(check_grant_chain(&[g[0].clone(), object_issuer], &intent).is_ok());
1556        // Unbound grants.
1557        let bare = grant("did:web:a", "did:web:b", json!({}));
1558        assert_eq!(
1559            err(&[g[0].clone(), bare]),
1560            "Delegation refused: grant 2 of the grant chain is not bound to the grant before it (delegation_parent_mismatch)"
1561        );
1562        let mut bad_digest = g[1].clone();
1563        bad_digest["credentialSubject"][PARENT_GRANT_DIGEST] = json!(7);
1564        assert_eq!(
1565            err(&[g[0].clone(), bad_digest]),
1566            "Delegation refused: grant 2 of the grant chain is not bound to the grant before it (malformed_delegation)"
1567        );
1568        // An older nested grant whose embedded chain is not the grants before it.
1569        let nested = grant(
1570            "did:web:a",
1571            "did:web:b",
1572            json!({ "delegationChain": [link(&g[0])] }),
1573        );
1574        let other_root = grant("did:web:root", "did:web:a", json!({"note": "other"}));
1575        assert_eq!(
1576            err(&[other_root, nested]),
1577            "Delegation refused: grant 2 of the grant chain embeds a chain that is not the grants before it"
1578        );
1579        assert_eq!(
1580            chain_capability(&[], false).unwrap_err().0,
1581            "Delegation refused: the grant chain is empty"
1582        );
1583    }
1584
1585    const BROADER: &str =
1586        "Delegation refused: a grant in the grant chain is broader than the grant before it on ";
1587
1588    #[test]
1589    fn an_intermediate_grant_broader_than_the_grant_above_it_is_refused() {
1590        let g = flat3();
1591        let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1592        let digest = json!(grant_digest(&g[0]).unwrap());
1593        let mut broad = g[1].clone();
1594        broad["credentialSubject"]["intent"]["action"] = json!(["read", "write"]);
1595        broad["credentialSubject"][PARENT_GRANT_DIGEST] = digest.clone();
1596        let chain = [g[0].clone(), broad.clone()];
1597        assert_eq!(
1598            check_grant_chain(&chain, &leaf).unwrap_err().0,
1599            format!("{BROADER}'action'")
1600        );
1601        // The same for the grant chain handed on with it.
1602        assert_eq!(
1603            grant_chain(&g[0], &broad).unwrap_err().0,
1604            format!("{BROADER}'action'")
1605        );
1606        // A grant that outlives (or starts before) the grant above it.
1607        for (k, v) in [
1608            ("validUntil", "2026-11-12T00:00:00Z"),
1609            ("validFrom", "2026-11-09T00:00:00Z"),
1610        ] {
1611            let mut long = g[1].clone();
1612            long[k] = json!(v);
1613            assert_eq!(
1614                check_grant_chain(&[g[0].clone(), long.clone()], &leaf)
1615                    .unwrap_err()
1616                    .0,
1617                format!("{BROADER}'time'"),
1618                "{k}"
1619            );
1620            assert_eq!(
1621                grant_chain(&g[0], &long).unwrap_err().0,
1622                format!("{BROADER}'time'")
1623            );
1624        }
1625        // Further down the chain, against the effective capability so far.
1626        let mut wide = g[2].clone();
1627        wide["credentialSubject"]["intent"]["resource"] = json!("https://x");
1628        let mut chain = g.clone();
1629        chain[2] = wide;
1630        assert_eq!(
1631            check_grant_chain(&chain, &leaf).unwrap_err().0,
1632            format!("{BROADER}'resource'")
1633        );
1634        // A narrower grant is fine, and a single grant has nothing above it.
1635        let mut narrow = g[1].clone();
1636        narrow["credentialSubject"]["intent"]["resource"] = json!("https://x/a/b");
1637        narrow["validUntil"] = json!("2026-11-10T12:00:00Z");
1638        assert!(check_grant_chain(&[g[0].clone(), narrow], &leaf).is_ok());
1639        let mut alone = g[0].clone();
1640        alone["credentialSubject"]["intent"]["action"] = json!(["read", "write"]);
1641        assert!(check_grant_chain(&[alone], &leaf).is_ok());
1642        // The binding rule comes before the breadth rule.
1643        let mut unbound = g[1].clone();
1644        unbound["credentialSubject"]
1645            .as_object_mut()
1646            .unwrap()
1647            .remove(PARENT_GRANT_DIGEST);
1648        unbound["credentialSubject"]["intent"]["action"] = json!("write");
1649        assert_eq!(
1650            check_grant_chain(&[g[0].clone(), unbound], &leaf)
1651                .unwrap_err()
1652                .0,
1653            "Delegation refused: grant 2 of the grant chain is not bound to the grant before it (delegation_parent_mismatch)"
1654        );
1655    }
1656
1657    #[test]
1658    fn a_malformed_first_grant_is_named_as_malformed() {
1659        let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1660        for (dimension, value) in [
1661            ("rate", json!("lots")),
1662            ("policy", json!(["not", "an", "object"])),
1663            ("action", json!(7)),
1664            ("target", json!([1])),
1665            ("resource", json!(7)),
1666            ("time", json!("soon")),
1667        ] {
1668            let mut g1 = grant("did:web:root", "did:web:a", json!({}));
1669            if dimension == "time" {
1670                g1["validUntil"] = value;
1671            } else {
1672                g1["credentialSubject"]["intent"][dimension] = value;
1673            }
1674            let g2 = grant(
1675                "did:web:a",
1676                "did:web:b",
1677                json!({ "parentGrantDigest": grant_digest(&g1).unwrap() }),
1678            );
1679            let message = format!(
1680                "Delegation refused: grant 1 of the grant chain has a malformed '{dimension}'"
1681            );
1682            assert_eq!(
1683                check_grant_chain(&[g1.clone(), g2.clone()], &leaf)
1684                    .unwrap_err()
1685                    .0,
1686                message
1687            );
1688            // The same for the grant chain handed on with it.
1689            assert_eq!(grant_chain(&g1, &g2).unwrap_err().0, message);
1690            // A single grant has no grant before it: the signer checks it.
1691            assert!(check_grant_chain(&[g1], &leaf).is_ok(), "{dimension}");
1692        }
1693        // A malformed later grant is still a broader one.
1694        let g = flat3();
1695        let mut g2 = g[1].clone();
1696        g2["credentialSubject"]["intent"]["rate"] = json!("lots");
1697        assert_eq!(
1698            check_grant_chain(&[g[0].clone(), g2], &leaf).unwrap_err().0,
1699            format!("{BROADER}'rate'")
1700        );
1701    }
1702
1703    #[test]
1704    fn the_helpers_refuse_a_grant_that_is_not_an_object() {
1705        let g = flat3();
1706        let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1707        let no_intent = "Delegation refused: the parent grant carries no intent object";
1708        let mut no_subject = g[1].clone();
1709        no_subject["credentialSubject"] = json!("subject");
1710        let mut no_intent_member = g[1].clone();
1711        no_intent_member["credentialSubject"]
1712            .as_object_mut()
1713            .unwrap()
1714            .remove("intent");
1715        // An older nested grant after a bad one: every grant's intent is read
1716        // before any embedded chain is compared.
1717        let nested_after = nested("did:web:a", "did:web:b", &g[0]);
1718        for bad in [
1719            json!("x"),
1720            Value::Null,
1721            json!(5),
1722            json!(["nested"]),
1723            no_subject,
1724            no_intent_member,
1725        ] {
1726            for grants in [
1727                vec![bad.clone()],
1728                vec![g[0].clone(), bad.clone()],
1729                vec![bad.clone(), g[0].clone()],
1730                vec![bad.clone(), nested_after.clone()],
1731            ] {
1732                assert_eq!(
1733                    check_grant_chain(&grants, &leaf).unwrap_err().0,
1734                    no_intent,
1735                    "{bad}"
1736                );
1737                assert_eq!(
1738                    chain_links(&grants, &leaf).unwrap_err().0,
1739                    no_intent,
1740                    "{bad}"
1741                );
1742            }
1743        }
1744    }
1745
1746    #[test]
1747    fn a_nested_grant_whose_embedded_link_lies_is_refused() {
1748        let g = flat3();
1749        let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1750        for (field, message) in [
1751            (
1752                "subject",
1753                "Delegation refused: grant 2 of the grant chain embeds a link whose subject is not the delegatee of grant 1",
1754            ),
1755            (
1756                "issuer",
1757                "Delegation refused: grant 2 of the grant chain embeds a link whose issuer is not the issuer of grant 1",
1758            ),
1759        ] {
1760            let mut links = nested_chain(&g[0], &intent_to("did:web:b"));
1761            links[0][field] = json!("did:web:x");
1762            let lying = grant("did:web:a", "did:web:b", json!({ "delegationChain": links }));
1763            let grants = parent_grants(&lying).unwrap();
1764            assert_eq!(check_grant_chain(&grants, &leaf).unwrap_err().0, message);
1765            assert_eq!(
1766                check_grant_chain(&[g[0].clone(), lying.clone()], &leaf)
1767                    .unwrap_err()
1768                    .0,
1769                message
1770            );
1771            assert_eq!(chain_links(&grants, &leaf).unwrap_err().0, message);
1772            // A missing field lies too; null reads as missing.
1773            let mut links = nested_chain(&g[0], &intent_to("did:web:b"));
1774            links[0].as_object_mut().unwrap().remove(field);
1775            let missing = grant("did:web:a", "did:web:b", json!({ "delegationChain": links }));
1776            assert_eq!(
1777                check_grant_chain(&[g[0].clone(), missing], &leaf)
1778                    .unwrap_err()
1779                    .0,
1780                message
1781            );
1782        }
1783        // The chain equality is checked first, then each link's issuer, then
1784        // its subject.
1785        let mut links = nested_chain(&g[0], &intent_to("did:web:b"));
1786        links[0]["issuer"] = json!("did:web:x");
1787        links[0]["subject"] = json!("did:web:x");
1788        let both = grant(
1789            "did:web:a",
1790            "did:web:b",
1791            json!({ "delegationChain": links }),
1792        );
1793        assert!(check_grant_chain(&[g[0].clone(), both.clone()], &leaf)
1794            .unwrap_err()
1795            .0
1796            .contains("whose issuer is not"));
1797        let other_root = grant("did:web:root", "did:web:a", json!({"note": "other"}));
1798        assert_eq!(
1799            check_grant_chain(&[other_root, both], &leaf).unwrap_err().0,
1800            "Delegation refused: grant 2 of the grant chain embeds a chain that is not the grants before it"
1801        );
1802        // An honest nested grant: its link is copied as it is.
1803        let honest = nested("did:web:a", "did:web:b", &g[0]);
1804        let out = check_grant_chain(&[g[0].clone(), honest.clone()], &leaf).unwrap();
1805        assert_eq!(out[0], honest["credentialSubject"]["delegationChain"][0]);
1806        assert_eq!(out[1]["parentCredential"], honest);
1807    }
1808
1809    #[test]
1810    fn an_issuer_object_is_carried_as_its_id() {
1811        let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1812        let mut root = grant("did:web:root", "did:web:a", json!({}));
1813        root["issuer"] = json!({"id": "did:web:root", "name": "Root"});
1814        let links = check_grant_chain(core::slice::from_ref(&root), &leaf).unwrap();
1815        assert_eq!(links[0]["issuer"], json!("did:web:root"));
1816        assert_eq!(links[0]["parentCredential"], root);
1817        assert_eq!(chain_binding_problem(&links), None);
1818        // chain_links on its own: an issuer that is not a string is "".
1819        let mut odd = root.clone();
1820        odd["issuer"] = json!(42);
1821        assert_eq!(
1822            chain_links(core::slice::from_ref(&odd), &leaf).unwrap()[0]["issuer"],
1823            json!("")
1824        );
1825    }
1826
1827    #[test]
1828    fn an_issuer_that_is_not_a_did_string_is_refused() {
1829        let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1830        for issuer in [
1831            json!(42),
1832            json!({"id": 5}),
1833            json!({"name": "Root"}),
1834            json!(["did:key:z"]),
1835            json!(true),
1836        ] {
1837            let mut root = grant("did:web:root", "did:web:a", json!({}));
1838            root["issuer"] = issuer.clone();
1839            assert_eq!(
1840                check_grant_chain(&[root], &leaf).unwrap_err().0,
1841                "Delegation refused: grant 1 of the grant chain has an issuer that is not a string or an object with a string id",
1842                "{issuer}"
1843            );
1844        }
1845        // An empty issuer, or an empty issuer object, is not a signed grant.
1846        for issuer in [json!(""), json!({}), Value::Null, json!(0), json!([])] {
1847            let mut root = grant("did:web:root", "did:web:a", json!({}));
1848            root["issuer"] = issuer.clone();
1849            assert_eq!(
1850                check_grant_chain(&[root], &leaf).unwrap_err().0,
1851                "Delegation refused: the parent grant is not a signed credential",
1852                "{issuer}"
1853            );
1854        }
1855    }
1856
1857    #[test]
1858    fn links_are_copies_of_the_grants() {
1859        // Owned values: the links equal the grants and intents they came from,
1860        // and changing one leaves the caller's grants as they were.
1861        let g = flat3();
1862        let before = g.clone();
1863        let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1864        let mut links = check_grant_chain(&g, &leaf).unwrap();
1865        assert_eq!(links[0]["parentCredential"], g[0]);
1866        assert_eq!(links[0]["intent"], g[1]["credentialSubject"]["intent"]);
1867        links[0]["intent"]["action"] = json!("write");
1868        links[1]["parentCredential"]["credentialSubject"]["intent"]["action"] = json!("write");
1869        assert_eq!(g, before);
1870    }
1871
1872    #[test]
1873    fn chain_capability_inherits_down_the_chain() {
1874        let mut g = flat3();
1875        g[0]["credentialSubject"]["intent"]["rate"] = json!("10/hour");
1876        g[2]["credentialSubject"]["intent"]
1877            .as_object_mut()
1878            .unwrap()
1879            .remove("resource");
1880        let cap = chain_capability(&g, false).unwrap();
1881        assert_eq!(cap["intent"]["resource"], json!("https://x/a"));
1882        assert_eq!(cap["rate"], json!("10/hour"));
1883        assert_eq!(cap["subject"], json!("did:web:c"));
1884        assert!(cap.get("validFrom").is_none());
1885        let timed = chain_capability(&g, true).unwrap();
1886        assert_eq!(timed["validUntil"], json!("2026-11-11T00:00:00Z"));
1887    }
1888
1889    #[test]
1890    fn python_repr_of_quoted_values() {
1891        assert_eq!(py_repr_str("did:web:a"), "'did:web:a'");
1892        assert_eq!(py_repr_str("it's"), "\"it's\"");
1893        assert_eq!(py_repr_str("a'b\"c"), "'a\\'b\"c'");
1894        assert_eq!(py_repr_str("a\\b\n\u{1}"), "'a\\\\b\\n\\x01'");
1895        assert_eq!(py_repr(None), "None");
1896        assert_eq!(py_repr(Some(&json!(["x", 1]))), "['x', 1]");
1897        // Every character Python's isprintable() rejects is escaped, in the
1898        // shortest form that holds it (repr in CPython 3.12).
1899        assert_eq!(
1900            py_repr_str(
1901                "\u{a0}\u{ad}\u{200b}\u{2028}\u{feff}\u{e000}\u{e0001}\u{10ffff} é中😀\u{3000}\u{7f}\u{1b}\u{85}"
1902            ),
1903            "'\\xa0\\xad\\u200b\\u2028\\ufeff\\ue000\\U000e0001\\U0010ffff é中😀\\u3000\\x7f\\x1b\\x85'"
1904        );
1905        assert_eq!(py_repr_str("it's \u{2029}"), "\"it's \\u2029\"");
1906        assert_eq!(py_repr_str("a\u{378}b"), "'a\\u0378b'");
1907        assert_eq!(
1908            py_repr(Some(&json!({"k\u{0}": ["\u{2066}"]}))),
1909            "{'k\\x00': ['\\u2066']}"
1910        );
1911    }
1912
1913    #[test]
1914    fn python_repr_of_numbers() {
1915        // Each JSON text read the way a verifier reads it, then written the
1916        // way Python's repr writes json.loads(text) (CPython 3.12).
1917        for (text, expected) in [
1918            ("0.0", "0.0"),
1919            ("-0.0", "-0.0"),
1920            ("1.0", "1.0"),
1921            ("-1.5", "-1.5"),
1922            ("0.1", "0.1"),
1923            ("0.30000000000000004", "0.30000000000000004"),
1924            ("100.0", "100.0"),
1925            ("1e2", "100.0"),
1926            ("0.0001", "0.0001"),
1927            ("0.00001", "1e-05"),
1928            ("1e-5", "1e-05"),
1929            ("0.000123", "0.000123"),
1930            ("9.999e-5", "9.999e-05"),
1931            ("1e-7", "1e-07"),
1932            ("123.456", "123.456"),
1933            ("9999999999999998.0", "9999999999999998.0"),
1934            ("1e16", "1e+16"),
1935            ("12345678901234567.0", "1.2345678901234568e+16"),
1936            ("1e21", "1e+21"),
1937            ("1e22", "1e+22"),
1938            ("1.5e300", "1.5e+300"),
1939            ("1.7976931348623157e308", "1.7976931348623157e+308"),
1940            ("5e-324", "5e-324"),
1941            ("2.2250738585072014e-308", "2.2250738585072014e-308"),
1942            // An exact tie between two shortest forms goes to the even digit.
1943            ("588197768793114.25", "588197768793114.2"),
1944            ("-164193784243384.125", "-164193784243384.12"),
1945            ("6.02214076e23", "6.02214076e+23"),
1946            ("-2.5e-10", "-2.5e-10"),
1947            ("4.35", "4.35"),
1948            ("1e100", "1e+100"),
1949            ("1E-100", "1e-100"),
1950            ("123e-20", "1.23e-18"),
1951            ("5", "5"),
1952            ("-7", "-7"),
1953            ("0", "0"),
1954            ("18446744073709551615", "18446744073709551615"),
1955            ("-9223372036854775808", "-9223372036854775808"),
1956            (
1957                "{\"maxSpend\": 1e-05, \"ratio\": [0.5, 1e16, 2]}",
1958                "{'maxSpend': 1e-05, 'ratio': [0.5, 1e+16, 2]}",
1959            ),
1960        ] {
1961            let value: Value = serde_json::from_str(text).unwrap();
1962            assert_eq!(py_repr(Some(&value)), expected, "{text}");
1963        }
1964        assert_eq!(py_repr_float(f64::INFINITY), "inf");
1965        assert_eq!(py_repr_float(f64::NEG_INFINITY), "-inf");
1966        assert_eq!(py_repr_float(f64::NAN), "nan");
1967    }
1968}