1use std::fmt;
54
55use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
56use serde_json::{Map, Value};
57use sha2::{Digest, Sha256};
58
59use crate::attenuation;
60use crate::delegation;
61use crate::error::CoreError;
62use crate::jcs;
63
64pub const REASON_PARENT_MISMATCH: &str = "delegation_parent_mismatch";
66pub const REASON_MALFORMED: &str = "malformed_delegation";
68pub const REASON_REPLICA_CHAIN_TOO_LONG: &str = "replica_chain_too_long";
71pub const REPLICA_OF: &str = "replicaOf";
73
74pub const PARENT_GRANT_DIGEST: &str = "parentGrantDigest";
76
77pub const NAMES_PARENT_GRANT: &str =
79 "this grant names a parent grant; pass the whole grant chain (a list, root first)";
80
81const MULTIHASH_SHA2_256: [u8; 2] = [0x12, 0x20];
83
84#[derive(Debug, Clone, PartialEq, Eq)]
89pub struct GrantDigestError(pub String);
90
91impl fmt::Display for GrantDigestError {
92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93 f.write_str(&self.0)
94 }
95}
96
97impl std::error::Error for GrantDigestError {}
98
99impl From<GrantDigestError> for CoreError {
100 fn from(e: GrantDigestError) -> Self {
101 CoreError::Json(e.0)
102 }
103}
104
105#[derive(Debug, Clone, PartialEq, Eq)]
108pub struct GrantChainError(pub String);
109
110impl fmt::Display for GrantChainError {
111 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112 f.write_str(&self.0)
113 }
114}
115
116impl std::error::Error for GrantChainError {}
117
118impl From<GrantChainError> for CoreError {
119 fn from(e: GrantChainError) -> Self {
120 CoreError::Json(e.0)
121 }
122}
123
124fn refused(msg: impl Into<String>) -> GrantChainError {
125 GrantChainError(msg.into())
126}
127
128pub fn grant_digest(grant: &Value) -> Result<String, GrantDigestError> {
136 if !grant.is_object() {
137 return Err(GrantDigestError("a grant must be a JSON object".into()));
138 }
139 let mut multihash = Vec::with_capacity(34);
140 multihash.extend_from_slice(&MULTIHASH_SHA2_256);
141 multihash.extend_from_slice(&Sha256::digest(jcs::canonicalize(grant)));
142 Ok(format!("u{}", URL_SAFE_NO_PAD.encode(multihash)))
143}
144
145fn subject_of(grant: &Value) -> Option<&Map<String, Value>> {
148 grant.get("credentialSubject").and_then(Value::as_object)
149}
150
151pub fn binding_fields_problem(subject: &Value) -> Option<&'static str> {
169 let subject = subject.as_object()?;
171 let digest = subject.get(PARENT_GRANT_DIGEST);
172 if digest.is_some_and(|d| !d.is_string()) {
173 return Some(REASON_MALFORMED);
174 }
175 let chain = subject.get("delegationChain");
176 if chain.is_some_and(|c| !c.is_array()) {
177 return Some(REASON_MALFORMED);
178 }
179 if digest.is_some()
180 && chain
181 .and_then(Value::as_array)
182 .is_some_and(|c| !c.is_empty())
183 {
184 return Some(REASON_MALFORMED);
185 }
186 None
187}
188
189fn bindings(cred: &Value) -> (Option<&Value>, &[Value]) {
192 let subject = subject_of(cred);
193 let digest = subject.and_then(|s| s.get(PARENT_GRANT_DIGEST));
194 let embedded = match subject.and_then(|s| s.get("delegationChain")) {
195 Some(Value::Array(a)) => a.as_slice(),
196 _ => &[],
197 };
198 (digest, embedded)
199}
200
201fn binding_failure(chain: &[Value]) -> Option<(usize, &'static str)> {
205 for (i, link) in chain.iter().enumerate() {
206 let Some(grant) = link.get("parentCredential").filter(|g| g.is_object()) else {
207 return Some((i, REASON_MALFORMED));
208 };
209 if let Some(malformed) = binding_fields_problem(&grant["credentialSubject"]) {
210 return Some((i, malformed));
211 }
212 let (digest, embedded) = bindings(grant);
213 let has_embedded = !embedded.is_empty();
215 if i == 0 {
216 if digest.is_some() || has_embedded {
218 return Some((i, REASON_PARENT_MISMATCH));
219 }
220 continue;
221 }
222 let bound = if let Some(Value::String(d)) = digest {
223 match grant_digest(&chain[i - 1]["parentCredential"]) {
224 Ok(expected) => *d == expected,
225 Err(_) => return Some((i, REASON_MALFORMED)),
226 }
227 } else if has_embedded {
228 embedded.len() == i
231 && embedded
232 .iter()
233 .zip(&chain[..i])
234 .all(|(a, b)| jcs::canonicalize(a) == jcs::canonicalize(b))
235 } else {
236 false
237 };
238 if !bound {
239 return Some((i, REASON_PARENT_MISMATCH));
240 }
241 }
242 None
243}
244
245pub fn chain_binding_problem(chain: &[Value]) -> Option<&'static str> {
269 binding_failure(chain)
270 .or_else(|| replica_failure(chain))
271 .map(|(_, reason)| reason)
272}
273
274pub fn is_replica_grant(grant: &Value) -> bool {
276 subject_of(grant)
277 .and_then(|s| s.get("intent"))
278 .and_then(Value::as_object)
279 .is_some_and(|i| i.contains_key(REPLICA_OF))
280}
281
282fn replica_failure(chain: &[Value]) -> Option<(usize, &'static str)> {
285 let last = chain.len().saturating_sub(1);
286 chain[..last]
287 .iter()
288 .position(|link| link.get("parentCredential").is_some_and(is_replica_grant))
289 .map(|i| (i, REASON_REPLICA_CHAIN_TOO_LONG))
290}
291
292pub fn presented_chain_problem(credentials: &[Value]) -> Option<(usize, &'static str)> {
318 for (i, cred) in credentials.iter().enumerate() {
319 if !cred.is_object() {
320 return Some((i, REASON_MALFORMED));
321 }
322 if let Some(malformed) = binding_fields_problem(&cred["credentialSubject"]) {
323 return Some((i, malformed));
324 }
325 let (digest, embedded) = bindings(cred);
326 if i == 0 {
327 if digest.is_some() || !embedded.is_empty() {
329 return Some((i, REASON_PARENT_MISMATCH));
330 }
331 continue;
332 }
333 let previous = &credentials[i - 1];
334 let bound = if let Some(digest) = digest {
335 match grant_digest(previous) {
336 Ok(expected) => digest.as_str() == Some(expected.as_str()),
337 Err(_) => return Some((i, REASON_MALFORMED)),
338 }
339 } else if let Some(last) = embedded.last() {
340 last.get("parentCredential")
343 .filter(|g| g.is_object())
344 .is_some_and(|g| jcs::canonicalize(g) == jcs::canonicalize(previous))
345 } else {
346 continue;
347 };
348 if !bound {
349 return Some((i, REASON_PARENT_MISMATCH));
350 }
351 }
352 None
353}
354
355fn embedded_chain(grant: &Value) -> &[Value] {
361 match subject_of(grant).and_then(|s| s.get("delegationChain")) {
362 Some(Value::Array(a)) => a.as_slice(),
363 _ => &[],
364 }
365}
366
367pub fn is_grant_intent(intent: &Value) -> bool {
370 intent
371 .get("delegatee")
372 .and_then(Value::as_str)
373 .is_some_and(|d| !d.is_empty())
374}
375
376pub fn parent_grants(parent: &Value) -> Result<Vec<Value>, GrantChainError> {
388 match parent {
389 Value::Object(_) => {
390 let subject = subject_of(parent);
391 if subject.is_some_and(|s| s.contains_key(PARENT_GRANT_DIGEST)) {
392 return Err(refused(NAMES_PARENT_GRANT));
393 }
394 if subject
395 .and_then(|s| s.get("delegationChain"))
396 .is_some_and(|c| !c.is_array())
397 {
398 return Err(refused(
399 "Delegation refused: the parent grant's delegationChain is not a list",
400 ));
401 }
402 let mut grants = Vec::new();
403 for link in embedded_chain(parent) {
404 let Some(grant) = link.get("parentCredential").filter(|g| g.is_object()) else {
405 return Err(refused(
406 "Delegation refused: a link in the parent grant's delegationChain \
407 carries no signed grant",
408 ));
409 };
410 grants.push(grant.clone());
411 }
412 grants.push(parent.clone());
413 Ok(grants)
414 }
415 Value::Array(items) => {
416 if items.is_empty() {
417 return Err(refused("Delegation refused: the grant chain is empty"));
418 }
419 if !items.iter().all(Value::is_object) {
420 return Err(refused(
421 "Delegation refused: every grant in the grant chain must be an object",
422 ));
423 }
424 Ok(items.clone())
425 }
426 _ => Err(refused(
427 "parent_credential must be a grant (a dict) or a grant chain (a list of grants, \
428 root first)",
429 )),
430 }
431}
432
433fn intent_of(grant: &Value) -> Result<&Value, GrantChainError> {
435 subject_of(grant)
436 .and_then(|s| s.get("intent"))
437 .filter(|i| i.is_object())
438 .ok_or_else(|| refused("Delegation refused: the parent grant carries no intent object"))
439}
440
441fn link_for(grant: &Value, intent: &Value) -> Result<Value, GrantChainError> {
448 let mut link = Map::new();
449 link.insert(
450 "issuer".into(),
451 Value::String(
452 issuer_value(grant)
453 .and_then(Value::as_str)
454 .unwrap_or_default()
455 .to_string(),
456 ),
457 );
458 link.insert(
459 "subject".into(),
460 intent_of(grant)?
461 .get("delegatee")
462 .cloned()
463 .unwrap_or(Value::Null),
464 );
465 link.insert("intent".into(), intent.clone());
466 for k in ["validFrom", "validUntil"] {
467 link.insert(k.into(), grant.get(k).cloned().unwrap_or(Value::Null));
468 }
469 let bound: String = delegation::parent_proof_binding_value(grant)
470 .chars()
471 .take(64)
472 .collect();
473 link.insert("parentProofValue".into(), Value::String(bound));
474 link.insert("parentCredential".into(), grant.clone());
475 Ok(Value::Object(link))
476}
477
478pub fn chain_links(grants: &[Value], intent: &Value) -> Result<Vec<Value>, GrantChainError> {
496 for grant in grants {
497 intent_of(grant)?;
498 }
499 let mut links: Vec<Value> = Vec::new();
500 let mut start = 0;
501 for j in (0..grants.len()).rev() {
502 let embedded = embedded_chain(&grants[j]);
503 if embedded.is_empty() {
504 continue;
505 }
506 let same = embedded.len() == j
507 && embedded.iter().enumerate().all(|(i, link)| {
508 link.get("parentCredential")
509 .filter(|g| g.is_object())
510 .is_some_and(|g| jcs::canonicalize(g) == jcs::canonicalize(&grants[i]))
511 });
512 if !same {
513 return Err(refused(format!(
514 "Delegation refused: grant {} of the grant chain embeds a chain that is not \
515 the grants before it",
516 j + 1
517 )));
518 }
519 for (i, link) in embedded.iter().enumerate() {
520 if present(link.get("issuer")) != present(issuer_value(&grants[i])) {
521 return Err(refused(format!(
522 "Delegation refused: grant {} of the grant chain embeds a link whose issuer \
523 is not the issuer of grant {}",
524 j + 1,
525 i + 1
526 )));
527 }
528 if present(link.get("subject")) != present(intent_of(&grants[i])?.get("delegatee")) {
529 return Err(refused(format!(
530 "Delegation refused: grant {} of the grant chain embeds a link whose subject \
531 is not the delegatee of grant {}",
532 j + 1,
533 i + 1
534 )));
535 }
536 }
537 links = embedded.to_vec();
538 start = j;
539 break;
540 }
541 for j in start..grants.len() {
542 let step_intent = if j + 1 < grants.len() {
543 intent_of(&grants[j + 1])?
544 } else {
545 intent
546 };
547 links.push(link_for(&grants[j], step_intent)?);
548 }
549 Ok(links)
550}
551
552fn issuer_value(grant: &Value) -> Option<&Value> {
554 match grant.get("issuer") {
555 Some(Value::Object(o)) => o.get("id"),
556 other => other,
557 }
558}
559
560fn present(v: Option<&Value>) -> Option<&Value> {
563 v.filter(|x| !x.is_null())
564}
565
566pub(crate) fn truthy(v: Option<&Value>) -> bool {
568 match v {
569 None | Some(Value::Null) => false,
570 Some(Value::Bool(b)) => *b,
571 Some(Value::Number(n)) => n.as_f64().is_some_and(|f| f != 0.0),
572 Some(Value::String(s)) => !s.is_empty(),
573 Some(Value::Array(a)) => !a.is_empty(),
574 Some(Value::Object(o)) => !o.is_empty(),
575 }
576}
577
578pub(crate) fn py_repr(v: Option<&Value>) -> String {
581 match v {
582 None | Some(Value::Null) => "None".into(),
583 Some(Value::Bool(true)) => "True".into(),
584 Some(Value::Bool(false)) => "False".into(),
585 Some(Value::Number(n)) => match n.as_f64() {
587 Some(f) if n.is_f64() => py_repr_float(f),
588 _ => n.to_string(),
589 },
590 Some(Value::String(s)) => py_repr_str(s),
591 Some(Value::Array(a)) => {
592 let items: Vec<String> = a.iter().map(|x| py_repr(Some(x))).collect();
593 format!("[{}]", items.join(", "))
594 }
595 Some(Value::Object(o)) => {
596 let items: Vec<String> = o
597 .iter()
598 .map(|(k, x)| format!("{}: {}", py_repr_str(k), py_repr(Some(x))))
599 .collect();
600 format!("{{{}}}", items.join(", "))
601 }
602 }
603}
604
605fn shortest_digits(f: f64) -> (String, i32) {
614 let mut buf = ryu_js::Buffer::new();
615 let text = buf.format(f);
616 let (number, exp) = match text.split_once('e') {
617 Some((n, e)) => (n, e.parse::<i32>().unwrap_or(0)),
618 None => (text, 0),
619 };
620 let (whole, fraction) = number.split_once('.').unwrap_or((number, ""));
621 let all = format!("{whole}{fraction}");
622 let significant = all.trim_start_matches('0');
623 let point = whole.len() as i32 + exp - (all.len() - significant.len()) as i32;
624 let significant = significant.trim_end_matches('0');
625 if significant.is_empty() {
626 return ("0".into(), 1);
627 }
628 (significant.to_string(), point)
629}
630
631pub(crate) fn py_repr_float(f: f64) -> String {
639 if f.is_nan() {
640 return "nan".into();
641 }
642 if f.is_infinite() {
643 return if f > 0.0 { "inf" } else { "-inf" }.into();
644 }
645 let sign = if f.is_sign_negative() { "-" } else { "" };
646 let (digits, point) = shortest_digits(f.abs());
647 let exp = point - 1;
648 if point <= -4 || point > 16 {
649 let (first, rest) = digits.split_at(1);
650 let fraction = if rest.is_empty() {
651 String::new()
652 } else {
653 format!(".{rest}")
654 };
655 let exp_sign = if exp < 0 { '-' } else { '+' };
656 return format!(
657 "{sign}{first}{fraction}e{exp_sign}{:02}",
658 exp.unsigned_abs()
659 );
660 }
661 let len = digits.len() as i32;
662 let body = if point <= 0 {
663 format!("0.{}{digits}", "0".repeat(point.unsigned_abs() as usize))
664 } else if point >= len {
665 format!("{digits}{}.0", "0".repeat((point - len) as usize))
666 } else {
667 let (whole, fraction) = digits.split_at(point as usize);
668 format!("{whole}.{fraction}")
669 };
670 format!("{sign}{body}")
671}
672
673pub(crate) fn py_repr_str(s: &str) -> String {
679 let quote = if s.contains('\'') && !s.contains('"') {
680 '"'
681 } else {
682 '\''
683 };
684 let mut out = String::with_capacity(s.len() + 2);
685 out.push(quote);
686 for c in s.chars() {
687 match c {
688 '\\' => out.push_str("\\\\"),
689 '\n' => out.push_str("\\n"),
690 '\r' => out.push_str("\\r"),
691 '\t' => out.push_str("\\t"),
692 c if c == quote => {
693 out.push('\\');
694 out.push(c);
695 }
696 c if crate::py_printable::is_printable(c) => out.push(c),
697 c if (c as u32) <= 0xff => out.push_str(&format!("\\x{:02x}", c as u32)),
698 c if (c as u32) <= 0xffff => out.push_str(&format!("\\u{:04x}", c as u32)),
699 c => out.push_str(&format!("\\U{:08x}", c as u32)),
700 }
701 }
702 out.push(quote);
703 out
704}
705
706pub fn check_grant_chain(grants: &[Value], intent: &Value) -> Result<Vec<Value>, GrantChainError> {
736 for (j, grant) in grants.iter().enumerate() {
737 intent_of(grant)?;
738 if !truthy(grant.get("issuer"))
739 || !matches!(grant.get("proof"), Some(Value::Object(_) | Value::Array(_)))
740 {
741 return Err(refused(
742 "Delegation refused: the parent grant is not a signed credential",
743 ));
744 }
745 if !issuer_value(grant).is_some_and(Value::is_string) {
746 return Err(refused(format!(
747 "Delegation refused: grant {} of the grant chain has an issuer that is not a \
748 string or an object with a string id",
749 j + 1
750 )));
751 }
752 }
753 for j in 0..grants.len().saturating_sub(1) {
754 let delegatee = intent_of(&grants[j])?
755 .get("delegatee")
756 .and_then(Value::as_str)
757 .filter(|d| !d.is_empty());
758 let Some(delegatee) = delegatee else {
759 return Err(refused(format!(
760 "Delegation refused: grant {} of the grant chain names no delegatee",
761 j + 1
762 )));
763 };
764 let next_issuer = issuer_value(&grants[j + 1]);
765 if next_issuer.and_then(Value::as_str) != Some(delegatee) {
766 return Err(refused(format!(
767 "Delegation refused: grant {} of the grant chain names delegatee {}, but grant \
768 {} is issued by {}",
769 j + 1,
770 py_repr_str(delegatee),
771 j + 2,
772 py_repr(next_issuer)
773 )));
774 }
775 }
776 let links = chain_links(grants, intent)?;
777 if let Some((index, reason)) = binding_failure(&links) {
778 return Err(refused(format!(
779 "Delegation refused: grant {} of the grant chain is not bound to the grant before \
780 it ({reason})",
781 index + 1
782 )));
783 }
784 let mut replica = replica_failure(&links).map(|(i, _)| i);
785 if replica.is_none() && grants.last().is_some_and(is_replica_grant) && is_grant_intent(intent) {
786 replica = Some(grants.len() - 1);
787 }
788 if let Some(index) = replica {
789 return Err(refused(format!(
790 "Delegation refused: grant {} of the grant chain is a replica grant, and a replica \
791 cannot hand its authority on (replica_chain_too_long)",
792 index + 1
793 )));
794 }
795 if grants.len() > 1 {
798 let views: Vec<Value> = grants
799 .iter()
800 .map(|g| delegation::capability_view(g, true))
801 .collect();
802 if let Some(dimension) = attenuation::malformed_dimension(&views[0]) {
805 return Err(refused(format!(
806 "Delegation refused: grant 1 of the grant chain has a malformed {}",
807 py_repr_str(dimension.as_str())
808 )));
809 }
810 if let Err(dimension) = attenuation::first_broader_step(&views) {
811 return Err(refused(format!(
812 "Delegation refused: a grant in the grant chain is broader than the grant before \
813 it on {}",
814 py_repr_str(dimension.as_str())
815 )));
816 }
817 }
818 Ok(links)
819}
820
821pub fn chain_capability(grants: &[Value], include_time: bool) -> Result<Value, GrantChainError> {
827 let mut effective: Option<Value> = None;
828 for grant in grants {
829 let view = delegation::capability_view(grant, include_time);
830 effective = Some(match effective {
831 None => view,
832 Some(e) => attenuation::inherit(&e, &view),
833 });
834 }
835 effective.ok_or_else(|| refused("Delegation refused: the grant chain is empty"))
836}
837
838pub fn grant_chain(parent: &Value, grant: &Value) -> Result<Vec<Value>, GrantChainError> {
850 let mut grants = parent_grants(parent)?;
851 if !grant.is_object() {
852 return Err(refused("grant must be a signed grant (a dict)"));
853 }
854 let intent = intent_of(grant)?;
855 if !is_grant_intent(intent) {
856 return Err(refused(
857 "this credential names no delegatee, so nobody can sign under it",
858 ));
859 }
860 grants.push(grant.clone());
861 check_grant_chain(&grants, intent)?;
862 Ok(grants)
863}
864
865#[cfg(test)]
866mod tests {
867 use super::*;
868 use serde_json::json;
869
870 fn grant(issuer: &str, delegatee: &str, extra: Value) -> Value {
871 let mut subject = json!({
872 "id": issuer,
873 "intent": {"action": "read", "target": "t", "resource": "https://x/a",
874 "delegatee": delegatee}
875 });
876 for (k, v) in extra.as_object().unwrap() {
877 subject[k] = v.clone();
878 }
879 json!({
880 "issuer": issuer,
881 "validFrom": "2026-11-10T00:00:00Z",
882 "validUntil": "2026-11-11T00:00:00Z",
883 "credentialSubject": subject,
884 "proof": {"type": "DataIntegrityProof", "proofValue": format!("z{issuer}")}
885 })
886 }
887
888 fn link(g: &Value) -> Value {
889 json!({"issuer": g["issuer"], "subject": g["credentialSubject"]["intent"]["delegatee"],
890 "parentCredential": g})
891 }
892
893 fn flat3() -> Vec<Value> {
895 let g1 = grant("did:web:root", "did:web:a", json!({}));
896 let g2 = grant(
897 "did:web:a",
898 "did:web:b",
899 json!({ "parentGrantDigest": grant_digest(&g1).unwrap() }),
900 );
901 let g3 = grant(
902 "did:web:b",
903 "did:web:c",
904 json!({ "parentGrantDigest": grant_digest(&g2).unwrap() }),
905 );
906 vec![g1, g2, g3]
907 }
908
909 fn links(grants: &[Value]) -> Vec<Value> {
910 grants.iter().map(link).collect()
911 }
912
913 #[test]
914 fn digest_shape_and_exactness() {
915 let g = grant("did:web:root", "did:web:a", json!({}));
916 let d = grant_digest(&g).unwrap();
917 assert!(d.starts_with("uEi"), "{d}");
918 assert_eq!(d.len(), 47);
919 assert!(!d.contains('=') && !d.contains('+') && !d.contains('/'));
920 let reordered: Value = serde_json::from_str(
922 &serde_json::to_string(&json!({
923 "proof": g["proof"], "credentialSubject": g["credentialSubject"],
924 "validUntil": g["validUntil"], "validFrom": g["validFrom"], "issuer": g["issuer"]
925 }))
926 .unwrap(),
927 )
928 .unwrap();
929 assert_eq!(grant_digest(&reordered).unwrap(), d);
930 let mut other = g.clone();
931 other["proof"]["proofValue"] = json!("zdifferent");
932 assert_ne!(grant_digest(&other).unwrap(), d);
933 for bad in [json!([]), json!("x"), Value::Null, json!(1), json!(true)] {
934 assert_eq!(
935 grant_digest(&bad),
936 Err(GrantDigestError("a grant must be a JSON object".into()))
937 );
938 }
939 }
940
941 #[test]
942 fn flat_and_nested_chains_bind() {
943 assert_eq!(chain_binding_problem(&links(&flat3())), None);
944 assert_eq!(chain_binding_problem(&[]), None);
945 let g = flat3();
947 let ls = links(&g[..2]);
948 let nested = grant(
949 "did:web:b",
950 "did:web:c",
951 json!({ "delegationChain": ls.clone() }),
952 );
953 let mut chain = ls.clone();
954 chain.push(link(&nested));
955 assert_eq!(chain_binding_problem(&chain), None);
956 let g = flat3();
958 let mut g2 = g[1].clone();
959 g2["credentialSubject"]["delegationChain"] = json!([]);
960 assert_eq!(chain_binding_problem(&[link(&g[0]), link(&g2)]), None);
961 }
962
963 #[test]
964 fn binding_refusals() {
965 let g = flat3();
966 let mismatch = Some(REASON_PARENT_MISMATCH);
967 let malformed = Some(REASON_MALFORMED);
968 assert_eq!(chain_binding_problem(&links(&g[1..])), mismatch);
970 let other_root = grant("did:web:root", "did:web:a", json!({"note": "other"}));
972 assert_eq!(
973 chain_binding_problem(&[link(&other_root), link(&g[1]), link(&g[2])]),
974 mismatch
975 );
976 let skip = grant(
978 "did:web:b",
979 "did:web:c",
980 json!({ "parentGrantDigest": grant_digest(&g[0]).unwrap() }),
981 );
982 assert_eq!(
983 chain_binding_problem(&[link(&g[0]), link(&g[1]), link(&skip)]),
984 mismatch
985 );
986 let bare = grant("did:web:a", "did:web:b", json!({}));
988 assert_eq!(chain_binding_problem(&[link(&g[0]), link(&bare)]), mismatch);
989 let right = grant_digest(&g[0]).unwrap();
991 for spelled in [
992 right.to_uppercase(),
993 format!("{right}="),
994 format!(" {right}"),
995 right.replacen('u', "z", 1),
996 ] {
997 let mut g2 = g[1].clone();
998 g2["credentialSubject"][PARENT_GRANT_DIGEST] = json!(spelled);
999 assert_eq!(
1000 chain_binding_problem(&[link(&g[0]), link(&g2)]),
1001 mismatch,
1002 "{spelled}"
1003 );
1004 }
1005 for v in [Value::Null, json!(5), json!({}), json!([right.clone()])] {
1007 let mut g2 = g[1].clone();
1008 g2["credentialSubject"][PARENT_GRANT_DIGEST] = v.clone();
1009 assert_eq!(
1010 chain_binding_problem(&[link(&g[0]), link(&g2)]),
1011 malformed,
1012 "{v}"
1013 );
1014 let mut g1 = g[0].clone();
1016 g1["credentialSubject"][PARENT_GRANT_DIGEST] = v.clone();
1017 assert_eq!(chain_binding_problem(&[link(&g1)]), malformed, "{v}");
1018 }
1019 for v in [Value::Null, json!({}), json!(""), json!(0)] {
1021 let mut g2 = g[1].clone();
1022 g2["credentialSubject"]["delegationChain"] = v.clone();
1023 assert_eq!(
1024 chain_binding_problem(&[link(&g[0]), link(&g2)]),
1025 malformed,
1026 "{v}"
1027 );
1028 }
1029 let mut both = g[1].clone();
1031 both["credentialSubject"]["delegationChain"] = json!([link(&g[0])]);
1032 assert_eq!(
1033 chain_binding_problem(&[link(&g[0]), link(&both)]),
1034 malformed
1035 );
1036 assert_eq!(chain_binding_problem(&[link(&both)]), malformed);
1038 let mut nested_first = g[0].clone();
1039 nested_first["credentialSubject"]["delegationChain"] = json!([link(&g[0])]);
1040 assert_eq!(chain_binding_problem(&[link(&nested_first)]), mismatch);
1041 let mut longer = g[1].clone();
1043 longer["credentialSubject"]
1044 .as_object_mut()
1045 .unwrap()
1046 .remove(PARENT_GRANT_DIGEST);
1047 longer["credentialSubject"]["delegationChain"] = json!([link(&g[0]), link(&g[0])]);
1048 assert_eq!(
1049 chain_binding_problem(&[link(&g[0]), link(&longer)]),
1050 mismatch
1051 );
1052 let mut tampered_link = link(&g[0]);
1053 tampered_link["note"] = json!("x");
1054 longer["credentialSubject"]["delegationChain"] = json!([tampered_link]);
1055 assert_eq!(
1056 chain_binding_problem(&[link(&g[0]), link(&longer)]),
1057 mismatch
1058 );
1059 let mut edited = g[0].clone();
1061 edited["credentialSubject"]["intent"]["resource"] = json!("https://x");
1062 assert_eq!(
1063 chain_binding_problem(&[link(&edited), link(&g[1]), link(&g[2])]),
1064 mismatch
1065 );
1066 assert_eq!(
1068 chain_binding_problem(&[json!({"issuer": "did:web:root"})]),
1069 malformed
1070 );
1071 assert_eq!(
1072 chain_binding_problem(&[link(&g[0]), json!({"parentCredential": "x"})]),
1073 malformed
1074 );
1075 let mut bad_type = g[2].clone();
1077 bad_type["credentialSubject"][PARENT_GRANT_DIGEST] = json!(1);
1078 assert_eq!(
1079 chain_binding_problem(&[link(&g[0]), link(&bare), link(&bad_type)]),
1080 mismatch
1081 );
1082 }
1083
1084 #[test]
1085 fn presented_chain_rule() {
1086 let g = flat3();
1087 assert_eq!(presented_chain_problem(&g), None);
1088 assert_eq!(presented_chain_problem(&[]), None);
1089 assert_eq!(
1091 presented_chain_problem(&g[1..]),
1092 Some((0, REASON_PARENT_MISMATCH))
1093 );
1094 assert_eq!(
1096 presented_chain_problem(&[g[0].clone(), g[2].clone()]),
1097 Some((1, REASON_PARENT_MISMATCH))
1098 );
1099 let mut bad = g[1].clone();
1101 bad["credentialSubject"][PARENT_GRANT_DIGEST] = Value::Null;
1102 assert_eq!(
1103 presented_chain_problem(&[g[0].clone(), bad.clone()]),
1104 Some((1, REASON_MALFORMED))
1105 );
1106 assert_eq!(
1107 presented_chain_problem(std::slice::from_ref(&bad)),
1108 Some((0, REASON_MALFORMED))
1109 );
1110 let plain = grant("did:web:a", "did:web:b", json!({}));
1112 assert_eq!(
1113 presented_chain_problem(&[g[0].clone(), plain.clone()]),
1114 None
1115 );
1116 for (position, value) in [(0, json!("{}")), (1, Value::Null), (2, json!(7))] {
1119 let mut creds = vec![g[0].clone(), plain.clone(), plain.clone()];
1120 creds[position] = value;
1121 assert_eq!(
1122 presented_chain_problem(&creds),
1123 Some((position, REASON_MALFORMED))
1124 );
1125 }
1126 assert_eq!(
1127 presented_chain_problem(&[json!("x"), g[1].clone()]),
1128 Some((0, REASON_MALFORMED))
1129 );
1130 }
1131
1132 fn nested_chain(parent: &Value, intent: &Value) -> Value {
1135 let mut chain = embedded_chain(parent).to_vec();
1136 let mut l = link(parent);
1137 l["intent"] = intent.clone();
1138 chain.push(l);
1139 Value::Array(chain)
1140 }
1141
1142 fn intent_to(delegatee: &str) -> Value {
1143 json!({"action": "read", "target": "t", "resource": "https://x/a", "delegatee": delegatee})
1144 }
1145
1146 fn nested(issuer: &str, delegatee: &str, parent: &Value) -> Value {
1148 grant(
1149 issuer,
1150 delegatee,
1151 json!({ "delegationChain": nested_chain(parent, &intent_to(delegatee)) }),
1152 )
1153 }
1154
1155 fn action(issuer: &str, links: Value) -> Value {
1157 json!({"issuer": issuer, "proof": {"proofValue": "z"},
1158 "credentialSubject": {"intent": {"action": "read"}, "delegationChain": links}})
1159 }
1160
1161 #[test]
1162 fn binding_fields_shape() {
1163 let malformed = Some(REASON_MALFORMED);
1164 let digest = json!("uEiA");
1165 for subject in [
1166 json!({}),
1167 json!({"parentGrantDigest": digest}),
1168 json!({"delegationChain": []}),
1169 json!({"parentGrantDigest": digest, "delegationChain": []}),
1170 json!({"delegationChain": [{"issuer": "x"}]}),
1171 Value::Null,
1173 json!([{"parentGrantDigest": 5}]),
1174 json!("parentGrantDigest"),
1175 ] {
1176 assert_eq!(binding_fields_problem(&subject), None, "{subject}");
1177 }
1178 for subject in [
1179 json!({"parentGrantDigest": null}),
1180 json!({"parentGrantDigest": 5}),
1181 json!({"parentGrantDigest": ["u"]}),
1182 json!({"parentGrantDigest": {}}),
1183 json!({"delegationChain": null}),
1184 json!({"delegationChain": {}}),
1185 json!({"delegationChain": ""}),
1186 json!({"delegationChain": 0}),
1187 json!({"delegationChain": false}),
1188 json!({"parentGrantDigest": digest, "delegationChain": [{}]}),
1189 json!({"parentGrantDigest": null, "delegationChain": [{}]}),
1190 ] {
1191 assert_eq!(binding_fields_problem(&subject), malformed, "{subject}");
1192 }
1193 }
1194
1195 #[test]
1196 fn presented_chains_with_embedded_chains() {
1197 let mismatch = |i| Some((i, REASON_PARENT_MISMATCH));
1198 let malformed = |i| Some((i, REASON_MALFORMED));
1199 let g = flat3();
1200 let (g1, g2) = (g[0].clone(), g[1].clone());
1201 let g1b = grant("did:web:root2", "did:web:a", json!({}));
1202 let g2b = grant(
1203 "did:web:a",
1204 "did:web:b",
1205 json!({ "parentGrantDigest": grant_digest(&g1b).unwrap() }),
1206 );
1207 let leaf = action("did:web:b", json!([]));
1208 let nested_b = nested("did:web:a", "did:web:b", &g1b);
1211 assert_eq!(
1212 presented_chain_problem(&[g1.clone(), nested_b.clone(), leaf.clone()]),
1213 mismatch(1)
1214 );
1215 assert_eq!(
1216 presented_chain_problem(&[g1b.clone(), nested_b.clone(), leaf.clone()]),
1217 None
1218 );
1219 let nested_a = nested("did:web:a", "did:web:b", &g1);
1221 assert_eq!(
1222 presented_chain_problem(&[nested_a.clone(), leaf.clone()]),
1223 mismatch(0)
1224 );
1225 assert_eq!(
1226 presented_chain_problem(&[g2.clone(), leaf.clone()]),
1227 mismatch(0)
1228 );
1229 let elsewhere = action("did:web:b", json!(links(&[g1b.clone(), g2b])));
1231 assert_eq!(
1232 presented_chain_problem(&[g1.clone(), g2.clone(), elsewhere]),
1233 mismatch(2)
1234 );
1235 let here = action("did:web:b", json!(links(&[g1.clone(), g2.clone()])));
1236 assert_eq!(
1237 presented_chain_problem(&[g1.clone(), g2.clone(), here]),
1238 None
1239 );
1240 for fields in [
1242 json!({ "parentGrantDigest": grant_digest(&g1).unwrap(),
1243 "delegationChain": nested_chain(&g1, &intent_to("did:web:b")) }),
1244 json!({"delegationChain": null}),
1245 json!({"delegationChain": {}}),
1246 json!({"parentGrantDigest": null}),
1247 ] {
1248 let sub = grant("did:web:a", "did:web:b", fields.clone());
1249 assert_eq!(
1250 presented_chain_problem(&[g1.clone(), sub, leaf.clone()]),
1251 malformed(1),
1252 "{fields}"
1253 );
1254 }
1255 let g2n = nested("did:web:a", "did:web:b", &g1);
1257 let g3n = nested("did:web:b", "did:web:c", &g2n);
1258 let leaf_c = action("did:web:c", json!([]));
1259 assert_eq!(
1260 presented_chain_problem(&[g1.clone(), g2n.clone(), g3n.clone(), leaf_c.clone()]),
1261 None
1262 );
1263 let nested_leaf = action("did:web:c", nested_chain(&g3n, &json!({"action": "read"})));
1264 assert_eq!(
1265 presented_chain_problem(&[g1.clone(), g2n.clone(), g3n.clone(), nested_leaf]),
1266 None
1267 );
1268 let g3 = grant(
1269 "did:web:b",
1270 "did:web:c",
1271 json!({ "parentGrantDigest": grant_digest(&g2n).unwrap() }),
1272 );
1273 assert_eq!(
1274 presented_chain_problem(&[g1.clone(), g2n.clone(), g3, leaf_c.clone()]),
1275 None
1276 );
1277 assert_eq!(
1279 presented_chain_problem(&[g1.clone(), g2n.clone(), g2n.clone(), g3n, leaf_c]),
1280 mismatch(2)
1281 );
1282 }
1283
1284 #[test]
1285 fn the_last_embedded_link_must_carry_the_previous_credential() {
1286 let g1 = flat3()[0].clone();
1287 let links = nested_chain(&g1, &intent_to("did:web:b"));
1288 let mut no_grant = links.clone();
1289 no_grant[0]
1290 .as_object_mut()
1291 .unwrap()
1292 .remove("parentCredential");
1293 let mut not_an_object = links.clone();
1294 not_an_object[0]["parentCredential"] = json!(g1.to_string());
1295 let mut not_a_link = links.clone();
1296 not_a_link[0] = json!("link");
1297 let mut edited = links.clone();
1299 edited[0]["parentCredential"]["validUntil"] = json!("2026-11-12T00:00:00Z");
1300 for embedded in [no_grant, not_an_object, not_a_link, edited] {
1301 let sub = json!({"issuer": "did:web:a",
1302 "credentialSubject": {"delegationChain": embedded}});
1303 assert_eq!(
1304 presented_chain_problem(&[g1.clone(), sub]),
1305 Some((1, REASON_PARENT_MISMATCH))
1306 );
1307 }
1308 let reordered: Value = serde_json::from_str(&jcs::canonicalize_to_string(&g1)).unwrap();
1310 let sub = json!({"issuer": "did:web:a",
1311 "credentialSubject": {"delegationChain": [{"parentCredential": reordered}]}});
1312 assert_eq!(presented_chain_problem(&[g1, sub]), None);
1313 }
1314
1315 #[test]
1316 fn grant_chains_for_signing() {
1317 let g = flat3();
1318 let leaf_intent = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1319 let ls = check_grant_chain(&g, &leaf_intent).unwrap();
1320 assert_eq!(ls.len(), 3);
1321 assert_eq!(chain_binding_problem(&ls), None);
1322 assert_eq!(ls[0]["intent"], g[1]["credentialSubject"]["intent"]);
1324 assert_eq!(ls[2]["intent"], leaf_intent);
1325 assert_eq!(ls[1]["subject"], json!("did:web:b"));
1326 assert_eq!(ls[1]["parentProofValue"], json!("zdid:web:a"));
1327 let keys: Vec<&str> = ls[0]
1328 .as_object()
1329 .unwrap()
1330 .keys()
1331 .map(|k| k.as_str())
1332 .collect();
1333 assert_eq!(
1334 keys,
1335 [
1336 "issuer",
1337 "subject",
1338 "intent",
1339 "validFrom",
1340 "validUntil",
1341 "parentProofValue",
1342 "parentCredential"
1343 ]
1344 );
1345 let sub = grant(
1347 "did:web:c",
1348 "did:web:d",
1349 json!({ "parentGrantDigest": grant_digest(&g[2]).unwrap() }),
1350 );
1351 let handed = grant_chain(&json!(g.clone()), &sub).unwrap();
1352 assert_eq!(handed.len(), 4);
1353 assert_eq!(handed[3], sub);
1354 assert_eq!(grant_chain(&g[1], &sub).unwrap_err().0, NAMES_PARENT_GRANT);
1356 assert_eq!(parent_grants(&g[2]).unwrap_err().0, NAMES_PARENT_GRANT);
1357 let nested = grant(
1359 "did:web:a",
1360 "did:web:b",
1361 json!({ "delegationChain": [link(&g[0])] }),
1362 );
1363 let pg = parent_grants(&nested).unwrap();
1364 assert_eq!(pg, vec![g[0].clone(), nested.clone()]);
1365 let copied = check_grant_chain(&pg, &leaf_intent).unwrap();
1367 assert_eq!(copied[0], link(&g[0]));
1368 assert_eq!(chain_binding_problem(&copied), None);
1369 let action = json!({"issuer": "did:web:c", "proof": {},
1371 "credentialSubject": {"intent": {"action": "read"}}});
1372 assert_eq!(
1373 grant_chain(&json!(g.clone()), &action).unwrap_err().0,
1374 "this credential names no delegatee, so nobody can sign under it"
1375 );
1376 assert_eq!(
1377 grant_chain(&json!(g.clone()), &json!([])).unwrap_err().0,
1378 "grant must be a signed grant (a dict)"
1379 );
1380 assert!(is_grant_intent(&json!({"delegatee": "did:web:x"})));
1381 for i in [
1382 json!({"delegatee": ""}),
1383 json!({"delegatee": 5}),
1384 json!({}),
1385 json!("x"),
1386 ] {
1387 assert!(!is_grant_intent(&i), "{i}");
1388 }
1389 }
1390
1391 #[test]
1392 fn grant_chain_refusals_match_the_reference_text() {
1393 let g = flat3();
1394 let intent = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1395 let err = |grants: &[Value]| check_grant_chain(grants, &intent).unwrap_err().0;
1396 assert_eq!(
1397 parent_grants(&json!([])).unwrap_err().0,
1398 "Delegation refused: the grant chain is empty"
1399 );
1400 assert_eq!(
1401 parent_grants(&json!([g[0].clone(), 5])).unwrap_err().0,
1402 "Delegation refused: every grant in the grant chain must be an object"
1403 );
1404 assert_eq!(
1405 parent_grants(&json!("x")).unwrap_err().0,
1406 "parent_credential must be a grant (a dict) or a grant chain (a list of grants, root first)"
1407 );
1408 let mut bad_chain = g[0].clone();
1409 bad_chain["credentialSubject"]["delegationChain"] = json!({});
1410 assert_eq!(
1411 parent_grants(&bad_chain).unwrap_err().0,
1412 "Delegation refused: the parent grant's delegationChain is not a list"
1413 );
1414 bad_chain["credentialSubject"]["delegationChain"] = json!([{"issuer": "x"}]);
1415 assert_eq!(
1416 parent_grants(&bad_chain).unwrap_err().0,
1417 "Delegation refused: a link in the parent grant's delegationChain carries no signed grant"
1418 );
1419 let mut unsigned = g[0].clone();
1421 unsigned.as_object_mut().unwrap().remove("proof");
1422 assert_eq!(
1423 err(&[unsigned]),
1424 "Delegation refused: the parent grant is not a signed credential"
1425 );
1426 let mut no_issuer = g[0].clone();
1427 no_issuer["issuer"] = json!("");
1428 assert_eq!(
1429 err(&[no_issuer]),
1430 "Delegation refused: the parent grant is not a signed credential"
1431 );
1432 let mut no_intent = g[0].clone();
1433 no_intent["credentialSubject"]["intent"] = json!("read");
1434 assert_eq!(
1435 err(&[no_intent]),
1436 "Delegation refused: the parent grant carries no intent object"
1437 );
1438 assert_eq!(
1439 err(&[g[0].clone(), g[2].clone()]),
1440 "Delegation refused: grant 1 of the grant chain names delegatee 'did:web:a', but grant 2 is issued by 'did:web:b'"
1441 );
1442 let mut no_issuer2 = g[1].clone();
1444 no_issuer2["issuer"] = json!({"name": "x"});
1445 assert_eq!(
1446 err(&[g[0].clone(), no_issuer2]),
1447 "Delegation refused: grant 2 of the grant chain has an issuer that is not a string or an object with a string id"
1448 );
1449 let mut no_delegatee = g[0].clone();
1450 no_delegatee["credentialSubject"]["intent"]
1451 .as_object_mut()
1452 .unwrap()
1453 .remove("delegatee");
1454 assert_eq!(
1455 err(&[no_delegatee, g[1].clone()]),
1456 "Delegation refused: grant 1 of the grant chain names no delegatee"
1457 );
1458 let mut object_issuer = g[1].clone();
1460 object_issuer["issuer"] = json!({"id": "did:web:a"});
1461 assert!(check_grant_chain(&[g[0].clone(), object_issuer], &intent).is_ok());
1462 let bare = grant("did:web:a", "did:web:b", json!({}));
1464 assert_eq!(
1465 err(&[g[0].clone(), bare]),
1466 "Delegation refused: grant 2 of the grant chain is not bound to the grant before it (delegation_parent_mismatch)"
1467 );
1468 let mut bad_digest = g[1].clone();
1469 bad_digest["credentialSubject"][PARENT_GRANT_DIGEST] = json!(7);
1470 assert_eq!(
1471 err(&[g[0].clone(), bad_digest]),
1472 "Delegation refused: grant 2 of the grant chain is not bound to the grant before it (malformed_delegation)"
1473 );
1474 let nested = grant(
1476 "did:web:a",
1477 "did:web:b",
1478 json!({ "delegationChain": [link(&g[0])] }),
1479 );
1480 let other_root = grant("did:web:root", "did:web:a", json!({"note": "other"}));
1481 assert_eq!(
1482 err(&[other_root, nested]),
1483 "Delegation refused: grant 2 of the grant chain embeds a chain that is not the grants before it"
1484 );
1485 assert_eq!(
1486 chain_capability(&[], false).unwrap_err().0,
1487 "Delegation refused: the grant chain is empty"
1488 );
1489 }
1490
1491 const BROADER: &str =
1492 "Delegation refused: a grant in the grant chain is broader than the grant before it on ";
1493
1494 #[test]
1495 fn an_intermediate_grant_broader_than_the_grant_above_it_is_refused() {
1496 let g = flat3();
1497 let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1498 let digest = json!(grant_digest(&g[0]).unwrap());
1499 let mut broad = g[1].clone();
1500 broad["credentialSubject"]["intent"]["action"] = json!(["read", "write"]);
1501 broad["credentialSubject"][PARENT_GRANT_DIGEST] = digest.clone();
1502 let chain = [g[0].clone(), broad.clone()];
1503 assert_eq!(
1504 check_grant_chain(&chain, &leaf).unwrap_err().0,
1505 format!("{BROADER}'action'")
1506 );
1507 assert_eq!(
1509 grant_chain(&g[0], &broad).unwrap_err().0,
1510 format!("{BROADER}'action'")
1511 );
1512 for (k, v) in [
1514 ("validUntil", "2026-11-12T00:00:00Z"),
1515 ("validFrom", "2026-11-09T00:00:00Z"),
1516 ] {
1517 let mut long = g[1].clone();
1518 long[k] = json!(v);
1519 assert_eq!(
1520 check_grant_chain(&[g[0].clone(), long.clone()], &leaf)
1521 .unwrap_err()
1522 .0,
1523 format!("{BROADER}'time'"),
1524 "{k}"
1525 );
1526 assert_eq!(
1527 grant_chain(&g[0], &long).unwrap_err().0,
1528 format!("{BROADER}'time'")
1529 );
1530 }
1531 let mut wide = g[2].clone();
1533 wide["credentialSubject"]["intent"]["resource"] = json!("https://x");
1534 let mut chain = g.clone();
1535 chain[2] = wide;
1536 assert_eq!(
1537 check_grant_chain(&chain, &leaf).unwrap_err().0,
1538 format!("{BROADER}'resource'")
1539 );
1540 let mut narrow = g[1].clone();
1542 narrow["credentialSubject"]["intent"]["resource"] = json!("https://x/a/b");
1543 narrow["validUntil"] = json!("2026-11-10T12:00:00Z");
1544 assert!(check_grant_chain(&[g[0].clone(), narrow], &leaf).is_ok());
1545 let mut alone = g[0].clone();
1546 alone["credentialSubject"]["intent"]["action"] = json!(["read", "write"]);
1547 assert!(check_grant_chain(&[alone], &leaf).is_ok());
1548 let mut unbound = g[1].clone();
1550 unbound["credentialSubject"]
1551 .as_object_mut()
1552 .unwrap()
1553 .remove(PARENT_GRANT_DIGEST);
1554 unbound["credentialSubject"]["intent"]["action"] = json!("write");
1555 assert_eq!(
1556 check_grant_chain(&[g[0].clone(), unbound], &leaf)
1557 .unwrap_err()
1558 .0,
1559 "Delegation refused: grant 2 of the grant chain is not bound to the grant before it (delegation_parent_mismatch)"
1560 );
1561 }
1562
1563 #[test]
1564 fn a_malformed_first_grant_is_named_as_malformed() {
1565 let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1566 for (dimension, value) in [
1567 ("rate", json!("lots")),
1568 ("policy", json!(["not", "an", "object"])),
1569 ("action", json!(7)),
1570 ("target", json!([1])),
1571 ("resource", json!(7)),
1572 ("time", json!("soon")),
1573 ] {
1574 let mut g1 = grant("did:web:root", "did:web:a", json!({}));
1575 if dimension == "time" {
1576 g1["validUntil"] = value;
1577 } else {
1578 g1["credentialSubject"]["intent"][dimension] = value;
1579 }
1580 let g2 = grant(
1581 "did:web:a",
1582 "did:web:b",
1583 json!({ "parentGrantDigest": grant_digest(&g1).unwrap() }),
1584 );
1585 let message = format!(
1586 "Delegation refused: grant 1 of the grant chain has a malformed '{dimension}'"
1587 );
1588 assert_eq!(
1589 check_grant_chain(&[g1.clone(), g2.clone()], &leaf)
1590 .unwrap_err()
1591 .0,
1592 message
1593 );
1594 assert_eq!(grant_chain(&g1, &g2).unwrap_err().0, message);
1596 assert!(check_grant_chain(&[g1], &leaf).is_ok(), "{dimension}");
1598 }
1599 let g = flat3();
1601 let mut g2 = g[1].clone();
1602 g2["credentialSubject"]["intent"]["rate"] = json!("lots");
1603 assert_eq!(
1604 check_grant_chain(&[g[0].clone(), g2], &leaf).unwrap_err().0,
1605 format!("{BROADER}'rate'")
1606 );
1607 }
1608
1609 #[test]
1610 fn the_helpers_refuse_a_grant_that_is_not_an_object() {
1611 let g = flat3();
1612 let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1613 let no_intent = "Delegation refused: the parent grant carries no intent object";
1614 let mut no_subject = g[1].clone();
1615 no_subject["credentialSubject"] = json!("subject");
1616 let mut no_intent_member = g[1].clone();
1617 no_intent_member["credentialSubject"]
1618 .as_object_mut()
1619 .unwrap()
1620 .remove("intent");
1621 let nested_after = nested("did:web:a", "did:web:b", &g[0]);
1624 for bad in [
1625 json!("x"),
1626 Value::Null,
1627 json!(5),
1628 json!(["nested"]),
1629 no_subject,
1630 no_intent_member,
1631 ] {
1632 for grants in [
1633 vec![bad.clone()],
1634 vec![g[0].clone(), bad.clone()],
1635 vec![bad.clone(), g[0].clone()],
1636 vec![bad.clone(), nested_after.clone()],
1637 ] {
1638 assert_eq!(
1639 check_grant_chain(&grants, &leaf).unwrap_err().0,
1640 no_intent,
1641 "{bad}"
1642 );
1643 assert_eq!(
1644 chain_links(&grants, &leaf).unwrap_err().0,
1645 no_intent,
1646 "{bad}"
1647 );
1648 }
1649 }
1650 }
1651
1652 #[test]
1653 fn a_nested_grant_whose_embedded_link_lies_is_refused() {
1654 let g = flat3();
1655 let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1656 for (field, message) in [
1657 (
1658 "subject",
1659 "Delegation refused: grant 2 of the grant chain embeds a link whose subject is not the delegatee of grant 1",
1660 ),
1661 (
1662 "issuer",
1663 "Delegation refused: grant 2 of the grant chain embeds a link whose issuer is not the issuer of grant 1",
1664 ),
1665 ] {
1666 let mut links = nested_chain(&g[0], &intent_to("did:web:b"));
1667 links[0][field] = json!("did:web:x");
1668 let lying = grant("did:web:a", "did:web:b", json!({ "delegationChain": links }));
1669 let grants = parent_grants(&lying).unwrap();
1670 assert_eq!(check_grant_chain(&grants, &leaf).unwrap_err().0, message);
1671 assert_eq!(
1672 check_grant_chain(&[g[0].clone(), lying.clone()], &leaf)
1673 .unwrap_err()
1674 .0,
1675 message
1676 );
1677 assert_eq!(chain_links(&grants, &leaf).unwrap_err().0, message);
1678 let mut links = nested_chain(&g[0], &intent_to("did:web:b"));
1680 links[0].as_object_mut().unwrap().remove(field);
1681 let missing = grant("did:web:a", "did:web:b", json!({ "delegationChain": links }));
1682 assert_eq!(
1683 check_grant_chain(&[g[0].clone(), missing], &leaf)
1684 .unwrap_err()
1685 .0,
1686 message
1687 );
1688 }
1689 let mut links = nested_chain(&g[0], &intent_to("did:web:b"));
1692 links[0]["issuer"] = json!("did:web:x");
1693 links[0]["subject"] = json!("did:web:x");
1694 let both = grant(
1695 "did:web:a",
1696 "did:web:b",
1697 json!({ "delegationChain": links }),
1698 );
1699 assert!(check_grant_chain(&[g[0].clone(), both.clone()], &leaf)
1700 .unwrap_err()
1701 .0
1702 .contains("whose issuer is not"));
1703 let other_root = grant("did:web:root", "did:web:a", json!({"note": "other"}));
1704 assert_eq!(
1705 check_grant_chain(&[other_root, both], &leaf).unwrap_err().0,
1706 "Delegation refused: grant 2 of the grant chain embeds a chain that is not the grants before it"
1707 );
1708 let honest = nested("did:web:a", "did:web:b", &g[0]);
1710 let out = check_grant_chain(&[g[0].clone(), honest.clone()], &leaf).unwrap();
1711 assert_eq!(out[0], honest["credentialSubject"]["delegationChain"][0]);
1712 assert_eq!(out[1]["parentCredential"], honest);
1713 }
1714
1715 #[test]
1716 fn an_issuer_object_is_carried_as_its_id() {
1717 let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1718 let mut root = grant("did:web:root", "did:web:a", json!({}));
1719 root["issuer"] = json!({"id": "did:web:root", "name": "Root"});
1720 let links = check_grant_chain(std::slice::from_ref(&root), &leaf).unwrap();
1721 assert_eq!(links[0]["issuer"], json!("did:web:root"));
1722 assert_eq!(links[0]["parentCredential"], root);
1723 assert_eq!(chain_binding_problem(&links), None);
1724 let mut odd = root.clone();
1726 odd["issuer"] = json!(42);
1727 assert_eq!(
1728 chain_links(std::slice::from_ref(&odd), &leaf).unwrap()[0]["issuer"],
1729 json!("")
1730 );
1731 }
1732
1733 #[test]
1734 fn an_issuer_that_is_not_a_did_string_is_refused() {
1735 let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1736 for issuer in [
1737 json!(42),
1738 json!({"id": 5}),
1739 json!({"name": "Root"}),
1740 json!(["did:key:z"]),
1741 json!(true),
1742 ] {
1743 let mut root = grant("did:web:root", "did:web:a", json!({}));
1744 root["issuer"] = issuer.clone();
1745 assert_eq!(
1746 check_grant_chain(&[root], &leaf).unwrap_err().0,
1747 "Delegation refused: grant 1 of the grant chain has an issuer that is not a string or an object with a string id",
1748 "{issuer}"
1749 );
1750 }
1751 for issuer in [json!(""), json!({}), Value::Null, json!(0), json!([])] {
1753 let mut root = grant("did:web:root", "did:web:a", json!({}));
1754 root["issuer"] = issuer.clone();
1755 assert_eq!(
1756 check_grant_chain(&[root], &leaf).unwrap_err().0,
1757 "Delegation refused: the parent grant is not a signed credential",
1758 "{issuer}"
1759 );
1760 }
1761 }
1762
1763 #[test]
1764 fn links_are_copies_of_the_grants() {
1765 let g = flat3();
1768 let before = g.clone();
1769 let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1770 let mut links = check_grant_chain(&g, &leaf).unwrap();
1771 assert_eq!(links[0]["parentCredential"], g[0]);
1772 assert_eq!(links[0]["intent"], g[1]["credentialSubject"]["intent"]);
1773 links[0]["intent"]["action"] = json!("write");
1774 links[1]["parentCredential"]["credentialSubject"]["intent"]["action"] = json!("write");
1775 assert_eq!(g, before);
1776 }
1777
1778 #[test]
1779 fn chain_capability_inherits_down_the_chain() {
1780 let mut g = flat3();
1781 g[0]["credentialSubject"]["intent"]["rate"] = json!("10/hour");
1782 g[2]["credentialSubject"]["intent"]
1783 .as_object_mut()
1784 .unwrap()
1785 .remove("resource");
1786 let cap = chain_capability(&g, false).unwrap();
1787 assert_eq!(cap["intent"]["resource"], json!("https://x/a"));
1788 assert_eq!(cap["rate"], json!("10/hour"));
1789 assert_eq!(cap["subject"], json!("did:web:c"));
1790 assert!(cap.get("validFrom").is_none());
1791 let timed = chain_capability(&g, true).unwrap();
1792 assert_eq!(timed["validUntil"], json!("2026-11-11T00:00:00Z"));
1793 }
1794
1795 #[test]
1796 fn python_repr_of_quoted_values() {
1797 assert_eq!(py_repr_str("did:web:a"), "'did:web:a'");
1798 assert_eq!(py_repr_str("it's"), "\"it's\"");
1799 assert_eq!(py_repr_str("a'b\"c"), "'a\\'b\"c'");
1800 assert_eq!(py_repr_str("a\\b\n\u{1}"), "'a\\\\b\\n\\x01'");
1801 assert_eq!(py_repr(None), "None");
1802 assert_eq!(py_repr(Some(&json!(["x", 1]))), "['x', 1]");
1803 assert_eq!(
1806 py_repr_str(
1807 "\u{a0}\u{ad}\u{200b}\u{2028}\u{feff}\u{e000}\u{e0001}\u{10ffff} é中😀\u{3000}\u{7f}\u{1b}\u{85}"
1808 ),
1809 "'\\xa0\\xad\\u200b\\u2028\\ufeff\\ue000\\U000e0001\\U0010ffff é中😀\\u3000\\x7f\\x1b\\x85'"
1810 );
1811 assert_eq!(py_repr_str("it's \u{2029}"), "\"it's \\u2029\"");
1812 assert_eq!(py_repr_str("a\u{378}b"), "'a\\u0378b'");
1813 assert_eq!(
1814 py_repr(Some(&json!({"k\u{0}": ["\u{2066}"]}))),
1815 "{'k\\x00': ['\\u2066']}"
1816 );
1817 }
1818
1819 #[test]
1820 fn python_repr_of_numbers() {
1821 for (text, expected) in [
1824 ("0.0", "0.0"),
1825 ("-0.0", "-0.0"),
1826 ("1.0", "1.0"),
1827 ("-1.5", "-1.5"),
1828 ("0.1", "0.1"),
1829 ("0.30000000000000004", "0.30000000000000004"),
1830 ("100.0", "100.0"),
1831 ("1e2", "100.0"),
1832 ("0.0001", "0.0001"),
1833 ("0.00001", "1e-05"),
1834 ("1e-5", "1e-05"),
1835 ("0.000123", "0.000123"),
1836 ("9.999e-5", "9.999e-05"),
1837 ("1e-7", "1e-07"),
1838 ("123.456", "123.456"),
1839 ("9999999999999998.0", "9999999999999998.0"),
1840 ("1e16", "1e+16"),
1841 ("12345678901234567.0", "1.2345678901234568e+16"),
1842 ("1e21", "1e+21"),
1843 ("1e22", "1e+22"),
1844 ("1.5e300", "1.5e+300"),
1845 ("1.7976931348623157e308", "1.7976931348623157e+308"),
1846 ("5e-324", "5e-324"),
1847 ("2.2250738585072014e-308", "2.2250738585072014e-308"),
1848 ("588197768793114.25", "588197768793114.2"),
1850 ("-164193784243384.125", "-164193784243384.12"),
1851 ("6.02214076e23", "6.02214076e+23"),
1852 ("-2.5e-10", "-2.5e-10"),
1853 ("4.35", "4.35"),
1854 ("1e100", "1e+100"),
1855 ("1E-100", "1e-100"),
1856 ("123e-20", "1.23e-18"),
1857 ("5", "5"),
1858 ("-7", "-7"),
1859 ("0", "0"),
1860 ("18446744073709551615", "18446744073709551615"),
1861 ("-9223372036854775808", "-9223372036854775808"),
1862 (
1863 "{\"maxSpend\": 1e-05, \"ratio\": [0.5, 1e16, 2]}",
1864 "{'maxSpend': 1e-05, 'ratio': [0.5, 1e+16, 2]}",
1865 ),
1866 ] {
1867 let value: Value = serde_json::from_str(text).unwrap();
1868 assert_eq!(py_repr(Some(&value)), expected, "{text}");
1869 }
1870 assert_eq!(py_repr_float(f64::INFINITY), "inf");
1871 assert_eq!(py_repr_float(f64::NEG_INFINITY), "-inf");
1872 assert_eq!(py_repr_float(f64::NAN), "nan");
1873 }
1874}