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";
68
69pub const PARENT_GRANT_DIGEST: &str = "parentGrantDigest";
71
72pub const NAMES_PARENT_GRANT: &str =
74 "this grant names a parent grant; pass the whole grant chain (a list, root first)";
75
76const MULTIHASH_SHA2_256: [u8; 2] = [0x12, 0x20];
78
79#[derive(Debug, Clone, PartialEq, Eq)]
84pub struct GrantDigestError(pub String);
85
86impl fmt::Display for GrantDigestError {
87 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88 f.write_str(&self.0)
89 }
90}
91
92impl std::error::Error for GrantDigestError {}
93
94impl From<GrantDigestError> for CoreError {
95 fn from(e: GrantDigestError) -> Self {
96 CoreError::Json(e.0)
97 }
98}
99
100#[derive(Debug, Clone, PartialEq, Eq)]
103pub struct GrantChainError(pub String);
104
105impl fmt::Display for GrantChainError {
106 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107 f.write_str(&self.0)
108 }
109}
110
111impl std::error::Error for GrantChainError {}
112
113impl From<GrantChainError> for CoreError {
114 fn from(e: GrantChainError) -> Self {
115 CoreError::Json(e.0)
116 }
117}
118
119fn refused(msg: impl Into<String>) -> GrantChainError {
120 GrantChainError(msg.into())
121}
122
123pub fn grant_digest(grant: &Value) -> Result<String, GrantDigestError> {
131 if !grant.is_object() {
132 return Err(GrantDigestError("a grant must be a JSON object".into()));
133 }
134 let mut multihash = Vec::with_capacity(34);
135 multihash.extend_from_slice(&MULTIHASH_SHA2_256);
136 multihash.extend_from_slice(&Sha256::digest(jcs::canonicalize(grant)));
137 Ok(format!("u{}", URL_SAFE_NO_PAD.encode(multihash)))
138}
139
140fn subject_of(grant: &Value) -> Option<&Map<String, Value>> {
143 grant.get("credentialSubject").and_then(Value::as_object)
144}
145
146pub fn binding_fields_problem(subject: &Value) -> Option<&'static str> {
164 let subject = subject.as_object()?;
166 let digest = subject.get(PARENT_GRANT_DIGEST);
167 if digest.is_some_and(|d| !d.is_string()) {
168 return Some(REASON_MALFORMED);
169 }
170 let chain = subject.get("delegationChain");
171 if chain.is_some_and(|c| !c.is_array()) {
172 return Some(REASON_MALFORMED);
173 }
174 if digest.is_some()
175 && chain
176 .and_then(Value::as_array)
177 .is_some_and(|c| !c.is_empty())
178 {
179 return Some(REASON_MALFORMED);
180 }
181 None
182}
183
184fn bindings(cred: &Value) -> (Option<&Value>, &[Value]) {
187 let subject = subject_of(cred);
188 let digest = subject.and_then(|s| s.get(PARENT_GRANT_DIGEST));
189 let embedded = match subject.and_then(|s| s.get("delegationChain")) {
190 Some(Value::Array(a)) => a.as_slice(),
191 _ => &[],
192 };
193 (digest, embedded)
194}
195
196fn binding_failure(chain: &[Value]) -> Option<(usize, &'static str)> {
200 for (i, link) in chain.iter().enumerate() {
201 let Some(grant) = link.get("parentCredential").filter(|g| g.is_object()) else {
202 return Some((i, REASON_MALFORMED));
203 };
204 if let Some(malformed) = binding_fields_problem(&grant["credentialSubject"]) {
205 return Some((i, malformed));
206 }
207 let (digest, embedded) = bindings(grant);
208 let has_embedded = !embedded.is_empty();
210 if i == 0 {
211 if digest.is_some() || has_embedded {
213 return Some((i, REASON_PARENT_MISMATCH));
214 }
215 continue;
216 }
217 let bound = if let Some(Value::String(d)) = digest {
218 match grant_digest(&chain[i - 1]["parentCredential"]) {
219 Ok(expected) => *d == expected,
220 Err(_) => return Some((i, REASON_MALFORMED)),
221 }
222 } else if has_embedded {
223 embedded.len() == i
226 && embedded
227 .iter()
228 .zip(&chain[..i])
229 .all(|(a, b)| jcs::canonicalize(a) == jcs::canonicalize(b))
230 } else {
231 false
232 };
233 if !bound {
234 return Some((i, REASON_PARENT_MISMATCH));
235 }
236 }
237 None
238}
239
240pub fn chain_binding_problem(chain: &[Value]) -> Option<&'static str> {
260 binding_failure(chain).map(|(_, reason)| reason)
261}
262
263pub fn presented_chain_problem(credentials: &[Value]) -> Option<(usize, &'static str)> {
289 for (i, cred) in credentials.iter().enumerate() {
290 if !cred.is_object() {
291 return Some((i, REASON_MALFORMED));
292 }
293 if let Some(malformed) = binding_fields_problem(&cred["credentialSubject"]) {
294 return Some((i, malformed));
295 }
296 let (digest, embedded) = bindings(cred);
297 if i == 0 {
298 if digest.is_some() || !embedded.is_empty() {
300 return Some((i, REASON_PARENT_MISMATCH));
301 }
302 continue;
303 }
304 let previous = &credentials[i - 1];
305 let bound = if let Some(digest) = digest {
306 match grant_digest(previous) {
307 Ok(expected) => digest.as_str() == Some(expected.as_str()),
308 Err(_) => return Some((i, REASON_MALFORMED)),
309 }
310 } else if let Some(last) = embedded.last() {
311 last.get("parentCredential")
314 .filter(|g| g.is_object())
315 .is_some_and(|g| jcs::canonicalize(g) == jcs::canonicalize(previous))
316 } else {
317 continue;
318 };
319 if !bound {
320 return Some((i, REASON_PARENT_MISMATCH));
321 }
322 }
323 None
324}
325
326fn embedded_chain(grant: &Value) -> &[Value] {
332 match subject_of(grant).and_then(|s| s.get("delegationChain")) {
333 Some(Value::Array(a)) => a.as_slice(),
334 _ => &[],
335 }
336}
337
338pub fn is_grant_intent(intent: &Value) -> bool {
341 intent
342 .get("delegatee")
343 .and_then(Value::as_str)
344 .is_some_and(|d| !d.is_empty())
345}
346
347pub fn parent_grants(parent: &Value) -> Result<Vec<Value>, GrantChainError> {
359 match parent {
360 Value::Object(_) => {
361 let subject = subject_of(parent);
362 if subject.is_some_and(|s| s.contains_key(PARENT_GRANT_DIGEST)) {
363 return Err(refused(NAMES_PARENT_GRANT));
364 }
365 if subject
366 .and_then(|s| s.get("delegationChain"))
367 .is_some_and(|c| !c.is_array())
368 {
369 return Err(refused(
370 "Delegation refused: the parent grant's delegationChain is not a list",
371 ));
372 }
373 let mut grants = Vec::new();
374 for link in embedded_chain(parent) {
375 let Some(grant) = link.get("parentCredential").filter(|g| g.is_object()) else {
376 return Err(refused(
377 "Delegation refused: a link in the parent grant's delegationChain \
378 carries no signed grant",
379 ));
380 };
381 grants.push(grant.clone());
382 }
383 grants.push(parent.clone());
384 Ok(grants)
385 }
386 Value::Array(items) => {
387 if items.is_empty() {
388 return Err(refused("Delegation refused: the grant chain is empty"));
389 }
390 if !items.iter().all(Value::is_object) {
391 return Err(refused(
392 "Delegation refused: every grant in the grant chain must be an object",
393 ));
394 }
395 Ok(items.clone())
396 }
397 _ => Err(refused(
398 "parent_credential must be a grant (a dict) or a grant chain (a list of grants, \
399 root first)",
400 )),
401 }
402}
403
404fn intent_of(grant: &Value) -> Result<&Value, GrantChainError> {
406 subject_of(grant)
407 .and_then(|s| s.get("intent"))
408 .filter(|i| i.is_object())
409 .ok_or_else(|| refused("Delegation refused: the parent grant carries no intent object"))
410}
411
412fn link_for(grant: &Value, intent: &Value) -> Result<Value, GrantChainError> {
419 let mut link = Map::new();
420 link.insert(
421 "issuer".into(),
422 Value::String(
423 issuer_value(grant)
424 .and_then(Value::as_str)
425 .unwrap_or_default()
426 .to_string(),
427 ),
428 );
429 link.insert(
430 "subject".into(),
431 intent_of(grant)?
432 .get("delegatee")
433 .cloned()
434 .unwrap_or(Value::Null),
435 );
436 link.insert("intent".into(), intent.clone());
437 for k in ["validFrom", "validUntil"] {
438 link.insert(k.into(), grant.get(k).cloned().unwrap_or(Value::Null));
439 }
440 let bound: String = delegation::parent_proof_binding_value(grant)
441 .chars()
442 .take(64)
443 .collect();
444 link.insert("parentProofValue".into(), Value::String(bound));
445 link.insert("parentCredential".into(), grant.clone());
446 Ok(Value::Object(link))
447}
448
449pub fn chain_links(grants: &[Value], intent: &Value) -> Result<Vec<Value>, GrantChainError> {
467 for grant in grants {
468 intent_of(grant)?;
469 }
470 let mut links: Vec<Value> = Vec::new();
471 let mut start = 0;
472 for j in (0..grants.len()).rev() {
473 let embedded = embedded_chain(&grants[j]);
474 if embedded.is_empty() {
475 continue;
476 }
477 let same = embedded.len() == j
478 && embedded.iter().enumerate().all(|(i, link)| {
479 link.get("parentCredential")
480 .filter(|g| g.is_object())
481 .is_some_and(|g| jcs::canonicalize(g) == jcs::canonicalize(&grants[i]))
482 });
483 if !same {
484 return Err(refused(format!(
485 "Delegation refused: grant {} of the grant chain embeds a chain that is not \
486 the grants before it",
487 j + 1
488 )));
489 }
490 for (i, link) in embedded.iter().enumerate() {
491 if present(link.get("issuer")) != present(issuer_value(&grants[i])) {
492 return Err(refused(format!(
493 "Delegation refused: grant {} of the grant chain embeds a link whose issuer \
494 is not the issuer of grant {}",
495 j + 1,
496 i + 1
497 )));
498 }
499 if present(link.get("subject")) != present(intent_of(&grants[i])?.get("delegatee")) {
500 return Err(refused(format!(
501 "Delegation refused: grant {} of the grant chain embeds a link whose subject \
502 is not the delegatee of grant {}",
503 j + 1,
504 i + 1
505 )));
506 }
507 }
508 links = embedded.to_vec();
509 start = j;
510 break;
511 }
512 for j in start..grants.len() {
513 let step_intent = if j + 1 < grants.len() {
514 intent_of(&grants[j + 1])?
515 } else {
516 intent
517 };
518 links.push(link_for(&grants[j], step_intent)?);
519 }
520 Ok(links)
521}
522
523fn issuer_value(grant: &Value) -> Option<&Value> {
525 match grant.get("issuer") {
526 Some(Value::Object(o)) => o.get("id"),
527 other => other,
528 }
529}
530
531fn present(v: Option<&Value>) -> Option<&Value> {
534 v.filter(|x| !x.is_null())
535}
536
537pub(crate) fn truthy(v: Option<&Value>) -> bool {
539 match v {
540 None | Some(Value::Null) => false,
541 Some(Value::Bool(b)) => *b,
542 Some(Value::Number(n)) => n.as_f64().is_some_and(|f| f != 0.0),
543 Some(Value::String(s)) => !s.is_empty(),
544 Some(Value::Array(a)) => !a.is_empty(),
545 Some(Value::Object(o)) => !o.is_empty(),
546 }
547}
548
549pub(crate) fn py_repr(v: Option<&Value>) -> String {
552 match v {
553 None | Some(Value::Null) => "None".into(),
554 Some(Value::Bool(true)) => "True".into(),
555 Some(Value::Bool(false)) => "False".into(),
556 Some(Value::Number(n)) => match n.as_f64() {
558 Some(f) if n.is_f64() => py_repr_float(f),
559 _ => n.to_string(),
560 },
561 Some(Value::String(s)) => py_repr_str(s),
562 Some(Value::Array(a)) => {
563 let items: Vec<String> = a.iter().map(|x| py_repr(Some(x))).collect();
564 format!("[{}]", items.join(", "))
565 }
566 Some(Value::Object(o)) => {
567 let items: Vec<String> = o
568 .iter()
569 .map(|(k, x)| format!("{}: {}", py_repr_str(k), py_repr(Some(x))))
570 .collect();
571 format!("{{{}}}", items.join(", "))
572 }
573 }
574}
575
576fn shortest_digits(f: f64) -> (String, i32) {
585 let mut buf = ryu_js::Buffer::new();
586 let text = buf.format(f);
587 let (number, exp) = match text.split_once('e') {
588 Some((n, e)) => (n, e.parse::<i32>().unwrap_or(0)),
589 None => (text, 0),
590 };
591 let (whole, fraction) = number.split_once('.').unwrap_or((number, ""));
592 let all = format!("{whole}{fraction}");
593 let significant = all.trim_start_matches('0');
594 let point = whole.len() as i32 + exp - (all.len() - significant.len()) as i32;
595 let significant = significant.trim_end_matches('0');
596 if significant.is_empty() {
597 return ("0".into(), 1);
598 }
599 (significant.to_string(), point)
600}
601
602pub(crate) fn py_repr_float(f: f64) -> String {
610 if f.is_nan() {
611 return "nan".into();
612 }
613 if f.is_infinite() {
614 return if f > 0.0 { "inf" } else { "-inf" }.into();
615 }
616 let sign = if f.is_sign_negative() { "-" } else { "" };
617 let (digits, point) = shortest_digits(f.abs());
618 let exp = point - 1;
619 if point <= -4 || point > 16 {
620 let (first, rest) = digits.split_at(1);
621 let fraction = if rest.is_empty() {
622 String::new()
623 } else {
624 format!(".{rest}")
625 };
626 let exp_sign = if exp < 0 { '-' } else { '+' };
627 return format!(
628 "{sign}{first}{fraction}e{exp_sign}{:02}",
629 exp.unsigned_abs()
630 );
631 }
632 let len = digits.len() as i32;
633 let body = if point <= 0 {
634 format!("0.{}{digits}", "0".repeat(point.unsigned_abs() as usize))
635 } else if point >= len {
636 format!("{digits}{}.0", "0".repeat((point - len) as usize))
637 } else {
638 let (whole, fraction) = digits.split_at(point as usize);
639 format!("{whole}.{fraction}")
640 };
641 format!("{sign}{body}")
642}
643
644pub(crate) fn py_repr_str(s: &str) -> String {
650 let quote = if s.contains('\'') && !s.contains('"') {
651 '"'
652 } else {
653 '\''
654 };
655 let mut out = String::with_capacity(s.len() + 2);
656 out.push(quote);
657 for c in s.chars() {
658 match c {
659 '\\' => out.push_str("\\\\"),
660 '\n' => out.push_str("\\n"),
661 '\r' => out.push_str("\\r"),
662 '\t' => out.push_str("\\t"),
663 c if c == quote => {
664 out.push('\\');
665 out.push(c);
666 }
667 c if crate::py_printable::is_printable(c) => out.push(c),
668 c if (c as u32) <= 0xff => out.push_str(&format!("\\x{:02x}", c as u32)),
669 c if (c as u32) <= 0xffff => out.push_str(&format!("\\u{:04x}", c as u32)),
670 c => out.push_str(&format!("\\U{:08x}", c as u32)),
671 }
672 }
673 out.push(quote);
674 out
675}
676
677pub fn check_grant_chain(grants: &[Value], intent: &Value) -> Result<Vec<Value>, GrantChainError> {
704 for (j, grant) in grants.iter().enumerate() {
705 intent_of(grant)?;
706 if !truthy(grant.get("issuer"))
707 || !matches!(grant.get("proof"), Some(Value::Object(_) | Value::Array(_)))
708 {
709 return Err(refused(
710 "Delegation refused: the parent grant is not a signed credential",
711 ));
712 }
713 if !issuer_value(grant).is_some_and(Value::is_string) {
714 return Err(refused(format!(
715 "Delegation refused: grant {} of the grant chain has an issuer that is not a \
716 string or an object with a string id",
717 j + 1
718 )));
719 }
720 }
721 for j in 0..grants.len().saturating_sub(1) {
722 let delegatee = intent_of(&grants[j])?
723 .get("delegatee")
724 .and_then(Value::as_str)
725 .filter(|d| !d.is_empty());
726 let Some(delegatee) = delegatee else {
727 return Err(refused(format!(
728 "Delegation refused: grant {} of the grant chain names no delegatee",
729 j + 1
730 )));
731 };
732 let next_issuer = issuer_value(&grants[j + 1]);
733 if next_issuer.and_then(Value::as_str) != Some(delegatee) {
734 return Err(refused(format!(
735 "Delegation refused: grant {} of the grant chain names delegatee {}, but grant \
736 {} is issued by {}",
737 j + 1,
738 py_repr_str(delegatee),
739 j + 2,
740 py_repr(next_issuer)
741 )));
742 }
743 }
744 let links = chain_links(grants, intent)?;
745 if let Some((index, reason)) = binding_failure(&links) {
746 return Err(refused(format!(
747 "Delegation refused: grant {} of the grant chain is not bound to the grant before \
748 it ({reason})",
749 index + 1
750 )));
751 }
752 if grants.len() > 1 {
755 let views: Vec<Value> = grants
756 .iter()
757 .map(|g| delegation::capability_view(g, true))
758 .collect();
759 if let Some(dimension) = attenuation::malformed_dimension(&views[0]) {
762 return Err(refused(format!(
763 "Delegation refused: grant 1 of the grant chain has a malformed {}",
764 py_repr_str(dimension.as_str())
765 )));
766 }
767 if let Err(dimension) = attenuation::first_broader_step(&views) {
768 return Err(refused(format!(
769 "Delegation refused: a grant in the grant chain is broader than the grant before \
770 it on {}",
771 py_repr_str(dimension.as_str())
772 )));
773 }
774 }
775 Ok(links)
776}
777
778pub fn chain_capability(grants: &[Value], include_time: bool) -> Result<Value, GrantChainError> {
784 let mut effective: Option<Value> = None;
785 for grant in grants {
786 let view = delegation::capability_view(grant, include_time);
787 effective = Some(match effective {
788 None => view,
789 Some(e) => attenuation::inherit(&e, &view),
790 });
791 }
792 effective.ok_or_else(|| refused("Delegation refused: the grant chain is empty"))
793}
794
795pub fn grant_chain(parent: &Value, grant: &Value) -> Result<Vec<Value>, GrantChainError> {
807 let mut grants = parent_grants(parent)?;
808 if !grant.is_object() {
809 return Err(refused("grant must be a signed grant (a dict)"));
810 }
811 let intent = intent_of(grant)?;
812 if !is_grant_intent(intent) {
813 return Err(refused(
814 "this credential names no delegatee, so nobody can sign under it",
815 ));
816 }
817 grants.push(grant.clone());
818 check_grant_chain(&grants, intent)?;
819 Ok(grants)
820}
821
822#[cfg(test)]
823mod tests {
824 use super::*;
825 use serde_json::json;
826
827 fn grant(issuer: &str, delegatee: &str, extra: Value) -> Value {
828 let mut subject = json!({
829 "id": issuer,
830 "intent": {"action": "read", "target": "t", "resource": "https://x/a",
831 "delegatee": delegatee}
832 });
833 for (k, v) in extra.as_object().unwrap() {
834 subject[k] = v.clone();
835 }
836 json!({
837 "issuer": issuer,
838 "validFrom": "2026-11-10T00:00:00Z",
839 "validUntil": "2026-11-11T00:00:00Z",
840 "credentialSubject": subject,
841 "proof": {"type": "DataIntegrityProof", "proofValue": format!("z{issuer}")}
842 })
843 }
844
845 fn link(g: &Value) -> Value {
846 json!({"issuer": g["issuer"], "subject": g["credentialSubject"]["intent"]["delegatee"],
847 "parentCredential": g})
848 }
849
850 fn flat3() -> Vec<Value> {
852 let g1 = grant("did:web:root", "did:web:a", json!({}));
853 let g2 = grant(
854 "did:web:a",
855 "did:web:b",
856 json!({ "parentGrantDigest": grant_digest(&g1).unwrap() }),
857 );
858 let g3 = grant(
859 "did:web:b",
860 "did:web:c",
861 json!({ "parentGrantDigest": grant_digest(&g2).unwrap() }),
862 );
863 vec![g1, g2, g3]
864 }
865
866 fn links(grants: &[Value]) -> Vec<Value> {
867 grants.iter().map(link).collect()
868 }
869
870 #[test]
871 fn digest_shape_and_exactness() {
872 let g = grant("did:web:root", "did:web:a", json!({}));
873 let d = grant_digest(&g).unwrap();
874 assert!(d.starts_with("uEi"), "{d}");
875 assert_eq!(d.len(), 47);
876 assert!(!d.contains('=') && !d.contains('+') && !d.contains('/'));
877 let reordered: Value = serde_json::from_str(
879 &serde_json::to_string(&json!({
880 "proof": g["proof"], "credentialSubject": g["credentialSubject"],
881 "validUntil": g["validUntil"], "validFrom": g["validFrom"], "issuer": g["issuer"]
882 }))
883 .unwrap(),
884 )
885 .unwrap();
886 assert_eq!(grant_digest(&reordered).unwrap(), d);
887 let mut other = g.clone();
888 other["proof"]["proofValue"] = json!("zdifferent");
889 assert_ne!(grant_digest(&other).unwrap(), d);
890 for bad in [json!([]), json!("x"), Value::Null, json!(1), json!(true)] {
891 assert_eq!(
892 grant_digest(&bad),
893 Err(GrantDigestError("a grant must be a JSON object".into()))
894 );
895 }
896 }
897
898 #[test]
899 fn flat_and_nested_chains_bind() {
900 assert_eq!(chain_binding_problem(&links(&flat3())), None);
901 assert_eq!(chain_binding_problem(&[]), None);
902 let g = flat3();
904 let ls = links(&g[..2]);
905 let nested = grant(
906 "did:web:b",
907 "did:web:c",
908 json!({ "delegationChain": ls.clone() }),
909 );
910 let mut chain = ls.clone();
911 chain.push(link(&nested));
912 assert_eq!(chain_binding_problem(&chain), None);
913 let g = flat3();
915 let mut g2 = g[1].clone();
916 g2["credentialSubject"]["delegationChain"] = json!([]);
917 assert_eq!(chain_binding_problem(&[link(&g[0]), link(&g2)]), None);
918 }
919
920 #[test]
921 fn binding_refusals() {
922 let g = flat3();
923 let mismatch = Some(REASON_PARENT_MISMATCH);
924 let malformed = Some(REASON_MALFORMED);
925 assert_eq!(chain_binding_problem(&links(&g[1..])), mismatch);
927 let other_root = grant("did:web:root", "did:web:a", json!({"note": "other"}));
929 assert_eq!(
930 chain_binding_problem(&[link(&other_root), link(&g[1]), link(&g[2])]),
931 mismatch
932 );
933 let skip = grant(
935 "did:web:b",
936 "did:web:c",
937 json!({ "parentGrantDigest": grant_digest(&g[0]).unwrap() }),
938 );
939 assert_eq!(
940 chain_binding_problem(&[link(&g[0]), link(&g[1]), link(&skip)]),
941 mismatch
942 );
943 let bare = grant("did:web:a", "did:web:b", json!({}));
945 assert_eq!(chain_binding_problem(&[link(&g[0]), link(&bare)]), mismatch);
946 let right = grant_digest(&g[0]).unwrap();
948 for spelled in [
949 right.to_uppercase(),
950 format!("{right}="),
951 format!(" {right}"),
952 right.replacen('u', "z", 1),
953 ] {
954 let mut g2 = g[1].clone();
955 g2["credentialSubject"][PARENT_GRANT_DIGEST] = json!(spelled);
956 assert_eq!(
957 chain_binding_problem(&[link(&g[0]), link(&g2)]),
958 mismatch,
959 "{spelled}"
960 );
961 }
962 for v in [Value::Null, json!(5), json!({}), json!([right.clone()])] {
964 let mut g2 = g[1].clone();
965 g2["credentialSubject"][PARENT_GRANT_DIGEST] = v.clone();
966 assert_eq!(
967 chain_binding_problem(&[link(&g[0]), link(&g2)]),
968 malformed,
969 "{v}"
970 );
971 let mut g1 = g[0].clone();
973 g1["credentialSubject"][PARENT_GRANT_DIGEST] = v.clone();
974 assert_eq!(chain_binding_problem(&[link(&g1)]), malformed, "{v}");
975 }
976 for v in [Value::Null, json!({}), json!(""), json!(0)] {
978 let mut g2 = g[1].clone();
979 g2["credentialSubject"]["delegationChain"] = v.clone();
980 assert_eq!(
981 chain_binding_problem(&[link(&g[0]), link(&g2)]),
982 malformed,
983 "{v}"
984 );
985 }
986 let mut both = g[1].clone();
988 both["credentialSubject"]["delegationChain"] = json!([link(&g[0])]);
989 assert_eq!(
990 chain_binding_problem(&[link(&g[0]), link(&both)]),
991 malformed
992 );
993 assert_eq!(chain_binding_problem(&[link(&both)]), malformed);
995 let mut nested_first = g[0].clone();
996 nested_first["credentialSubject"]["delegationChain"] = json!([link(&g[0])]);
997 assert_eq!(chain_binding_problem(&[link(&nested_first)]), mismatch);
998 let mut longer = g[1].clone();
1000 longer["credentialSubject"]
1001 .as_object_mut()
1002 .unwrap()
1003 .remove(PARENT_GRANT_DIGEST);
1004 longer["credentialSubject"]["delegationChain"] = json!([link(&g[0]), link(&g[0])]);
1005 assert_eq!(
1006 chain_binding_problem(&[link(&g[0]), link(&longer)]),
1007 mismatch
1008 );
1009 let mut tampered_link = link(&g[0]);
1010 tampered_link["note"] = json!("x");
1011 longer["credentialSubject"]["delegationChain"] = json!([tampered_link]);
1012 assert_eq!(
1013 chain_binding_problem(&[link(&g[0]), link(&longer)]),
1014 mismatch
1015 );
1016 let mut edited = g[0].clone();
1018 edited["credentialSubject"]["intent"]["resource"] = json!("https://x");
1019 assert_eq!(
1020 chain_binding_problem(&[link(&edited), link(&g[1]), link(&g[2])]),
1021 mismatch
1022 );
1023 assert_eq!(
1025 chain_binding_problem(&[json!({"issuer": "did:web:root"})]),
1026 malformed
1027 );
1028 assert_eq!(
1029 chain_binding_problem(&[link(&g[0]), json!({"parentCredential": "x"})]),
1030 malformed
1031 );
1032 let mut bad_type = g[2].clone();
1034 bad_type["credentialSubject"][PARENT_GRANT_DIGEST] = json!(1);
1035 assert_eq!(
1036 chain_binding_problem(&[link(&g[0]), link(&bare), link(&bad_type)]),
1037 mismatch
1038 );
1039 }
1040
1041 #[test]
1042 fn presented_chain_rule() {
1043 let g = flat3();
1044 assert_eq!(presented_chain_problem(&g), None);
1045 assert_eq!(presented_chain_problem(&[]), None);
1046 assert_eq!(
1048 presented_chain_problem(&g[1..]),
1049 Some((0, REASON_PARENT_MISMATCH))
1050 );
1051 assert_eq!(
1053 presented_chain_problem(&[g[0].clone(), g[2].clone()]),
1054 Some((1, REASON_PARENT_MISMATCH))
1055 );
1056 let mut bad = g[1].clone();
1058 bad["credentialSubject"][PARENT_GRANT_DIGEST] = Value::Null;
1059 assert_eq!(
1060 presented_chain_problem(&[g[0].clone(), bad.clone()]),
1061 Some((1, REASON_MALFORMED))
1062 );
1063 assert_eq!(
1064 presented_chain_problem(std::slice::from_ref(&bad)),
1065 Some((0, REASON_MALFORMED))
1066 );
1067 let plain = grant("did:web:a", "did:web:b", json!({}));
1069 assert_eq!(
1070 presented_chain_problem(&[g[0].clone(), plain.clone()]),
1071 None
1072 );
1073 for (position, value) in [(0, json!("{}")), (1, Value::Null), (2, json!(7))] {
1076 let mut creds = vec![g[0].clone(), plain.clone(), plain.clone()];
1077 creds[position] = value;
1078 assert_eq!(
1079 presented_chain_problem(&creds),
1080 Some((position, REASON_MALFORMED))
1081 );
1082 }
1083 assert_eq!(
1084 presented_chain_problem(&[json!("x"), g[1].clone()]),
1085 Some((0, REASON_MALFORMED))
1086 );
1087 }
1088
1089 fn nested_chain(parent: &Value, intent: &Value) -> Value {
1092 let mut chain = embedded_chain(parent).to_vec();
1093 let mut l = link(parent);
1094 l["intent"] = intent.clone();
1095 chain.push(l);
1096 Value::Array(chain)
1097 }
1098
1099 fn intent_to(delegatee: &str) -> Value {
1100 json!({"action": "read", "target": "t", "resource": "https://x/a", "delegatee": delegatee})
1101 }
1102
1103 fn nested(issuer: &str, delegatee: &str, parent: &Value) -> Value {
1105 grant(
1106 issuer,
1107 delegatee,
1108 json!({ "delegationChain": nested_chain(parent, &intent_to(delegatee)) }),
1109 )
1110 }
1111
1112 fn action(issuer: &str, links: Value) -> Value {
1114 json!({"issuer": issuer, "proof": {"proofValue": "z"},
1115 "credentialSubject": {"intent": {"action": "read"}, "delegationChain": links}})
1116 }
1117
1118 #[test]
1119 fn binding_fields_shape() {
1120 let malformed = Some(REASON_MALFORMED);
1121 let digest = json!("uEiA");
1122 for subject in [
1123 json!({}),
1124 json!({"parentGrantDigest": digest}),
1125 json!({"delegationChain": []}),
1126 json!({"parentGrantDigest": digest, "delegationChain": []}),
1127 json!({"delegationChain": [{"issuer": "x"}]}),
1128 Value::Null,
1130 json!([{"parentGrantDigest": 5}]),
1131 json!("parentGrantDigest"),
1132 ] {
1133 assert_eq!(binding_fields_problem(&subject), None, "{subject}");
1134 }
1135 for subject in [
1136 json!({"parentGrantDigest": null}),
1137 json!({"parentGrantDigest": 5}),
1138 json!({"parentGrantDigest": ["u"]}),
1139 json!({"parentGrantDigest": {}}),
1140 json!({"delegationChain": null}),
1141 json!({"delegationChain": {}}),
1142 json!({"delegationChain": ""}),
1143 json!({"delegationChain": 0}),
1144 json!({"delegationChain": false}),
1145 json!({"parentGrantDigest": digest, "delegationChain": [{}]}),
1146 json!({"parentGrantDigest": null, "delegationChain": [{}]}),
1147 ] {
1148 assert_eq!(binding_fields_problem(&subject), malformed, "{subject}");
1149 }
1150 }
1151
1152 #[test]
1153 fn presented_chains_with_embedded_chains() {
1154 let mismatch = |i| Some((i, REASON_PARENT_MISMATCH));
1155 let malformed = |i| Some((i, REASON_MALFORMED));
1156 let g = flat3();
1157 let (g1, g2) = (g[0].clone(), g[1].clone());
1158 let g1b = grant("did:web:root2", "did:web:a", json!({}));
1159 let g2b = grant(
1160 "did:web:a",
1161 "did:web:b",
1162 json!({ "parentGrantDigest": grant_digest(&g1b).unwrap() }),
1163 );
1164 let leaf = action("did:web:b", json!([]));
1165 let nested_b = nested("did:web:a", "did:web:b", &g1b);
1168 assert_eq!(
1169 presented_chain_problem(&[g1.clone(), nested_b.clone(), leaf.clone()]),
1170 mismatch(1)
1171 );
1172 assert_eq!(
1173 presented_chain_problem(&[g1b.clone(), nested_b.clone(), leaf.clone()]),
1174 None
1175 );
1176 let nested_a = nested("did:web:a", "did:web:b", &g1);
1178 assert_eq!(
1179 presented_chain_problem(&[nested_a.clone(), leaf.clone()]),
1180 mismatch(0)
1181 );
1182 assert_eq!(
1183 presented_chain_problem(&[g2.clone(), leaf.clone()]),
1184 mismatch(0)
1185 );
1186 let elsewhere = action("did:web:b", json!(links(&[g1b.clone(), g2b])));
1188 assert_eq!(
1189 presented_chain_problem(&[g1.clone(), g2.clone(), elsewhere]),
1190 mismatch(2)
1191 );
1192 let here = action("did:web:b", json!(links(&[g1.clone(), g2.clone()])));
1193 assert_eq!(
1194 presented_chain_problem(&[g1.clone(), g2.clone(), here]),
1195 None
1196 );
1197 for fields in [
1199 json!({ "parentGrantDigest": grant_digest(&g1).unwrap(),
1200 "delegationChain": nested_chain(&g1, &intent_to("did:web:b")) }),
1201 json!({"delegationChain": null}),
1202 json!({"delegationChain": {}}),
1203 json!({"parentGrantDigest": null}),
1204 ] {
1205 let sub = grant("did:web:a", "did:web:b", fields.clone());
1206 assert_eq!(
1207 presented_chain_problem(&[g1.clone(), sub, leaf.clone()]),
1208 malformed(1),
1209 "{fields}"
1210 );
1211 }
1212 let g2n = nested("did:web:a", "did:web:b", &g1);
1214 let g3n = nested("did:web:b", "did:web:c", &g2n);
1215 let leaf_c = action("did:web:c", json!([]));
1216 assert_eq!(
1217 presented_chain_problem(&[g1.clone(), g2n.clone(), g3n.clone(), leaf_c.clone()]),
1218 None
1219 );
1220 let nested_leaf = action("did:web:c", nested_chain(&g3n, &json!({"action": "read"})));
1221 assert_eq!(
1222 presented_chain_problem(&[g1.clone(), g2n.clone(), g3n.clone(), nested_leaf]),
1223 None
1224 );
1225 let g3 = grant(
1226 "did:web:b",
1227 "did:web:c",
1228 json!({ "parentGrantDigest": grant_digest(&g2n).unwrap() }),
1229 );
1230 assert_eq!(
1231 presented_chain_problem(&[g1.clone(), g2n.clone(), g3, leaf_c.clone()]),
1232 None
1233 );
1234 assert_eq!(
1236 presented_chain_problem(&[g1.clone(), g2n.clone(), g2n.clone(), g3n, leaf_c]),
1237 mismatch(2)
1238 );
1239 }
1240
1241 #[test]
1242 fn the_last_embedded_link_must_carry_the_previous_credential() {
1243 let g1 = flat3()[0].clone();
1244 let links = nested_chain(&g1, &intent_to("did:web:b"));
1245 let mut no_grant = links.clone();
1246 no_grant[0]
1247 .as_object_mut()
1248 .unwrap()
1249 .remove("parentCredential");
1250 let mut not_an_object = links.clone();
1251 not_an_object[0]["parentCredential"] = json!(g1.to_string());
1252 let mut not_a_link = links.clone();
1253 not_a_link[0] = json!("link");
1254 let mut edited = links.clone();
1256 edited[0]["parentCredential"]["validUntil"] = json!("2026-11-12T00:00:00Z");
1257 for embedded in [no_grant, not_an_object, not_a_link, edited] {
1258 let sub = json!({"issuer": "did:web:a",
1259 "credentialSubject": {"delegationChain": embedded}});
1260 assert_eq!(
1261 presented_chain_problem(&[g1.clone(), sub]),
1262 Some((1, REASON_PARENT_MISMATCH))
1263 );
1264 }
1265 let reordered: Value = serde_json::from_str(&jcs::canonicalize_to_string(&g1)).unwrap();
1267 let sub = json!({"issuer": "did:web:a",
1268 "credentialSubject": {"delegationChain": [{"parentCredential": reordered}]}});
1269 assert_eq!(presented_chain_problem(&[g1, sub]), None);
1270 }
1271
1272 #[test]
1273 fn grant_chains_for_signing() {
1274 let g = flat3();
1275 let leaf_intent = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1276 let ls = check_grant_chain(&g, &leaf_intent).unwrap();
1277 assert_eq!(ls.len(), 3);
1278 assert_eq!(chain_binding_problem(&ls), None);
1279 assert_eq!(ls[0]["intent"], g[1]["credentialSubject"]["intent"]);
1281 assert_eq!(ls[2]["intent"], leaf_intent);
1282 assert_eq!(ls[1]["subject"], json!("did:web:b"));
1283 assert_eq!(ls[1]["parentProofValue"], json!("zdid:web:a"));
1284 let keys: Vec<&str> = ls[0]
1285 .as_object()
1286 .unwrap()
1287 .keys()
1288 .map(|k| k.as_str())
1289 .collect();
1290 assert_eq!(
1291 keys,
1292 [
1293 "issuer",
1294 "subject",
1295 "intent",
1296 "validFrom",
1297 "validUntil",
1298 "parentProofValue",
1299 "parentCredential"
1300 ]
1301 );
1302 let sub = grant(
1304 "did:web:c",
1305 "did:web:d",
1306 json!({ "parentGrantDigest": grant_digest(&g[2]).unwrap() }),
1307 );
1308 let handed = grant_chain(&json!(g.clone()), &sub).unwrap();
1309 assert_eq!(handed.len(), 4);
1310 assert_eq!(handed[3], sub);
1311 assert_eq!(grant_chain(&g[1], &sub).unwrap_err().0, NAMES_PARENT_GRANT);
1313 assert_eq!(parent_grants(&g[2]).unwrap_err().0, NAMES_PARENT_GRANT);
1314 let nested = grant(
1316 "did:web:a",
1317 "did:web:b",
1318 json!({ "delegationChain": [link(&g[0])] }),
1319 );
1320 let pg = parent_grants(&nested).unwrap();
1321 assert_eq!(pg, vec![g[0].clone(), nested.clone()]);
1322 let copied = check_grant_chain(&pg, &leaf_intent).unwrap();
1324 assert_eq!(copied[0], link(&g[0]));
1325 assert_eq!(chain_binding_problem(&copied), None);
1326 let action = json!({"issuer": "did:web:c", "proof": {},
1328 "credentialSubject": {"intent": {"action": "read"}}});
1329 assert_eq!(
1330 grant_chain(&json!(g.clone()), &action).unwrap_err().0,
1331 "this credential names no delegatee, so nobody can sign under it"
1332 );
1333 assert_eq!(
1334 grant_chain(&json!(g.clone()), &json!([])).unwrap_err().0,
1335 "grant must be a signed grant (a dict)"
1336 );
1337 assert!(is_grant_intent(&json!({"delegatee": "did:web:x"})));
1338 for i in [
1339 json!({"delegatee": ""}),
1340 json!({"delegatee": 5}),
1341 json!({}),
1342 json!("x"),
1343 ] {
1344 assert!(!is_grant_intent(&i), "{i}");
1345 }
1346 }
1347
1348 #[test]
1349 fn grant_chain_refusals_match_the_reference_text() {
1350 let g = flat3();
1351 let intent = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1352 let err = |grants: &[Value]| check_grant_chain(grants, &intent).unwrap_err().0;
1353 assert_eq!(
1354 parent_grants(&json!([])).unwrap_err().0,
1355 "Delegation refused: the grant chain is empty"
1356 );
1357 assert_eq!(
1358 parent_grants(&json!([g[0].clone(), 5])).unwrap_err().0,
1359 "Delegation refused: every grant in the grant chain must be an object"
1360 );
1361 assert_eq!(
1362 parent_grants(&json!("x")).unwrap_err().0,
1363 "parent_credential must be a grant (a dict) or a grant chain (a list of grants, root first)"
1364 );
1365 let mut bad_chain = g[0].clone();
1366 bad_chain["credentialSubject"]["delegationChain"] = json!({});
1367 assert_eq!(
1368 parent_grants(&bad_chain).unwrap_err().0,
1369 "Delegation refused: the parent grant's delegationChain is not a list"
1370 );
1371 bad_chain["credentialSubject"]["delegationChain"] = json!([{"issuer": "x"}]);
1372 assert_eq!(
1373 parent_grants(&bad_chain).unwrap_err().0,
1374 "Delegation refused: a link in the parent grant's delegationChain carries no signed grant"
1375 );
1376 let mut unsigned = g[0].clone();
1378 unsigned.as_object_mut().unwrap().remove("proof");
1379 assert_eq!(
1380 err(&[unsigned]),
1381 "Delegation refused: the parent grant is not a signed credential"
1382 );
1383 let mut no_issuer = g[0].clone();
1384 no_issuer["issuer"] = json!("");
1385 assert_eq!(
1386 err(&[no_issuer]),
1387 "Delegation refused: the parent grant is not a signed credential"
1388 );
1389 let mut no_intent = g[0].clone();
1390 no_intent["credentialSubject"]["intent"] = json!("read");
1391 assert_eq!(
1392 err(&[no_intent]),
1393 "Delegation refused: the parent grant carries no intent object"
1394 );
1395 assert_eq!(
1396 err(&[g[0].clone(), g[2].clone()]),
1397 "Delegation refused: grant 1 of the grant chain names delegatee 'did:web:a', but grant 2 is issued by 'did:web:b'"
1398 );
1399 let mut no_issuer2 = g[1].clone();
1401 no_issuer2["issuer"] = json!({"name": "x"});
1402 assert_eq!(
1403 err(&[g[0].clone(), no_issuer2]),
1404 "Delegation refused: grant 2 of the grant chain has an issuer that is not a string or an object with a string id"
1405 );
1406 let mut no_delegatee = g[0].clone();
1407 no_delegatee["credentialSubject"]["intent"]
1408 .as_object_mut()
1409 .unwrap()
1410 .remove("delegatee");
1411 assert_eq!(
1412 err(&[no_delegatee, g[1].clone()]),
1413 "Delegation refused: grant 1 of the grant chain names no delegatee"
1414 );
1415 let mut object_issuer = g[1].clone();
1417 object_issuer["issuer"] = json!({"id": "did:web:a"});
1418 assert!(check_grant_chain(&[g[0].clone(), object_issuer], &intent).is_ok());
1419 let bare = grant("did:web:a", "did:web:b", json!({}));
1421 assert_eq!(
1422 err(&[g[0].clone(), bare]),
1423 "Delegation refused: grant 2 of the grant chain is not bound to the grant before it (delegation_parent_mismatch)"
1424 );
1425 let mut bad_digest = g[1].clone();
1426 bad_digest["credentialSubject"][PARENT_GRANT_DIGEST] = json!(7);
1427 assert_eq!(
1428 err(&[g[0].clone(), bad_digest]),
1429 "Delegation refused: grant 2 of the grant chain is not bound to the grant before it (malformed_delegation)"
1430 );
1431 let nested = grant(
1433 "did:web:a",
1434 "did:web:b",
1435 json!({ "delegationChain": [link(&g[0])] }),
1436 );
1437 let other_root = grant("did:web:root", "did:web:a", json!({"note": "other"}));
1438 assert_eq!(
1439 err(&[other_root, nested]),
1440 "Delegation refused: grant 2 of the grant chain embeds a chain that is not the grants before it"
1441 );
1442 assert_eq!(
1443 chain_capability(&[], false).unwrap_err().0,
1444 "Delegation refused: the grant chain is empty"
1445 );
1446 }
1447
1448 const BROADER: &str =
1449 "Delegation refused: a grant in the grant chain is broader than the grant before it on ";
1450
1451 #[test]
1452 fn an_intermediate_grant_broader_than_the_grant_above_it_is_refused() {
1453 let g = flat3();
1454 let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1455 let digest = json!(grant_digest(&g[0]).unwrap());
1456 let mut broad = g[1].clone();
1457 broad["credentialSubject"]["intent"]["action"] = json!(["read", "write"]);
1458 broad["credentialSubject"][PARENT_GRANT_DIGEST] = digest.clone();
1459 let chain = [g[0].clone(), broad.clone()];
1460 assert_eq!(
1461 check_grant_chain(&chain, &leaf).unwrap_err().0,
1462 format!("{BROADER}'action'")
1463 );
1464 assert_eq!(
1466 grant_chain(&g[0], &broad).unwrap_err().0,
1467 format!("{BROADER}'action'")
1468 );
1469 for (k, v) in [
1471 ("validUntil", "2026-11-12T00:00:00Z"),
1472 ("validFrom", "2026-11-09T00:00:00Z"),
1473 ] {
1474 let mut long = g[1].clone();
1475 long[k] = json!(v);
1476 assert_eq!(
1477 check_grant_chain(&[g[0].clone(), long.clone()], &leaf)
1478 .unwrap_err()
1479 .0,
1480 format!("{BROADER}'time'"),
1481 "{k}"
1482 );
1483 assert_eq!(
1484 grant_chain(&g[0], &long).unwrap_err().0,
1485 format!("{BROADER}'time'")
1486 );
1487 }
1488 let mut wide = g[2].clone();
1490 wide["credentialSubject"]["intent"]["resource"] = json!("https://x");
1491 let mut chain = g.clone();
1492 chain[2] = wide;
1493 assert_eq!(
1494 check_grant_chain(&chain, &leaf).unwrap_err().0,
1495 format!("{BROADER}'resource'")
1496 );
1497 let mut narrow = g[1].clone();
1499 narrow["credentialSubject"]["intent"]["resource"] = json!("https://x/a/b");
1500 narrow["validUntil"] = json!("2026-11-10T12:00:00Z");
1501 assert!(check_grant_chain(&[g[0].clone(), narrow], &leaf).is_ok());
1502 let mut alone = g[0].clone();
1503 alone["credentialSubject"]["intent"]["action"] = json!(["read", "write"]);
1504 assert!(check_grant_chain(&[alone], &leaf).is_ok());
1505 let mut unbound = g[1].clone();
1507 unbound["credentialSubject"]
1508 .as_object_mut()
1509 .unwrap()
1510 .remove(PARENT_GRANT_DIGEST);
1511 unbound["credentialSubject"]["intent"]["action"] = json!("write");
1512 assert_eq!(
1513 check_grant_chain(&[g[0].clone(), unbound], &leaf)
1514 .unwrap_err()
1515 .0,
1516 "Delegation refused: grant 2 of the grant chain is not bound to the grant before it (delegation_parent_mismatch)"
1517 );
1518 }
1519
1520 #[test]
1521 fn a_malformed_first_grant_is_named_as_malformed() {
1522 let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1523 for (dimension, value) in [
1524 ("rate", json!("lots")),
1525 ("policy", json!(["not", "an", "object"])),
1526 ("action", json!(7)),
1527 ("target", json!([1])),
1528 ("resource", json!(7)),
1529 ("time", json!("soon")),
1530 ] {
1531 let mut g1 = grant("did:web:root", "did:web:a", json!({}));
1532 if dimension == "time" {
1533 g1["validUntil"] = value;
1534 } else {
1535 g1["credentialSubject"]["intent"][dimension] = value;
1536 }
1537 let g2 = grant(
1538 "did:web:a",
1539 "did:web:b",
1540 json!({ "parentGrantDigest": grant_digest(&g1).unwrap() }),
1541 );
1542 let message = format!(
1543 "Delegation refused: grant 1 of the grant chain has a malformed '{dimension}'"
1544 );
1545 assert_eq!(
1546 check_grant_chain(&[g1.clone(), g2.clone()], &leaf)
1547 .unwrap_err()
1548 .0,
1549 message
1550 );
1551 assert_eq!(grant_chain(&g1, &g2).unwrap_err().0, message);
1553 assert!(check_grant_chain(&[g1], &leaf).is_ok(), "{dimension}");
1555 }
1556 let g = flat3();
1558 let mut g2 = g[1].clone();
1559 g2["credentialSubject"]["intent"]["rate"] = json!("lots");
1560 assert_eq!(
1561 check_grant_chain(&[g[0].clone(), g2], &leaf).unwrap_err().0,
1562 format!("{BROADER}'rate'")
1563 );
1564 }
1565
1566 #[test]
1567 fn the_helpers_refuse_a_grant_that_is_not_an_object() {
1568 let g = flat3();
1569 let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1570 let no_intent = "Delegation refused: the parent grant carries no intent object";
1571 let mut no_subject = g[1].clone();
1572 no_subject["credentialSubject"] = json!("subject");
1573 let mut no_intent_member = g[1].clone();
1574 no_intent_member["credentialSubject"]
1575 .as_object_mut()
1576 .unwrap()
1577 .remove("intent");
1578 let nested_after = nested("did:web:a", "did:web:b", &g[0]);
1581 for bad in [
1582 json!("x"),
1583 Value::Null,
1584 json!(5),
1585 json!(["nested"]),
1586 no_subject,
1587 no_intent_member,
1588 ] {
1589 for grants in [
1590 vec![bad.clone()],
1591 vec![g[0].clone(), bad.clone()],
1592 vec![bad.clone(), g[0].clone()],
1593 vec![bad.clone(), nested_after.clone()],
1594 ] {
1595 assert_eq!(
1596 check_grant_chain(&grants, &leaf).unwrap_err().0,
1597 no_intent,
1598 "{bad}"
1599 );
1600 assert_eq!(
1601 chain_links(&grants, &leaf).unwrap_err().0,
1602 no_intent,
1603 "{bad}"
1604 );
1605 }
1606 }
1607 }
1608
1609 #[test]
1610 fn a_nested_grant_whose_embedded_link_lies_is_refused() {
1611 let g = flat3();
1612 let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1613 for (field, message) in [
1614 (
1615 "subject",
1616 "Delegation refused: grant 2 of the grant chain embeds a link whose subject is not the delegatee of grant 1",
1617 ),
1618 (
1619 "issuer",
1620 "Delegation refused: grant 2 of the grant chain embeds a link whose issuer is not the issuer of grant 1",
1621 ),
1622 ] {
1623 let mut links = nested_chain(&g[0], &intent_to("did:web:b"));
1624 links[0][field] = json!("did:web:x");
1625 let lying = grant("did:web:a", "did:web:b", json!({ "delegationChain": links }));
1626 let grants = parent_grants(&lying).unwrap();
1627 assert_eq!(check_grant_chain(&grants, &leaf).unwrap_err().0, message);
1628 assert_eq!(
1629 check_grant_chain(&[g[0].clone(), lying.clone()], &leaf)
1630 .unwrap_err()
1631 .0,
1632 message
1633 );
1634 assert_eq!(chain_links(&grants, &leaf).unwrap_err().0, message);
1635 let mut links = nested_chain(&g[0], &intent_to("did:web:b"));
1637 links[0].as_object_mut().unwrap().remove(field);
1638 let missing = grant("did:web:a", "did:web:b", json!({ "delegationChain": links }));
1639 assert_eq!(
1640 check_grant_chain(&[g[0].clone(), missing], &leaf)
1641 .unwrap_err()
1642 .0,
1643 message
1644 );
1645 }
1646 let mut links = nested_chain(&g[0], &intent_to("did:web:b"));
1649 links[0]["issuer"] = json!("did:web:x");
1650 links[0]["subject"] = json!("did:web:x");
1651 let both = grant(
1652 "did:web:a",
1653 "did:web:b",
1654 json!({ "delegationChain": links }),
1655 );
1656 assert!(check_grant_chain(&[g[0].clone(), both.clone()], &leaf)
1657 .unwrap_err()
1658 .0
1659 .contains("whose issuer is not"));
1660 let other_root = grant("did:web:root", "did:web:a", json!({"note": "other"}));
1661 assert_eq!(
1662 check_grant_chain(&[other_root, both], &leaf).unwrap_err().0,
1663 "Delegation refused: grant 2 of the grant chain embeds a chain that is not the grants before it"
1664 );
1665 let honest = nested("did:web:a", "did:web:b", &g[0]);
1667 let out = check_grant_chain(&[g[0].clone(), honest.clone()], &leaf).unwrap();
1668 assert_eq!(out[0], honest["credentialSubject"]["delegationChain"][0]);
1669 assert_eq!(out[1]["parentCredential"], honest);
1670 }
1671
1672 #[test]
1673 fn an_issuer_object_is_carried_as_its_id() {
1674 let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1675 let mut root = grant("did:web:root", "did:web:a", json!({}));
1676 root["issuer"] = json!({"id": "did:web:root", "name": "Root"});
1677 let links = check_grant_chain(std::slice::from_ref(&root), &leaf).unwrap();
1678 assert_eq!(links[0]["issuer"], json!("did:web:root"));
1679 assert_eq!(links[0]["parentCredential"], root);
1680 assert_eq!(chain_binding_problem(&links), None);
1681 let mut odd = root.clone();
1683 odd["issuer"] = json!(42);
1684 assert_eq!(
1685 chain_links(std::slice::from_ref(&odd), &leaf).unwrap()[0]["issuer"],
1686 json!("")
1687 );
1688 }
1689
1690 #[test]
1691 fn an_issuer_that_is_not_a_did_string_is_refused() {
1692 let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1693 for issuer in [
1694 json!(42),
1695 json!({"id": 5}),
1696 json!({"name": "Root"}),
1697 json!(["did:key:z"]),
1698 json!(true),
1699 ] {
1700 let mut root = grant("did:web:root", "did:web:a", json!({}));
1701 root["issuer"] = issuer.clone();
1702 assert_eq!(
1703 check_grant_chain(&[root], &leaf).unwrap_err().0,
1704 "Delegation refused: grant 1 of the grant chain has an issuer that is not a string or an object with a string id",
1705 "{issuer}"
1706 );
1707 }
1708 for issuer in [json!(""), json!({}), Value::Null, json!(0), json!([])] {
1710 let mut root = grant("did:web:root", "did:web:a", json!({}));
1711 root["issuer"] = issuer.clone();
1712 assert_eq!(
1713 check_grant_chain(&[root], &leaf).unwrap_err().0,
1714 "Delegation refused: the parent grant is not a signed credential",
1715 "{issuer}"
1716 );
1717 }
1718 }
1719
1720 #[test]
1721 fn links_are_copies_of_the_grants() {
1722 let g = flat3();
1725 let before = g.clone();
1726 let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1727 let mut links = check_grant_chain(&g, &leaf).unwrap();
1728 assert_eq!(links[0]["parentCredential"], g[0]);
1729 assert_eq!(links[0]["intent"], g[1]["credentialSubject"]["intent"]);
1730 links[0]["intent"]["action"] = json!("write");
1731 links[1]["parentCredential"]["credentialSubject"]["intent"]["action"] = json!("write");
1732 assert_eq!(g, before);
1733 }
1734
1735 #[test]
1736 fn chain_capability_inherits_down_the_chain() {
1737 let mut g = flat3();
1738 g[0]["credentialSubject"]["intent"]["rate"] = json!("10/hour");
1739 g[2]["credentialSubject"]["intent"]
1740 .as_object_mut()
1741 .unwrap()
1742 .remove("resource");
1743 let cap = chain_capability(&g, false).unwrap();
1744 assert_eq!(cap["intent"]["resource"], json!("https://x/a"));
1745 assert_eq!(cap["rate"], json!("10/hour"));
1746 assert_eq!(cap["subject"], json!("did:web:c"));
1747 assert!(cap.get("validFrom").is_none());
1748 let timed = chain_capability(&g, true).unwrap();
1749 assert_eq!(timed["validUntil"], json!("2026-11-11T00:00:00Z"));
1750 }
1751
1752 #[test]
1753 fn python_repr_of_quoted_values() {
1754 assert_eq!(py_repr_str("did:web:a"), "'did:web:a'");
1755 assert_eq!(py_repr_str("it's"), "\"it's\"");
1756 assert_eq!(py_repr_str("a'b\"c"), "'a\\'b\"c'");
1757 assert_eq!(py_repr_str("a\\b\n\u{1}"), "'a\\\\b\\n\\x01'");
1758 assert_eq!(py_repr(None), "None");
1759 assert_eq!(py_repr(Some(&json!(["x", 1]))), "['x', 1]");
1760 assert_eq!(
1763 py_repr_str(
1764 "\u{a0}\u{ad}\u{200b}\u{2028}\u{feff}\u{e000}\u{e0001}\u{10ffff} é中😀\u{3000}\u{7f}\u{1b}\u{85}"
1765 ),
1766 "'\\xa0\\xad\\u200b\\u2028\\ufeff\\ue000\\U000e0001\\U0010ffff é中😀\\u3000\\x7f\\x1b\\x85'"
1767 );
1768 assert_eq!(py_repr_str("it's \u{2029}"), "\"it's \\u2029\"");
1769 assert_eq!(py_repr_str("a\u{378}b"), "'a\\u0378b'");
1770 assert_eq!(
1771 py_repr(Some(&json!({"k\u{0}": ["\u{2066}"]}))),
1772 "{'k\\x00': ['\\u2066']}"
1773 );
1774 }
1775
1776 #[test]
1777 fn python_repr_of_numbers() {
1778 for (text, expected) in [
1781 ("0.0", "0.0"),
1782 ("-0.0", "-0.0"),
1783 ("1.0", "1.0"),
1784 ("-1.5", "-1.5"),
1785 ("0.1", "0.1"),
1786 ("0.30000000000000004", "0.30000000000000004"),
1787 ("100.0", "100.0"),
1788 ("1e2", "100.0"),
1789 ("0.0001", "0.0001"),
1790 ("0.00001", "1e-05"),
1791 ("1e-5", "1e-05"),
1792 ("0.000123", "0.000123"),
1793 ("9.999e-5", "9.999e-05"),
1794 ("1e-7", "1e-07"),
1795 ("123.456", "123.456"),
1796 ("9999999999999998.0", "9999999999999998.0"),
1797 ("1e16", "1e+16"),
1798 ("12345678901234567.0", "1.2345678901234568e+16"),
1799 ("1e21", "1e+21"),
1800 ("1e22", "1e+22"),
1801 ("1.5e300", "1.5e+300"),
1802 ("1.7976931348623157e308", "1.7976931348623157e+308"),
1803 ("5e-324", "5e-324"),
1804 ("2.2250738585072014e-308", "2.2250738585072014e-308"),
1805 ("588197768793114.25", "588197768793114.2"),
1807 ("-164193784243384.125", "-164193784243384.12"),
1808 ("6.02214076e23", "6.02214076e+23"),
1809 ("-2.5e-10", "-2.5e-10"),
1810 ("4.35", "4.35"),
1811 ("1e100", "1e+100"),
1812 ("1E-100", "1e-100"),
1813 ("123e-20", "1.23e-18"),
1814 ("5", "5"),
1815 ("-7", "-7"),
1816 ("0", "0"),
1817 ("18446744073709551615", "18446744073709551615"),
1818 ("-9223372036854775808", "-9223372036854775808"),
1819 (
1820 "{\"maxSpend\": 1e-05, \"ratio\": [0.5, 1e16, 2]}",
1821 "{'maxSpend': 1e-05, 'ratio': [0.5, 1e+16, 2]}",
1822 ),
1823 ] {
1824 let value: Value = serde_json::from_str(text).unwrap();
1825 assert_eq!(py_repr(Some(&value)), expected, "{text}");
1826 }
1827 assert_eq!(py_repr_float(f64::INFINITY), "inf");
1828 assert_eq!(py_repr_float(f64::NEG_INFINITY), "-inf");
1829 assert_eq!(py_repr_float(f64::NAN), "nan");
1830 }
1831}