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