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