1#[allow(unused_imports)]
46use crate::prelude::*;
47
48use alloc::collections::BTreeMap;
49
50use serde_json::{json, Map, Value};
51
52use crate::attenuation;
53use crate::credentials;
54use crate::delegation::{self, ChainOptions};
55use crate::grant_chain::{self, py_repr, py_repr_str, truthy};
56use crate::status_list;
57use crate::time::parse_protocol_time_ns;
58
59#[derive(Debug, Clone, Copy)]
61pub struct FleetOptions<'a> {
62 pub trusted_roots: &'a BTreeMap<String, Vec<u8>>,
67 pub revoked: &'a [String],
70 pub now_iso: &'a str,
72 pub clock_skew_seconds: i64,
74 pub require_action: Option<&'a str>,
76 pub require_target: Option<&'a str>,
78 pub require_resource: Option<&'a str>,
80 pub check_status: bool,
83 pub status_lists: Option<&'a Map<String, Value>>,
87}
88
89#[derive(Debug, Clone, PartialEq)]
91pub struct FleetResult {
92 pub ok: bool,
94 pub reason: Option<String>,
96 pub leaf: Option<Value>,
98 pub root_did: Option<String>,
100}
101
102impl FleetResult {
103 fn fail(reason: String) -> Self {
104 FleetResult {
105 ok: false,
106 reason: Some(reason),
107 leaf: None,
108 root_did: None,
109 }
110 }
111
112 pub fn to_json(&self) -> Value {
114 crate::nesting::deep_guard!(Value::Null; self);
115 json!({
116 "ok": self.ok,
117 "reason": self.reason,
118 "leaf": self.leaf,
119 "rootDid": self.root_did,
120 })
121 }
122}
123
124fn issuer_of(cred: &Value) -> Option<String> {
127 let issuer = match cred.get("issuer") {
128 Some(Value::Array(items)) => items.first(),
129 Some(Value::Object(o)) => o.get("id"),
130 other => other,
131 };
132 issuer
133 .and_then(Value::as_str)
134 .filter(|s| !s.is_empty())
135 .map(String::from)
136}
137
138fn intent_of(cred: &Value) -> Option<&Map<String, Value>> {
139 cred.get("credentialSubject")
140 .and_then(|s| s.get("intent"))
141 .and_then(Value::as_object)
142}
143
144fn post_quantum_proof(cred: &Value) -> bool {
148 matches!(cred.get("proof"), Some(Value::Array(_)))
149}
150
151fn embedded_grants(cred: &Value) -> Vec<&Value> {
153 cred.get("credentialSubject")
154 .and_then(|s| s.get("delegationChain"))
155 .and_then(Value::as_array)
156 .map(|links| {
157 links
158 .iter()
159 .filter_map(|l| l.get("parentCredential").filter(|g| g.is_object()))
160 .collect()
161 })
162 .unwrap_or_default()
163}
164
165fn status_ok(cred: &Value, cred_key: &[u8], opts: &FleetOptions) -> bool {
168 let mut checked: Vec<(&Value, Option<Vec<u8>>)> = vec![(cred, Some(cred_key.to_vec()))];
169 for grant in embedded_grants(cred) {
170 let key = issuer_of(grant).and_then(|i| opts.trusted_roots.get(&i).cloned());
171 checked.push((grant, key));
172 }
173 for (c, key) in checked {
174 if c.get("credentialStatus").is_none() {
175 continue;
176 }
177 let Some(lists) = opts.status_lists else {
178 return false;
181 };
182 match status_list::check_credential_status(
183 c,
184 lists,
185 key.as_deref(),
186 None,
187 opts.now_iso,
188 opts.clock_skew_seconds,
189 ) {
190 Ok(r) if r.ok => {}
191 _ => return false,
192 }
193 }
194 true
195}
196
197fn window_within(child: &Value, parent: &Value) -> bool {
199 let t = |c: &Value, k: &str| {
200 c.get(k)
201 .and_then(Value::as_str)
202 .and_then(|s| parse_protocol_time_ns(s).ok())
203 };
204 match (
205 t(child, "validFrom"),
206 t(child, "validUntil"),
207 t(parent, "validFrom"),
208 t(parent, "validUntil"),
209 ) {
210 (Some(cf), Some(cu), Some(pf), Some(pu)) => cf >= pf && cu <= pu,
211 _ => false,
212 }
213}
214
215pub fn revocation_candidates(credentials: &[Value]) -> Vec<String> {
225 let mut out: Vec<String> = Vec::new();
226 let mut push = |s: Option<String>| {
227 if let Some(s) = s.filter(|s| !s.is_empty()) {
228 if !out.contains(&s) {
229 out.push(s);
230 }
231 }
232 };
233 for cred in credentials {
234 if crate::nesting::too_deep_here(cred) {
235 continue;
236 }
237 push(issuer_of(cred));
238 push(cred.get("id").and_then(Value::as_str).map(String::from));
239 }
240 for cred in credentials {
241 if crate::nesting::too_deep_here(cred) {
242 continue;
243 }
244 push(
245 intent_of(cred)
246 .and_then(|i| i.get("delegatee"))
247 .and_then(Value::as_str)
248 .map(String::from),
249 );
250 }
251 out
252}
253
254pub fn verify_delegated_chain(credentials: &[Value], opts: &FleetOptions) -> FleetResult {
257 crate::nesting::deep_guard!(FleetResult::fail(crate::nesting::TOO_DEEP.into()); credentials, opts);
258 if credentials.is_empty() {
259 return FleetResult::fail("empty chain".into());
260 }
261 for (index, cred) in credentials.iter().enumerate() {
262 if !cred.is_object() {
263 return FleetResult::fail(format!("credential {index} is not a JSON object"));
264 }
265 }
266 if let Some((index, code)) = grant_chain::presented_chain_problem(credentials) {
269 return FleetResult::fail(format!("credential {index}: {code}"));
270 }
271 let is_revoked = |id: &str| opts.revoked.iter().any(|r| r == id);
272 let root_dids: Vec<String> = opts.trusted_roots.keys().cloned().collect();
273 let chain_opts = ChainOptions {
276 trusted_roots: Some(&root_dids),
277 grant_keys: Some(opts.trusted_roots),
278 ..Default::default()
279 };
280
281 let mut issuers: Vec<String> = Vec::with_capacity(credentials.len());
282 for (index, cred) in credentials.iter().enumerate() {
283 let Some(issuer) = issuer_of(cred) else {
284 return FleetResult::fail(format!("credential {index} has no issuer"));
285 };
286 let given = opts.trusted_roots.get(&issuer);
289 if index == 0 && given.is_none() {
290 return FleetResult::fail(format!(
291 "root issuer {} is not in trusted_roots",
292 py_repr_str(&issuer)
293 ));
294 }
295 let key = match given {
296 Some(k) => Some(k.clone()),
297 None => crate::keys::did_key_to_ed25519(&issuer).ok(),
298 };
299 let failed = || FleetResult::fail(format!("credential {index} failed verification"));
300 let Some(key) = key else {
301 return failed();
302 };
303 let verdict = credentials::verify_with_keys(
304 cred,
305 &key,
306 None,
307 opts.now_iso,
308 opts.clock_skew_seconds,
309 &chain_opts,
310 );
311 match verdict {
312 Ok((r, _)) if r.is_valid() => {}
313 Ok((r, _)) => {
314 if given.is_some()
318 && crate::keys::strict_verifying_key(&key).is_ok()
319 && r.time_valid
320 && !r.proof_valid
321 && post_quantum_proof(cred)
322 {
323 return FleetResult::fail(format!("credential {index} needs an ML-DSA-44 key"));
324 }
325 return failed();
326 }
327 Err(_) => return failed(),
328 }
329 if opts.check_status && !status_ok(cred, &key, opts) {
330 return failed();
331 }
332
333 if is_revoked(&issuer) {
336 return FleetResult::fail(format!(
337 "credential {index} issuer {} is revoked",
338 py_repr_str(&issuer)
339 ));
340 }
341 if let Some(id) = cred.get("id").filter(|v| truthy(Some(v))) {
342 if id.as_str().is_some_and(is_revoked) {
343 let shown = id
344 .as_str()
345 .map(String::from)
346 .unwrap_or_else(|| id.to_string());
347 return FleetResult::fail(format!("credential {index} ({shown}) is revoked"));
348 }
349 }
350 issuers.push(issuer);
351 }
352
353 let mut effective = delegation::capability_view(&credentials[0], false);
356 for i in 0..credentials.len() - 1 {
357 let (parent, child) = (&credentials[i], &credentials[i + 1]);
358 let parent_intent = intent_of(parent);
359 let delegatee = parent_intent.and_then(|it| it.get("delegatee"));
360 if !truthy(delegatee) {
361 return FleetResult::fail(format!(
362 "link {i} (grant by {}) names no delegatee",
363 py_repr_str(&issuers[i])
364 ));
365 }
366 if delegatee.and_then(Value::as_str).is_some_and(is_revoked) {
367 return FleetResult::fail(format!(
368 "link {i}: delegatee {} is revoked",
369 py_repr(delegatee)
370 ));
371 }
372 if delegatee.and_then(Value::as_str) != Some(issuers[i + 1].as_str()) {
373 return FleetResult::fail(format!(
374 "link {i}: child issuer {} is not the delegatee {} the parent authorized",
375 py_repr_str(&issuers[i + 1]),
376 py_repr(delegatee)
377 ));
378 }
379
380 let child_view = delegation::capability_view(child, false);
381 let dimension = attenuation::non_expansion(&effective, &child_view);
382 effective = attenuation::inherit(&effective, &child_view);
383 if let Err(dim) = dimension {
384 let name = dim.as_str();
385 let granted = parent_intent.and_then(|it| it.get(name));
386 let asked = intent_of(child).and_then(|it| it.get(name));
387 return FleetResult::fail(format!(
388 "link {i}: {name} {} is not within the granted {}",
389 py_repr(asked),
390 py_repr(granted)
391 ));
392 }
393
394 if !window_within(child, parent) {
395 return FleetResult::fail(format!(
396 "link {i}: child validity is outside the grant window"
397 ));
398 }
399 }
400
401 let leaf = &credentials[credentials.len() - 1];
402 let leaf_intent = intent_of(leaf);
403 for (field, expected) in [
404 ("action", opts.require_action),
405 ("target", opts.require_target),
406 ("resource", opts.require_resource),
407 ] {
408 let Some(expected) = expected else { continue };
409 if leaf_intent
410 .and_then(|it| it.get(field))
411 .and_then(Value::as_str)
412 != Some(expected)
413 {
414 return FleetResult {
415 ok: false,
416 reason: Some(format!("leaf intent.{field} != {}", py_repr_str(expected))),
417 leaf: Some(leaf.clone()),
418 root_did: None,
419 };
420 }
421 }
422
423 FleetResult {
424 ok: true,
425 reason: None,
426 leaf: Some(leaf.clone()),
427 root_did: Some(issuers[0].clone()),
428 }
429}
430
431crate::nesting::nested_fields!(FleetOptions<'_>; status_lists);
433crate::nesting::nested_fields!(FleetResult; leaf);
434
435#[cfg(test)]
436mod tests {
437 use super::*;
438 use crate::credentials::{sign_sub_grant, sign_vouch_credential, BuildCredentialOptions};
439 use crate::data_integrity::BuildProofOptions;
440 use crate::hybrid;
441 use crate::keys::Ed25519KeyPair;
442
443 const NOW: &str = "2026-11-10T12:00:00Z";
444 const FROM: &str = "2026-11-10T00:00:00Z";
445 const UNTIL: &str = "2026-11-11T00:00:00Z";
446
447 struct Who {
448 seed: [u8; 32],
449 did: String,
450 }
451
452 fn key_party(n: u8) -> Who {
453 let seed = [n; 32];
454 Who {
455 seed,
456 did: Ed25519KeyPair::from_seed(&seed).did_key(),
457 }
458 }
459
460 fn web_party(n: u8, host: &str) -> Who {
461 Who {
462 seed: [n; 32],
463 did: format!("did:web:{host}"),
464 }
465 }
466
467 fn public(w: &Who) -> Vec<u8> {
468 Ed25519KeyPair::from_seed(&w.seed).public_key().to_vec()
469 }
470
471 fn intent(action: &str, target: &str, resource: &str, extra: Value) -> Value {
472 let mut i = json!({"action": action, "target": target, "resource": resource});
473 for (k, v) in extra.as_object().unwrap() {
474 i[k] = v.clone();
475 }
476 i
477 }
478
479 fn opts(
480 who: &Who,
481 intent: Value,
482 id: &str,
483 window: (&str, &str),
484 chain: Option<Vec<Value>>,
485 ) -> BuildCredentialOptions {
486 BuildCredentialOptions {
487 issuer_did: who.did.clone(),
488 credential_id: id.into(),
489 intent,
490 valid_from: window.0.into(),
491 valid_until: window.1.into(),
492 reputation_score: None,
493 delegation_chain: chain.map(Value::Array),
494 credential_status: None,
495 }
496 }
497
498 fn proof(who: &Who) -> BuildProofOptions {
499 BuildProofOptions::new(format!("{}#key-1", who.did), FROM)
500 }
501
502 fn sign(who: &Who, intent: Value, id: &str) -> Value {
503 sign_vouch_credential(
504 &opts(who, intent, id, (FROM, UNTIL), None),
505 &who.seed,
506 &proof(who),
507 )
508 .unwrap()
509 }
510
511 fn sign_window(who: &Who, intent: Value, id: &str, window: (&str, &str)) -> Value {
512 sign_vouch_credential(&opts(who, intent, id, window, None), &who.seed, &proof(who)).unwrap()
513 }
514
515 fn roots(ws: &[&Who]) -> BTreeMap<String, Vec<u8>> {
516 ws.iter().map(|w| (w.did.clone(), public(w))).collect()
517 }
518
519 fn check(
520 creds: &[Value],
521 roots: &BTreeMap<String, Vec<u8>>,
522 revoked: &[String],
523 ) -> FleetResult {
524 verify_delegated_chain(
525 creds,
526 &FleetOptions {
527 trusted_roots: roots,
528 revoked,
529 now_iso: NOW,
530 clock_skew_seconds: 30,
531 require_action: None,
532 require_target: None,
533 require_resource: None,
534 check_status: true,
535 status_lists: None,
536 },
537 )
538 }
539
540 fn reason(r: FleetResult) -> String {
541 assert!(!r.ok);
542 r.reason.unwrap()
543 }
544
545 struct Fleet {
547 root: Who,
548 device: Who,
549 impostor: Who,
550 grant: Value,
551 }
552
553 fn fleet() -> Fleet {
554 let (root, device, impostor) =
555 (web_party(31, "root.example"), key_party(32), key_party(33));
556 let grant = sign(
557 &root,
558 intent(
559 "read",
560 "calendar",
561 "https://cal.example/team",
562 json!({"delegatee": device.did, "rate": {"limit": 10, "window": "PT1H"}}),
563 ),
564 "urn:uuid:00000000-0000-4000-8000-000000000001",
565 );
566 Fleet {
567 root,
568 device,
569 impostor,
570 grant,
571 }
572 }
573
574 fn leaf_by(
575 f: &Fleet,
576 who: &Who,
577 action: &str,
578 target: &str,
579 resource: &str,
580 extra: Value,
581 ) -> Value {
582 let _ = f;
583 sign(
584 who,
585 intent(action, target, resource, extra),
586 "urn:uuid:00000000-0000-4000-8000-000000000002",
587 )
588 }
589
590 #[test]
591 fn a_narrowing_chain_verifies_and_returns_the_leaf() {
592 let f = fleet();
593 let leaf = leaf_by(
594 &f,
595 &f.device,
596 "read",
597 "calendar",
598 "https://cal.example/team/1",
599 json!({}),
600 );
601 let r = check(&[f.grant.clone(), leaf.clone()], &roots(&[&f.root]), &[]);
602 assert!(r.ok, "{:?}", r.reason);
603 assert_eq!(r.root_did.as_deref(), Some("did:web:root.example"));
604 assert_eq!(r.leaf, Some(leaf));
605 assert_eq!(r.reason, None);
606 assert_eq!(r.to_json()["ok"], json!(true));
607 }
608
609 #[test]
610 fn widening_steps_are_refused_with_the_reference_text() {
611 let f = fleet();
612 let roots = roots(&[&f.root]);
613 let cases = [
614 (
615 leaf_by(&f, &f.device, "write", "calendar", "https://cal.example/team", json!({})),
616 "link 0: action 'write' is not within the granted 'read'",
617 ),
618 (
619 leaf_by(&f, &f.device, "read", "mail", "https://cal.example/team", json!({})),
620 "link 0: target 'mail' is not within the granted 'calendar'",
621 ),
622 (
623 leaf_by(&f, &f.device, "read", "calendar", "https://cal.example/other", json!({})),
624 "link 0: resource 'https://cal.example/other' is not within the granted 'https://cal.example/team'",
625 ),
626 (
627 leaf_by(
628 &f,
629 &f.device,
630 "read",
631 "calendar",
632 "https://cal.example/team",
633 json!({"rate": {"limit": 100, "window": "PT1H"}}),
634 ),
635 "link 0: rate {'limit': 100, 'window': 'PT1H'} is not within the granted {'limit': 10, 'window': 'PT1H'}",
636 ),
637 (
638 leaf_by(
640 &f,
641 &f.device,
642 "read",
643 "calendar",
644 "https://cal.example/team",
645 json!({"rate": {"limit": 2.5e-05, "window": "PT1H"}}),
646 ),
647 "link 0: rate {'limit': 2.5e-05, 'window': 'PT1H'} is not within the granted {'limit': 10, 'window': 'PT1H'}",
648 ),
649 (
650 leaf_by(&f, &f.device, "read", "calendar", "https://cal.example/team", json!({"rate": null})),
651 "link 0: rate None is not within the granted {'limit': 10, 'window': 'PT1H'}",
652 ),
653 (
654 leaf_by(&f, &f.device, "read", "calendar", "https://cal.example/../x", json!({})),
655 "link 0: resource 'https://cal.example/../x' is not within the granted 'https://cal.example/team'",
656 ),
657 ];
658 for (leaf, want) in cases {
659 assert_eq!(reason(check(&[f.grant.clone(), leaf], &roots, &[])), want);
660 }
661 let mut body = crate::credentials::build_vouch_credential(&opts(
663 &f.device,
664 intent("read", "calendar", "https://cal.example/team", json!({})),
665 "urn:uuid:00000000-0000-4000-8000-000000000003",
666 (FROM, UNTIL),
667 None,
668 ))
669 .unwrap();
670 body["credentialSubject"]["intent"]["action"] = json!(["read", "delete"]);
671 let both_actions =
672 crate::data_integrity::sign(&body, &f.device.seed, &proof(&f.device)).unwrap();
673 assert_eq!(
674 reason(check(&[f.grant.clone(), both_actions], &roots, &[])),
675 "link 0: action ['read', 'delete'] is not within the granted 'read'"
676 );
677 }
678
679 #[test]
680 fn the_issuer_is_a_string_the_first_of_a_list_or_an_object_id() {
681 for (issuer, expected) in [
683 (json!("did:web:a"), Some("did:web:a")),
684 (json!(["did:web:a", "did:web:b"]), Some("did:web:a")),
685 (json!({"id": "did:web:a", "name": "x"}), Some("did:web:a")),
686 (json!([]), None),
687 (json!([{"id": "did:web:a"}]), None),
688 (json!([""]), None),
689 (json!([["did:web:a"]]), None),
690 (json!([5]), None),
691 (json!({"id": 5}), None),
692 (json!({"id": ""}), None),
693 (json!({"id": ["did:web:a"]}), None),
694 (json!({}), None),
695 (json!(""), None),
696 (json!(5), None),
697 (json!(true), None),
698 (Value::Null, None),
699 ] {
700 let cred = json!({ "issuer": issuer });
701 assert_eq!(issuer_of(&cred).as_deref(), expected, "{issuer}");
702 }
703 assert_eq!(issuer_of(&json!({})), None);
704 let f = fleet();
706 let roots = roots(&[&f.root]);
707 let good = leaf_by(
708 &f,
709 &f.device,
710 "read",
711 "calendar",
712 "https://cal.example/team",
713 json!({}),
714 );
715 for issuer in [json!(5), json!({"id": 5}), json!([]), json!({}), json!("")] {
716 let mut grant = f.grant.clone();
717 grant["issuer"] = issuer.clone();
718 assert_eq!(
719 reason(check(&[grant, good.clone()], &roots, &[])),
720 "credential 0 has no issuer",
721 "{issuer}"
722 );
723 let mut leaf = good.clone();
724 leaf["issuer"] = issuer.clone();
725 assert_eq!(
726 reason(check(&[f.grant.clone(), leaf], &roots, &[])),
727 "credential 1 has no issuer",
728 "{issuer}"
729 );
730 }
731 }
732
733 #[test]
734 fn omitted_dimensions_are_inherited_down_the_chain() {
735 let f = fleet();
738 let helper = key_party(34);
739 let sub_intent = intent(
740 "read",
741 "calendar",
742 "https://cal.example/team",
743 json!({"delegatee": helper.did}),
744 );
745 let sub = sign_sub_grant(
746 &opts(
747 &f.device,
748 sub_intent,
749 "urn:uuid:00000000-0000-4000-8000-000000000004",
750 (FROM, UNTIL),
751 None,
752 ),
753 &grant_chain::grant_digest(&f.grant).unwrap(),
754 &f.device.seed,
755 &proof(&f.device),
756 )
757 .unwrap();
758 let ok_leaf = sign(
759 &helper,
760 intent("read", "calendar", "https://cal.example/team", json!({})),
761 "urn:uuid:00000000-0000-4000-8000-000000000005",
762 );
763 let roots = roots(&[&f.root]);
764 let r = check(&[f.grant.clone(), sub.clone(), ok_leaf], &roots, &[]);
765 assert!(r.ok, "{:?}", r.reason);
766 let greedy = sign(
767 &helper,
768 intent(
769 "read",
770 "calendar",
771 "https://cal.example/team",
772 json!({"rate": {"limit": 11, "window": "PT1H"}}),
773 ),
774 "urn:uuid:00000000-0000-4000-8000-000000000006",
775 );
776 assert_eq!(
777 reason(check(&[f.grant.clone(), sub.clone(), greedy], &roots, &[])),
778 "link 1: rate {'limit': 11, 'window': 'PT1H'} is not within the granted None"
779 );
780 let other = sign(
782 &f.root,
783 intent(
784 "read",
785 "calendar",
786 "https://cal.example/team",
787 json!({"delegatee": f.device.did}),
788 ),
789 "urn:uuid:00000000-0000-4000-8000-000000000007",
790 );
791 let leaf = sign(
792 &helper,
793 intent("read", "calendar", "https://cal.example/team", json!({})),
794 "urn:uuid:00000000-0000-4000-8000-000000000008",
795 );
796 assert_eq!(
797 reason(check(&[other, sub, leaf], &roots, &[])),
798 "credential 1: delegation_parent_mismatch"
799 );
800 }
801
802 #[test]
803 fn the_walk_checks_delegatees_revocation_and_windows() {
804 let f = fleet();
805 let roots = roots(&[&f.root]);
806 let good = leaf_by(
807 &f,
808 &f.device,
809 "read",
810 "calendar",
811 "https://cal.example/team",
812 json!({}),
813 );
814 let by_impostor = leaf_by(
815 &f,
816 &f.impostor,
817 "read",
818 "calendar",
819 "https://cal.example/team",
820 json!({}),
821 );
822 assert_eq!(
823 reason(check(&[f.grant.clone(), by_impostor.clone()], &roots, &[])),
824 format!(
825 "link 0: child issuer '{}' is not the delegatee '{}' the parent authorized",
826 f.impostor.did, f.device.did
827 )
828 );
829 assert_eq!(
831 reason(check(
832 &[f.grant.clone(), good.clone()],
833 &roots,
834 core::slice::from_ref(&f.device.did)
835 )),
836 format!("credential 1 issuer '{}' is revoked", f.device.did)
837 );
838 let leaf_id = good["id"].as_str().unwrap().to_string();
839 assert_eq!(
840 reason(check(
841 &[f.grant.clone(), good.clone()],
842 &roots,
843 core::slice::from_ref(&leaf_id)
844 )),
845 format!("credential 1 ({leaf_id}) is revoked")
846 );
847 assert_eq!(
848 reason(check(
849 &[f.grant.clone(), by_impostor],
850 &roots,
851 core::slice::from_ref(&f.device.did)
852 )),
853 format!("link 0: delegatee '{}' is revoked", f.device.did)
854 );
855 assert_eq!(
856 reason(check(
857 &[f.grant.clone(), good.clone()],
858 &roots,
859 core::slice::from_ref(&f.root.did)
860 )),
861 "credential 0 issuer 'did:web:root.example' is revoked"
862 );
863 let late = sign_window(
865 &f.device,
866 intent("read", "calendar", "https://cal.example/team", json!({})),
867 "urn:uuid:00000000-0000-4000-8000-000000000009",
868 (FROM, "2026-11-12T00:00:00Z"),
869 );
870 let early = sign_window(
871 &f.device,
872 intent("read", "calendar", "https://cal.example/team", json!({})),
873 "urn:uuid:00000000-0000-4000-8000-000000000010",
874 ("2026-11-09T00:00:00Z", UNTIL),
875 );
876 for leaf in [late, early] {
877 assert_eq!(
878 reason(check(&[f.grant.clone(), leaf], &roots, &[])),
879 "link 0: child validity is outside the grant window"
880 );
881 }
882 let no_delegatee = sign(
884 &f.root,
885 intent("read", "calendar", "https://cal.example/team", json!({})),
886 "urn:uuid:00000000-0000-4000-8000-000000000011",
887 );
888 assert_eq!(
889 reason(check(&[no_delegatee, good], &roots, &[])),
890 "link 0 (grant by 'did:web:root.example') names no delegatee"
891 );
892 }
893
894 #[test]
895 fn trust_identity_and_proofs_come_first() {
896 let f = fleet();
897 let roots = roots(&[&f.root]);
898 let good = leaf_by(
899 &f,
900 &f.device,
901 "read",
902 "calendar",
903 "https://cal.example/team",
904 json!({}),
905 );
906 assert_eq!(reason(check(&[], &roots, &[])), "empty chain");
907 assert_eq!(
908 reason(check(
909 &[f.grant.clone(), good.clone()],
910 &BTreeMap::new(),
911 &[]
912 )),
913 "root issuer 'did:web:root.example' is not in trusted_roots"
914 );
915 let mut wrong = BTreeMap::new();
917 wrong.insert(f.root.did.clone(), vec![7u8; 32]);
918 assert_eq!(
919 reason(check(&[f.grant.clone(), good.clone()], &wrong, &[])),
920 "credential 0 failed verification"
921 );
922 let mut no_issuer = good.clone();
923 no_issuer.as_object_mut().unwrap().remove("issuer");
924 assert_eq!(
925 reason(check(&[f.grant.clone(), no_issuer], &roots, &[])),
926 "credential 1 has no issuer"
927 );
928 let mut tampered = good.clone();
929 tampered["credentialSubject"]["intent"]["resource"] = json!("https://cal.example/team/2");
930 assert_eq!(
931 reason(check(&[f.grant.clone(), tampered], &roots, &[])),
932 "credential 1 failed verification"
933 );
934 let web_device = web_party(35, "device.example");
936 let web_grant = sign(
937 &f.root,
938 intent(
939 "read",
940 "calendar",
941 "https://cal.example/team",
942 json!({"delegatee": web_device.did}),
943 ),
944 "urn:uuid:00000000-0000-4000-8000-000000000012",
945 );
946 let web_leaf = leaf_by(
947 &f,
948 &web_device,
949 "read",
950 "calendar",
951 "https://cal.example/team",
952 json!({}),
953 );
954 assert_eq!(
955 reason(check(&[web_grant.clone(), web_leaf.clone()], &roots, &[])),
956 "credential 1 failed verification"
957 );
958 let both = super::tests::roots(&[&f.root, &web_device]);
959 assert!(check(&[web_grant, web_leaf], &both, &[]).ok);
960 let sub = sign_sub_grant(
962 &opts(
963 &f.device,
964 intent(
965 "read",
966 "calendar",
967 "https://cal.example/team",
968 json!({"delegatee": f.impostor.did}),
969 ),
970 "urn:uuid:00000000-0000-4000-8000-000000000013",
971 (FROM, UNTIL),
972 None,
973 ),
974 &grant_chain::grant_digest(&f.grant).unwrap(),
975 &f.device.seed,
976 &proof(&f.device),
977 )
978 .unwrap();
979 assert_eq!(
980 reason(check(&[sub], &BTreeMap::new(), &[])),
981 "credential 0: delegation_parent_mismatch"
982 );
983 }
984
985 #[test]
986 fn shape_and_binding_come_before_any_key() {
987 let f = fleet();
988 let roots = roots(&[&f.root]);
989 let none = BTreeMap::new();
990 let good = leaf_by(
991 &f,
992 &f.device,
993 "read",
994 "calendar",
995 "https://cal.example/team",
996 json!({}),
997 );
998 for (position, value) in [
1001 (0, json!(f.grant.to_string())),
1002 (1, Value::Null),
1003 (1, json!(["x"])),
1004 (2, json!(7)),
1005 ] {
1006 let mut creds = vec![f.grant.clone(), good.clone(), good.clone()];
1007 creds[position] = value;
1008 for r in [&roots, &none] {
1009 assert_eq!(
1010 reason(check(&creds, r, &[])),
1011 format!("credential {position} is not a JSON object")
1012 );
1013 }
1014 }
1015 let named = json!({"issuer": f.device.did,
1017 "credentialSubject": {"parentGrantDigest": "uEiA"}});
1018 assert_eq!(
1019 reason(check(&[named, json!("x")], &roots, &[])),
1020 "credential 1 is not a JSON object"
1021 );
1022 let other = sign(
1025 &f.impostor,
1026 intent(
1027 "read",
1028 "calendar",
1029 "https://cal.example/team",
1030 json!({"delegatee": f.device.did}),
1031 ),
1032 "urn:uuid:00000000-0000-4000-8000-000000000020",
1033 );
1034 let link = |grant: &Value| {
1035 json!({"issuer": grant["issuer"], "subject": f.device.did,
1036 "parentCredential": grant})
1037 };
1038 let nested = json!({"issuer": f.device.did, "credentialSubject": {
1039 "intent": {"action": "read", "delegatee": f.impostor.did},
1040 "delegationChain": [link(&other)]}});
1041 assert_eq!(
1042 reason(check(
1043 &[f.grant.clone(), nested.clone(), good.clone()],
1044 &none,
1045 &[]
1046 )),
1047 "credential 1: delegation_parent_mismatch"
1048 );
1049 let elsewhere = json!({"issuer": f.device.did, "credentialSubject": {
1051 "intent": {"action": "read"}, "delegationChain": [link(&other)]}});
1052 assert_eq!(
1053 reason(check(&[f.grant.clone(), elsewhere], &none, &[])),
1054 "credential 1: delegation_parent_mismatch"
1055 );
1056 for subject in [
1058 json!({"delegationChain": null}),
1059 json!({"delegationChain": {}}),
1060 json!({"parentGrantDigest": null}),
1061 json!({"parentGrantDigest": grant_chain::grant_digest(&f.grant).unwrap(),
1062 "delegationChain": [link(&f.grant)]}),
1063 ] {
1064 let sub = json!({"issuer": f.device.did, "credentialSubject": subject});
1065 assert_eq!(
1066 reason(check(&[f.grant.clone(), sub, good.clone()], &none, &[])),
1067 "credential 1: malformed_delegation"
1068 );
1069 }
1070 }
1071
1072 #[test]
1073 #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
1074 fn a_post_quantum_root_grant_needs_its_mldsa_key() {
1075 let f = fleet();
1076 let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
1077 let body = crate::credentials::build_vouch_credential(&opts(
1078 &f.root,
1079 intent(
1080 "read",
1081 "calendar",
1082 "https://cal.example/team",
1083 json!({"delegatee": f.device.did}),
1084 ),
1085 "urn:uuid:00000000-0000-4000-8000-000000000014",
1086 (FROM, UNTIL),
1087 None,
1088 ))
1089 .unwrap();
1090 let dual = hybrid::sign_dual(
1091 &body,
1092 &f.root.seed,
1093 &ml,
1094 &format!("{}#key-1", f.root.did),
1095 &format!("{}#mldsa", f.root.did),
1096 FROM,
1097 )
1098 .unwrap();
1099 let good = leaf_by(
1100 &f,
1101 &f.device,
1102 "read",
1103 "calendar",
1104 "https://cal.example/team",
1105 json!({}),
1106 );
1107 assert_eq!(
1108 reason(check(
1109 &[dual.clone(), good.clone()],
1110 &roots(&[&f.root]),
1111 &[]
1112 )),
1113 "credential 0 needs an ML-DSA-44 key"
1114 );
1115 let mut short = roots(&[&f.root]);
1118 for key in short.values_mut() {
1119 key.truncate(31);
1120 }
1121 assert_eq!(
1122 reason(check(&[dual, good], &short, &[])),
1123 "credential 0 failed verification"
1124 );
1125 }
1126
1127 #[test]
1128 fn leaf_policy_and_status() {
1129 let f = fleet();
1130 let roots = roots(&[&f.root]);
1131 let good = leaf_by(
1132 &f,
1133 &f.device,
1134 "read",
1135 "calendar",
1136 "https://cal.example/team/1",
1137 json!({}),
1138 );
1139 let creds = [f.grant.clone(), good.clone()];
1140 let with = |action: Option<&str>, target: Option<&str>, resource: Option<&str>| {
1141 verify_delegated_chain(
1142 &creds,
1143 &FleetOptions {
1144 trusted_roots: &roots,
1145 revoked: &[],
1146 now_iso: NOW,
1147 clock_skew_seconds: 30,
1148 require_action: action,
1149 require_target: target,
1150 require_resource: resource,
1151 check_status: true,
1152 status_lists: None,
1153 },
1154 )
1155 };
1156 assert!(
1157 with(
1158 Some("read"),
1159 Some("calendar"),
1160 Some("https://cal.example/team/1")
1161 )
1162 .ok
1163 );
1164 for (r, want) in [
1165 (
1166 with(Some("write"), None, None),
1167 "leaf intent.action != 'write'",
1168 ),
1169 (
1170 with(None, Some("mail"), None),
1171 "leaf intent.target != 'mail'",
1172 ),
1173 (
1174 with(None, None, Some("https://cal.example/team")),
1175 "leaf intent.resource != 'https://cal.example/team'",
1176 ),
1177 ] {
1178 assert!(!r.ok);
1179 assert_eq!(r.leaf.as_ref(), Some(&good));
1180 assert_eq!(r.root_did, None);
1181 assert_eq!(r.reason.as_deref(), Some(want));
1182 }
1183 let status = json!({"id": "https://status.example/1#5", "type": "BitstringStatusListEntry",
1186 "statusPurpose": "revocation", "statusListIndex": "5",
1187 "statusListCredential": "https://status.example/1"});
1188 let mut o = opts(
1189 &f.root,
1190 intent(
1191 "read",
1192 "calendar",
1193 "https://cal.example/team",
1194 json!({"delegatee": f.device.did}),
1195 ),
1196 "urn:uuid:00000000-0000-4000-8000-000000000015",
1197 (FROM, UNTIL),
1198 None,
1199 );
1200 o.credential_status = Some(status);
1201 let with_status = sign_vouch_credential(&o, &f.root.seed, &proof(&f.root)).unwrap();
1202 let creds = [with_status, good];
1203 let base = FleetOptions {
1204 trusted_roots: &roots,
1205 revoked: &[],
1206 now_iso: NOW,
1207 clock_skew_seconds: 30,
1208 require_action: None,
1209 require_target: None,
1210 require_resource: None,
1211 check_status: true,
1212 status_lists: None,
1213 };
1214 assert_eq!(
1215 verify_delegated_chain(&creds, &base).reason.as_deref(),
1216 Some("credential 0 failed verification")
1217 );
1218 let empty = Map::new();
1219 let listed = FleetOptions {
1220 status_lists: Some(&empty),
1221 ..base
1222 };
1223 assert_eq!(
1224 verify_delegated_chain(&creds, &listed).reason.as_deref(),
1225 Some("credential 0 failed verification")
1226 );
1227 let unchecked = FleetOptions {
1228 check_status: false,
1229 ..base
1230 };
1231 assert!(verify_delegated_chain(&creds, &unchecked).ok);
1232 }
1233
1234 #[test]
1235 fn embedded_chains_start_at_the_fleet_roots() {
1236 let f = fleet();
1240 let leaf_intent = intent("read", "calendar", "https://cal.example/team", json!({}));
1241 let links =
1242 grant_chain::check_grant_chain(core::slice::from_ref(&f.grant), &leaf_intent).unwrap();
1243 let leaf = sign_vouch_credential(
1244 &opts(
1245 &f.device,
1246 leaf_intent,
1247 "urn:uuid:00000000-0000-4000-8000-000000000016",
1248 (FROM, UNTIL),
1249 Some(links),
1250 ),
1251 &f.device.seed,
1252 &proof(&f.device),
1253 )
1254 .unwrap();
1255 assert!(check(&[f.grant.clone(), leaf.clone()], &roots(&[&f.root]), &[]).ok);
1256 let other = web_party(36, "other.example");
1258 let mut two = roots(&[&f.root]);
1259 two.insert(other.did.clone(), public(&other));
1260 assert!(check(&[f.grant.clone(), leaf.clone()], &two, &[]).ok);
1261 let mut wrong_key = roots(&[&f.root]);
1262 wrong_key.insert(f.root.did.clone(), public(&other));
1263 assert_eq!(
1264 reason(check(&[f.grant.clone(), leaf], &wrong_key, &[])),
1265 "credential 0 failed verification"
1266 );
1267 }
1268
1269 #[test]
1270 fn revocation_candidates_cover_every_identifier_asked_about() {
1271 let f = fleet();
1272 let good = leaf_by(
1273 &f,
1274 &f.device,
1275 "read",
1276 "calendar",
1277 "https://cal.example/team",
1278 json!({}),
1279 );
1280 assert_eq!(
1281 revocation_candidates(&[f.grant.clone(), good]),
1282 vec![
1283 "did:web:root.example".to_string(),
1284 "urn:uuid:00000000-0000-4000-8000-000000000001".to_string(),
1285 f.device.did.clone(),
1286 "urn:uuid:00000000-0000-4000-8000-000000000002".to_string(),
1287 ]
1288 );
1289 assert!(
1290 revocation_candidates(&[json!("x"), json!({"issuer": ["did:web:a"]})])
1291 .contains(&"did:web:a".to_string())
1292 );
1293 }
1294}