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