1#[allow(unused_imports)]
54use crate::prelude::*;
55
56use core::fmt;
57
58use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
59use serde_json::{json, Map, Value};
60use sha2::{Digest, Sha256};
61
62use crate::attenuation;
63use crate::delegation;
64use crate::error::CoreError;
65use crate::jcs;
66
67pub const REASON_PARENT_MISMATCH: &str = "delegation_parent_mismatch";
69pub const REASON_MALFORMED: &str = "malformed_delegation";
71pub const REASON_REPLICA_CHAIN_TOO_LONG: &str = "replica_chain_too_long";
74pub const REPLICA_OF: &str = "replicaOf";
76
77pub const PARENT_GRANT_DIGEST: &str = "parentGrantDigest";
79
80pub const NAMES_PARENT_GRANT: &str =
82 "this grant names a parent grant; pass the whole grant chain (a list, root first)";
83
84const MULTIHASH_SHA2_256: [u8; 2] = [0x12, 0x20];
86
87#[derive(Debug, Clone, PartialEq, Eq)]
92pub struct GrantDigestError(pub String);
93
94impl fmt::Display for GrantDigestError {
95 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96 f.write_str(&self.0)
97 }
98}
99
100impl core::error::Error for GrantDigestError {}
101
102impl From<GrantDigestError> for CoreError {
103 fn from(e: GrantDigestError) -> Self {
104 CoreError::Json(e.0)
105 }
106}
107
108#[derive(Debug, Clone, PartialEq, Eq)]
111pub struct GrantChainError(pub String);
112
113impl fmt::Display for GrantChainError {
114 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115 f.write_str(&self.0)
116 }
117}
118
119impl core::error::Error for GrantChainError {}
120
121impl From<GrantChainError> for CoreError {
122 fn from(e: GrantChainError) -> Self {
123 CoreError::Json(e.0)
124 }
125}
126
127fn refused(msg: impl Into<String>) -> GrantChainError {
128 GrantChainError(msg.into())
129}
130
131pub fn grant_digest(grant: &Value) -> Result<String, GrantDigestError> {
139 crate::nesting::deep_guard!(Err(GrantDigestError(crate::nesting::TOO_DEEP.into())); grant);
140 if !grant.is_object() {
141 return Err(GrantDigestError("a grant must be a JSON object".into()));
142 }
143 let mut multihash = Vec::with_capacity(34);
144 multihash.extend_from_slice(&MULTIHASH_SHA2_256);
145 multihash.extend_from_slice(&Sha256::digest(jcs::canonicalize(grant)));
146 Ok(format!("u{}", URL_SAFE_NO_PAD.encode(multihash)))
147}
148
149fn subject_of(grant: &Value) -> Option<&Map<String, Value>> {
152 grant.get("credentialSubject").and_then(Value::as_object)
153}
154
155pub fn binding_fields_problem(subject: &Value) -> Option<&'static str> {
173 crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP); subject);
174 let subject = subject.as_object()?;
176 let digest = subject.get(PARENT_GRANT_DIGEST);
177 if digest.is_some_and(|d| !d.is_string()) {
178 return Some(REASON_MALFORMED);
179 }
180 let chain = subject.get("delegationChain");
181 if chain.is_some_and(|c| !c.is_array()) {
182 return Some(REASON_MALFORMED);
183 }
184 if digest.is_some()
185 && chain
186 .and_then(Value::as_array)
187 .is_some_and(|c| !c.is_empty())
188 {
189 return Some(REASON_MALFORMED);
190 }
191 None
192}
193
194fn bindings(cred: &Value) -> (Option<&Value>, &[Value]) {
197 let subject = subject_of(cred);
198 let digest = subject.and_then(|s| s.get(PARENT_GRANT_DIGEST));
199 let embedded = match subject.and_then(|s| s.get("delegationChain")) {
200 Some(Value::Array(a)) => a.as_slice(),
201 _ => &[],
202 };
203 (digest, embedded)
204}
205
206fn binding_failure(chain: &[Value]) -> Option<(usize, &'static str)> {
210 for (i, link) in chain.iter().enumerate() {
211 let Some(grant) = link.get("parentCredential").filter(|g| g.is_object()) else {
212 return Some((i, REASON_MALFORMED));
213 };
214 if let Some(malformed) = binding_fields_problem(&grant["credentialSubject"]) {
215 return Some((i, malformed));
216 }
217 let (digest, embedded) = bindings(grant);
218 let has_embedded = !embedded.is_empty();
220 if i == 0 {
221 if digest.is_some() || has_embedded {
223 return Some((i, REASON_PARENT_MISMATCH));
224 }
225 continue;
226 }
227 let bound = if let Some(Value::String(d)) = digest {
228 match grant_digest(&chain[i - 1]["parentCredential"]) {
229 Ok(expected) => *d == expected,
230 Err(_) => return Some((i, REASON_MALFORMED)),
231 }
232 } else if has_embedded {
233 embedded.len() == i
236 && embedded
237 .iter()
238 .zip(&chain[..i])
239 .all(|(a, b)| jcs::canonicalize(a) == jcs::canonicalize(b))
240 } else {
241 false
242 };
243 if !bound {
244 return Some((i, REASON_PARENT_MISMATCH));
245 }
246 }
247 None
248}
249
250pub fn chain_binding_problem(chain: &[Value]) -> Option<&'static str> {
274 crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP); chain);
275 binding_failure(chain)
276 .or_else(|| replica_failure(chain))
277 .map(|(_, reason)| reason)
278}
279
280pub fn is_replica_grant(grant: &Value) -> bool {
282 crate::nesting::deep_guard!(false; grant);
283 subject_of(grant)
284 .and_then(|s| s.get("intent"))
285 .and_then(Value::as_object)
286 .is_some_and(|i| i.contains_key(REPLICA_OF))
287}
288
289fn replica_failure(chain: &[Value]) -> Option<(usize, &'static str)> {
292 let last = chain.len().saturating_sub(1);
293 chain[..last]
294 .iter()
295 .position(|link| link.get("parentCredential").is_some_and(is_replica_grant))
296 .map(|i| (i, REASON_REPLICA_CHAIN_TOO_LONG))
297}
298
299pub fn presented_chain_problem(credentials: &[Value]) -> Option<(usize, &'static str)> {
325 crate::nesting::deep_guard!(Some((0, crate::nesting::TOO_DEEP)); credentials);
326 for (i, cred) in credentials.iter().enumerate() {
327 if !cred.is_object() {
328 return Some((i, REASON_MALFORMED));
329 }
330 if let Some(malformed) = binding_fields_problem(&cred["credentialSubject"]) {
331 return Some((i, malformed));
332 }
333 let (digest, embedded) = bindings(cred);
334 if i == 0 {
335 if digest.is_some() || !embedded.is_empty() {
337 return Some((i, REASON_PARENT_MISMATCH));
338 }
339 continue;
340 }
341 let previous = &credentials[i - 1];
342 let bound = if let Some(digest) = digest {
343 match grant_digest(previous) {
344 Ok(expected) => digest.as_str() == Some(expected.as_str()),
345 Err(_) => return Some((i, REASON_MALFORMED)),
346 }
347 } else if let Some(last) = embedded.last() {
348 last.get("parentCredential")
351 .filter(|g| g.is_object())
352 .is_some_and(|g| jcs::canonicalize(g) == jcs::canonicalize(previous))
353 } else {
354 continue;
355 };
356 if !bound {
357 return Some((i, REASON_PARENT_MISMATCH));
358 }
359 }
360 None
361}
362
363fn embedded_chain(grant: &Value) -> &[Value] {
369 match subject_of(grant).and_then(|s| s.get("delegationChain")) {
370 Some(Value::Array(a)) => a.as_slice(),
371 _ => &[],
372 }
373}
374
375pub fn is_grant_intent(intent: &Value) -> bool {
378 crate::nesting::deep_guard!(false; intent);
379 intent
380 .get("delegatee")
381 .and_then(Value::as_str)
382 .is_some_and(|d| !d.is_empty())
383}
384
385pub fn parent_grants(parent: &Value) -> Result<Vec<Value>, GrantChainError> {
397 crate::nesting::deep_guard!(Err(GrantChainError(crate::nesting::TOO_DEEP.into())); parent);
398 match parent {
399 Value::Object(_) => {
400 let subject = subject_of(parent);
401 if subject.is_some_and(|s| s.contains_key(PARENT_GRANT_DIGEST)) {
402 return Err(refused(NAMES_PARENT_GRANT));
403 }
404 if subject
405 .and_then(|s| s.get("delegationChain"))
406 .is_some_and(|c| !c.is_array())
407 {
408 return Err(refused(
409 "Delegation refused: the parent grant's delegationChain is not a list",
410 ));
411 }
412 let mut grants = Vec::new();
413 for link in embedded_chain(parent) {
414 let Some(grant) = link.get("parentCredential").filter(|g| g.is_object()) else {
415 return Err(refused(
416 "Delegation refused: a link in the parent grant's delegationChain \
417 carries no signed grant",
418 ));
419 };
420 grants.push(grant.clone());
421 }
422 grants.push(parent.clone());
423 Ok(grants)
424 }
425 Value::Array(items) => {
426 if items.is_empty() {
427 return Err(refused("Delegation refused: the grant chain is empty"));
428 }
429 if !items.iter().all(Value::is_object) {
430 return Err(refused(
431 "Delegation refused: every grant in the grant chain must be an object",
432 ));
433 }
434 Ok(items.clone())
435 }
436 _ => Err(refused(
437 "parent_credential must be a grant (a dict) or a grant chain (a list of grants, \
438 root first)",
439 )),
440 }
441}
442
443fn intent_of(grant: &Value) -> Result<&Value, GrantChainError> {
445 subject_of(grant)
446 .and_then(|s| s.get("intent"))
447 .filter(|i| i.is_object())
448 .ok_or_else(|| refused("Delegation refused: the parent grant carries no intent object"))
449}
450
451fn link_for(grant: &Value, intent: &Value) -> Result<Value, GrantChainError> {
458 let mut link = Map::new();
459 link.insert(
460 "issuer".into(),
461 Value::String(
462 issuer_value(grant)
463 .and_then(Value::as_str)
464 .unwrap_or_default()
465 .to_string(),
466 ),
467 );
468 link.insert(
469 "subject".into(),
470 intent_of(grant)?
471 .get("delegatee")
472 .cloned()
473 .unwrap_or(Value::Null),
474 );
475 link.insert("intent".into(), intent.clone());
476 for k in ["validFrom", "validUntil"] {
477 link.insert(k.into(), grant.get(k).cloned().unwrap_or(Value::Null));
478 }
479 let bound: String = delegation::parent_proof_binding_value(grant)
480 .chars()
481 .take(64)
482 .collect();
483 link.insert("parentProofValue".into(), Value::String(bound));
484 link.insert("parentCredential".into(), grant.clone());
485 Ok(Value::Object(link))
486}
487
488pub fn chain_links(grants: &[Value], intent: &Value) -> Result<Vec<Value>, GrantChainError> {
506 crate::nesting::deep_guard!(Err(GrantChainError(crate::nesting::TOO_DEEP.into())); grants, intent);
507 for grant in grants {
508 intent_of(grant)?;
509 }
510 let mut links: Vec<Value> = Vec::new();
511 let mut start = 0;
512 for j in (0..grants.len()).rev() {
513 let embedded = embedded_chain(&grants[j]);
514 if embedded.is_empty() {
515 continue;
516 }
517 let same = embedded.len() == j
518 && embedded.iter().enumerate().all(|(i, link)| {
519 link.get("parentCredential")
520 .filter(|g| g.is_object())
521 .is_some_and(|g| jcs::canonicalize(g) == jcs::canonicalize(&grants[i]))
522 });
523 if !same {
524 return Err(refused(format!(
525 "Delegation refused: grant {} of the grant chain embeds a chain that is not \
526 the grants before it",
527 j + 1
528 )));
529 }
530 for (i, link) in embedded.iter().enumerate() {
531 if present(link.get("issuer")) != present(issuer_value(&grants[i])) {
532 return Err(refused(format!(
533 "Delegation refused: grant {} of the grant chain embeds a link whose issuer \
534 is not the issuer of grant {}",
535 j + 1,
536 i + 1
537 )));
538 }
539 if present(link.get("subject")) != present(intent_of(&grants[i])?.get("delegatee")) {
540 return Err(refused(format!(
541 "Delegation refused: grant {} of the grant chain embeds a link whose subject \
542 is not the delegatee of grant {}",
543 j + 1,
544 i + 1
545 )));
546 }
547 }
548 links = embedded.to_vec();
549 start = j;
550 break;
551 }
552 for j in start..grants.len() {
553 let step_intent = if j + 1 < grants.len() {
554 intent_of(&grants[j + 1])?
555 } else {
556 intent
557 };
558 links.push(link_for(&grants[j], step_intent)?);
559 }
560 Ok(links)
561}
562
563fn issuer_value(grant: &Value) -> Option<&Value> {
565 match grant.get("issuer") {
566 Some(Value::Object(o)) => o.get("id"),
567 other => other,
568 }
569}
570
571fn present(v: Option<&Value>) -> Option<&Value> {
574 v.filter(|x| !x.is_null())
575}
576
577pub(crate) fn truthy(v: Option<&Value>) -> bool {
579 match v {
580 None | Some(Value::Null) => false,
581 Some(Value::Bool(b)) => *b,
582 Some(Value::Number(n)) => n.as_f64().is_some_and(|f| f != 0.0),
583 Some(Value::String(s)) => !s.is_empty(),
584 Some(Value::Array(a)) => !a.is_empty(),
585 Some(Value::Object(o)) => !o.is_empty(),
586 }
587}
588
589pub(crate) fn py_repr(v: Option<&Value>) -> String {
592 match v {
593 None | Some(Value::Null) => "None".into(),
594 Some(Value::Bool(true)) => "True".into(),
595 Some(Value::Bool(false)) => "False".into(),
596 Some(Value::Number(n)) => match n.as_f64() {
598 Some(f) if n.is_f64() => py_repr_float(f),
599 _ => n.to_string(),
600 },
601 Some(Value::String(s)) => py_repr_str(s),
602 Some(Value::Array(a)) => {
603 let items: Vec<String> = a.iter().map(|x| py_repr(Some(x))).collect();
604 format!("[{}]", items.join(", "))
605 }
606 Some(Value::Object(o)) => {
607 let items: Vec<String> = o
608 .iter()
609 .map(|(k, x)| format!("{}: {}", py_repr_str(k), py_repr(Some(x))))
610 .collect();
611 format!("{{{}}}", items.join(", "))
612 }
613 }
614}
615
616fn shortest_digits(f: f64) -> (String, i32) {
625 let mut buf = ryu_js::Buffer::new();
626 let text = buf.format(f);
627 let (number, exp) = match text.split_once('e') {
628 Some((n, e)) => (n, e.parse::<i32>().unwrap_or(0)),
629 None => (text, 0),
630 };
631 let (whole, fraction) = number.split_once('.').unwrap_or((number, ""));
632 let all = format!("{whole}{fraction}");
633 let significant = all.trim_start_matches('0');
634 let point = whole.len() as i32 + exp - (all.len() - significant.len()) as i32;
635 let significant = significant.trim_end_matches('0');
636 if significant.is_empty() {
637 return ("0".into(), 1);
638 }
639 (significant.to_string(), point)
640}
641
642pub(crate) fn py_repr_float(f: f64) -> String {
650 if f.is_nan() {
651 return "nan".into();
652 }
653 if f.is_infinite() {
654 return if f > 0.0 { "inf" } else { "-inf" }.into();
655 }
656 let sign = if f.is_sign_negative() { "-" } else { "" };
657 let (digits, point) = shortest_digits(f.abs());
658 let exp = point - 1;
659 if point <= -4 || point > 16 {
660 let (first, rest) = digits.split_at(1);
661 let fraction = if rest.is_empty() {
662 String::new()
663 } else {
664 format!(".{rest}")
665 };
666 let exp_sign = if exp < 0 { '-' } else { '+' };
667 return format!(
668 "{sign}{first}{fraction}e{exp_sign}{:02}",
669 exp.unsigned_abs()
670 );
671 }
672 let len = digits.len() as i32;
673 let body = if point <= 0 {
674 format!("0.{}{digits}", "0".repeat(point.unsigned_abs() as usize))
675 } else if point >= len {
676 format!("{digits}{}.0", "0".repeat((point - len) as usize))
677 } else {
678 let (whole, fraction) = digits.split_at(point as usize);
679 format!("{whole}.{fraction}")
680 };
681 format!("{sign}{body}")
682}
683
684pub(crate) fn py_repr_str(s: &str) -> String {
690 let quote = if s.contains('\'') && !s.contains('"') {
691 '"'
692 } else {
693 '\''
694 };
695 let mut out = String::with_capacity(s.len() + 2);
696 out.push(quote);
697 for c in s.chars() {
698 match c {
699 '\\' => out.push_str("\\\\"),
700 '\n' => out.push_str("\\n"),
701 '\r' => out.push_str("\\r"),
702 '\t' => out.push_str("\\t"),
703 c if c == quote => {
704 out.push('\\');
705 out.push(c);
706 }
707 c if crate::py_printable::is_printable(c) => out.push(c),
708 c if (c as u32) <= 0xff => out.push_str(&format!("\\x{:02x}", c as u32)),
709 c if (c as u32) <= 0xffff => out.push_str(&format!("\\u{:04x}", c as u32)),
710 c => out.push_str(&format!("\\U{:08x}", c as u32)),
711 }
712 }
713 out.push(quote);
714 out
715}
716
717pub fn check_grant_chain(grants: &[Value], intent: &Value) -> Result<Vec<Value>, GrantChainError> {
747 crate::nesting::deep_guard!(Err(GrantChainError(crate::nesting::TOO_DEEP.into())); grants, intent);
748 for (j, grant) in grants.iter().enumerate() {
749 intent_of(grant)?;
750 if !truthy(grant.get("issuer"))
751 || !matches!(grant.get("proof"), Some(Value::Object(_) | Value::Array(_)))
752 {
753 return Err(refused(
754 "Delegation refused: the parent grant is not a signed credential",
755 ));
756 }
757 if !issuer_value(grant).is_some_and(Value::is_string) {
758 return Err(refused(format!(
759 "Delegation refused: grant {} of the grant chain has an issuer that is not a \
760 string or an object with a string id",
761 j + 1
762 )));
763 }
764 }
765 for j in 0..grants.len().saturating_sub(1) {
766 let delegatee = intent_of(&grants[j])?
767 .get("delegatee")
768 .and_then(Value::as_str)
769 .filter(|d| !d.is_empty());
770 let Some(delegatee) = delegatee else {
771 return Err(refused(format!(
772 "Delegation refused: grant {} of the grant chain names no delegatee",
773 j + 1
774 )));
775 };
776 let next_issuer = issuer_value(&grants[j + 1]);
777 if next_issuer.and_then(Value::as_str) != Some(delegatee) {
778 return Err(refused(format!(
779 "Delegation refused: grant {} of the grant chain names delegatee {}, but grant \
780 {} is issued by {}",
781 j + 1,
782 py_repr_str(delegatee),
783 j + 2,
784 py_repr(next_issuer)
785 )));
786 }
787 }
788 let links = chain_links(grants, intent)?;
789 if let Some((index, reason)) = binding_failure(&links) {
790 return Err(refused(format!(
791 "Delegation refused: grant {} of the grant chain is not bound to the grant before \
792 it ({reason})",
793 index + 1
794 )));
795 }
796 let mut replica = replica_failure(&links).map(|(i, _)| i);
797 if replica.is_none() && grants.last().is_some_and(is_replica_grant) && is_grant_intent(intent) {
798 replica = Some(grants.len() - 1);
799 }
800 if let Some(index) = replica {
801 return Err(refused(format!(
802 "Delegation refused: grant {} of the grant chain is a replica grant, and a replica \
803 cannot hand its authority on (replica_chain_too_long)",
804 index + 1
805 )));
806 }
807 if grants.len() > 1 {
810 let views: Vec<Value> = grants
811 .iter()
812 .map(|g| delegation::capability_view(g, true))
813 .collect();
814 if let Some(dimension) = attenuation::malformed_dimension(&views[0]) {
817 return Err(refused(format!(
818 "Delegation refused: grant 1 of the grant chain has a malformed {}",
819 py_repr_str(dimension.as_str())
820 )));
821 }
822 if let Err(dimension) = attenuation::first_broader_step(&views) {
823 return Err(refused(format!(
824 "Delegation refused: a grant in the grant chain is broader than the grant before \
825 it on {}",
826 py_repr_str(dimension.as_str())
827 )));
828 }
829 }
830 Ok(links)
831}
832
833pub fn chain_capability(grants: &[Value], include_time: bool) -> Result<Value, GrantChainError> {
839 crate::nesting::deep_guard!(Err(GrantChainError(crate::nesting::TOO_DEEP.into())); grants);
840 let mut effective: Option<Value> = None;
841 for grant in grants {
842 let view = delegation::capability_view(grant, include_time);
843 effective = Some(match effective {
844 None => view,
845 Some(e) => attenuation::inherit(&e, &view),
846 });
847 }
848 effective.ok_or_else(|| refused("Delegation refused: the grant chain is empty"))
849}
850
851pub fn grant_chain(parent: &Value, grant: &Value) -> Result<Vec<Value>, GrantChainError> {
863 crate::nesting::deep_guard!(Err(GrantChainError(crate::nesting::TOO_DEEP.into())); parent, grant);
864 let mut grants = parent_grants(parent)?;
865 if !grant.is_object() {
866 return Err(refused("grant must be a signed grant (a dict)"));
867 }
868 let intent = intent_of(grant)?;
869 if !is_grant_intent(intent) {
870 return Err(refused(
871 "this credential names no delegatee, so nobody can sign under it",
872 ));
873 }
874 grants.push(grant.clone());
875 check_grant_chain(&grants, intent)?;
876 Ok(grants)
877}
878
879pub fn rules_json(request: &Value) -> crate::error::Result<Value> {
895 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
896 let arg = |name: &str| request.get(name).unwrap_or(&Value::Null);
897 let list = |name: &str| -> Vec<Value> { arg(name).as_array().cloned().unwrap_or_default() };
898 let chain_error = |e: GrantChainError| {
899 let kind = if e.0.starts_with("parent_credential must be")
900 || e.0.starts_with("grant must be a signed grant")
901 {
902 "type"
903 } else {
904 "refused"
905 };
906 json!({ "error": e.0, "kind": kind })
907 };
908 let ok = |v: Value| json!({ "ok": v });
909 let name = request.get("fn").and_then(Value::as_str).unwrap_or("");
910 Ok(match name {
911 "grantDigest" => match grant_digest(arg("grant")) {
912 Ok(d) => ok(json!(d)),
913 Err(e) => json!({ "error": e.0, "kind": "digest" }),
914 },
915 "bindingFieldsProblem" => ok(json!(binding_fields_problem(arg("subject")))),
916 "chainBindingProblem" => ok(json!(chain_binding_problem(&list("chain")))),
917 "isReplicaGrant" => ok(json!(is_replica_grant(arg("grant")))),
918 "isGrantIntent" => ok(json!(is_grant_intent(arg("intent")))),
919 "presentedChainProblem" => ok(match presented_chain_problem(&list("credentials")) {
920 Some((i, reason)) => json!([i, reason]),
921 None => Value::Null,
922 }),
923 "parentGrants" => match parent_grants(arg("parent")) {
924 Ok(g) => ok(Value::Array(g)),
925 Err(e) => chain_error(e),
926 },
927 "chainLinks" => match chain_links(&list("grants"), arg("intent")) {
928 Ok(l) => ok(Value::Array(l)),
929 Err(e) => chain_error(e),
930 },
931 "checkGrantChain" => match check_grant_chain(&list("grants"), arg("intent")) {
932 Ok(l) => ok(Value::Array(l)),
933 Err(e) => chain_error(e),
934 },
935 "chainCapability" => {
936 let include_time = arg("includeTime").as_bool().unwrap_or(true);
937 match chain_capability(&list("grants"), include_time) {
938 Ok(c) => ok(c),
939 Err(e) => chain_error(e),
940 }
941 }
942 "grantChain" => match grant_chain(arg("parent"), arg("grant")) {
943 Ok(g) => ok(Value::Array(g)),
944 Err(e) => chain_error(e),
945 },
946 other => {
947 return Err(CoreError::Json(format!(
948 "unknown grant chain rule {:?}",
949 other.chars().take(40).collect::<String>()
950 )))
951 }
952 })
953}
954
955#[cfg(test)]
956mod tests {
957 use super::*;
958 use serde_json::json;
959
960 fn grant(issuer: &str, delegatee: &str, extra: Value) -> Value {
961 let mut subject = json!({
962 "id": issuer,
963 "intent": {"action": "read", "target": "t", "resource": "https://x/a",
964 "delegatee": delegatee}
965 });
966 for (k, v) in extra.as_object().unwrap() {
967 subject[k] = v.clone();
968 }
969 json!({
970 "issuer": issuer,
971 "validFrom": "2026-11-10T00:00:00Z",
972 "validUntil": "2026-11-11T00:00:00Z",
973 "credentialSubject": subject,
974 "proof": {"type": "DataIntegrityProof", "proofValue": format!("z{issuer}")}
975 })
976 }
977
978 fn link(g: &Value) -> Value {
979 json!({"issuer": g["issuer"], "subject": g["credentialSubject"]["intent"]["delegatee"],
980 "parentCredential": g})
981 }
982
983 fn flat3() -> Vec<Value> {
985 let g1 = grant("did:web:root", "did:web:a", json!({}));
986 let g2 = grant(
987 "did:web:a",
988 "did:web:b",
989 json!({ "parentGrantDigest": grant_digest(&g1).unwrap() }),
990 );
991 let g3 = grant(
992 "did:web:b",
993 "did:web:c",
994 json!({ "parentGrantDigest": grant_digest(&g2).unwrap() }),
995 );
996 vec![g1, g2, g3]
997 }
998
999 fn links(grants: &[Value]) -> Vec<Value> {
1000 grants.iter().map(link).collect()
1001 }
1002
1003 #[test]
1004 fn digest_shape_and_exactness() {
1005 let g = grant("did:web:root", "did:web:a", json!({}));
1006 let d = grant_digest(&g).unwrap();
1007 assert!(d.starts_with("uEi"), "{d}");
1008 assert_eq!(d.len(), 47);
1009 assert!(!d.contains('=') && !d.contains('+') && !d.contains('/'));
1010 let reordered: Value = serde_json::from_str(
1012 &serde_json::to_string(&json!({
1013 "proof": g["proof"], "credentialSubject": g["credentialSubject"],
1014 "validUntil": g["validUntil"], "validFrom": g["validFrom"], "issuer": g["issuer"]
1015 }))
1016 .unwrap(),
1017 )
1018 .unwrap();
1019 assert_eq!(grant_digest(&reordered).unwrap(), d);
1020 let mut other = g.clone();
1021 other["proof"]["proofValue"] = json!("zdifferent");
1022 assert_ne!(grant_digest(&other).unwrap(), d);
1023 for bad in [json!([]), json!("x"), Value::Null, json!(1), json!(true)] {
1024 assert_eq!(
1025 grant_digest(&bad),
1026 Err(GrantDigestError("a grant must be a JSON object".into()))
1027 );
1028 }
1029 }
1030
1031 #[test]
1032 fn flat_and_nested_chains_bind() {
1033 assert_eq!(chain_binding_problem(&links(&flat3())), None);
1034 assert_eq!(chain_binding_problem(&[]), None);
1035 let g = flat3();
1037 let ls = links(&g[..2]);
1038 let nested = grant(
1039 "did:web:b",
1040 "did:web:c",
1041 json!({ "delegationChain": ls.clone() }),
1042 );
1043 let mut chain = ls.clone();
1044 chain.push(link(&nested));
1045 assert_eq!(chain_binding_problem(&chain), None);
1046 let g = flat3();
1048 let mut g2 = g[1].clone();
1049 g2["credentialSubject"]["delegationChain"] = json!([]);
1050 assert_eq!(chain_binding_problem(&[link(&g[0]), link(&g2)]), None);
1051 }
1052
1053 #[test]
1054 fn binding_refusals() {
1055 let g = flat3();
1056 let mismatch = Some(REASON_PARENT_MISMATCH);
1057 let malformed = Some(REASON_MALFORMED);
1058 assert_eq!(chain_binding_problem(&links(&g[1..])), mismatch);
1060 let other_root = grant("did:web:root", "did:web:a", json!({"note": "other"}));
1062 assert_eq!(
1063 chain_binding_problem(&[link(&other_root), link(&g[1]), link(&g[2])]),
1064 mismatch
1065 );
1066 let skip = grant(
1068 "did:web:b",
1069 "did:web:c",
1070 json!({ "parentGrantDigest": grant_digest(&g[0]).unwrap() }),
1071 );
1072 assert_eq!(
1073 chain_binding_problem(&[link(&g[0]), link(&g[1]), link(&skip)]),
1074 mismatch
1075 );
1076 let bare = grant("did:web:a", "did:web:b", json!({}));
1078 assert_eq!(chain_binding_problem(&[link(&g[0]), link(&bare)]), mismatch);
1079 let right = grant_digest(&g[0]).unwrap();
1081 for spelled in [
1082 right.to_uppercase(),
1083 format!("{right}="),
1084 format!(" {right}"),
1085 right.replacen('u', "z", 1),
1086 ] {
1087 let mut g2 = g[1].clone();
1088 g2["credentialSubject"][PARENT_GRANT_DIGEST] = json!(spelled);
1089 assert_eq!(
1090 chain_binding_problem(&[link(&g[0]), link(&g2)]),
1091 mismatch,
1092 "{spelled}"
1093 );
1094 }
1095 for v in [Value::Null, json!(5), json!({}), json!([right.clone()])] {
1097 let mut g2 = g[1].clone();
1098 g2["credentialSubject"][PARENT_GRANT_DIGEST] = v.clone();
1099 assert_eq!(
1100 chain_binding_problem(&[link(&g[0]), link(&g2)]),
1101 malformed,
1102 "{v}"
1103 );
1104 let mut g1 = g[0].clone();
1106 g1["credentialSubject"][PARENT_GRANT_DIGEST] = v.clone();
1107 assert_eq!(chain_binding_problem(&[link(&g1)]), malformed, "{v}");
1108 }
1109 for v in [Value::Null, json!({}), json!(""), json!(0)] {
1111 let mut g2 = g[1].clone();
1112 g2["credentialSubject"]["delegationChain"] = v.clone();
1113 assert_eq!(
1114 chain_binding_problem(&[link(&g[0]), link(&g2)]),
1115 malformed,
1116 "{v}"
1117 );
1118 }
1119 let mut both = g[1].clone();
1121 both["credentialSubject"]["delegationChain"] = json!([link(&g[0])]);
1122 assert_eq!(
1123 chain_binding_problem(&[link(&g[0]), link(&both)]),
1124 malformed
1125 );
1126 assert_eq!(chain_binding_problem(&[link(&both)]), malformed);
1128 let mut nested_first = g[0].clone();
1129 nested_first["credentialSubject"]["delegationChain"] = json!([link(&g[0])]);
1130 assert_eq!(chain_binding_problem(&[link(&nested_first)]), mismatch);
1131 let mut longer = g[1].clone();
1133 longer["credentialSubject"]
1134 .as_object_mut()
1135 .unwrap()
1136 .remove(PARENT_GRANT_DIGEST);
1137 longer["credentialSubject"]["delegationChain"] = json!([link(&g[0]), link(&g[0])]);
1138 assert_eq!(
1139 chain_binding_problem(&[link(&g[0]), link(&longer)]),
1140 mismatch
1141 );
1142 let mut tampered_link = link(&g[0]);
1143 tampered_link["note"] = json!("x");
1144 longer["credentialSubject"]["delegationChain"] = json!([tampered_link]);
1145 assert_eq!(
1146 chain_binding_problem(&[link(&g[0]), link(&longer)]),
1147 mismatch
1148 );
1149 let mut edited = g[0].clone();
1151 edited["credentialSubject"]["intent"]["resource"] = json!("https://x");
1152 assert_eq!(
1153 chain_binding_problem(&[link(&edited), link(&g[1]), link(&g[2])]),
1154 mismatch
1155 );
1156 assert_eq!(
1158 chain_binding_problem(&[json!({"issuer": "did:web:root"})]),
1159 malformed
1160 );
1161 assert_eq!(
1162 chain_binding_problem(&[link(&g[0]), json!({"parentCredential": "x"})]),
1163 malformed
1164 );
1165 let mut bad_type = g[2].clone();
1167 bad_type["credentialSubject"][PARENT_GRANT_DIGEST] = json!(1);
1168 assert_eq!(
1169 chain_binding_problem(&[link(&g[0]), link(&bare), link(&bad_type)]),
1170 mismatch
1171 );
1172 }
1173
1174 #[test]
1175 fn presented_chain_rule() {
1176 let g = flat3();
1177 assert_eq!(presented_chain_problem(&g), None);
1178 assert_eq!(presented_chain_problem(&[]), None);
1179 assert_eq!(
1181 presented_chain_problem(&g[1..]),
1182 Some((0, REASON_PARENT_MISMATCH))
1183 );
1184 assert_eq!(
1186 presented_chain_problem(&[g[0].clone(), g[2].clone()]),
1187 Some((1, REASON_PARENT_MISMATCH))
1188 );
1189 let mut bad = g[1].clone();
1191 bad["credentialSubject"][PARENT_GRANT_DIGEST] = Value::Null;
1192 assert_eq!(
1193 presented_chain_problem(&[g[0].clone(), bad.clone()]),
1194 Some((1, REASON_MALFORMED))
1195 );
1196 assert_eq!(
1197 presented_chain_problem(core::slice::from_ref(&bad)),
1198 Some((0, REASON_MALFORMED))
1199 );
1200 let plain = grant("did:web:a", "did:web:b", json!({}));
1202 assert_eq!(
1203 presented_chain_problem(&[g[0].clone(), plain.clone()]),
1204 None
1205 );
1206 for (position, value) in [(0, json!("{}")), (1, Value::Null), (2, json!(7))] {
1209 let mut creds = vec![g[0].clone(), plain.clone(), plain.clone()];
1210 creds[position] = value;
1211 assert_eq!(
1212 presented_chain_problem(&creds),
1213 Some((position, REASON_MALFORMED))
1214 );
1215 }
1216 assert_eq!(
1217 presented_chain_problem(&[json!("x"), g[1].clone()]),
1218 Some((0, REASON_MALFORMED))
1219 );
1220 }
1221
1222 fn nested_chain(parent: &Value, intent: &Value) -> Value {
1225 let mut chain = embedded_chain(parent).to_vec();
1226 let mut l = link(parent);
1227 l["intent"] = intent.clone();
1228 chain.push(l);
1229 Value::Array(chain)
1230 }
1231
1232 fn intent_to(delegatee: &str) -> Value {
1233 json!({"action": "read", "target": "t", "resource": "https://x/a", "delegatee": delegatee})
1234 }
1235
1236 fn nested(issuer: &str, delegatee: &str, parent: &Value) -> Value {
1238 grant(
1239 issuer,
1240 delegatee,
1241 json!({ "delegationChain": nested_chain(parent, &intent_to(delegatee)) }),
1242 )
1243 }
1244
1245 fn action(issuer: &str, links: Value) -> Value {
1247 json!({"issuer": issuer, "proof": {"proofValue": "z"},
1248 "credentialSubject": {"intent": {"action": "read"}, "delegationChain": links}})
1249 }
1250
1251 #[test]
1252 fn binding_fields_shape() {
1253 let malformed = Some(REASON_MALFORMED);
1254 let digest = json!("uEiA");
1255 for subject in [
1256 json!({}),
1257 json!({"parentGrantDigest": digest}),
1258 json!({"delegationChain": []}),
1259 json!({"parentGrantDigest": digest, "delegationChain": []}),
1260 json!({"delegationChain": [{"issuer": "x"}]}),
1261 Value::Null,
1263 json!([{"parentGrantDigest": 5}]),
1264 json!("parentGrantDigest"),
1265 ] {
1266 assert_eq!(binding_fields_problem(&subject), None, "{subject}");
1267 }
1268 for subject in [
1269 json!({"parentGrantDigest": null}),
1270 json!({"parentGrantDigest": 5}),
1271 json!({"parentGrantDigest": ["u"]}),
1272 json!({"parentGrantDigest": {}}),
1273 json!({"delegationChain": null}),
1274 json!({"delegationChain": {}}),
1275 json!({"delegationChain": ""}),
1276 json!({"delegationChain": 0}),
1277 json!({"delegationChain": false}),
1278 json!({"parentGrantDigest": digest, "delegationChain": [{}]}),
1279 json!({"parentGrantDigest": null, "delegationChain": [{}]}),
1280 ] {
1281 assert_eq!(binding_fields_problem(&subject), malformed, "{subject}");
1282 }
1283 }
1284
1285 #[test]
1286 fn presented_chains_with_embedded_chains() {
1287 let mismatch = |i| Some((i, REASON_PARENT_MISMATCH));
1288 let malformed = |i| Some((i, REASON_MALFORMED));
1289 let g = flat3();
1290 let (g1, g2) = (g[0].clone(), g[1].clone());
1291 let g1b = grant("did:web:root2", "did:web:a", json!({}));
1292 let g2b = grant(
1293 "did:web:a",
1294 "did:web:b",
1295 json!({ "parentGrantDigest": grant_digest(&g1b).unwrap() }),
1296 );
1297 let leaf = action("did:web:b", json!([]));
1298 let nested_b = nested("did:web:a", "did:web:b", &g1b);
1301 assert_eq!(
1302 presented_chain_problem(&[g1.clone(), nested_b.clone(), leaf.clone()]),
1303 mismatch(1)
1304 );
1305 assert_eq!(
1306 presented_chain_problem(&[g1b.clone(), nested_b.clone(), leaf.clone()]),
1307 None
1308 );
1309 let nested_a = nested("did:web:a", "did:web:b", &g1);
1311 assert_eq!(
1312 presented_chain_problem(&[nested_a.clone(), leaf.clone()]),
1313 mismatch(0)
1314 );
1315 assert_eq!(
1316 presented_chain_problem(&[g2.clone(), leaf.clone()]),
1317 mismatch(0)
1318 );
1319 let elsewhere = action("did:web:b", json!(links(&[g1b.clone(), g2b])));
1321 assert_eq!(
1322 presented_chain_problem(&[g1.clone(), g2.clone(), elsewhere]),
1323 mismatch(2)
1324 );
1325 let here = action("did:web:b", json!(links(&[g1.clone(), g2.clone()])));
1326 assert_eq!(
1327 presented_chain_problem(&[g1.clone(), g2.clone(), here]),
1328 None
1329 );
1330 for fields in [
1332 json!({ "parentGrantDigest": grant_digest(&g1).unwrap(),
1333 "delegationChain": nested_chain(&g1, &intent_to("did:web:b")) }),
1334 json!({"delegationChain": null}),
1335 json!({"delegationChain": {}}),
1336 json!({"parentGrantDigest": null}),
1337 ] {
1338 let sub = grant("did:web:a", "did:web:b", fields.clone());
1339 assert_eq!(
1340 presented_chain_problem(&[g1.clone(), sub, leaf.clone()]),
1341 malformed(1),
1342 "{fields}"
1343 );
1344 }
1345 let g2n = nested("did:web:a", "did:web:b", &g1);
1347 let g3n = nested("did:web:b", "did:web:c", &g2n);
1348 let leaf_c = action("did:web:c", json!([]));
1349 assert_eq!(
1350 presented_chain_problem(&[g1.clone(), g2n.clone(), g3n.clone(), leaf_c.clone()]),
1351 None
1352 );
1353 let nested_leaf = action("did:web:c", nested_chain(&g3n, &json!({"action": "read"})));
1354 assert_eq!(
1355 presented_chain_problem(&[g1.clone(), g2n.clone(), g3n.clone(), nested_leaf]),
1356 None
1357 );
1358 let g3 = grant(
1359 "did:web:b",
1360 "did:web:c",
1361 json!({ "parentGrantDigest": grant_digest(&g2n).unwrap() }),
1362 );
1363 assert_eq!(
1364 presented_chain_problem(&[g1.clone(), g2n.clone(), g3, leaf_c.clone()]),
1365 None
1366 );
1367 assert_eq!(
1369 presented_chain_problem(&[g1.clone(), g2n.clone(), g2n.clone(), g3n, leaf_c]),
1370 mismatch(2)
1371 );
1372 }
1373
1374 #[test]
1375 fn the_last_embedded_link_must_carry_the_previous_credential() {
1376 let g1 = flat3()[0].clone();
1377 let links = nested_chain(&g1, &intent_to("did:web:b"));
1378 let mut no_grant = links.clone();
1379 no_grant[0]
1380 .as_object_mut()
1381 .unwrap()
1382 .remove("parentCredential");
1383 let mut not_an_object = links.clone();
1384 not_an_object[0]["parentCredential"] = json!(g1.to_string());
1385 let mut not_a_link = links.clone();
1386 not_a_link[0] = json!("link");
1387 let mut edited = links.clone();
1389 edited[0]["parentCredential"]["validUntil"] = json!("2026-11-12T00:00:00Z");
1390 for embedded in [no_grant, not_an_object, not_a_link, edited] {
1391 let sub = json!({"issuer": "did:web:a",
1392 "credentialSubject": {"delegationChain": embedded}});
1393 assert_eq!(
1394 presented_chain_problem(&[g1.clone(), sub]),
1395 Some((1, REASON_PARENT_MISMATCH))
1396 );
1397 }
1398 let reordered: Value = serde_json::from_str(&jcs::canonicalize_to_string(&g1)).unwrap();
1400 let sub = json!({"issuer": "did:web:a",
1401 "credentialSubject": {"delegationChain": [{"parentCredential": reordered}]}});
1402 assert_eq!(presented_chain_problem(&[g1, sub]), None);
1403 }
1404
1405 #[test]
1406 #[cfg_attr(
1407 not(feature = "std"),
1408 ignore = "member order follows insertion only with std"
1409 )]
1410 fn grant_chains_for_signing() {
1411 let g = flat3();
1412 let leaf_intent = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1413 let ls = check_grant_chain(&g, &leaf_intent).unwrap();
1414 assert_eq!(ls.len(), 3);
1415 assert_eq!(chain_binding_problem(&ls), None);
1416 assert_eq!(ls[0]["intent"], g[1]["credentialSubject"]["intent"]);
1418 assert_eq!(ls[2]["intent"], leaf_intent);
1419 assert_eq!(ls[1]["subject"], json!("did:web:b"));
1420 assert_eq!(ls[1]["parentProofValue"], json!("zdid:web:a"));
1421 let keys: Vec<&str> = ls[0]
1422 .as_object()
1423 .unwrap()
1424 .keys()
1425 .map(|k| k.as_str())
1426 .collect();
1427 assert_eq!(
1428 keys,
1429 [
1430 "issuer",
1431 "subject",
1432 "intent",
1433 "validFrom",
1434 "validUntil",
1435 "parentProofValue",
1436 "parentCredential"
1437 ]
1438 );
1439 let sub = grant(
1441 "did:web:c",
1442 "did:web:d",
1443 json!({ "parentGrantDigest": grant_digest(&g[2]).unwrap() }),
1444 );
1445 let handed = grant_chain(&json!(g.clone()), &sub).unwrap();
1446 assert_eq!(handed.len(), 4);
1447 assert_eq!(handed[3], sub);
1448 assert_eq!(grant_chain(&g[1], &sub).unwrap_err().0, NAMES_PARENT_GRANT);
1450 assert_eq!(parent_grants(&g[2]).unwrap_err().0, NAMES_PARENT_GRANT);
1451 let nested = grant(
1453 "did:web:a",
1454 "did:web:b",
1455 json!({ "delegationChain": [link(&g[0])] }),
1456 );
1457 let pg = parent_grants(&nested).unwrap();
1458 assert_eq!(pg, vec![g[0].clone(), nested.clone()]);
1459 let copied = check_grant_chain(&pg, &leaf_intent).unwrap();
1461 assert_eq!(copied[0], link(&g[0]));
1462 assert_eq!(chain_binding_problem(&copied), None);
1463 let action = json!({"issuer": "did:web:c", "proof": {},
1465 "credentialSubject": {"intent": {"action": "read"}}});
1466 assert_eq!(
1467 grant_chain(&json!(g.clone()), &action).unwrap_err().0,
1468 "this credential names no delegatee, so nobody can sign under it"
1469 );
1470 assert_eq!(
1471 grant_chain(&json!(g.clone()), &json!([])).unwrap_err().0,
1472 "grant must be a signed grant (a dict)"
1473 );
1474 assert!(is_grant_intent(&json!({"delegatee": "did:web:x"})));
1475 for i in [
1476 json!({"delegatee": ""}),
1477 json!({"delegatee": 5}),
1478 json!({}),
1479 json!("x"),
1480 ] {
1481 assert!(!is_grant_intent(&i), "{i}");
1482 }
1483 }
1484
1485 #[test]
1486 fn grant_chain_refusals_match_the_reference_text() {
1487 let g = flat3();
1488 let intent = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1489 let err = |grants: &[Value]| check_grant_chain(grants, &intent).unwrap_err().0;
1490 assert_eq!(
1491 parent_grants(&json!([])).unwrap_err().0,
1492 "Delegation refused: the grant chain is empty"
1493 );
1494 assert_eq!(
1495 parent_grants(&json!([g[0].clone(), 5])).unwrap_err().0,
1496 "Delegation refused: every grant in the grant chain must be an object"
1497 );
1498 assert_eq!(
1499 parent_grants(&json!("x")).unwrap_err().0,
1500 "parent_credential must be a grant (a dict) or a grant chain (a list of grants, root first)"
1501 );
1502 let mut bad_chain = g[0].clone();
1503 bad_chain["credentialSubject"]["delegationChain"] = json!({});
1504 assert_eq!(
1505 parent_grants(&bad_chain).unwrap_err().0,
1506 "Delegation refused: the parent grant's delegationChain is not a list"
1507 );
1508 bad_chain["credentialSubject"]["delegationChain"] = json!([{"issuer": "x"}]);
1509 assert_eq!(
1510 parent_grants(&bad_chain).unwrap_err().0,
1511 "Delegation refused: a link in the parent grant's delegationChain carries no signed grant"
1512 );
1513 let mut unsigned = g[0].clone();
1515 unsigned.as_object_mut().unwrap().remove("proof");
1516 assert_eq!(
1517 err(&[unsigned]),
1518 "Delegation refused: the parent grant is not a signed credential"
1519 );
1520 let mut no_issuer = g[0].clone();
1521 no_issuer["issuer"] = json!("");
1522 assert_eq!(
1523 err(&[no_issuer]),
1524 "Delegation refused: the parent grant is not a signed credential"
1525 );
1526 let mut no_intent = g[0].clone();
1527 no_intent["credentialSubject"]["intent"] = json!("read");
1528 assert_eq!(
1529 err(&[no_intent]),
1530 "Delegation refused: the parent grant carries no intent object"
1531 );
1532 assert_eq!(
1533 err(&[g[0].clone(), g[2].clone()]),
1534 "Delegation refused: grant 1 of the grant chain names delegatee 'did:web:a', but grant 2 is issued by 'did:web:b'"
1535 );
1536 let mut no_issuer2 = g[1].clone();
1538 no_issuer2["issuer"] = json!({"name": "x"});
1539 assert_eq!(
1540 err(&[g[0].clone(), no_issuer2]),
1541 "Delegation refused: grant 2 of the grant chain has an issuer that is not a string or an object with a string id"
1542 );
1543 let mut no_delegatee = g[0].clone();
1544 no_delegatee["credentialSubject"]["intent"]
1545 .as_object_mut()
1546 .unwrap()
1547 .remove("delegatee");
1548 assert_eq!(
1549 err(&[no_delegatee, g[1].clone()]),
1550 "Delegation refused: grant 1 of the grant chain names no delegatee"
1551 );
1552 let mut object_issuer = g[1].clone();
1554 object_issuer["issuer"] = json!({"id": "did:web:a"});
1555 assert!(check_grant_chain(&[g[0].clone(), object_issuer], &intent).is_ok());
1556 let bare = grant("did:web:a", "did:web:b", json!({}));
1558 assert_eq!(
1559 err(&[g[0].clone(), bare]),
1560 "Delegation refused: grant 2 of the grant chain is not bound to the grant before it (delegation_parent_mismatch)"
1561 );
1562 let mut bad_digest = g[1].clone();
1563 bad_digest["credentialSubject"][PARENT_GRANT_DIGEST] = json!(7);
1564 assert_eq!(
1565 err(&[g[0].clone(), bad_digest]),
1566 "Delegation refused: grant 2 of the grant chain is not bound to the grant before it (malformed_delegation)"
1567 );
1568 let nested = grant(
1570 "did:web:a",
1571 "did:web:b",
1572 json!({ "delegationChain": [link(&g[0])] }),
1573 );
1574 let other_root = grant("did:web:root", "did:web:a", json!({"note": "other"}));
1575 assert_eq!(
1576 err(&[other_root, nested]),
1577 "Delegation refused: grant 2 of the grant chain embeds a chain that is not the grants before it"
1578 );
1579 assert_eq!(
1580 chain_capability(&[], false).unwrap_err().0,
1581 "Delegation refused: the grant chain is empty"
1582 );
1583 }
1584
1585 const BROADER: &str =
1586 "Delegation refused: a grant in the grant chain is broader than the grant before it on ";
1587
1588 #[test]
1589 fn an_intermediate_grant_broader_than_the_grant_above_it_is_refused() {
1590 let g = flat3();
1591 let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1592 let digest = json!(grant_digest(&g[0]).unwrap());
1593 let mut broad = g[1].clone();
1594 broad["credentialSubject"]["intent"]["action"] = json!(["read", "write"]);
1595 broad["credentialSubject"][PARENT_GRANT_DIGEST] = digest.clone();
1596 let chain = [g[0].clone(), broad.clone()];
1597 assert_eq!(
1598 check_grant_chain(&chain, &leaf).unwrap_err().0,
1599 format!("{BROADER}'action'")
1600 );
1601 assert_eq!(
1603 grant_chain(&g[0], &broad).unwrap_err().0,
1604 format!("{BROADER}'action'")
1605 );
1606 for (k, v) in [
1608 ("validUntil", "2026-11-12T00:00:00Z"),
1609 ("validFrom", "2026-11-09T00:00:00Z"),
1610 ] {
1611 let mut long = g[1].clone();
1612 long[k] = json!(v);
1613 assert_eq!(
1614 check_grant_chain(&[g[0].clone(), long.clone()], &leaf)
1615 .unwrap_err()
1616 .0,
1617 format!("{BROADER}'time'"),
1618 "{k}"
1619 );
1620 assert_eq!(
1621 grant_chain(&g[0], &long).unwrap_err().0,
1622 format!("{BROADER}'time'")
1623 );
1624 }
1625 let mut wide = g[2].clone();
1627 wide["credentialSubject"]["intent"]["resource"] = json!("https://x");
1628 let mut chain = g.clone();
1629 chain[2] = wide;
1630 assert_eq!(
1631 check_grant_chain(&chain, &leaf).unwrap_err().0,
1632 format!("{BROADER}'resource'")
1633 );
1634 let mut narrow = g[1].clone();
1636 narrow["credentialSubject"]["intent"]["resource"] = json!("https://x/a/b");
1637 narrow["validUntil"] = json!("2026-11-10T12:00:00Z");
1638 assert!(check_grant_chain(&[g[0].clone(), narrow], &leaf).is_ok());
1639 let mut alone = g[0].clone();
1640 alone["credentialSubject"]["intent"]["action"] = json!(["read", "write"]);
1641 assert!(check_grant_chain(&[alone], &leaf).is_ok());
1642 let mut unbound = g[1].clone();
1644 unbound["credentialSubject"]
1645 .as_object_mut()
1646 .unwrap()
1647 .remove(PARENT_GRANT_DIGEST);
1648 unbound["credentialSubject"]["intent"]["action"] = json!("write");
1649 assert_eq!(
1650 check_grant_chain(&[g[0].clone(), unbound], &leaf)
1651 .unwrap_err()
1652 .0,
1653 "Delegation refused: grant 2 of the grant chain is not bound to the grant before it (delegation_parent_mismatch)"
1654 );
1655 }
1656
1657 #[test]
1658 fn a_malformed_first_grant_is_named_as_malformed() {
1659 let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1660 for (dimension, value) in [
1661 ("rate", json!("lots")),
1662 ("policy", json!(["not", "an", "object"])),
1663 ("action", json!(7)),
1664 ("target", json!([1])),
1665 ("resource", json!(7)),
1666 ("time", json!("soon")),
1667 ] {
1668 let mut g1 = grant("did:web:root", "did:web:a", json!({}));
1669 if dimension == "time" {
1670 g1["validUntil"] = value;
1671 } else {
1672 g1["credentialSubject"]["intent"][dimension] = value;
1673 }
1674 let g2 = grant(
1675 "did:web:a",
1676 "did:web:b",
1677 json!({ "parentGrantDigest": grant_digest(&g1).unwrap() }),
1678 );
1679 let message = format!(
1680 "Delegation refused: grant 1 of the grant chain has a malformed '{dimension}'"
1681 );
1682 assert_eq!(
1683 check_grant_chain(&[g1.clone(), g2.clone()], &leaf)
1684 .unwrap_err()
1685 .0,
1686 message
1687 );
1688 assert_eq!(grant_chain(&g1, &g2).unwrap_err().0, message);
1690 assert!(check_grant_chain(&[g1], &leaf).is_ok(), "{dimension}");
1692 }
1693 let g = flat3();
1695 let mut g2 = g[1].clone();
1696 g2["credentialSubject"]["intent"]["rate"] = json!("lots");
1697 assert_eq!(
1698 check_grant_chain(&[g[0].clone(), g2], &leaf).unwrap_err().0,
1699 format!("{BROADER}'rate'")
1700 );
1701 }
1702
1703 #[test]
1704 fn the_helpers_refuse_a_grant_that_is_not_an_object() {
1705 let g = flat3();
1706 let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1707 let no_intent = "Delegation refused: the parent grant carries no intent object";
1708 let mut no_subject = g[1].clone();
1709 no_subject["credentialSubject"] = json!("subject");
1710 let mut no_intent_member = g[1].clone();
1711 no_intent_member["credentialSubject"]
1712 .as_object_mut()
1713 .unwrap()
1714 .remove("intent");
1715 let nested_after = nested("did:web:a", "did:web:b", &g[0]);
1718 for bad in [
1719 json!("x"),
1720 Value::Null,
1721 json!(5),
1722 json!(["nested"]),
1723 no_subject,
1724 no_intent_member,
1725 ] {
1726 for grants in [
1727 vec![bad.clone()],
1728 vec![g[0].clone(), bad.clone()],
1729 vec![bad.clone(), g[0].clone()],
1730 vec![bad.clone(), nested_after.clone()],
1731 ] {
1732 assert_eq!(
1733 check_grant_chain(&grants, &leaf).unwrap_err().0,
1734 no_intent,
1735 "{bad}"
1736 );
1737 assert_eq!(
1738 chain_links(&grants, &leaf).unwrap_err().0,
1739 no_intent,
1740 "{bad}"
1741 );
1742 }
1743 }
1744 }
1745
1746 #[test]
1747 fn a_nested_grant_whose_embedded_link_lies_is_refused() {
1748 let g = flat3();
1749 let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1750 for (field, message) in [
1751 (
1752 "subject",
1753 "Delegation refused: grant 2 of the grant chain embeds a link whose subject is not the delegatee of grant 1",
1754 ),
1755 (
1756 "issuer",
1757 "Delegation refused: grant 2 of the grant chain embeds a link whose issuer is not the issuer of grant 1",
1758 ),
1759 ] {
1760 let mut links = nested_chain(&g[0], &intent_to("did:web:b"));
1761 links[0][field] = json!("did:web:x");
1762 let lying = grant("did:web:a", "did:web:b", json!({ "delegationChain": links }));
1763 let grants = parent_grants(&lying).unwrap();
1764 assert_eq!(check_grant_chain(&grants, &leaf).unwrap_err().0, message);
1765 assert_eq!(
1766 check_grant_chain(&[g[0].clone(), lying.clone()], &leaf)
1767 .unwrap_err()
1768 .0,
1769 message
1770 );
1771 assert_eq!(chain_links(&grants, &leaf).unwrap_err().0, message);
1772 let mut links = nested_chain(&g[0], &intent_to("did:web:b"));
1774 links[0].as_object_mut().unwrap().remove(field);
1775 let missing = grant("did:web:a", "did:web:b", json!({ "delegationChain": links }));
1776 assert_eq!(
1777 check_grant_chain(&[g[0].clone(), missing], &leaf)
1778 .unwrap_err()
1779 .0,
1780 message
1781 );
1782 }
1783 let mut links = nested_chain(&g[0], &intent_to("did:web:b"));
1786 links[0]["issuer"] = json!("did:web:x");
1787 links[0]["subject"] = json!("did:web:x");
1788 let both = grant(
1789 "did:web:a",
1790 "did:web:b",
1791 json!({ "delegationChain": links }),
1792 );
1793 assert!(check_grant_chain(&[g[0].clone(), both.clone()], &leaf)
1794 .unwrap_err()
1795 .0
1796 .contains("whose issuer is not"));
1797 let other_root = grant("did:web:root", "did:web:a", json!({"note": "other"}));
1798 assert_eq!(
1799 check_grant_chain(&[other_root, both], &leaf).unwrap_err().0,
1800 "Delegation refused: grant 2 of the grant chain embeds a chain that is not the grants before it"
1801 );
1802 let honest = nested("did:web:a", "did:web:b", &g[0]);
1804 let out = check_grant_chain(&[g[0].clone(), honest.clone()], &leaf).unwrap();
1805 assert_eq!(out[0], honest["credentialSubject"]["delegationChain"][0]);
1806 assert_eq!(out[1]["parentCredential"], honest);
1807 }
1808
1809 #[test]
1810 fn an_issuer_object_is_carried_as_its_id() {
1811 let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1812 let mut root = grant("did:web:root", "did:web:a", json!({}));
1813 root["issuer"] = json!({"id": "did:web:root", "name": "Root"});
1814 let links = check_grant_chain(core::slice::from_ref(&root), &leaf).unwrap();
1815 assert_eq!(links[0]["issuer"], json!("did:web:root"));
1816 assert_eq!(links[0]["parentCredential"], root);
1817 assert_eq!(chain_binding_problem(&links), None);
1818 let mut odd = root.clone();
1820 odd["issuer"] = json!(42);
1821 assert_eq!(
1822 chain_links(core::slice::from_ref(&odd), &leaf).unwrap()[0]["issuer"],
1823 json!("")
1824 );
1825 }
1826
1827 #[test]
1828 fn an_issuer_that_is_not_a_did_string_is_refused() {
1829 let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1830 for issuer in [
1831 json!(42),
1832 json!({"id": 5}),
1833 json!({"name": "Root"}),
1834 json!(["did:key:z"]),
1835 json!(true),
1836 ] {
1837 let mut root = grant("did:web:root", "did:web:a", json!({}));
1838 root["issuer"] = issuer.clone();
1839 assert_eq!(
1840 check_grant_chain(&[root], &leaf).unwrap_err().0,
1841 "Delegation refused: grant 1 of the grant chain has an issuer that is not a string or an object with a string id",
1842 "{issuer}"
1843 );
1844 }
1845 for issuer in [json!(""), json!({}), Value::Null, json!(0), json!([])] {
1847 let mut root = grant("did:web:root", "did:web:a", json!({}));
1848 root["issuer"] = issuer.clone();
1849 assert_eq!(
1850 check_grant_chain(&[root], &leaf).unwrap_err().0,
1851 "Delegation refused: the parent grant is not a signed credential",
1852 "{issuer}"
1853 );
1854 }
1855 }
1856
1857 #[test]
1858 fn links_are_copies_of_the_grants() {
1859 let g = flat3();
1862 let before = g.clone();
1863 let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
1864 let mut links = check_grant_chain(&g, &leaf).unwrap();
1865 assert_eq!(links[0]["parentCredential"], g[0]);
1866 assert_eq!(links[0]["intent"], g[1]["credentialSubject"]["intent"]);
1867 links[0]["intent"]["action"] = json!("write");
1868 links[1]["parentCredential"]["credentialSubject"]["intent"]["action"] = json!("write");
1869 assert_eq!(g, before);
1870 }
1871
1872 #[test]
1873 fn chain_capability_inherits_down_the_chain() {
1874 let mut g = flat3();
1875 g[0]["credentialSubject"]["intent"]["rate"] = json!("10/hour");
1876 g[2]["credentialSubject"]["intent"]
1877 .as_object_mut()
1878 .unwrap()
1879 .remove("resource");
1880 let cap = chain_capability(&g, false).unwrap();
1881 assert_eq!(cap["intent"]["resource"], json!("https://x/a"));
1882 assert_eq!(cap["rate"], json!("10/hour"));
1883 assert_eq!(cap["subject"], json!("did:web:c"));
1884 assert!(cap.get("validFrom").is_none());
1885 let timed = chain_capability(&g, true).unwrap();
1886 assert_eq!(timed["validUntil"], json!("2026-11-11T00:00:00Z"));
1887 }
1888
1889 #[test]
1890 fn python_repr_of_quoted_values() {
1891 assert_eq!(py_repr_str("did:web:a"), "'did:web:a'");
1892 assert_eq!(py_repr_str("it's"), "\"it's\"");
1893 assert_eq!(py_repr_str("a'b\"c"), "'a\\'b\"c'");
1894 assert_eq!(py_repr_str("a\\b\n\u{1}"), "'a\\\\b\\n\\x01'");
1895 assert_eq!(py_repr(None), "None");
1896 assert_eq!(py_repr(Some(&json!(["x", 1]))), "['x', 1]");
1897 assert_eq!(
1900 py_repr_str(
1901 "\u{a0}\u{ad}\u{200b}\u{2028}\u{feff}\u{e000}\u{e0001}\u{10ffff} é中😀\u{3000}\u{7f}\u{1b}\u{85}"
1902 ),
1903 "'\\xa0\\xad\\u200b\\u2028\\ufeff\\ue000\\U000e0001\\U0010ffff é中😀\\u3000\\x7f\\x1b\\x85'"
1904 );
1905 assert_eq!(py_repr_str("it's \u{2029}"), "\"it's \\u2029\"");
1906 assert_eq!(py_repr_str("a\u{378}b"), "'a\\u0378b'");
1907 assert_eq!(
1908 py_repr(Some(&json!({"k\u{0}": ["\u{2066}"]}))),
1909 "{'k\\x00': ['\\u2066']}"
1910 );
1911 }
1912
1913 #[test]
1914 fn python_repr_of_numbers() {
1915 for (text, expected) in [
1918 ("0.0", "0.0"),
1919 ("-0.0", "-0.0"),
1920 ("1.0", "1.0"),
1921 ("-1.5", "-1.5"),
1922 ("0.1", "0.1"),
1923 ("0.30000000000000004", "0.30000000000000004"),
1924 ("100.0", "100.0"),
1925 ("1e2", "100.0"),
1926 ("0.0001", "0.0001"),
1927 ("0.00001", "1e-05"),
1928 ("1e-5", "1e-05"),
1929 ("0.000123", "0.000123"),
1930 ("9.999e-5", "9.999e-05"),
1931 ("1e-7", "1e-07"),
1932 ("123.456", "123.456"),
1933 ("9999999999999998.0", "9999999999999998.0"),
1934 ("1e16", "1e+16"),
1935 ("12345678901234567.0", "1.2345678901234568e+16"),
1936 ("1e21", "1e+21"),
1937 ("1e22", "1e+22"),
1938 ("1.5e300", "1.5e+300"),
1939 ("1.7976931348623157e308", "1.7976931348623157e+308"),
1940 ("5e-324", "5e-324"),
1941 ("2.2250738585072014e-308", "2.2250738585072014e-308"),
1942 ("588197768793114.25", "588197768793114.2"),
1944 ("-164193784243384.125", "-164193784243384.12"),
1945 ("6.02214076e23", "6.02214076e+23"),
1946 ("-2.5e-10", "-2.5e-10"),
1947 ("4.35", "4.35"),
1948 ("1e100", "1e+100"),
1949 ("1E-100", "1e-100"),
1950 ("123e-20", "1.23e-18"),
1951 ("5", "5"),
1952 ("-7", "-7"),
1953 ("0", "0"),
1954 ("18446744073709551615", "18446744073709551615"),
1955 ("-9223372036854775808", "-9223372036854775808"),
1956 (
1957 "{\"maxSpend\": 1e-05, \"ratio\": [0.5, 1e16, 2]}",
1958 "{'maxSpend': 1e-05, 'ratio': [0.5, 1e+16, 2]}",
1959 ),
1960 ] {
1961 let value: Value = serde_json::from_str(text).unwrap();
1962 assert_eq!(py_repr(Some(&value)), expected, "{text}");
1963 }
1964 assert_eq!(py_repr_float(f64::INFINITY), "inf");
1965 assert_eq!(py_repr_float(f64::NEG_INFINITY), "-inf");
1966 assert_eq!(py_repr_float(f64::NAN), "nan");
1967 }
1968}