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::status_list;
54use crate::time::parse_protocol_time_ns;
55
56/// How a fleet chain is verified.
57#[derive(Debug, Clone, Copy)]
58pub struct FleetOptions<'a> {
59    /// The accepted roots: DID to Ed25519 public key. The first credential's
60    /// issuer must be here. Its DIDs are the trusted starting points of any
61    /// embedded delegation chain, and its keys resolve later issuers and
62    /// embedded grants before a `did:key` is decoded.
63    pub trusted_roots: &'a BTreeMap<String, Vec<u8>>,
64    /// Revoked identifiers: device DIDs and credential ids. A chain whose
65    /// issuer, credential id or delegatee is listed is refused.
66    pub revoked: &'a [String],
67    /// The current instant (protocol time).
68    pub now_iso: &'a str,
69    /// The allowed clock drift, 0 to 120 seconds.
70    pub clock_skew_seconds: i64,
71    /// An exact `intent.action` the leaf must carry.
72    pub require_action: Option<&'a str>,
73    /// An exact `intent.target` the leaf must carry.
74    pub require_target: Option<&'a str>,
75    /// An exact `intent.resource` the leaf must carry.
76    pub require_resource: Option<&'a str>,
77    /// Check the `credentialStatus` of every credential and embedded grant
78    /// that carries one (the reference's default).
79    pub check_status: bool,
80    /// The status lists the caller fetched, keyed by `statusListCredential`
81    /// URL. `None` refuses any credential that carries a status entry while
82    /// `check_status` is on.
83    pub status_lists: Option<&'a Map<String, Value>>,
84}
85
86/// The outcome of verifying a fleet chain.
87#[derive(Debug, Clone, PartialEq)]
88pub struct FleetResult {
89    /// True only when every check passes.
90    pub ok: bool,
91    /// The first check that failed.
92    pub reason: Option<String>,
93    /// The leaf credential: on success, and when only the leaf policy failed.
94    pub leaf: Option<Value>,
95    /// The root issuer, on success.
96    pub root_did: Option<String>,
97}
98
99impl FleetResult {
100    fn fail(reason: String) -> Self {
101        FleetResult {
102            ok: false,
103            reason: Some(reason),
104            leaf: None,
105            root_did: None,
106        }
107    }
108
109    /// The result as JSON: `{"ok", "reason", "leaf", "rootDid"}`.
110    pub fn to_json(&self) -> Value {
111        json!({
112            "ok": self.ok,
113            "reason": self.reason,
114            "leaf": self.leaf,
115            "rootDid": self.root_did,
116        })
117    }
118}
119
120/// The issuer the reference reads (`_issuer_of`): the `issuer` string, the
121/// first entry of an issuer list, or the `id` of an issuer object.
122fn issuer_of(cred: &Value) -> Option<String> {
123    let issuer = match cred.get("issuer") {
124        Some(Value::Array(items)) => items.first(),
125        Some(Value::Object(o)) => o.get("id"),
126        other => other,
127    };
128    issuer
129        .and_then(Value::as_str)
130        .filter(|s| !s.is_empty())
131        .map(String::from)
132}
133
134fn intent_of(cred: &Value) -> Option<&Map<String, Value>> {
135    cred.get("credentialSubject")
136        .and_then(|s| s.get("intent"))
137        .and_then(Value::as_object)
138}
139
140/// The proof is a proof set, which needs a post-quantum key. (One proof
141/// object is an eddsa-jcs-2022 proof or it is refused: the earlier composite
142/// proof is no longer read.)
143fn post_quantum_proof(cred: &Value) -> bool {
144    matches!(cred.get("proof"), Some(Value::Array(_)))
145}
146
147/// The grants of a credential's embedded delegation chain.
148fn embedded_grants(cred: &Value) -> Vec<&Value> {
149    cred.get("credentialSubject")
150        .and_then(|s| s.get("delegationChain"))
151        .and_then(Value::as_array)
152        .map(|links| {
153            links
154                .iter()
155                .filter_map(|l| l.get("parentCredential").filter(|g| g.is_object()))
156                .collect()
157        })
158        .unwrap_or_default()
159}
160
161/// The status of a credential and of every grant in its embedded chain, each
162/// against a list signed by that credential's issuer. True when acceptable.
163fn status_ok(cred: &Value, cred_key: &[u8], opts: &FleetOptions) -> bool {
164    let mut checked: Vec<(&Value, Option<Vec<u8>>)> = vec![(cred, Some(cred_key.to_vec()))];
165    for grant in embedded_grants(cred) {
166        let key = issuer_of(grant).and_then(|i| opts.trusted_roots.get(&i).cloned());
167        checked.push((grant, key));
168    }
169    for (c, key) in checked {
170        if c.get("credentialStatus").is_none() {
171            continue;
172        }
173        let Some(lists) = opts.status_lists else {
174            // Offline means no fetch: a status that cannot be read is not a
175            // good status.
176            return false;
177        };
178        match status_list::check_credential_status(
179            c,
180            lists,
181            key.as_deref(),
182            None,
183            opts.now_iso,
184            opts.clock_skew_seconds,
185        ) {
186            Ok(r) if r.ok => {}
187            _ => return false,
188        }
189    }
190    true
191}
192
193/// True if the child's validity window sits inside the parent's.
194fn window_within(child: &Value, parent: &Value) -> bool {
195    let t = |c: &Value, k: &str| {
196        c.get(k)
197            .and_then(Value::as_str)
198            .and_then(|s| parse_protocol_time_ns(s).ok())
199    };
200    match (
201        t(child, "validFrom"),
202        t(child, "validUntil"),
203        t(parent, "validFrom"),
204        t(parent, "validUntil"),
205    ) {
206        (Some(cf), Some(cu), Some(pf), Some(pu)) => cf >= pf && cu <= pu,
207        _ => false,
208    }
209}
210
211/// Every identifier the revocation check asks about, in the order it asks:
212/// each credential's issuer and id, and each credential's delegatee. A caller
213/// with a revocation callback passes the ones it reports as revoked.
214pub fn revocation_candidates(credentials: &[Value]) -> Vec<String> {
215    let mut out: Vec<String> = Vec::new();
216    let mut push = |s: Option<String>| {
217        if let Some(s) = s.filter(|s| !s.is_empty()) {
218            if !out.contains(&s) {
219                out.push(s);
220            }
221        }
222    };
223    for cred in credentials {
224        push(issuer_of(cred));
225        push(cred.get("id").and_then(Value::as_str).map(String::from));
226    }
227    for cred in credentials {
228        push(
229            intent_of(cred)
230                .and_then(|i| i.get("delegatee"))
231                .and_then(Value::as_str)
232                .map(String::from),
233        );
234    }
235    out
236}
237
238/// Verify a fleet chain: credentials presented one by one, root grant first,
239/// leaf action last. See the module documentation for every check, in order.
240pub fn verify_delegated_chain(credentials: &[Value], opts: &FleetOptions) -> FleetResult {
241    if credentials.is_empty() {
242        return FleetResult::fail("empty chain".into());
243    }
244    for (index, cred) in credentials.iter().enumerate() {
245        if !cred.is_object() {
246            return FleetResult::fail(format!("credential {index} is not a JSON object"));
247        }
248    }
249    // Every credential is bound to the one above it: checked from the
250    // credentials alone, before any key is looked up.
251    if let Some((index, code)) = grant_chain::presented_chain_problem(credentials) {
252        return FleetResult::fail(format!("credential {index}: {code}"));
253    }
254    let is_revoked = |id: &str| opts.revoked.iter().any(|r| r == id);
255    let root_dids: Vec<String> = opts.trusted_roots.keys().cloned().collect();
256    // The embedded delegation chain starts at the fleet's root, so the fleet's
257    // trusted roots are the chain's trusted starting points.
258    let chain_opts = ChainOptions {
259        trusted_roots: Some(&root_dids),
260        grant_keys: Some(opts.trusted_roots),
261        ..Default::default()
262    };
263
264    let mut issuers: Vec<String> = Vec::with_capacity(credentials.len());
265    for (index, cred) in credentials.iter().enumerate() {
266        let Some(issuer) = issuer_of(cred) else {
267            return FleetResult::fail(format!("credential {index} has no issuer"));
268        };
269        // The root anchor must be explicitly trusted. Later links resolve
270        // their key from the trusted roots if present, otherwise by DID.
271        let given = opts.trusted_roots.get(&issuer);
272        if index == 0 && given.is_none() {
273            return FleetResult::fail(format!(
274                "root issuer {} is not in trusted_roots",
275                py_repr_str(&issuer)
276            ));
277        }
278        let key = match given {
279            Some(k) => Some(k.clone()),
280            None => crate::keys::did_key_to_ed25519(&issuer).ok(),
281        };
282        let failed = || FleetResult::fail(format!("credential {index} failed verification"));
283        let Some(key) = key else {
284            return failed();
285        };
286        let verdict = credentials::verify_with_keys(
287            cred,
288            &key,
289            None,
290            opts.now_iso,
291            opts.clock_skew_seconds,
292            &chain_opts,
293        );
294        match verdict {
295            Ok((r, _)) if r.is_valid() => {}
296            Ok((r, _)) => {
297                // A post-quantum proof with only an Ed25519 key given for its
298                // issuer: the reference raises MissingMLDSA44KeyError, once
299                // the key is a usable Ed25519 key (an unusable one fails first).
300                if given.is_some()
301                    && crate::keys::strict_verifying_key(&key).is_ok()
302                    && r.time_valid
303                    && !r.proof_valid
304                    && post_quantum_proof(cred)
305                {
306                    return FleetResult::fail(format!("credential {index} needs an ML-DSA-44 key"));
307                }
308                return failed();
309            }
310            Err(_) => return failed(),
311        }
312        if opts.check_status && !status_ok(cred, &key, opts) {
313            return failed();
314        }
315
316        // Revocation: a revoked issuer (device or root) or a revoked specific
317        // credential breaks the chain.
318        if is_revoked(&issuer) {
319            return FleetResult::fail(format!(
320                "credential {index} issuer {} is revoked",
321                py_repr_str(&issuer)
322            ));
323        }
324        if let Some(id) = cred.get("id").filter(|v| truthy(Some(v))) {
325            if id.as_str().is_some_and(is_revoked) {
326                let shown = id
327                    .as_str()
328                    .map(String::from)
329                    .unwrap_or_else(|| id.to_string());
330                return FleetResult::fail(format!("credential {index} ({shown}) is revoked"));
331            }
332        }
333        issuers.push(issuer);
334    }
335
336    // Walk parent -> child links, comparing each child against its parent's
337    // effective capability (dimensions a grant omits are inherited).
338    let mut effective = delegation::capability_view(&credentials[0], false);
339    for i in 0..credentials.len() - 1 {
340        let (parent, child) = (&credentials[i], &credentials[i + 1]);
341        let parent_intent = intent_of(parent);
342        let delegatee = parent_intent.and_then(|it| it.get("delegatee"));
343        if !truthy(delegatee) {
344            return FleetResult::fail(format!(
345                "link {i} (grant by {}) names no delegatee",
346                py_repr_str(&issuers[i])
347            ));
348        }
349        if delegatee.and_then(Value::as_str).is_some_and(is_revoked) {
350            return FleetResult::fail(format!(
351                "link {i}: delegatee {} is revoked",
352                py_repr(delegatee)
353            ));
354        }
355        if delegatee.and_then(Value::as_str) != Some(issuers[i + 1].as_str()) {
356            return FleetResult::fail(format!(
357                "link {i}: child issuer {} is not the delegatee {} the parent authorized",
358                py_repr_str(&issuers[i + 1]),
359                py_repr(delegatee)
360            ));
361        }
362
363        let child_view = delegation::capability_view(child, false);
364        let dimension = attenuation::non_expansion(&effective, &child_view);
365        effective = attenuation::inherit(&effective, &child_view);
366        if let Err(dim) = dimension {
367            let name = dim.as_str();
368            let granted = parent_intent.and_then(|it| it.get(name));
369            let asked = intent_of(child).and_then(|it| it.get(name));
370            return FleetResult::fail(format!(
371                "link {i}: {name} {} is not within the granted {}",
372                py_repr(asked),
373                py_repr(granted)
374            ));
375        }
376
377        if !window_within(child, parent) {
378            return FleetResult::fail(format!(
379                "link {i}: child validity is outside the grant window"
380            ));
381        }
382    }
383
384    let leaf = &credentials[credentials.len() - 1];
385    let leaf_intent = intent_of(leaf);
386    for (field, expected) in [
387        ("action", opts.require_action),
388        ("target", opts.require_target),
389        ("resource", opts.require_resource),
390    ] {
391        let Some(expected) = expected else { continue };
392        if leaf_intent
393            .and_then(|it| it.get(field))
394            .and_then(Value::as_str)
395            != Some(expected)
396        {
397            return FleetResult {
398                ok: false,
399                reason: Some(format!("leaf intent.{field} != {}", py_repr_str(expected))),
400                leaf: Some(leaf.clone()),
401                root_did: None,
402            };
403        }
404    }
405
406    FleetResult {
407        ok: true,
408        reason: None,
409        leaf: Some(leaf.clone()),
410        root_did: Some(issuers[0].clone()),
411    }
412}
413
414#[cfg(test)]
415mod tests {
416    use super::*;
417    use crate::credentials::{sign_sub_grant, sign_vouch_credential, BuildCredentialOptions};
418    use crate::data_integrity::BuildProofOptions;
419    use crate::hybrid;
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(
1087                &[dual.clone(), good.clone()],
1088                &roots(&[&f.root]),
1089                &[]
1090            )),
1091            "credential 0 needs an ML-DSA-44 key"
1092        );
1093        // A trusted key that is not a usable Ed25519 key fails first, as in
1094        // the reference.
1095        let mut short = roots(&[&f.root]);
1096        for key in short.values_mut() {
1097            key.truncate(31);
1098        }
1099        assert_eq!(
1100            reason(check(&[dual, good], &short, &[])),
1101            "credential 0 failed verification"
1102        );
1103    }
1104
1105    #[test]
1106    fn leaf_policy_and_status() {
1107        let f = fleet();
1108        let roots = roots(&[&f.root]);
1109        let good = leaf_by(
1110            &f,
1111            &f.device,
1112            "read",
1113            "calendar",
1114            "https://cal.example/team/1",
1115            json!({}),
1116        );
1117        let creds = [f.grant.clone(), good.clone()];
1118        let with = |action: Option<&str>, target: Option<&str>, resource: Option<&str>| {
1119            verify_delegated_chain(
1120                &creds,
1121                &FleetOptions {
1122                    trusted_roots: &roots,
1123                    revoked: &[],
1124                    now_iso: NOW,
1125                    clock_skew_seconds: 30,
1126                    require_action: action,
1127                    require_target: target,
1128                    require_resource: resource,
1129                    check_status: true,
1130                    status_lists: None,
1131                },
1132            )
1133        };
1134        assert!(
1135            with(
1136                Some("read"),
1137                Some("calendar"),
1138                Some("https://cal.example/team/1")
1139            )
1140            .ok
1141        );
1142        for (r, want) in [
1143            (
1144                with(Some("write"), None, None),
1145                "leaf intent.action != 'write'",
1146            ),
1147            (
1148                with(None, Some("mail"), None),
1149                "leaf intent.target != 'mail'",
1150            ),
1151            (
1152                with(None, None, Some("https://cal.example/team")),
1153                "leaf intent.resource != 'https://cal.example/team'",
1154            ),
1155        ] {
1156            assert!(!r.ok);
1157            assert_eq!(r.leaf.as_ref(), Some(&good));
1158            assert_eq!(r.root_did, None);
1159            assert_eq!(r.reason.as_deref(), Some(want));
1160        }
1161        // A grant that carries a status entry: refused with no status lists
1162        // (offline), accepted when the status check is turned off.
1163        let status = json!({"id": "https://status.example/1#5", "type": "BitstringStatusListEntry",
1164            "statusPurpose": "revocation", "statusListIndex": "5",
1165            "statusListCredential": "https://status.example/1"});
1166        let mut o = opts(
1167            &f.root,
1168            intent(
1169                "read",
1170                "calendar",
1171                "https://cal.example/team",
1172                json!({"delegatee": f.device.did}),
1173            ),
1174            "urn:uuid:00000000-0000-4000-8000-000000000015",
1175            (FROM, UNTIL),
1176            None,
1177        );
1178        o.credential_status = Some(status);
1179        let with_status = sign_vouch_credential(&o, &f.root.seed, &proof(&f.root)).unwrap();
1180        let creds = [with_status, good];
1181        let base = FleetOptions {
1182            trusted_roots: &roots,
1183            revoked: &[],
1184            now_iso: NOW,
1185            clock_skew_seconds: 30,
1186            require_action: None,
1187            require_target: None,
1188            require_resource: None,
1189            check_status: true,
1190            status_lists: None,
1191        };
1192        assert_eq!(
1193            verify_delegated_chain(&creds, &base).reason.as_deref(),
1194            Some("credential 0 failed verification")
1195        );
1196        let empty = Map::new();
1197        let listed = FleetOptions {
1198            status_lists: Some(&empty),
1199            ..base
1200        };
1201        assert_eq!(
1202            verify_delegated_chain(&creds, &listed).reason.as_deref(),
1203            Some("credential 0 failed verification")
1204        );
1205        let unchecked = FleetOptions {
1206            check_status: false,
1207            ..base
1208        };
1209        assert!(verify_delegated_chain(&creds, &unchecked).ok);
1210    }
1211
1212    #[test]
1213    fn embedded_chains_start_at_the_fleet_roots() {
1214        // A leaf that carries the chain above it (signed under the grant)
1215        // verifies with the fleet's root as its trusted start and the map's
1216        // key for the did:web root grant.
1217        let f = fleet();
1218        let leaf_intent = intent("read", "calendar", "https://cal.example/team", json!({}));
1219        let links =
1220            grant_chain::check_grant_chain(std::slice::from_ref(&f.grant), &leaf_intent).unwrap();
1221        let leaf = sign_vouch_credential(
1222            &opts(
1223                &f.device,
1224                leaf_intent,
1225                "urn:uuid:00000000-0000-4000-8000-000000000016",
1226                (FROM, UNTIL),
1227                Some(links),
1228            ),
1229            &f.device.seed,
1230            &proof(&f.device),
1231        )
1232        .unwrap();
1233        assert!(check(&[f.grant.clone(), leaf.clone()], &roots(&[&f.root]), &[]).ok);
1234        // A different fleet root is not this chain's start.
1235        let other = web_party(36, "other.example");
1236        let mut two = roots(&[&f.root]);
1237        two.insert(other.did.clone(), public(&other));
1238        assert!(check(&[f.grant.clone(), leaf.clone()], &two, &[]).ok);
1239        let mut wrong_key = roots(&[&f.root]);
1240        wrong_key.insert(f.root.did.clone(), public(&other));
1241        assert_eq!(
1242            reason(check(&[f.grant.clone(), leaf], &wrong_key, &[])),
1243            "credential 0 failed verification"
1244        );
1245    }
1246
1247    #[test]
1248    fn revocation_candidates_cover_every_identifier_asked_about() {
1249        let f = fleet();
1250        let good = leaf_by(
1251            &f,
1252            &f.device,
1253            "read",
1254            "calendar",
1255            "https://cal.example/team",
1256            json!({}),
1257        );
1258        assert_eq!(
1259            revocation_candidates(&[f.grant.clone(), good]),
1260            vec![
1261                "did:web:root.example".to_string(),
1262                "urn:uuid:00000000-0000-4000-8000-000000000001".to_string(),
1263                f.device.did.clone(),
1264                "urn:uuid:00000000-0000-4000-8000-000000000002".to_string(),
1265            ]
1266        );
1267        assert!(
1268            revocation_candidates(&[json!("x"), json!({"issuer": ["did:web:a"]})])
1269                .contains(&"did:web:a".to_string())
1270        );
1271    }
1272}