1#[allow(unused_imports)]
24use crate::prelude::*;
25
26use serde_json::{json, Map, Value};
27
28use crate::credentials::{PROTOCOL_VERSION, VC_CONTEXT_V2, VC_TYPE, VOUCH_CONTEXT_V1};
29use crate::data_integrity::{self, BuildProofOptions};
30use crate::error::{CoreError, Result};
31use crate::keys::{did_key_to_ed25519, ed25519_to_did_key, Ed25519KeyPair};
32use crate::time::{iso_to_epoch_seconds, parse_protocol_time_ns, seconds_to_ns};
33
34pub const ROOT_OF_TRUST_TYPE: &str = "VouchRootOfTrust";
36pub const RECOGNIZED_ISSUER_TYPE: &str = "RecognizedIssuerCredential";
37pub const AGENT_IDENTITY_TYPE: &str = "AgentIdentityCredential";
38
39pub const ACTION_ISSUE_AGENT_IDENTITY: &str = "issueAgentIdentity";
41pub const ACTION_ISSUE_ROBOT_IDENTITY: &str = "issueRobotIdentity";
42
43const TRUST_TYPES: [&str; 3] = [
47 ROOT_OF_TRUST_TYPE,
48 RECOGNIZED_ISSUER_TYPE,
49 AGENT_IDENTITY_TYPE,
50];
51
52pub const ROOT_VALID_SECONDS: i64 = 10 * 365 * 24 * 3600;
55pub const ISSUER_VALID_SECONDS: i64 = 365 * 24 * 3600;
56pub const IDENTITY_VALID_SECONDS: i64 = 365 * 24 * 3600;
57
58fn verification_method_of(did: &str) -> String {
60 format!("{did}#key-1")
61}
62
63#[derive(Debug, Clone, PartialEq, Eq)]
68pub struct IdentityChainResult {
69 pub ok: bool,
70 pub reason: Option<String>,
71 pub agent_did: Option<String>,
72 pub issuer_did: Option<String>,
73 pub root_did: Option<String>,
74 pub attributes: Option<Value>,
75}
76
77impl IdentityChainResult {
78 fn fail(reason: impl Into<String>) -> Self {
79 Self {
80 ok: false,
81 reason: Some(reason.into()),
82 agent_did: None,
83 issuer_did: None,
84 root_did: None,
85 attributes: None,
86 }
87 }
88}
89
90#[allow(clippy::too_many_arguments)]
101pub fn build_root_of_trust(
102 root_seed: &[u8],
103 name: &str,
104 scope: Option<&[&str]>,
105 valid_seconds: i64,
106 valid_from: &str,
107 created: &str,
108 credential_id: &str,
109) -> Result<Value> {
110 let root_did = did_of_seed(root_seed)?;
111 let scope_val: Vec<Value> = match scope {
112 Some(s) => s.iter().map(|x| json!(x)).collect(),
113 None => vec![json!("ai-agent"), json!("robot")],
114 };
115 let mut subject = Map::new();
116 subject.insert("id".into(), json!(root_did));
117 subject.insert("vouchVersion".into(), json!(PROTOCOL_VERSION));
118 subject.insert(
119 "rootOfTrust".into(),
120 json!({ "name": name, "scope": scope_val }),
121 );
122
123 let credential = envelope(
124 credential_id,
125 &[VC_TYPE, ROOT_OF_TRUST_TYPE],
126 &root_did,
127 Value::Object(subject),
128 valid_from,
129 valid_seconds,
130 None,
131 )?;
132 sign(&credential, root_seed, &root_did, created)
133}
134
135#[allow(clippy::too_many_arguments)]
141pub fn build_recognized_issuer(
142 root_seed: &[u8],
143 issuer_did: &str,
144 recognized_actions: Option<&[&str]>,
145 valid_seconds: i64,
146 valid_from: &str,
147 created: &str,
148 credential_status: Option<Value>,
149 credential_id: &str,
150) -> Result<Value> {
151 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); drop credential_status);
152 if issuer_did.is_empty() {
153 return Err(CoreError::Json("issuer_did is required".into()));
154 }
155 let root_did = did_of_seed(root_seed)?;
156 let actions: Vec<Value> = match recognized_actions {
157 Some(a) => a.iter().map(|x| json!(x)).collect(),
158 None => vec![json!(ACTION_ISSUE_AGENT_IDENTITY)],
159 };
160 let mut subject = Map::new();
161 subject.insert("id".into(), json!(issuer_did));
162 subject.insert("recognizedActions".into(), Value::Array(actions));
163 subject.insert("recognizedIn".into(), json!(root_did));
164
165 let credential = envelope(
166 credential_id,
167 &[VC_TYPE, RECOGNIZED_ISSUER_TYPE],
168 &root_did,
169 Value::Object(subject),
170 valid_from,
171 valid_seconds,
172 credential_status,
173 )?;
174 sign(&credential, root_seed, &root_did, created)
175}
176
177#[allow(clippy::too_many_arguments)]
183pub fn build_agent_identity(
184 issuer_seed: &[u8],
185 subject_did: &str,
186 attributes: &Value,
187 valid_seconds: i64,
188 valid_from: &str,
189 created: &str,
190 credential_status: Option<Value>,
191 credential_id: &str,
192) -> Result<Value> {
193 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); attributes; drop credential_status);
194 if subject_did.is_empty() {
195 return Err(CoreError::Json("subject_did is required".into()));
196 }
197 match attributes.as_object() {
198 Some(o) if !o.is_empty() => {}
199 _ => {
200 return Err(CoreError::Json(
201 "attributes must be a non-empty object".into(),
202 ))
203 }
204 }
205 let issuer_did = did_of_seed(issuer_seed)?;
206 let mut subject = Map::new();
207 subject.insert("id".into(), json!(subject_did));
208 subject.insert("identity".into(), attributes.clone());
209
210 let credential = envelope(
211 credential_id,
212 &[VC_TYPE, AGENT_IDENTITY_TYPE],
213 &issuer_did,
214 Value::Object(subject),
215 valid_from,
216 valid_seconds,
217 credential_status,
218 )?;
219 sign(&credential, issuer_seed, &issuer_did, created)
220}
221
222#[derive(Debug, Clone, PartialEq, Eq)]
228pub enum ChainAsk {
229 Key { did: String, vm: String },
231 Revoked(&'static str),
234 Action,
237}
238
239pub trait ChainHost {
243 fn key(&mut self, did: &str, vm: &str) -> Option<Option<Vec<u8>>>;
246 fn revoked(&mut self, which: &'static str) -> Option<bool>;
249 fn action(&mut self) -> Option<(bool, Option<String>)>;
251 fn unreadable(&mut self, _slot: &'static str) -> bool {
258 false
259 }
260}
261
262#[derive(Debug, Clone, PartialEq)]
264pub enum ChainWalk {
265 Done(IdentityChainResult),
266 Ask(ChainAsk),
267}
268
269enum Stop {
271 Reason(&'static str),
272 Ask(ChainAsk),
273}
274
275#[allow(clippy::too_many_arguments)]
293pub fn walk_identity_chain(
294 identity_credential: &Value,
295 recognized_issuer_credential: &Value,
296 trusted_root: &str,
297 root_credential: Option<&Value>,
298 has_action: bool,
299 required_action: &Value,
300 now_iso: &str,
301 clock_skew_seconds: i64,
302 host: &mut dyn ChainHost,
303) -> ChainWalk {
304 crate::nesting::deep_guard!(ChainWalk::Done(IdentityChainResult::fail(crate::nesting::TOO_DEEP)); identity_credential, recognized_issuer_credential, root_credential, required_action);
305 let fail = |r: &str| ChainWalk::Done(IdentityChainResult::fail(r));
306 if crate::time::check_clock_skew(clock_skew_seconds).is_err() {
308 return fail("invalid_clock_skew");
309 }
310 if trusted_root.is_empty() {
311 return fail("no_trusted_root");
312 }
313 macro_rules! check {
314 ($cred:expr, $ty:expr, $slot:expr, $prefix:expr) => {
315 match verify_trust_credential($cred, $ty, $slot, now_iso, clock_skew_seconds, host) {
316 Ok(()) => {}
317 Err(Stop::Ask(ask)) => return ChainWalk::Ask(ask),
318 Err(Stop::Reason(r)) => return fail(&format!("{}{r}", $prefix)),
319 }
320 };
321 }
322
323 check!(
325 recognized_issuer_credential,
326 RECOGNIZED_ISSUER_TYPE,
327 "recognized",
328 "recognized_issuer_"
329 );
330 if issuer_of(recognized_issuer_credential).as_deref() != Some(trusted_root) {
331 return fail("recognized_issuer_not_from_root");
332 }
333 let rec_subject = match recognized_issuer_credential.get("credentialSubject") {
334 Some(Value::Object(o)) => o,
335 _ => return fail("recognized_issuer_bad_subject"),
336 };
337 let recognized_did = match rec_subject.get("id").and_then(|v| v.as_str()) {
338 Some(s) if !s.is_empty() => s.to_string(),
339 _ => return fail("recognized_issuer_no_subject"),
340 };
341 let actions_ok = rec_subject
342 .get("recognizedActions")
343 .and_then(|v| v.as_array())
344 .map(|a| a.iter().any(|x| x == required_action))
347 .unwrap_or(false)
348 && !host.unreadable("requiredAction");
351 if !actions_ok {
352 return fail("issuer_not_recognized_for_action");
353 }
354 match host.revoked("recognized") {
355 None => return ChainWalk::Ask(ChainAsk::Revoked("recognized")),
356 Some(true) => return fail("recognized_issuer_revoked"),
357 Some(false) => {}
358 }
359
360 check!(
362 identity_credential,
363 AGENT_IDENTITY_TYPE,
364 "identity",
365 "identity_"
366 );
367 if issuer_of(identity_credential).as_deref() != Some(recognized_did.as_str()) {
368 return fail("identity_not_from_recognized_issuer");
369 }
370 match host.revoked("identity") {
371 None => return ChainWalk::Ask(ChainAsk::Revoked("identity")),
372 Some(true) => return fail("identity_revoked"),
373 Some(false) => {}
374 }
375 let id_subject = match identity_credential.get("credentialSubject") {
376 Some(Value::Object(o)) => o,
377 _ => return fail("identity_bad_subject"),
378 };
379 let agent_did = match id_subject.get("id").and_then(|v| v.as_str()) {
380 Some(s) if !s.is_empty() => s.to_string(),
381 _ => return fail("identity_no_subject"),
382 };
383 let attributes = id_subject.get("identity").cloned();
384
385 if let Some(root_cred) = root_credential {
387 check!(root_cred, ROOT_OF_TRUST_TYPE, "root", "root_");
388 let root_sub = match root_cred.get("credentialSubject") {
389 Some(Value::Object(o)) => o,
390 _ => return fail("root_bad_subject"),
391 };
392 if issuer_of(root_cred).as_deref() != Some(trusted_root)
393 || root_sub.get("id").and_then(|v| v.as_str()) != Some(trusted_root)
394 {
395 return fail("root_not_self_issued");
396 }
397 }
398
399 if has_action {
401 match host.action() {
402 None => return ChainWalk::Ask(ChainAsk::Action),
403 Some((false, _)) => return fail("action_proof_invalid"),
404 Some((true, issuer)) => {
405 if issuer.as_deref() != Some(agent_did.as_str()) {
406 return fail("action_not_from_agent");
407 }
408 }
409 }
410 }
411
412 ChainWalk::Done(IdentityChainResult {
413 ok: true,
414 reason: None,
415 agent_did: Some(agent_did),
416 issuer_did: Some(recognized_did),
417 root_did: Some(trusted_root.to_string()),
418 attributes,
419 })
420}
421
422struct DidKeyHost;
424
425impl ChainHost for DidKeyHost {
426 fn key(&mut self, did: &str, _vm: &str) -> Option<Option<Vec<u8>>> {
427 Some(resolve_key(did))
428 }
429 fn revoked(&mut self, _which: &'static str) -> Option<bool> {
430 Some(false)
431 }
432 fn action(&mut self) -> Option<(bool, Option<String>)> {
433 None
434 }
435}
436
437#[allow(clippy::too_many_arguments)]
443pub fn verify_identity_chain(
444 identity_credential: &Value,
445 recognized_issuer_credential: &Value,
446 trusted_root: &str,
447 root_credential: Option<&Value>,
448 action_credential: Option<&Value>,
449 required_action: &str,
450 now_iso: &str,
451 clock_skew_seconds: i64,
452) -> IdentityChainResult {
453 crate::nesting::deep_guard!(IdentityChainResult::fail(crate::nesting::TOO_DEEP); identity_credential, recognized_issuer_credential, root_credential, action_credential);
454 let walked = walk_identity_chain(
455 identity_credential,
456 recognized_issuer_credential,
457 trusted_root,
458 root_credential,
459 false,
460 &Value::String(required_action.to_string()),
461 now_iso,
462 clock_skew_seconds,
463 &mut DidKeyHost,
464 );
465 let result = match walked {
466 ChainWalk::Done(r) => r,
467 ChainWalk::Ask(_) => return IdentityChainResult::fail("unresolved_key"),
469 };
470 let Some(action_cred) = action_credential.filter(|_| result.ok) else {
471 return result;
472 };
473 let action_issuer = match issuer_of(action_cred) {
474 Some(i) => i,
475 None => return IdentityChainResult::fail("action_proof_invalid"),
476 };
477 match resolve_key(&action_issuer) {
478 Some(pk) => match data_integrity::verify_proof(action_cred, &pk) {
479 Ok(true) => {}
480 _ => return IdentityChainResult::fail("action_proof_invalid"),
481 },
482 None => return IdentityChainResult::fail("action_proof_invalid"),
483 }
484 if !within_window(action_cred, now_iso, clock_skew_seconds) {
485 return IdentityChainResult::fail("action_proof_invalid");
486 }
487 if Some(action_issuer.as_str()) != result.agent_did.as_deref() {
488 return IdentityChainResult::fail("action_not_from_agent");
489 }
490 result
491}
492
493#[allow(clippy::too_many_arguments)]
499fn envelope(
500 credential_id: &str,
501 types: &[&str],
502 issuer: &str,
503 subject: Value,
504 valid_from: &str,
505 valid_seconds: i64,
506 credential_status: Option<Value>,
507) -> Result<Value> {
508 let from = iso_to_epoch_seconds(valid_from)?;
509 const LAST_SECOND: i64 = 253_402_300_799; let until = from
512 .checked_add(valid_seconds)
513 .filter(|u| *u <= LAST_SECOND)
514 .ok_or_else(|| {
515 CoreError::Json("valid_seconds puts validUntil past 9999-12-31T23:59:59Z".into())
516 })?;
517 let valid_until = epoch_to_iso(until);
518 let types_val: Vec<Value> = types.iter().map(|t| json!(t)).collect();
519
520 let mut vc = Map::new();
521 vc.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
522 vc.insert("id".into(), json!(credential_id));
523 vc.insert("type".into(), Value::Array(types_val));
524 vc.insert("issuer".into(), json!(issuer));
525 vc.insert("validFrom".into(), json!(valid_from));
526 vc.insert("validUntil".into(), json!(valid_until));
527 vc.insert("credentialSubject".into(), subject);
528 if let Some(status) = credential_status {
529 vc.insert("credentialStatus".into(), status);
530 }
531 Ok(Value::Object(vc))
532}
533
534fn sign(credential: &Value, seed: &[u8], issuer_did: &str, created: &str) -> Result<Value> {
536 let opts = BuildProofOptions::new(verification_method_of(issuer_did), created);
537 data_integrity::sign(credential, seed, &opts)
538}
539
540fn did_of_seed(seed: &[u8]) -> Result<String> {
542 let kp = Ed25519KeyPair::from_seed_slice(seed)?;
543 ed25519_to_did_key(&kp.public_key())
544}
545
546fn verify_trust_credential(
553 credential: &Value,
554 expected_type: &str,
555 slot: &'static str,
556 now_iso: &str,
557 clock_skew_seconds: i64,
558 host: &mut dyn ChainHost,
559) -> core::result::Result<(), Stop> {
560 let reason = |r: &'static str| Err(Stop::Reason(r));
561 let Some(obj) = credential.as_object() else {
562 return reason("not_a_credential");
563 };
564 let types = match obj.get("type").and_then(|v| v.as_array()) {
565 Some(t) if t.iter().any(|t| t.as_str() == Some(expected_type)) => t,
566 _ => return reason("wrong_type"),
567 };
568 let trust_count = TRUST_TYPES
571 .iter()
572 .filter(|tt| types.iter().any(|t| t.as_str() == Some(**tt)))
573 .count();
574 let nested = types.iter().any(|t| t.is_array() || t.is_object());
577 if trust_count != 1 || nested {
578 return reason("ambiguous_type");
579 }
580 let issuer = match issuer_of(credential) {
581 Some(i) if !i.is_empty() => i,
582 _ => return reason("no_issuer"),
583 };
584 let Some(proof) = obj.get("proof").and_then(|p| p.as_object()) else {
585 return reason("no_proof");
586 };
587 if proof.get("proofPurpose").and_then(|v| v.as_str()) != Some("assertionMethod") {
588 return reason("bad_proof_purpose");
589 }
590 let vm = match proof.get("verificationMethod").and_then(|v| v.as_str()) {
591 Some(vm) if !vm.is_empty() && vm.split('#').next() == Some(issuer.as_str()) => vm,
592 _ => return reason("vm_mismatch"),
593 };
594 let public_key = match host.key(&issuer, vm) {
595 None => {
596 return Err(Stop::Ask(ChainAsk::Key {
597 did: issuer,
598 vm: vm.to_string(),
599 }))
600 }
601 Some(None) => return reason("unresolved_key"),
602 Some(Some(k)) => k,
603 };
604 if host.unreadable(slot) {
607 return reason("proof_malformed");
608 }
609 match crate::proof_json::verify_eddsa(credential, &public_key) {
610 Ok(true) => {}
611 Ok(false) => return reason("proof_invalid"),
612 Err(_) => return reason("proof_malformed"),
613 }
614
615 let time = |name: &str| {
617 obj.get(name)
618 .and_then(|v| v.as_str())
619 .and_then(|t| parse_protocol_time_ns(t).ok())
620 };
621 let (Some(valid_from), Some(valid_until)) = (time("validFrom"), time("validUntil")) else {
622 return reason("no_validity_window");
623 };
624 let Ok(now) = parse_protocol_time_ns(now_iso) else {
625 return reason("no_validity_window");
626 };
627 let skew = seconds_to_ns(clock_skew_seconds);
628 if now - valid_until > skew {
629 return reason("expired");
630 }
631 if valid_from - now > skew {
632 return reason("not_yet_valid");
633 }
634 Ok(())
635}
636
637fn within_window(credential: &Value, now_iso: &str, clock_skew_seconds: i64) -> bool {
640 let obj = match credential.as_object() {
641 Some(o) => o,
642 None => return false,
643 };
644 let vf = obj.get("validFrom").and_then(|v| v.as_str());
645 let vu = obj.get("validUntil").and_then(|v| v.as_str());
646 let (vf, vu) = match (vf, vu) {
647 (Some(a), Some(b)) => (a, b),
648 _ => return false,
649 };
650 let now = match parse_protocol_time_ns(now_iso) {
651 Ok(n) => n,
652 Err(_) => return false,
653 };
654 let from = match parse_protocol_time_ns(vf) {
655 Ok(t) => t,
656 Err(_) => return false,
657 };
658 let until = match parse_protocol_time_ns(vu) {
659 Ok(t) => t,
660 Err(_) => return false,
661 };
662 let skew = seconds_to_ns(clock_skew_seconds);
663 from <= until && now >= from - skew && now <= until + skew
664}
665
666fn resolve_key(did: &str) -> Option<Vec<u8>> {
669 if did.starts_with("did:key:") {
670 did_key_to_ed25519(did).ok()
671 } else {
672 None
673 }
674}
675
676fn issuer_of(credential: &Value) -> Option<String> {
678 match credential.get("issuer") {
679 Some(Value::String(s)) => Some(s.clone()),
680 Some(Value::Array(a)) => a.first().and_then(|v| v.as_str()).map(|s| s.to_string()),
681 _ => None,
682 }
683}
684
685fn epoch_to_iso(epoch: i64) -> String {
688 let days = epoch.div_euclid(86400);
689 let secs = epoch.rem_euclid(86400);
690 let (y, m, d) = civil_from_days(days);
691 let hh = secs / 3600;
692 let mm = (secs % 3600) / 60;
693 let ss = secs % 60;
694 format!("{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}Z")
695}
696
697fn civil_from_days(z: i64) -> (i64, i64, i64) {
700 let z = z + 719468;
701 let era = (if z >= 0 { z } else { z - 146096 }) / 146097;
702 let doe = z - era * 146097;
703 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
704 let y = yoe + era * 400;
705 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
706 let mp = (5 * doy + 2) / 153;
707 let d = doy - (153 * mp + 2) / 5 + 1;
708 let m = if mp < 10 { mp + 3 } else { mp - 9 };
709 (if m <= 2 { y + 1 } else { y }, m, d)
710}
711
712struct JsonHost<'a> {
718 unreadable: &'a [Value],
719 keys: &'a [Value],
720 check_revoked: bool,
721 revoked: Option<&'a Map<String, Value>>,
722 action: Option<&'a Value>,
723}
724
725impl ChainHost for JsonHost<'_> {
726 fn key(&mut self, did: &str, vm: &str) -> Option<Option<Vec<u8>>> {
727 use base64::{engine::general_purpose::STANDARD, Engine};
728 let entry = self.keys.iter().find(|k| {
729 k.get("did").and_then(Value::as_str) == Some(did)
730 && k.get("vm").and_then(Value::as_str) == Some(vm)
731 })?;
732 Some(
733 entry
734 .get("publicKey")
735 .and_then(Value::as_str)
736 .and_then(|k| STANDARD.decode(k).ok()),
737 )
738 }
739 fn revoked(&mut self, which: &'static str) -> Option<bool> {
740 if !self.check_revoked {
741 return Some(false);
742 }
743 self.revoked?.get(which).and_then(Value::as_bool)
744 }
745 fn unreadable(&mut self, slot: &'static str) -> bool {
746 self.unreadable.iter().any(|v| v.as_str() == Some(slot))
747 }
748 fn action(&mut self) -> Option<(bool, Option<String>)> {
749 let a = self.action.filter(|a| a.is_object())?;
750 Some((
751 a.get("valid").and_then(Value::as_bool) == Some(true),
752 a.get("issuer").and_then(Value::as_str).map(String::from),
753 ))
754 }
755}
756
757fn ask_json(ask: &ChainAsk) -> Value {
758 match ask {
759 ChainAsk::Key { did, vm } => json!({"kind": "key", "did": did, "vm": vm}),
760 ChainAsk::Revoked(which) => json!({"kind": "revoked", "which": which}),
761 ChainAsk::Action => json!({"kind": "action"}),
762 }
763}
764
765fn chain_json(r: &IdentityChainResult) -> Value {
766 json!({
767 "ok": r.ok, "reason": r.reason, "agentDid": r.agent_did,
768 "issuerDid": r.issuer_did, "rootDid": r.root_did, "attributes": r.attributes,
769 })
770}
771
772fn trusted_root_of(request: &Value) -> String {
776 match request.get("trustedRoot") {
777 Some(Value::String(s)) => s.clone(),
778 None | Some(Value::Null) | Some(Value::Bool(false)) => String::new(),
779 Some(Value::Number(n)) if n.as_f64() == Some(0.0) => String::new(),
780 Some(Value::Array(a)) if a.is_empty() => String::new(),
781 Some(Value::Object(o)) if o.is_empty() => String::new(),
782 Some(_) => "\u{0}not a DID".to_string(),
784 }
785}
786
787fn optional_bool(request: &Value, name: &str) -> Result<bool> {
790 match request.get(name) {
791 None | Some(Value::Null) => Ok(false),
792 Some(Value::Bool(b)) => Ok(*b),
793 Some(_) => Err(CoreError::Json(format!("{name} must be true or false"))),
794 }
795}
796
797fn optional_array<'a>(request: &'a Value, name: &str) -> Result<Option<&'a Vec<Value>>> {
798 match request.get(name) {
799 None | Some(Value::Null) => Ok(None),
800 Some(Value::Array(a)) => Ok(Some(a)),
801 Some(_) => Err(CoreError::Json(format!("{name} must be a list"))),
802 }
803}
804
805fn required_text<'a>(request: &'a Value, name: &str) -> Result<&'a str> {
806 request
807 .get(name)
808 .and_then(Value::as_str)
809 .ok_or_else(|| CoreError::Json(format!("{name} must be text")))
810}
811
812fn optional_object<'a>(request: &'a Value, name: &str) -> Option<&'a Value> {
813 request.get(name).filter(|v| !v.is_null())
814}
815
816fn valid_seconds_of(request: &Value, default: i64) -> Result<i64> {
818 let refused = || {
819 CoreError::Json("valid_seconds must be a whole number of seconds greater than zero".into())
820 };
821 match request.get("validSeconds") {
822 None => Ok(default),
823 Some(v) => v
824 .as_i64()
825 .filter(|n| *n > 0 && !v.is_f64())
826 .ok_or_else(refused),
827 }
828}
829
830fn walk_json(
831 request: &Value,
832 identity: &Value,
833 recognized: &Value,
834 required_action: &Value,
835 has_action: bool,
836) -> Result<core::result::Result<IdentityChainResult, Value>> {
837 let skew = match request.get("clockSkewSeconds") {
838 None | Some(Value::Null) => 30,
839 Some(v) => crate::time_json::check_skew(v)?,
840 };
841 let empty = Vec::new();
842 let unreadable = optional_array(request, "unreadable")?.unwrap_or(&empty);
843 let root = if unreadable.iter().any(|v| v.as_str() == Some("root")) {
847 Some(request.get("root").unwrap_or(&Value::Null))
848 } else {
849 optional_object(request, "root")
850 };
851 let mut host = JsonHost {
852 unreadable,
853 keys: request
854 .get("keys")
855 .and_then(Value::as_array)
856 .unwrap_or(&empty),
857 check_revoked: optional_bool(request, "checkRevoked")?,
858 revoked: request.get("revoked").and_then(Value::as_object),
859 action: optional_object(request, "action"),
860 };
861 let walked = walk_identity_chain(
862 identity,
863 recognized,
864 &trusted_root_of(request),
865 root,
866 has_action,
867 required_action,
868 required_text(request, "now")?,
869 skew,
870 &mut host,
871 );
872 Ok(match walked {
873 ChainWalk::Done(r) => Ok(r),
874 ChainWalk::Ask(ask) => Err(json!({ "ask": ask_json(&ask) })),
875 })
876}
877
878pub fn rules_json(request: &Value) -> Result<Value> {
911 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
912 let op = required_text(request, "op")?;
913 let field = |name: &str| request.get(name).unwrap_or(&Value::Null);
914 match op {
915 "verifyChain" => {
916 let default_action = Value::String(ACTION_ISSUE_AGENT_IDENTITY.into());
919 let required = request.get("requiredAction").unwrap_or(&default_action);
920 let has_action = optional_bool(request, "hasAction")?;
921 Ok(
922 match walk_json(
923 request,
924 field("identity"),
925 field("recognized"),
926 required,
927 has_action,
928 )? {
929 Ok(r) => json!({ "result": chain_json(&r) }),
930 Err(ask) => ask,
931 },
932 )
933 }
934 "verifyRobotChain" => {
935 use base64::{engine::general_purpose::STANDARD, Engine};
936 let root = request
937 .get("trustedRoot")
938 .and_then(Value::as_str)
939 .unwrap_or("");
940 let robot_action = Value::String(ACTION_ISSUE_ROBOT_IDENTITY.into());
941 let chain = match walk_json(
942 request,
943 field("authorityIdentity"),
944 field("recognized"),
945 &robot_action,
946 false,
947 )? {
948 Ok(r) => r,
949 Err(ask) => return Ok(ask),
950 };
951 let key = request
952 .get("robotPublicKey")
953 .and_then(Value::as_str)
954 .and_then(|k| STANDARD.decode(k).ok())
955 .unwrap_or_default();
956 let r = crate::robotics::robot_identity_chain_tail(
957 chain,
958 if optional_array(request, "unreadable")?
960 .is_some_and(|u| u.iter().any(|v| v.as_str() == Some("hardwareCredential")))
961 {
962 &Value::Null
963 } else {
964 field("hardwareCredential")
965 },
966 root,
967 &key,
968 required_text(request, "now")?,
969 );
970 Ok(json!({"result": {
971 "ok": r.ok, "reason": r.reason, "robotDid": r.robot_did,
972 "issuerDid": r.issuer_did, "rootDid": r.root_did,
973 "attributes": r.attributes, "hardwareRooted": r.hardware_rooted,
974 }}))
975 }
976 "build" => {
977 let issuer = required_text(request, "issuerDid")?;
978 let status = optional_object(request, "credentialStatus").cloned();
979 if request.get("kind").and_then(Value::as_str) != Some("robotIdentity") {
982 valid_seconds_of(request, 1)?;
983 }
984 let (types, subject, default_seconds, status) = match required_text(request, "kind")? {
985 "root" => {
986 let scope = match list_or_default(request, "scope", "scope")? {
987 Some(a) => Value::Array(a.clone()),
988 None => json!(["ai-agent", "robot"]),
989 };
990 let mut subject = Map::new();
991 subject.insert("id".into(), json!(issuer));
992 subject.insert("vouchVersion".into(), json!(PROTOCOL_VERSION));
993 subject.insert(
994 "rootOfTrust".into(),
995 json!({"name": field("name"), "scope": scope}),
996 );
997 (ROOT_OF_TRUST_TYPE, subject, ROOT_VALID_SECONDS, None)
998 }
999 "recognizedIssuer" => {
1000 let subject_did = request
1001 .get("subjectDid")
1002 .and_then(Value::as_str)
1003 .filter(|d| !d.is_empty())
1004 .ok_or_else(|| CoreError::Json("issuer_did is required".into()))?;
1005 let actions = match list_or_default(
1006 request,
1007 "recognizedActions",
1008 "recognized_actions",
1009 )? {
1010 Some(a) => Value::Array(a.clone()),
1011 None => json!([ACTION_ISSUE_AGENT_IDENTITY]),
1012 };
1013 let mut subject = Map::new();
1014 subject.insert("id".into(), json!(subject_did));
1015 subject.insert("recognizedActions".into(), actions);
1016 subject.insert("recognizedIn".into(), json!(issuer));
1017 (
1018 RECOGNIZED_ISSUER_TYPE,
1019 subject,
1020 ISSUER_VALID_SECONDS,
1021 status,
1022 )
1023 }
1024 kind @ ("agentIdentity" | "robotIdentity") => {
1025 let robot = kind == "robotIdentity";
1026 let name = if robot { "robotDid" } else { "subjectDid" };
1027 let subject_did = request
1028 .get(name)
1029 .and_then(Value::as_str)
1030 .filter(|d| !d.is_empty())
1031 .ok_or_else(|| {
1032 CoreError::Json(if robot {
1033 "robot_did is required".into()
1034 } else {
1035 "subject_did is required".into()
1036 })
1037 })?;
1038 let attributes = if robot {
1039 let hw = request
1040 .get("hardwareKeyMultibase")
1041 .and_then(Value::as_str)
1042 .filter(|k| !k.is_empty())
1043 .ok_or_else(|| {
1044 CoreError::Json("hardware_key_multibase is required".into())
1045 })?;
1046 let mut attributes = attribute_map(field("attributes"))?;
1047 attributes.insert("kind".into(), json!("robot"));
1048 attributes.insert("hardwareKey".into(), json!(hw));
1049 match optional_object(request, "hardwareRootKeyMultibase") {
1050 None => {}
1051 Some(Value::String(k)) if !k.is_empty() => {
1052 attributes.insert("hardwareRootKey".into(), json!(k));
1053 }
1054 Some(_) => {
1055 return Err(CoreError::Json(
1056 "hardware_root_key_multibase must be a multikey string".into(),
1057 ))
1058 }
1059 }
1060 attributes
1061 } else {
1062 attribute_map(field("attributes"))?
1063 };
1064 let mut subject = Map::new();
1065 subject.insert("id".into(), json!(subject_did));
1066 subject.insert("identity".into(), Value::Object(attributes));
1067 (AGENT_IDENTITY_TYPE, subject, IDENTITY_VALID_SECONDS, status)
1068 }
1069 other => {
1070 return Err(CoreError::Json(format!(
1071 "no root of trust credential of kind {other:?}"
1072 )))
1073 }
1074 };
1075 let valid_seconds = valid_seconds_of(request, default_seconds)?;
1076 let credential = envelope(
1077 required_text(request, "credentialId")?,
1078 &[VC_TYPE, types],
1079 issuer,
1080 Value::Object(subject),
1081 required_text(request, "validFrom")?,
1082 valid_seconds,
1083 status,
1084 )?;
1085 Ok(json!({ "credential": credential }))
1086 }
1087 other => Err(CoreError::Json(format!(
1088 "unknown root of trust op {other:?}"
1089 ))),
1090 }
1091}
1092
1093pub fn rules_json_text(text: &str) -> Result<Value> {
1097 rules_json(&crate::jcs::parse_deep(text)?)
1098}
1099
1100fn list_or_default<'a>(
1103 request: &'a Value,
1104 name: &str,
1105 text: &str,
1106) -> Result<Option<&'a Vec<Value>>> {
1107 match request.get(name) {
1108 None | Some(Value::Null) => Ok(None),
1109 Some(Value::Array(a)) if a.is_empty() => Ok(None),
1110 Some(Value::Array(a)) => Ok(Some(a)),
1111 Some(_) => Err(CoreError::Json(format!("{text} must be a list"))),
1112 }
1113}
1114
1115fn attribute_map(v: &Value) -> Result<Map<String, Value>> {
1116 match v.as_object() {
1117 Some(o) if !o.is_empty() => Ok(o.clone()),
1118 _ => Err(CoreError::Json(
1119 "attributes must be a non-empty dict".into(),
1120 )),
1121 }
1122}
1123
1124#[cfg(test)]
1125mod tests {
1126 use super::*;
1127 use std::path::PathBuf;
1128
1129 const ROOT_SEED: [u8; 32] = [0x01; 32];
1130 const ISSUER_SEED: [u8; 32] = [0x02; 32];
1131 const AGENT_SEED: [u8; 32] = [0x03; 32];
1132
1133 const VALID_FROM: &str = "2026-01-01T00:00:00Z";
1134 const CREATED: &str = "2026-01-01T00:00:00Z";
1135 const VALID_SECONDS: i64 = 100 * 365 * 24 * 3600;
1136 const NOW: &str = "2026-07-01T00:00:00Z";
1137
1138 const ROOT_ID: &str = "urn:uuid:11111111-1111-1111-1111-111111111111";
1139 const RECOGNITION_ID: &str = "urn:uuid:22222222-2222-2222-2222-222222222222";
1140 const IDENTITY_ID: &str = "urn:uuid:33333333-3333-3333-3333-333333333333";
1141
1142 fn load_vector() -> Value {
1143 let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1144 .join("../../test-vectors/root-of-trust/vector.json");
1145 let text = std::fs::read_to_string(&path)
1146 .unwrap_or_else(|e| panic!("read vector {}: {e}", path.display()));
1147 serde_json::from_str(&text).expect("vector is valid JSON")
1148 }
1149
1150 fn agent_attributes() -> Value {
1151 json!({ "owner": "Acme", "model": "gpt-x", "capabilityClass": "shopping" })
1152 }
1153
1154 fn build_all() -> (Value, Value, Value) {
1155 let issuer_did = did_of_seed(&ISSUER_SEED).unwrap();
1156 let agent_did = did_of_seed(&AGENT_SEED).unwrap();
1157
1158 let root = build_root_of_trust(
1159 &ROOT_SEED,
1160 "Vouch Machine Identity Root",
1161 None,
1162 VALID_SECONDS,
1163 VALID_FROM,
1164 CREATED,
1165 ROOT_ID,
1166 )
1167 .unwrap();
1168
1169 let recognition = build_recognized_issuer(
1170 &ROOT_SEED,
1171 &issuer_did,
1172 Some(&[ACTION_ISSUE_AGENT_IDENTITY]),
1173 VALID_SECONDS,
1174 VALID_FROM,
1175 CREATED,
1176 None,
1177 RECOGNITION_ID,
1178 )
1179 .unwrap();
1180
1181 let identity = build_agent_identity(
1182 &ISSUER_SEED,
1183 &agent_did,
1184 &agent_attributes(),
1185 VALID_SECONDS,
1186 VALID_FROM,
1187 CREATED,
1188 None,
1189 IDENTITY_ID,
1190 )
1191 .unwrap();
1192
1193 (root, recognition, identity)
1194 }
1195
1196 #[test]
1198 fn verifies_python_signed_vector() {
1199 let vector = load_vector();
1200 let trusted_root = vector["trustedRoot"].as_str().unwrap();
1201 let result = verify_identity_chain(
1202 &vector["agentIdentity"],
1203 &vector["recognizedIssuer"],
1204 trusted_root,
1205 Some(&vector["rootOfTrust"]),
1206 None,
1207 ACTION_ISSUE_AGENT_IDENTITY,
1208 NOW,
1209 30,
1210 );
1211 assert!(result.ok, "chain must verify: {:?}", result.reason);
1212 assert_eq!(
1213 result.agent_did.as_deref(),
1214 vector["expected"]["agentDid"].as_str()
1215 );
1216 assert_eq!(
1217 result.issuer_did.as_deref(),
1218 vector["expected"]["issuerDid"].as_str()
1219 );
1220 assert_eq!(result.root_did.as_deref(), Some(trusted_root));
1221 }
1222
1223 #[test]
1225 fn reproduces_vector_byte_for_byte() {
1226 let vector = load_vector();
1227 let (root, recognition, identity) = build_all();
1228
1229 assert_eq!(
1230 root["proof"]["proofValue"], vector["rootOfTrust"]["proof"]["proofValue"],
1231 "root of trust proofValue diverges from Python"
1232 );
1233 assert_eq!(
1234 recognition["proof"]["proofValue"], vector["recognizedIssuer"]["proof"]["proofValue"],
1235 "recognized issuer proofValue diverges from Python"
1236 );
1237 assert_eq!(
1238 identity["proof"]["proofValue"], vector["agentIdentity"]["proof"]["proofValue"],
1239 "agent identity proofValue diverges from Python"
1240 );
1241
1242 assert_eq!(root["issuer"], vector["trustedRoot"]);
1244 assert_eq!(root["validUntil"], vector["rootOfTrust"]["validUntil"]);
1245 assert_eq!(identity["issuer"], vector["agentIdentity"]["issuer"]);
1246 }
1247
1248 #[test]
1250 fn self_built_chain_verifies() {
1251 let (root, recognition, identity) = build_all();
1252 let root_did = did_of_seed(&ROOT_SEED).unwrap();
1253 let agent_did = did_of_seed(&AGENT_SEED).unwrap();
1254 let issuer_did = did_of_seed(&ISSUER_SEED).unwrap();
1255
1256 let result = verify_identity_chain(
1257 &identity,
1258 &recognition,
1259 &root_did,
1260 Some(&root),
1261 None,
1262 ACTION_ISSUE_AGENT_IDENTITY,
1263 NOW,
1264 30,
1265 );
1266 assert!(
1267 result.ok,
1268 "self-built chain must verify: {:?}",
1269 result.reason
1270 );
1271 assert_eq!(result.agent_did.as_deref(), Some(agent_did.as_str()));
1272 assert_eq!(result.issuer_did.as_deref(), Some(issuer_did.as_str()));
1273 assert_eq!(result.attributes, Some(agent_attributes()));
1274 }
1275
1276 #[test]
1277 fn skew_outside_zero_to_120_is_refused() {
1278 let (root, recognition, identity) = build_all();
1279 let root_did = did_of_seed(&ROOT_SEED).unwrap();
1280 for skew in [-1, 121, 300, 1_000_000_000] {
1281 let result = verify_identity_chain(
1282 &identity,
1283 &recognition,
1284 &root_did,
1285 Some(&root),
1286 None,
1287 ACTION_ISSUE_AGENT_IDENTITY,
1288 NOW,
1289 skew,
1290 );
1291 assert!(!result.ok, "skew {skew} must be refused");
1292 assert_eq!(result.reason.as_deref(), Some("invalid_clock_skew"));
1293 }
1294 }
1295
1296 #[test]
1298 fn tampered_identity_proof_is_rejected() {
1299 let vector = load_vector();
1300 let mut identity = vector["agentIdentity"].clone();
1301 identity["credentialSubject"]["identity"]["capabilityClass"] = json!("admin");
1305 let result = verify_identity_chain(
1306 &identity,
1307 &vector["recognizedIssuer"],
1308 vector["trustedRoot"].as_str().unwrap(),
1309 Some(&vector["rootOfTrust"]),
1310 None,
1311 ACTION_ISSUE_AGENT_IDENTITY,
1312 NOW,
1313 30,
1314 );
1315 assert!(!result.ok, "tampered proof must be rejected");
1316 assert_eq!(
1317 result.reason.as_deref(),
1318 Some("identity_proof_invalid"),
1319 "unexpected reason for tampered proof"
1320 );
1321 }
1322
1323 #[test]
1325 fn wrong_action_is_rejected() {
1326 let (root, _recognition, identity) = build_all();
1327 let root_did = did_of_seed(&ROOT_SEED).unwrap();
1328 let issuer_did = did_of_seed(&ISSUER_SEED).unwrap();
1329 let recognition = build_recognized_issuer(
1330 &ROOT_SEED,
1331 &issuer_did,
1332 Some(&[ACTION_ISSUE_ROBOT_IDENTITY]),
1333 VALID_SECONDS,
1334 VALID_FROM,
1335 CREATED,
1336 None,
1337 RECOGNITION_ID,
1338 )
1339 .unwrap();
1340 let result = verify_identity_chain(
1341 &identity,
1342 &recognition,
1343 &root_did,
1344 Some(&root),
1345 None,
1346 ACTION_ISSUE_AGENT_IDENTITY,
1347 NOW,
1348 30,
1349 );
1350 assert!(!result.ok);
1351 assert_eq!(
1352 result.reason.as_deref(),
1353 Some("issuer_not_recognized_for_action")
1354 );
1355 }
1356
1357 #[test]
1359 fn ambiguous_type_is_rejected() {
1360 let (_root, recognition, mut identity) = build_all();
1361 identity["type"] = json!([VC_TYPE, AGENT_IDENTITY_TYPE, RECOGNIZED_ISSUER_TYPE]);
1362 let root_did = did_of_seed(&ROOT_SEED).unwrap();
1363 let result = verify_identity_chain(
1364 &identity,
1365 &recognition,
1366 &root_did,
1367 None,
1368 None,
1369 ACTION_ISSUE_AGENT_IDENTITY,
1370 NOW,
1371 30,
1372 );
1373 assert!(!result.ok);
1374 assert_eq!(result.reason.as_deref(), Some("identity_ambiguous_type"));
1375 }
1376
1377 #[test]
1378 fn epoch_iso_roundtrip() {
1379 assert_eq!(epoch_to_iso(0), "1970-01-01T00:00:00Z");
1380 let from = iso_to_epoch_seconds(VALID_FROM).unwrap();
1381 assert_eq!(epoch_to_iso(from + VALID_SECONDS), "2125-12-08T00:00:00Z");
1382 }
1383
1384 fn walk_request(extra: Value) -> Value {
1385 let (root, recognition, identity) = build_all();
1386 let mut req = json!({
1387 "op": "verifyChain",
1388 "identity": identity,
1389 "recognized": recognition,
1390 "trustedRoot": did_of_seed(&ROOT_SEED).unwrap(),
1391 "root": root,
1392 "now": NOW,
1393 });
1394 for (k, v) in extra.as_object().unwrap() {
1395 req[k] = v.clone();
1396 }
1397 req
1398 }
1399
1400 fn walk(mut req: Value) -> Value {
1402 use base64::{engine::general_purpose::STANDARD, Engine};
1403 for _ in 0..8 {
1404 let out = rules_json(&req).unwrap();
1405 let Some(ask) = out.get("ask") else {
1406 return out["result"].clone();
1407 };
1408 assert_eq!(ask["kind"], "key", "{out}");
1409 let did = ask["did"].as_str().unwrap();
1410 let key = did_key_to_ed25519(did).unwrap();
1411 let keys = req
1412 .as_object_mut()
1413 .unwrap()
1414 .entry("keys")
1415 .or_insert(json!([]));
1416 keys.as_array_mut()
1417 .unwrap()
1418 .push(json!({"did": did, "vm": ask["vm"], "publicKey": STANDARD.encode(key)}));
1419 }
1420 panic!("the walk did not finish");
1421 }
1422
1423 #[test]
1424 fn a_required_action_is_compared_as_given() {
1425 assert_eq!(walk(walk_request(json!({})))["ok"], json!(true));
1426 for odd in [
1427 json!(null),
1428 json!(5),
1429 json!(["issueAgentIdentity"]),
1430 json!(""),
1431 ] {
1432 let got = walk(walk_request(json!({ "requiredAction": odd })));
1433 assert_eq!(
1434 got["reason"],
1435 json!("issuer_not_recognized_for_action"),
1436 "{odd}"
1437 );
1438 }
1439 }
1440
1441 #[test]
1442 fn flags_that_are_not_true_or_false_are_refused() {
1443 for (name, value) in [("checkRevoked", json!(1)), ("hasAction", json!("true"))] {
1444 let err = rules_json(&walk_request(json!({ name: value }))).unwrap_err();
1445 assert_eq!(
1446 err,
1447 CoreError::Json(format!("{name} must be true or false"))
1448 );
1449 }
1450 }
1451
1452 #[test]
1453 fn an_unreadable_credential_has_a_malformed_proof() {
1454 let got = walk(walk_request(json!({"unreadable": ["identity"]})));
1455 assert_eq!(got["reason"], json!("identity_proof_malformed"));
1456 let got = walk(walk_request(json!({"unreadable": ["recognized"]})));
1457 assert_eq!(got["reason"], json!("recognized_issuer_proof_malformed"));
1458 }
1459
1460 #[test]
1461 fn an_unreadable_required_action_matches_no_action() {
1462 let got = walk(walk_request(json!({
1463 "requiredAction": null, "unreadable": ["requiredAction"]
1464 })));
1465 assert_eq!(got["reason"], json!("issuer_not_recognized_for_action"));
1466 let got = walk(walk_request(json!({
1467 "requiredAction": "issueAgentIdentity", "unreadable": ["requiredAction"]
1468 })));
1469 assert_eq!(got["reason"], json!("issuer_not_recognized_for_action"));
1470 }
1471
1472 #[test]
1473 fn an_unreadable_root_that_is_not_an_object_is_not_a_credential() {
1474 let got = walk(walk_request(json!({"root": null, "unreadable": ["root"]})));
1477 assert_eq!(got["reason"], json!("root_not_a_credential"));
1478 let got = walk(walk_request(json!({"root": null})));
1479 assert_eq!(got["ok"], json!(true));
1480 }
1481
1482 #[test]
1483 fn a_trust_type_list_with_a_nested_list_is_ambiguous() {
1484 let (_, mut recognition, identity) = build_all();
1485 recognition["type"]
1486 .as_array_mut()
1487 .unwrap()
1488 .push(json!(["VouchRootOfTrust"]));
1489 let got = walk(walk_request(
1490 json!({"recognized": recognition, "identity": identity}),
1491 ));
1492 assert_eq!(got["reason"], json!("recognized_issuer_ambiguous_type"));
1493 }
1494
1495 #[test]
1496 fn a_trusted_root_that_is_not_text_pins_nothing_an_issuer_can_be() {
1497 let got = walk(walk_request(json!({"trustedRoot": 5})));
1498 assert_eq!(got["reason"], json!("recognized_issuer_not_from_root"));
1499 let got = walk(walk_request(json!({"trustedRoot": ""})));
1500 assert_eq!(got["reason"], json!("no_trusted_root"));
1501 }
1502
1503 #[test]
1504 #[cfg_attr(not(feature = "std"), ignore = "the std build's 512-level allowance")]
1505 fn a_deep_credential_is_read_and_judged_by_its_proof() {
1506 let (_, recognition, mut identity) = build_all();
1507 let deep =
1508 crate::jcs::parse_deep(&format!("{}{}", "[".repeat(130), "]".repeat(130))).unwrap();
1509 identity["x"] = deep;
1510 let mut req = walk_request(json!({"recognized": recognition}));
1511 req["identity"] = identity;
1512 let text = req.to_string();
1513 assert!(
1514 serde_json::from_str::<Value>(&text).is_err(),
1515 "deeper than the default reader"
1516 );
1517 let out = rules_json_text(&text).unwrap();
1518 assert!(out.get("ask").is_some() || out.get("result").is_some());
1519 }
1520
1521 #[test]
1522 #[cfg_attr(feature = "std", ignore = "checks the no_std build")]
1523 fn no_std_text_entry_refuses_past_the_cap_before_parsing() {
1524 let (_, recognition, _) = build_all();
1525 let req = walk_request(json!({"recognized": recognition})).to_string();
1526 for n in [32, 129, 600] {
1527 let deep = format!("{}{}", "[".repeat(n), "]".repeat(n));
1528 let text = format!("{{\"x\":{deep},{}", &req[1..]);
1529 assert_eq!(
1530 rules_json_text(&text).unwrap_err(),
1531 crate::nesting::too_deep(),
1532 "{n} levels"
1533 );
1534 }
1535 }
1536
1537 #[test]
1538 fn build_refuses_wrong_types_and_a_window_past_year_9999() {
1539 let base = json!({"op": "build", "issuerDid": "did:web:a.example", "credentialId": "urn:x",
1540 "validFrom": "2026-01-01T00:00:00Z"});
1541 let with = |k: &str, v: Value, kind: &str| {
1542 let mut r = base.clone();
1543 r["kind"] = json!(kind);
1544 r["name"] = json!("n");
1545 r["subjectDid"] = json!("did:web:b.example");
1546 r[k] = v;
1547 rules_json(&r)
1548 };
1549 assert_eq!(
1550 with("scope", json!("robot"), "root").unwrap_err(),
1551 CoreError::Json("scope must be a list".into())
1552 );
1553 assert_eq!(
1554 with("recognizedActions", json!({"a": 1}), "recognizedIssuer").unwrap_err(),
1555 CoreError::Json("recognized_actions must be a list".into())
1556 );
1557 assert!(with("validSeconds", json!(null), "root").is_err());
1558 let err = with("validSeconds", json!(i64::MAX), "root").unwrap_err();
1559 assert_eq!(
1560 err,
1561 CoreError::Json("valid_seconds puts validUntil past 9999-12-31T23:59:59Z".into())
1562 );
1563 let mut r = base.clone();
1564 r["kind"] = json!("root");
1565 r["validFrom"] = json!("9999-12-31T23:59:58Z");
1566 r["validSeconds"] = json!(1);
1567 assert_eq!(
1568 rules_json(&r).unwrap()["credential"]["validUntil"],
1569 json!("9999-12-31T23:59:59Z")
1570 );
1571 }
1572}