Skip to main content

vouch_core/
fleet.rs

1//! Fleet chains: credentials presented one by one, root first.
2//!
3//! A port of `vouch.fleet.verify_delegated_chain` (Python is the reference).
4//! A root identity grants a device's DID a scope; the device signs its own
5//! actions (or sub-grants) with its own key. A verifier is handed the chain as
6//! separate credentials, `[root_grant, ...sub_grants, leaf_action]`, and checks
7//! it back to a trusted root:
8//!
9//! 1. before any credential is verified or any key is looked up, from the
10//!    credentials' fields alone: every credential is a JSON object (else
11//!    `"credential {i} is not a JSON object"`), then the presented-chain
12//!    binding rule ([`crate::grant_chain::presented_chain_problem`]: binding
13//!    fields of the right shape, credential 0 a root grant, and every later
14//!    credential that carries a digest or a non-empty `delegationChain` bound
15//!    to the credential before it; else `"credential {i}: {code}"`);
16//! 2. for every credential, in order: it names an issuer, the first issuer is a
17//!    trusted root, it verifies (proof, window, and any embedded delegation
18//!    chain, with the fleet's trusted roots as that chain's trusted starting
19//!    points and their keys resolving its grants), its status when it carries
20//!    one, and neither its issuer nor its id is revoked;
21//! 3. for every adjacent pair: the parent names a delegatee, the delegatee is
22//!    not revoked, the child is issued by it, the child is no broader than the
23//!    effective capability so far (the same `capability_view` / `inherit` /
24//!    `non_expansion` rules as embedded chains, time left out), and the child's
25//!    window sits inside the parent's;
26//! 4. the leaf's intent meets the caller's exact `require_action`,
27//!    `require_target` and `require_resource`.
28//!
29//! Refusal texts match the reference byte for byte. Three differences follow
30//! from the core being stateless and offline:
31//!
32//! * revocation is a list of revoked identifiers (device DIDs, credential ids),
33//!   not a callback; [`revocation_candidates`] lists every identifier the check
34//!   asks about, so a caller with a callback can build the list first;
35//! * keys come from the trusted-roots map, then from a `did:key` issuer; there
36//!   is no `did:web` resolution (put such keys in the map);
37//! * a credential (or an embedded grant) that carries `credentialStatus` is
38//!   checked against the status lists the caller supplies; with none supplied it
39//!   is refused, as the reference refuses it offline. `check_status: false`
40//!   skips the status check, as `check_status=False` does in the reference.
41//!
42//! The leaf is returned so the caller can mark it in its replay store; the core
43//! keeps no replay state.
44
45use std::collections::BTreeMap;
46
47use serde_json::{json, Map, Value};
48
49use crate::attenuation;
50use crate::credentials;
51use crate::delegation::{self, ChainOptions};
52use crate::grant_chain::{self, py_repr, py_repr_str, truthy};
53use crate::hybrid;
54use crate::status_list;
55use crate::time::parse_protocol_time_ns;
56
57/// How a fleet chain is verified.
58#[derive(Debug, Clone, Copy)]
59pub struct FleetOptions<'a> {
60    /// The accepted roots: DID to Ed25519 public key. The first credential's
61    /// issuer must be here. Its DIDs are the trusted starting points of any
62    /// embedded delegation chain, and its keys resolve later issuers and
63    /// embedded grants before a `did:key` is decoded.
64    pub trusted_roots: &'a BTreeMap<String, Vec<u8>>,
65    /// Revoked identifiers: device DIDs and credential ids. A chain whose
66    /// issuer, credential id or delegatee is listed is refused.
67    pub revoked: &'a [String],
68    /// The current instant (protocol time).
69    pub now_iso: &'a str,
70    /// The allowed clock drift, 0 to 120 seconds.
71    pub clock_skew_seconds: i64,
72    /// An exact `intent.action` the leaf must carry.
73    pub require_action: Option<&'a str>,
74    /// An exact `intent.target` the leaf must carry.
75    pub require_target: Option<&'a str>,
76    /// An exact `intent.resource` the leaf must carry.
77    pub require_resource: Option<&'a str>,
78    /// Check the `credentialStatus` of every credential and embedded grant
79    /// that carries one (the reference's default).
80    pub check_status: bool,
81    /// The status lists the caller fetched, keyed by `statusListCredential`
82    /// URL. `None` refuses any credential that carries a status entry while
83    /// `check_status` is on.
84    pub status_lists: Option<&'a Map<String, Value>>,
85}
86
87/// The outcome of verifying a fleet chain.
88#[derive(Debug, Clone, PartialEq)]
89pub struct FleetResult {
90    /// True only when every check passes.
91    pub ok: bool,
92    /// The first check that failed.
93    pub reason: Option<String>,
94    /// The leaf credential: on success, and when only the leaf policy failed.
95    pub leaf: Option<Value>,
96    /// The root issuer, on success.
97    pub root_did: Option<String>,
98}
99
100impl FleetResult {
101    fn fail(reason: String) -> Self {
102        FleetResult {
103            ok: false,
104            reason: Some(reason),
105            leaf: None,
106            root_did: None,
107        }
108    }
109
110    /// The result as JSON: `{"ok", "reason", "leaf", "rootDid"}`.
111    pub fn to_json(&self) -> Value {
112        json!({
113            "ok": self.ok,
114            "reason": self.reason,
115            "leaf": self.leaf,
116            "rootDid": self.root_did,
117        })
118    }
119}
120
121/// The issuer the reference reads (`_issuer_of`): the `issuer` string, the
122/// first entry of an issuer list, or the `id` of an issuer object.
123fn issuer_of(cred: &Value) -> Option<String> {
124    let issuer = match cred.get("issuer") {
125        Some(Value::Array(items)) => items.first(),
126        Some(Value::Object(o)) => o.get("id"),
127        other => other,
128    };
129    issuer
130        .and_then(Value::as_str)
131        .filter(|s| !s.is_empty())
132        .map(String::from)
133}
134
135fn intent_of(cred: &Value) -> Option<&Map<String, Value>> {
136    cred.get("credentialSubject")
137        .and_then(|s| s.get("intent"))
138        .and_then(Value::as_object)
139}
140
141/// The proof is a proof set or the earlier composite proof: both need an
142/// ML-DSA-44 key.
143fn post_quantum_proof(cred: &Value) -> bool {
144    match cred.get("proof") {
145        Some(Value::Array(_)) => true,
146        Some(p) => {
147            p.get("cryptosuite").and_then(Value::as_str)
148                == Some(hybrid::HYBRID_COMPOSITE_CRYPTOSUITE_ID)
149        }
150        None => false,
151    }
152}
153
154/// The grants of a credential's embedded delegation chain.
155fn embedded_grants(cred: &Value) -> Vec<&Value> {
156    cred.get("credentialSubject")
157        .and_then(|s| s.get("delegationChain"))
158        .and_then(Value::as_array)
159        .map(|links| {
160            links
161                .iter()
162                .filter_map(|l| l.get("parentCredential").filter(|g| g.is_object()))
163                .collect()
164        })
165        .unwrap_or_default()
166}
167
168/// The status of a credential and of every grant in its embedded chain, each
169/// against a list signed by that credential's issuer. True when acceptable.
170fn status_ok(cred: &Value, cred_key: &[u8], opts: &FleetOptions) -> bool {
171    let mut checked: Vec<(&Value, Option<Vec<u8>>)> = vec![(cred, Some(cred_key.to_vec()))];
172    for grant in embedded_grants(cred) {
173        let key = issuer_of(grant).and_then(|i| opts.trusted_roots.get(&i).cloned());
174        checked.push((grant, key));
175    }
176    for (c, key) in checked {
177        if c.get("credentialStatus").is_none() {
178            continue;
179        }
180        let Some(lists) = opts.status_lists else {
181            // Offline means no fetch: a status that cannot be read is not a
182            // good status.
183            return false;
184        };
185        match status_list::check_credential_status(
186            c,
187            lists,
188            key.as_deref(),
189            None,
190            opts.now_iso,
191            opts.clock_skew_seconds,
192        ) {
193            Ok(r) if r.ok => {}
194            _ => return false,
195        }
196    }
197    true
198}
199
200/// True if the child's validity window sits inside the parent's.
201fn window_within(child: &Value, parent: &Value) -> bool {
202    let t = |c: &Value, k: &str| {
203        c.get(k)
204            .and_then(Value::as_str)
205            .and_then(|s| parse_protocol_time_ns(s).ok())
206    };
207    match (
208        t(child, "validFrom"),
209        t(child, "validUntil"),
210        t(parent, "validFrom"),
211        t(parent, "validUntil"),
212    ) {
213        (Some(cf), Some(cu), Some(pf), Some(pu)) => cf >= pf && cu <= pu,
214        _ => false,
215    }
216}
217
218/// Every identifier the revocation check asks about, in the order it asks:
219/// each credential's issuer and id, and each credential's delegatee. A caller
220/// with a revocation callback passes the ones it reports as revoked.
221pub fn revocation_candidates(credentials: &[Value]) -> Vec<String> {
222    let mut out: Vec<String> = Vec::new();
223    let mut push = |s: Option<String>| {
224        if let Some(s) = s.filter(|s| !s.is_empty()) {
225            if !out.contains(&s) {
226                out.push(s);
227            }
228        }
229    };
230    for cred in credentials {
231        push(issuer_of(cred));
232        push(cred.get("id").and_then(Value::as_str).map(String::from));
233    }
234    for cred in credentials {
235        push(
236            intent_of(cred)
237                .and_then(|i| i.get("delegatee"))
238                .and_then(Value::as_str)
239                .map(String::from),
240        );
241    }
242    out
243}
244
245/// Verify a fleet chain: credentials presented one by one, root grant first,
246/// leaf action last. See the module documentation for every check, in order.
247pub fn verify_delegated_chain(credentials: &[Value], opts: &FleetOptions) -> FleetResult {
248    if credentials.is_empty() {
249        return FleetResult::fail("empty chain".into());
250    }
251    for (index, cred) in credentials.iter().enumerate() {
252        if !cred.is_object() {
253            return FleetResult::fail(format!("credential {index} is not a JSON object"));
254        }
255    }
256    // Every credential is bound to the one above it: checked from the
257    // credentials alone, before any key is looked up.
258    if let Some((index, code)) = grant_chain::presented_chain_problem(credentials) {
259        return FleetResult::fail(format!("credential {index}: {code}"));
260    }
261    let is_revoked = |id: &str| opts.revoked.iter().any(|r| r == id);
262    let root_dids: Vec<String> = opts.trusted_roots.keys().cloned().collect();
263    // The embedded delegation chain starts at the fleet's root, so the fleet's
264    // trusted roots are the chain's trusted starting points.
265    let chain_opts = ChainOptions {
266        trusted_roots: Some(&root_dids),
267        grant_keys: Some(opts.trusted_roots),
268        ..Default::default()
269    };
270
271    let mut issuers: Vec<String> = Vec::with_capacity(credentials.len());
272    for (index, cred) in credentials.iter().enumerate() {
273        let Some(issuer) = issuer_of(cred) else {
274            return FleetResult::fail(format!("credential {index} has no issuer"));
275        };
276        // The root anchor must be explicitly trusted. Later links resolve
277        // their key from the trusted roots if present, otherwise by DID.
278        let given = opts.trusted_roots.get(&issuer);
279        if index == 0 && given.is_none() {
280            return FleetResult::fail(format!(
281                "root issuer {} is not in trusted_roots",
282                py_repr_str(&issuer)
283            ));
284        }
285        let key = match given {
286            Some(k) => Some(k.clone()),
287            None => crate::keys::did_key_to_ed25519(&issuer).ok(),
288        };
289        let failed = || FleetResult::fail(format!("credential {index} failed verification"));
290        let Some(key) = key else {
291            return failed();
292        };
293        let verdict = credentials::verify_with_keys(
294            cred,
295            &key,
296            None,
297            opts.now_iso,
298            opts.clock_skew_seconds,
299            &chain_opts,
300        );
301        match verdict {
302            Ok((r, _)) if r.is_valid() => {}
303            Ok((r, _)) => {
304                // A post-quantum proof with only an Ed25519 key given for its
305                // issuer: the reference raises MissingMLDSA44KeyError.
306                if given.is_some() && r.time_valid && !r.proof_valid && post_quantum_proof(cred) {
307                    return FleetResult::fail(format!("credential {index} needs an ML-DSA-44 key"));
308                }
309                return failed();
310            }
311            Err(_) => return failed(),
312        }
313        if opts.check_status && !status_ok(cred, &key, opts) {
314            return failed();
315        }
316
317        // Revocation: a revoked issuer (device or root) or a revoked specific
318        // credential breaks the chain.
319        if is_revoked(&issuer) {
320            return FleetResult::fail(format!(
321                "credential {index} issuer {} is revoked",
322                py_repr_str(&issuer)
323            ));
324        }
325        if let Some(id) = cred.get("id").filter(|v| truthy(Some(v))) {
326            if id.as_str().is_some_and(is_revoked) {
327                let shown = id
328                    .as_str()
329                    .map(String::from)
330                    .unwrap_or_else(|| id.to_string());
331                return FleetResult::fail(format!("credential {index} ({shown}) is revoked"));
332            }
333        }
334        issuers.push(issuer);
335    }
336
337    // Walk parent -> child links, comparing each child against its parent's
338    // effective capability (dimensions a grant omits are inherited).
339    let mut effective = delegation::capability_view(&credentials[0], false);
340    for i in 0..credentials.len() - 1 {
341        let (parent, child) = (&credentials[i], &credentials[i + 1]);
342        let parent_intent = intent_of(parent);
343        let delegatee = parent_intent.and_then(|it| it.get("delegatee"));
344        if !truthy(delegatee) {
345            return FleetResult::fail(format!(
346                "link {i} (grant by {}) names no delegatee",
347                py_repr_str(&issuers[i])
348            ));
349        }
350        if delegatee.and_then(Value::as_str).is_some_and(is_revoked) {
351            return FleetResult::fail(format!(
352                "link {i}: delegatee {} is revoked",
353                py_repr(delegatee)
354            ));
355        }
356        if delegatee.and_then(Value::as_str) != Some(issuers[i + 1].as_str()) {
357            return FleetResult::fail(format!(
358                "link {i}: child issuer {} is not the delegatee {} the parent authorized",
359                py_repr_str(&issuers[i + 1]),
360                py_repr(delegatee)
361            ));
362        }
363
364        let child_view = delegation::capability_view(child, false);
365        let dimension = attenuation::non_expansion(&effective, &child_view);
366        effective = attenuation::inherit(&effective, &child_view);
367        if let Err(dim) = dimension {
368            let name = dim.as_str();
369            let granted = parent_intent.and_then(|it| it.get(name));
370            let asked = intent_of(child).and_then(|it| it.get(name));
371            return FleetResult::fail(format!(
372                "link {i}: {name} {} is not within the granted {}",
373                py_repr(asked),
374                py_repr(granted)
375            ));
376        }
377
378        if !window_within(child, parent) {
379            return FleetResult::fail(format!(
380                "link {i}: child validity is outside the grant window"
381            ));
382        }
383    }
384
385    let leaf = &credentials[credentials.len() - 1];
386    let leaf_intent = intent_of(leaf);
387    for (field, expected) in [
388        ("action", opts.require_action),
389        ("target", opts.require_target),
390        ("resource", opts.require_resource),
391    ] {
392        let Some(expected) = expected else { continue };
393        if leaf_intent
394            .and_then(|it| it.get(field))
395            .and_then(Value::as_str)
396            != Some(expected)
397        {
398            return FleetResult {
399                ok: false,
400                reason: Some(format!("leaf intent.{field} != {}", py_repr_str(expected))),
401                leaf: Some(leaf.clone()),
402                root_did: None,
403            };
404        }
405    }
406
407    FleetResult {
408        ok: true,
409        reason: None,
410        leaf: Some(leaf.clone()),
411        root_did: Some(issuers[0].clone()),
412    }
413}
414
415#[cfg(test)]
416mod tests {
417    use super::*;
418    use crate::credentials::{sign_sub_grant, sign_vouch_credential, BuildCredentialOptions};
419    use crate::data_integrity::BuildProofOptions;
420    use crate::keys::Ed25519KeyPair;
421
422    const NOW: &str = "2026-11-10T12:00:00Z";
423    const FROM: &str = "2026-11-10T00:00:00Z";
424    const UNTIL: &str = "2026-11-11T00:00:00Z";
425
426    struct Who {
427        seed: [u8; 32],
428        did: String,
429    }
430
431    fn key_party(n: u8) -> Who {
432        let seed = [n; 32];
433        Who {
434            seed,
435            did: Ed25519KeyPair::from_seed(&seed).did_key(),
436        }
437    }
438
439    fn web_party(n: u8, host: &str) -> Who {
440        Who {
441            seed: [n; 32],
442            did: format!("did:web:{host}"),
443        }
444    }
445
446    fn public(w: &Who) -> Vec<u8> {
447        Ed25519KeyPair::from_seed(&w.seed).public_key().to_vec()
448    }
449
450    fn intent(action: &str, target: &str, resource: &str, extra: Value) -> Value {
451        let mut i = json!({"action": action, "target": target, "resource": resource});
452        for (k, v) in extra.as_object().unwrap() {
453            i[k] = v.clone();
454        }
455        i
456    }
457
458    fn opts(
459        who: &Who,
460        intent: Value,
461        id: &str,
462        window: (&str, &str),
463        chain: Option<Vec<Value>>,
464    ) -> BuildCredentialOptions {
465        BuildCredentialOptions {
466            issuer_did: who.did.clone(),
467            credential_id: id.into(),
468            intent,
469            valid_from: window.0.into(),
470            valid_until: window.1.into(),
471            reputation_score: None,
472            delegation_chain: chain.map(Value::Array),
473            credential_status: None,
474        }
475    }
476
477    fn proof(who: &Who) -> BuildProofOptions {
478        BuildProofOptions::new(format!("{}#key-1", who.did), FROM)
479    }
480
481    fn sign(who: &Who, intent: Value, id: &str) -> Value {
482        sign_vouch_credential(
483            &opts(who, intent, id, (FROM, UNTIL), None),
484            &who.seed,
485            &proof(who),
486        )
487        .unwrap()
488    }
489
490    fn sign_window(who: &Who, intent: Value, id: &str, window: (&str, &str)) -> Value {
491        sign_vouch_credential(&opts(who, intent, id, window, None), &who.seed, &proof(who)).unwrap()
492    }
493
494    fn roots(ws: &[&Who]) -> BTreeMap<String, Vec<u8>> {
495        ws.iter().map(|w| (w.did.clone(), public(w))).collect()
496    }
497
498    fn check(
499        creds: &[Value],
500        roots: &BTreeMap<String, Vec<u8>>,
501        revoked: &[String],
502    ) -> FleetResult {
503        verify_delegated_chain(
504            creds,
505            &FleetOptions {
506                trusted_roots: roots,
507                revoked,
508                now_iso: NOW,
509                clock_skew_seconds: 30,
510                require_action: None,
511                require_target: None,
512                require_resource: None,
513                check_status: true,
514                status_lists: None,
515            },
516        )
517    }
518
519    fn reason(r: FleetResult) -> String {
520        assert!(!r.ok);
521        r.reason.unwrap()
522    }
523
524    /// root (did:web, key in the map) grants read on calendar/team to device.
525    struct Fleet {
526        root: Who,
527        device: Who,
528        impostor: Who,
529        grant: Value,
530    }
531
532    fn fleet() -> Fleet {
533        let (root, device, impostor) =
534            (web_party(31, "root.example"), key_party(32), key_party(33));
535        let grant = sign(
536            &root,
537            intent(
538                "read",
539                "calendar",
540                "https://cal.example/team",
541                json!({"delegatee": device.did, "rate": {"limit": 10, "window": "PT1H"}}),
542            ),
543            "urn:uuid:00000000-0000-4000-8000-000000000001",
544        );
545        Fleet {
546            root,
547            device,
548            impostor,
549            grant,
550        }
551    }
552
553    fn leaf_by(
554        f: &Fleet,
555        who: &Who,
556        action: &str,
557        target: &str,
558        resource: &str,
559        extra: Value,
560    ) -> Value {
561        let _ = f;
562        sign(
563            who,
564            intent(action, target, resource, extra),
565            "urn:uuid:00000000-0000-4000-8000-000000000002",
566        )
567    }
568
569    #[test]
570    fn a_narrowing_chain_verifies_and_returns_the_leaf() {
571        let f = fleet();
572        let leaf = leaf_by(
573            &f,
574            &f.device,
575            "read",
576            "calendar",
577            "https://cal.example/team/1",
578            json!({}),
579        );
580        let r = check(&[f.grant.clone(), leaf.clone()], &roots(&[&f.root]), &[]);
581        assert!(r.ok, "{:?}", r.reason);
582        assert_eq!(r.root_did.as_deref(), Some("did:web:root.example"));
583        assert_eq!(r.leaf, Some(leaf));
584        assert_eq!(r.reason, None);
585        assert_eq!(r.to_json()["ok"], json!(true));
586    }
587
588    #[test]
589    fn widening_steps_are_refused_with_the_reference_text() {
590        let f = fleet();
591        let roots = roots(&[&f.root]);
592        let cases = [
593            (
594                leaf_by(&f, &f.device, "write", "calendar", "https://cal.example/team", json!({})),
595                "link 0: action 'write' is not within the granted 'read'",
596            ),
597            (
598                leaf_by(&f, &f.device, "read", "mail", "https://cal.example/team", json!({})),
599                "link 0: target 'mail' is not within the granted 'calendar'",
600            ),
601            (
602                leaf_by(&f, &f.device, "read", "calendar", "https://cal.example/other", json!({})),
603                "link 0: resource 'https://cal.example/other' is not within the granted 'https://cal.example/team'",
604            ),
605            (
606                leaf_by(
607                    &f,
608                    &f.device,
609                    "read",
610                    "calendar",
611                    "https://cal.example/team",
612                    json!({"rate": {"limit": 100, "window": "PT1H"}}),
613                ),
614                "link 0: rate {'limit': 100, 'window': 'PT1H'} is not within the granted {'limit': 10, 'window': 'PT1H'}",
615            ),
616            (
617                // A float is quoted the way Python's repr writes it.
618                leaf_by(
619                    &f,
620                    &f.device,
621                    "read",
622                    "calendar",
623                    "https://cal.example/team",
624                    json!({"rate": {"limit": 2.5e-05, "window": "PT1H"}}),
625                ),
626                "link 0: rate {'limit': 2.5e-05, 'window': 'PT1H'} is not within the granted {'limit': 10, 'window': 'PT1H'}",
627            ),
628            (
629                leaf_by(&f, &f.device, "read", "calendar", "https://cal.example/team", json!({"rate": null})),
630                "link 0: rate None is not within the granted {'limit': 10, 'window': 'PT1H'}",
631            ),
632            (
633                leaf_by(&f, &f.device, "read", "calendar", "https://cal.example/../x", json!({})),
634                "link 0: resource 'https://cal.example/../x' is not within the granted 'https://cal.example/team'",
635            ),
636        ];
637        for (leaf, want) in cases {
638            assert_eq!(reason(check(&[f.grant.clone(), leaf], &roots, &[])), want);
639        }
640        // A list of actions is a set: one outside the grant is refused.
641        let mut body = crate::credentials::build_vouch_credential(&opts(
642            &f.device,
643            intent("read", "calendar", "https://cal.example/team", json!({})),
644            "urn:uuid:00000000-0000-4000-8000-000000000003",
645            (FROM, UNTIL),
646            None,
647        ))
648        .unwrap();
649        body["credentialSubject"]["intent"]["action"] = json!(["read", "delete"]);
650        let both_actions =
651            crate::data_integrity::sign(&body, &f.device.seed, &proof(&f.device)).unwrap();
652        assert_eq!(
653            reason(check(&[f.grant.clone(), both_actions], &roots, &[])),
654            "link 0: action ['read', 'delete'] is not within the granted 'read'"
655        );
656    }
657
658    #[test]
659    fn the_issuer_is_a_string_the_first_of_a_list_or_an_object_id() {
660        // The reference's _issuer_of, shape by shape.
661        for (issuer, expected) in [
662            (json!("did:web:a"), Some("did:web:a")),
663            (json!(["did:web:a", "did:web:b"]), Some("did:web:a")),
664            (json!({"id": "did:web:a", "name": "x"}), Some("did:web:a")),
665            (json!([]), None),
666            (json!([{"id": "did:web:a"}]), None),
667            (json!([""]), None),
668            (json!([["did:web:a"]]), None),
669            (json!([5]), None),
670            (json!({"id": 5}), None),
671            (json!({"id": ""}), None),
672            (json!({"id": ["did:web:a"]}), None),
673            (json!({}), None),
674            (json!(""), None),
675            (json!(5), None),
676            (json!(true), None),
677            (Value::Null, None),
678        ] {
679            let cred = json!({ "issuer": issuer });
680            assert_eq!(issuer_of(&cred).as_deref(), expected, "{issuer}");
681        }
682        assert_eq!(issuer_of(&json!({})), None);
683        // Anything that is no issuer is refused by name, wherever it sits.
684        let f = fleet();
685        let roots = roots(&[&f.root]);
686        let good = leaf_by(
687            &f,
688            &f.device,
689            "read",
690            "calendar",
691            "https://cal.example/team",
692            json!({}),
693        );
694        for issuer in [json!(5), json!({"id": 5}), json!([]), json!({}), json!("")] {
695            let mut grant = f.grant.clone();
696            grant["issuer"] = issuer.clone();
697            assert_eq!(
698                reason(check(&[grant, good.clone()], &roots, &[])),
699                "credential 0 has no issuer",
700                "{issuer}"
701            );
702            let mut leaf = good.clone();
703            leaf["issuer"] = issuer.clone();
704            assert_eq!(
705                reason(check(&[f.grant.clone(), leaf], &roots, &[])),
706                "credential 1 has no issuer",
707                "{issuer}"
708            );
709        }
710    }
711
712    #[test]
713    fn omitted_dimensions_are_inherited_down_the_chain() {
714        // The device passes a sub-grant on without a rate; the helper's action
715        // asks for more than the root's rate.
716        let f = fleet();
717        let helper = key_party(34);
718        let sub_intent = intent(
719            "read",
720            "calendar",
721            "https://cal.example/team",
722            json!({"delegatee": helper.did}),
723        );
724        let sub = sign_sub_grant(
725            &opts(
726                &f.device,
727                sub_intent,
728                "urn:uuid:00000000-0000-4000-8000-000000000004",
729                (FROM, UNTIL),
730                None,
731            ),
732            &grant_chain::grant_digest(&f.grant).unwrap(),
733            &f.device.seed,
734            &proof(&f.device),
735        )
736        .unwrap();
737        let ok_leaf = sign(
738            &helper,
739            intent("read", "calendar", "https://cal.example/team", json!({})),
740            "urn:uuid:00000000-0000-4000-8000-000000000005",
741        );
742        let roots = roots(&[&f.root]);
743        let r = check(&[f.grant.clone(), sub.clone(), ok_leaf], &roots, &[]);
744        assert!(r.ok, "{:?}", r.reason);
745        let greedy = sign(
746            &helper,
747            intent(
748                "read",
749                "calendar",
750                "https://cal.example/team",
751                json!({"rate": {"limit": 11, "window": "PT1H"}}),
752            ),
753            "urn:uuid:00000000-0000-4000-8000-000000000006",
754        );
755        assert_eq!(
756            reason(check(&[f.grant.clone(), sub.clone(), greedy], &roots, &[])),
757            "link 1: rate {'limit': 11, 'window': 'PT1H'} is not within the granted None"
758        );
759        // A sub-grant presented under the wrong grant fails the binding rule first.
760        let other = sign(
761            &f.root,
762            intent(
763                "read",
764                "calendar",
765                "https://cal.example/team",
766                json!({"delegatee": f.device.did}),
767            ),
768            "urn:uuid:00000000-0000-4000-8000-000000000007",
769        );
770        let leaf = sign(
771            &helper,
772            intent("read", "calendar", "https://cal.example/team", json!({})),
773            "urn:uuid:00000000-0000-4000-8000-000000000008",
774        );
775        assert_eq!(
776            reason(check(&[other, sub, leaf], &roots, &[])),
777            "credential 1: delegation_parent_mismatch"
778        );
779    }
780
781    #[test]
782    fn the_walk_checks_delegatees_revocation_and_windows() {
783        let f = fleet();
784        let roots = roots(&[&f.root]);
785        let good = leaf_by(
786            &f,
787            &f.device,
788            "read",
789            "calendar",
790            "https://cal.example/team",
791            json!({}),
792        );
793        let by_impostor = leaf_by(
794            &f,
795            &f.impostor,
796            "read",
797            "calendar",
798            "https://cal.example/team",
799            json!({}),
800        );
801        assert_eq!(
802            reason(check(&[f.grant.clone(), by_impostor.clone()], &roots, &[])),
803            format!(
804                "link 0: child issuer '{}' is not the delegatee '{}' the parent authorized",
805                f.impostor.did, f.device.did
806            )
807        );
808        // A revoked device, a revoked credential, a revoked delegatee, a revoked root.
809        assert_eq!(
810            reason(check(
811                &[f.grant.clone(), good.clone()],
812                &roots,
813                std::slice::from_ref(&f.device.did)
814            )),
815            format!("credential 1 issuer '{}' is revoked", f.device.did)
816        );
817        let leaf_id = good["id"].as_str().unwrap().to_string();
818        assert_eq!(
819            reason(check(
820                &[f.grant.clone(), good.clone()],
821                &roots,
822                std::slice::from_ref(&leaf_id)
823            )),
824            format!("credential 1 ({leaf_id}) is revoked")
825        );
826        assert_eq!(
827            reason(check(
828                &[f.grant.clone(), by_impostor],
829                &roots,
830                std::slice::from_ref(&f.device.did)
831            )),
832            format!("link 0: delegatee '{}' is revoked", f.device.did)
833        );
834        assert_eq!(
835            reason(check(
836                &[f.grant.clone(), good.clone()],
837                &roots,
838                std::slice::from_ref(&f.root.did)
839            )),
840            "credential 0 issuer 'did:web:root.example' is revoked"
841        );
842        // A leaf that outlives its grant, or starts before it.
843        let late = sign_window(
844            &f.device,
845            intent("read", "calendar", "https://cal.example/team", json!({})),
846            "urn:uuid:00000000-0000-4000-8000-000000000009",
847            (FROM, "2026-11-12T00:00:00Z"),
848        );
849        let early = sign_window(
850            &f.device,
851            intent("read", "calendar", "https://cal.example/team", json!({})),
852            "urn:uuid:00000000-0000-4000-8000-000000000010",
853            ("2026-11-09T00:00:00Z", UNTIL),
854        );
855        for leaf in [late, early] {
856            assert_eq!(
857                reason(check(&[f.grant.clone(), leaf], &roots, &[])),
858                "link 0: child validity is outside the grant window"
859            );
860        }
861        // A grant that names no delegatee.
862        let no_delegatee = sign(
863            &f.root,
864            intent("read", "calendar", "https://cal.example/team", json!({})),
865            "urn:uuid:00000000-0000-4000-8000-000000000011",
866        );
867        assert_eq!(
868            reason(check(&[no_delegatee, good], &roots, &[])),
869            "link 0 (grant by 'did:web:root.example') names no delegatee"
870        );
871    }
872
873    #[test]
874    fn trust_identity_and_proofs_come_first() {
875        let f = fleet();
876        let roots = roots(&[&f.root]);
877        let good = leaf_by(
878            &f,
879            &f.device,
880            "read",
881            "calendar",
882            "https://cal.example/team",
883            json!({}),
884        );
885        assert_eq!(reason(check(&[], &roots, &[])), "empty chain");
886        assert_eq!(
887            reason(check(
888                &[f.grant.clone(), good.clone()],
889                &BTreeMap::new(),
890                &[]
891            )),
892            "root issuer 'did:web:root.example' is not in trusted_roots"
893        );
894        // The root's key is the map's: a wrong one fails verification.
895        let mut wrong = BTreeMap::new();
896        wrong.insert(f.root.did.clone(), vec![7u8; 32]);
897        assert_eq!(
898            reason(check(&[f.grant.clone(), good.clone()], &wrong, &[])),
899            "credential 0 failed verification"
900        );
901        let mut no_issuer = good.clone();
902        no_issuer.as_object_mut().unwrap().remove("issuer");
903        assert_eq!(
904            reason(check(&[f.grant.clone(), no_issuer], &roots, &[])),
905            "credential 1 has no issuer"
906        );
907        let mut tampered = good.clone();
908        tampered["credentialSubject"]["intent"]["resource"] = json!("https://cal.example/team/2");
909        assert_eq!(
910            reason(check(&[f.grant.clone(), tampered], &roots, &[])),
911            "credential 1 failed verification"
912        );
913        // A did:web device that is not in the map cannot be resolved offline.
914        let web_device = web_party(35, "device.example");
915        let web_grant = sign(
916            &f.root,
917            intent(
918                "read",
919                "calendar",
920                "https://cal.example/team",
921                json!({"delegatee": web_device.did}),
922            ),
923            "urn:uuid:00000000-0000-4000-8000-000000000012",
924        );
925        let web_leaf = leaf_by(
926            &f,
927            &web_device,
928            "read",
929            "calendar",
930            "https://cal.example/team",
931            json!({}),
932        );
933        assert_eq!(
934            reason(check(&[web_grant.clone(), web_leaf.clone()], &roots, &[])),
935            "credential 1 failed verification"
936        );
937        let both = super::tests::roots(&[&f.root, &web_device]);
938        assert!(check(&[web_grant, web_leaf], &both, &[]).ok);
939        // The binding rule runs before the trust check.
940        let sub = sign_sub_grant(
941            &opts(
942                &f.device,
943                intent(
944                    "read",
945                    "calendar",
946                    "https://cal.example/team",
947                    json!({"delegatee": f.impostor.did}),
948                ),
949                "urn:uuid:00000000-0000-4000-8000-000000000013",
950                (FROM, UNTIL),
951                None,
952            ),
953            &grant_chain::grant_digest(&f.grant).unwrap(),
954            &f.device.seed,
955            &proof(&f.device),
956        )
957        .unwrap();
958        assert_eq!(
959            reason(check(&[sub], &BTreeMap::new(), &[])),
960            "credential 0: delegation_parent_mismatch"
961        );
962    }
963
964    #[test]
965    fn shape_and_binding_come_before_any_key() {
966        let f = fleet();
967        let roots = roots(&[&f.root]);
968        let none = BTreeMap::new();
969        let good = leaf_by(
970            &f,
971            &f.device,
972            "read",
973            "calendar",
974            "https://cal.example/team",
975            json!({}),
976        );
977        // A credential that is not a JSON object, wherever it sits, and before
978        // the trust check.
979        for (position, value) in [
980            (0, json!(f.grant.to_string())),
981            (1, Value::Null),
982            (1, json!(["x"])),
983            (2, json!(7)),
984        ] {
985            let mut creds = vec![f.grant.clone(), good.clone(), good.clone()];
986            creds[position] = value;
987            for r in [&roots, &none] {
988                assert_eq!(
989                    reason(check(&creds, r, &[])),
990                    format!("credential {position} is not a JSON object")
991                );
992            }
993        }
994        // That check runs over every credential before the binding rule.
995        let named = json!({"issuer": f.device.did,
996                           "credentialSubject": {"parentGrantDigest": "uEiA"}});
997        assert_eq!(
998            reason(check(&[named, json!("x")], &roots, &[])),
999            "credential 1 is not a JSON object"
1000        );
1001        // An older nested sub-grant made under another root's grant: refused
1002        // from its fields, with no key looked up (the roots are empty).
1003        let other = sign(
1004            &f.impostor,
1005            intent(
1006                "read",
1007                "calendar",
1008                "https://cal.example/team",
1009                json!({"delegatee": f.device.did}),
1010            ),
1011            "urn:uuid:00000000-0000-4000-8000-000000000020",
1012        );
1013        let link = |grant: &Value| {
1014            json!({"issuer": grant["issuer"], "subject": f.device.did,
1015                   "parentCredential": grant})
1016        };
1017        let nested = json!({"issuer": f.device.did, "credentialSubject": {
1018            "intent": {"action": "read", "delegatee": f.impostor.did},
1019            "delegationChain": [link(&other)]}});
1020        assert_eq!(
1021            reason(check(
1022                &[f.grant.clone(), nested.clone(), good.clone()],
1023                &none,
1024                &[]
1025            )),
1026            "credential 1: delegation_parent_mismatch"
1027        );
1028        // An action that embeds a chain ending somewhere else.
1029        let elsewhere = json!({"issuer": f.device.did, "credentialSubject": {
1030            "intent": {"action": "read"}, "delegationChain": [link(&other)]}});
1031        assert_eq!(
1032            reason(check(&[f.grant.clone(), elsewhere], &none, &[])),
1033            "credential 1: delegation_parent_mismatch"
1034        );
1035        // Binding fields of the wrong shape.
1036        for subject in [
1037            json!({"delegationChain": null}),
1038            json!({"delegationChain": {}}),
1039            json!({"parentGrantDigest": null}),
1040            json!({"parentGrantDigest": grant_chain::grant_digest(&f.grant).unwrap(),
1041                   "delegationChain": [link(&f.grant)]}),
1042        ] {
1043            let sub = json!({"issuer": f.device.did, "credentialSubject": subject});
1044            assert_eq!(
1045                reason(check(&[f.grant.clone(), sub, good.clone()], &none, &[])),
1046                "credential 1: malformed_delegation"
1047            );
1048        }
1049    }
1050
1051    #[test]
1052    fn a_post_quantum_root_grant_needs_its_mldsa_key() {
1053        let f = fleet();
1054        let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
1055        let body = crate::credentials::build_vouch_credential(&opts(
1056            &f.root,
1057            intent(
1058                "read",
1059                "calendar",
1060                "https://cal.example/team",
1061                json!({"delegatee": f.device.did}),
1062            ),
1063            "urn:uuid:00000000-0000-4000-8000-000000000014",
1064            (FROM, UNTIL),
1065            None,
1066        ))
1067        .unwrap();
1068        let dual = hybrid::sign_dual(
1069            &body,
1070            &f.root.seed,
1071            &ml,
1072            &format!("{}#key-1", f.root.did),
1073            &format!("{}#mldsa", f.root.did),
1074            FROM,
1075        )
1076        .unwrap();
1077        let good = leaf_by(
1078            &f,
1079            &f.device,
1080            "read",
1081            "calendar",
1082            "https://cal.example/team",
1083            json!({}),
1084        );
1085        assert_eq!(
1086            reason(check(&[dual, good], &roots(&[&f.root]), &[])),
1087            "credential 0 needs an ML-DSA-44 key"
1088        );
1089    }
1090
1091    #[test]
1092    fn leaf_policy_and_status() {
1093        let f = fleet();
1094        let roots = roots(&[&f.root]);
1095        let good = leaf_by(
1096            &f,
1097            &f.device,
1098            "read",
1099            "calendar",
1100            "https://cal.example/team/1",
1101            json!({}),
1102        );
1103        let creds = [f.grant.clone(), good.clone()];
1104        let with = |action: Option<&str>, target: Option<&str>, resource: Option<&str>| {
1105            verify_delegated_chain(
1106                &creds,
1107                &FleetOptions {
1108                    trusted_roots: &roots,
1109                    revoked: &[],
1110                    now_iso: NOW,
1111                    clock_skew_seconds: 30,
1112                    require_action: action,
1113                    require_target: target,
1114                    require_resource: resource,
1115                    check_status: true,
1116                    status_lists: None,
1117                },
1118            )
1119        };
1120        assert!(
1121            with(
1122                Some("read"),
1123                Some("calendar"),
1124                Some("https://cal.example/team/1")
1125            )
1126            .ok
1127        );
1128        for (r, want) in [
1129            (
1130                with(Some("write"), None, None),
1131                "leaf intent.action != 'write'",
1132            ),
1133            (
1134                with(None, Some("mail"), None),
1135                "leaf intent.target != 'mail'",
1136            ),
1137            (
1138                with(None, None, Some("https://cal.example/team")),
1139                "leaf intent.resource != 'https://cal.example/team'",
1140            ),
1141        ] {
1142            assert!(!r.ok);
1143            assert_eq!(r.leaf.as_ref(), Some(&good));
1144            assert_eq!(r.root_did, None);
1145            assert_eq!(r.reason.as_deref(), Some(want));
1146        }
1147        // A grant that carries a status entry: refused with no status lists
1148        // (offline), accepted when the status check is turned off.
1149        let status = json!({"id": "https://status.example/1#5", "type": "BitstringStatusListEntry",
1150            "statusPurpose": "revocation", "statusListIndex": "5",
1151            "statusListCredential": "https://status.example/1"});
1152        let mut o = opts(
1153            &f.root,
1154            intent(
1155                "read",
1156                "calendar",
1157                "https://cal.example/team",
1158                json!({"delegatee": f.device.did}),
1159            ),
1160            "urn:uuid:00000000-0000-4000-8000-000000000015",
1161            (FROM, UNTIL),
1162            None,
1163        );
1164        o.credential_status = Some(status);
1165        let with_status = sign_vouch_credential(&o, &f.root.seed, &proof(&f.root)).unwrap();
1166        let creds = [with_status, good];
1167        let base = FleetOptions {
1168            trusted_roots: &roots,
1169            revoked: &[],
1170            now_iso: NOW,
1171            clock_skew_seconds: 30,
1172            require_action: None,
1173            require_target: None,
1174            require_resource: None,
1175            check_status: true,
1176            status_lists: None,
1177        };
1178        assert_eq!(
1179            verify_delegated_chain(&creds, &base).reason.as_deref(),
1180            Some("credential 0 failed verification")
1181        );
1182        let empty = Map::new();
1183        let listed = FleetOptions {
1184            status_lists: Some(&empty),
1185            ..base
1186        };
1187        assert_eq!(
1188            verify_delegated_chain(&creds, &listed).reason.as_deref(),
1189            Some("credential 0 failed verification")
1190        );
1191        let unchecked = FleetOptions {
1192            check_status: false,
1193            ..base
1194        };
1195        assert!(verify_delegated_chain(&creds, &unchecked).ok);
1196    }
1197
1198    #[test]
1199    fn embedded_chains_start_at_the_fleet_roots() {
1200        // A leaf that carries the chain above it (signed under the grant)
1201        // verifies with the fleet's root as its trusted start and the map's
1202        // key for the did:web root grant.
1203        let f = fleet();
1204        let leaf_intent = intent("read", "calendar", "https://cal.example/team", json!({}));
1205        let links =
1206            grant_chain::check_grant_chain(std::slice::from_ref(&f.grant), &leaf_intent).unwrap();
1207        let leaf = sign_vouch_credential(
1208            &opts(
1209                &f.device,
1210                leaf_intent,
1211                "urn:uuid:00000000-0000-4000-8000-000000000016",
1212                (FROM, UNTIL),
1213                Some(links),
1214            ),
1215            &f.device.seed,
1216            &proof(&f.device),
1217        )
1218        .unwrap();
1219        assert!(check(&[f.grant.clone(), leaf.clone()], &roots(&[&f.root]), &[]).ok);
1220        // A different fleet root is not this chain's start.
1221        let other = web_party(36, "other.example");
1222        let mut two = roots(&[&f.root]);
1223        two.insert(other.did.clone(), public(&other));
1224        assert!(check(&[f.grant.clone(), leaf.clone()], &two, &[]).ok);
1225        let mut wrong_key = roots(&[&f.root]);
1226        wrong_key.insert(f.root.did.clone(), public(&other));
1227        assert_eq!(
1228            reason(check(&[f.grant.clone(), leaf], &wrong_key, &[])),
1229            "credential 0 failed verification"
1230        );
1231    }
1232
1233    #[test]
1234    fn revocation_candidates_cover_every_identifier_asked_about() {
1235        let f = fleet();
1236        let good = leaf_by(
1237            &f,
1238            &f.device,
1239            "read",
1240            "calendar",
1241            "https://cal.example/team",
1242            json!({}),
1243        );
1244        assert_eq!(
1245            revocation_candidates(&[f.grant.clone(), good]),
1246            vec![
1247                "did:web:root.example".to_string(),
1248                "urn:uuid:00000000-0000-4000-8000-000000000001".to_string(),
1249                f.device.did.clone(),
1250                "urn:uuid:00000000-0000-4000-8000-000000000002".to_string(),
1251            ]
1252        );
1253        assert!(
1254            revocation_candidates(&[json!("x"), json!({"issuer": ["did:web:a"]})])
1255                .contains(&"did:web:a".to_string())
1256        );
1257    }
1258}