1use 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#[derive(Debug, Clone, Copy)]
59pub struct FleetOptions<'a> {
60 pub trusted_roots: &'a BTreeMap<String, Vec<u8>>,
65 pub revoked: &'a [String],
68 pub now_iso: &'a str,
70 pub clock_skew_seconds: i64,
72 pub require_action: Option<&'a str>,
74 pub require_target: Option<&'a str>,
76 pub require_resource: Option<&'a str>,
78 pub check_status: bool,
81 pub status_lists: Option<&'a Map<String, Value>>,
85}
86
87#[derive(Debug, Clone, PartialEq)]
89pub struct FleetResult {
90 pub ok: bool,
92 pub reason: Option<String>,
94 pub leaf: Option<Value>,
96 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 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
121fn 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
141fn 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
154fn 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
168fn 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 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
200fn 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
218pub 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
245pub 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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}