Skip to main content

vouch_core/
root_of_trust.rs

1//! Root of Trust for Machine Identity (Vouch Protocol).
2//!
3//! Byte-exact port of the Python reference `vouch/root_of_trust.py`. Lets Vouch
4//! Protocol act as the trust anchor for AI agent and robot identity. A verifier
5//! pins ONE Vouch root, then verifies any agent offline by walking:
6//!
7//! ```text
8//! agent identity credential  ->  recognized-issuer credential  ->  Vouch root
9//! ```
10//!
11//! Three credential types compose this chain, all secured with the same
12//! `eddsa-jcs-2022` Data Integrity proof used elsewhere in the core:
13//!
14//!   1. Root of Trust credential: self-issued by the root (issuer == subject).
15//!   2. Recognized-issuer credential: issued by the root, naming an issuer that may attest agent or robot identity.
16//!   3. Agent identity credential: issued by a recognized issuer, binding an agent key to real attributes (issuer != subject).
17//!
18//! The core is deterministic and clock-free: the caller supplies `valid_from`,
19//! `created`, and the current instant used for verification. That keeps the
20//! proofs reproducible and interoperable with the Python and TypeScript SDKs
21//! (see `test-vectors/root-of-trust/vector.json`).
22
23#[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
34/// Credential type identifiers (the second entry in each `type` array).
35pub const ROOT_OF_TRUST_TYPE: &str = "VouchRootOfTrust";
36pub const RECOGNIZED_ISSUER_TYPE: &str = "RecognizedIssuerCredential";
37pub const AGENT_IDENTITY_TYPE: &str = "AgentIdentityCredential";
38
39/// Actions an issuer can be recognized to perform.
40pub const ACTION_ISSUE_AGENT_IDENTITY: &str = "issueAgentIdentity";
41pub const ACTION_ISSUE_ROBOT_IDENTITY: &str = "issueRobotIdentity";
42
43/// The three trust-layer credential types. A single credential must carry exactly
44/// one of these, otherwise one signed object could be replayed into a different
45/// slot of the chain (type confusion).
46const TRUST_TYPES: [&str; 3] = [
47    ROOT_OF_TRUST_TYPE,
48    RECOGNIZED_ISSUER_TYPE,
49    AGENT_IDENTITY_TYPE,
50];
51
52/// Default validity windows. Roots are long lived; issuer and identity
53/// credentials rotate more often. All are overridable per call.
54pub 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
58/// The Ed25519 proof verification method of a signer: `did:key:<mb>#<mb>` for a
59/// did:key, `{did}#key-1` for any other DID.
60fn verification_method_of(did: &str) -> String {
61    crate::verification_method::ed25519_method(did)
62}
63
64/// Outcome of [`verify_identity_chain`].
65///
66/// `ok` is true only if every link verified and anchored to the pinned root.
67/// On failure `reason` carries a structured code matching the Python reference.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct IdentityChainResult {
70    pub ok: bool,
71    pub reason: Option<String>,
72    pub agent_did: Option<String>,
73    pub issuer_did: Option<String>,
74    pub root_did: Option<String>,
75    pub attributes: Option<Value>,
76}
77
78impl IdentityChainResult {
79    fn fail(reason: impl Into<String>) -> Self {
80        Self {
81            ok: false,
82            reason: Some(reason.into()),
83            agent_did: None,
84            issuer_did: None,
85            root_did: None,
86            attributes: None,
87        }
88    }
89}
90
91// ---------------------------------------------------------------------------
92// Credential builders
93// ---------------------------------------------------------------------------
94
95/// Self-issue the Vouch Root of Trust credential.
96///
97/// Issuer and subject are both the root's own DID (derived from `root_seed`).
98/// `scope` defaults to `["ai-agent", "robot"]` when None. `valid_from` and
99/// `created` are ISO-8601 instants ("YYYY-MM-DDTHH:MM:SSZ"); the core does not
100/// read a clock.
101#[allow(clippy::too_many_arguments)]
102pub fn build_root_of_trust(
103    root_seed: &[u8],
104    name: &str,
105    scope: Option<&[&str]>,
106    valid_seconds: i64,
107    valid_from: &str,
108    created: &str,
109    credential_id: &str,
110) -> Result<Value> {
111    let root_did = did_of_seed(root_seed)?;
112    let scope_val: Vec<Value> = match scope {
113        Some(s) => s.iter().map(|x| json!(x)).collect(),
114        None => vec![json!("ai-agent"), json!("robot")],
115    };
116    let mut subject = Map::new();
117    subject.insert("id".into(), json!(root_did));
118    subject.insert("vouchVersion".into(), json!(PROTOCOL_VERSION));
119    subject.insert(
120        "rootOfTrust".into(),
121        json!({ "name": name, "scope": scope_val }),
122    );
123
124    let credential = envelope(
125        credential_id,
126        &[VC_TYPE, ROOT_OF_TRUST_TYPE],
127        &root_did,
128        Value::Object(subject),
129        valid_from,
130        valid_seconds,
131        None,
132    )?;
133    sign(&credential, root_seed, &root_did, created)
134}
135
136/// Issue a recognized-issuer credential from the root.
137///
138/// The root attests that `issuer_did` may perform `recognized_actions`
139/// (default `["issueAgentIdentity"]`). `recognizedIn` chains back to the root
140/// DID so a verifier can trace the recognition to the anchor it pinned.
141#[allow(clippy::too_many_arguments)]
142pub fn build_recognized_issuer(
143    root_seed: &[u8],
144    issuer_did: &str,
145    recognized_actions: Option<&[&str]>,
146    valid_seconds: i64,
147    valid_from: &str,
148    created: &str,
149    credential_status: Option<Value>,
150    credential_id: &str,
151) -> Result<Value> {
152    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); drop credential_status);
153    if issuer_did.is_empty() {
154        return Err(CoreError::Json("issuer_did is required".into()));
155    }
156    let root_did = did_of_seed(root_seed)?;
157    let actions: Vec<Value> = match recognized_actions {
158        Some(a) => a.iter().map(|x| json!(x)).collect(),
159        None => vec![json!(ACTION_ISSUE_AGENT_IDENTITY)],
160    };
161    let mut subject = Map::new();
162    subject.insert("id".into(), json!(issuer_did));
163    subject.insert("recognizedActions".into(), Value::Array(actions));
164    subject.insert("recognizedIn".into(), json!(root_did));
165
166    let credential = envelope(
167        credential_id,
168        &[VC_TYPE, RECOGNIZED_ISSUER_TYPE],
169        &root_did,
170        Value::Object(subject),
171        valid_from,
172        valid_seconds,
173        credential_status,
174    )?;
175    sign(&credential, root_seed, &root_did, created)
176}
177
178/// Issue an authority-issued identity credential for an agent.
179///
180/// Here the issuer (derived from `issuer_seed`) differs from the subject: a
181/// recognized issuer binds `subject_did` to real `attributes` (owner, model,
182/// capability class, and so on). `attributes` MUST be a non-empty JSON object.
183#[allow(clippy::too_many_arguments)]
184pub fn build_agent_identity(
185    issuer_seed: &[u8],
186    subject_did: &str,
187    attributes: &Value,
188    valid_seconds: i64,
189    valid_from: &str,
190    created: &str,
191    credential_status: Option<Value>,
192    credential_id: &str,
193) -> Result<Value> {
194    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); attributes; drop credential_status);
195    if subject_did.is_empty() {
196        return Err(CoreError::Json("subject_did is required".into()));
197    }
198    match attributes.as_object() {
199        Some(o) if !o.is_empty() => {}
200        _ => {
201            return Err(CoreError::Json(
202                "attributes must be a non-empty object".into(),
203            ))
204        }
205    }
206    let issuer_did = did_of_seed(issuer_seed)?;
207    let mut subject = Map::new();
208    subject.insert("id".into(), json!(subject_did));
209    subject.insert("identity".into(), attributes.clone());
210
211    let credential = envelope(
212        credential_id,
213        &[VC_TYPE, AGENT_IDENTITY_TYPE],
214        &issuer_did,
215        Value::Object(subject),
216        valid_from,
217        valid_seconds,
218        credential_status,
219    )?;
220    sign(&credential, issuer_seed, &issuer_did, created)
221}
222
223// ---------------------------------------------------------------------------
224// Verification
225// ---------------------------------------------------------------------------
226
227/// What a host is asked for while a chain is walked (see [`walk_identity_chain`]).
228#[derive(Debug, Clone, PartialEq, Eq)]
229pub enum ChainAsk {
230    /// The Ed25519 public key of `did` for the proof's verification method.
231    Key { did: String, vm: String },
232    /// Whether the recognized-issuer ("recognized") or the identity
233    /// ("identity") credential is revoked.
234    Revoked(&'static str),
235    /// The action credential's verdict: does it verify (the host's verifier,
236    /// which runs the core decision), and who issued it.
237    Action,
238}
239
240/// A host's answers. Each method answers None when it has not been asked
241/// before: the walk then stops with that [`ChainAsk`], the host finds the
242/// answer, and the walk runs again from the start with it.
243pub trait ChainHost {
244    /// The issuer's key: Some(Some(key)), Some(None) when it cannot be
245    /// resolved, None when not yet asked.
246    fn key(&mut self, did: &str, vm: &str) -> Option<Option<Vec<u8>>>;
247    /// Whether a credential is revoked; a host with no revocation check
248    /// answers Some(false).
249    fn revoked(&mut self, which: &'static str) -> Option<bool>;
250    /// The action credential's (verifies, issuer).
251    fn action(&mut self) -> Option<(bool, Option<String>)>;
252    /// Whether the credential in a slot ("recognized", "identity", "root")
253    /// has no JSON form the host could hand over (a NaN, an infinity, a lone
254    /// surrogate, a number out of range, nesting too deep): the host sends a
255    /// copy with those values as null, and its proof is malformed. The slot
256    /// "requiredAction" names a required action with no JSON form, which no
257    /// issuer holds.
258    fn unreadable(&mut self, _slot: &'static str) -> bool {
259        false
260    }
261}
262
263/// Where a walk stopped.
264#[derive(Debug, Clone, PartialEq)]
265pub enum ChainWalk {
266    Done(IdentityChainResult),
267    Ask(ChainAsk),
268}
269
270/// Why a trust credential check stopped: a reason code, or a question.
271enum Stop {
272    Reason(&'static str),
273    Ask(ChainAsk),
274}
275
276/// Walk an agent identity to a pinned Vouch root, the reference's checks in
277/// the reference's order:
278///
279/// 1. the recognized-issuer credential is a valid trust credential, issued
280///    by `trusted_root`, with a subject that is recognized for
281///    `required_action`, and not revoked;
282/// 2. the identity credential is a valid trust credential issued by that
283///    recognized issuer, not revoked, with a subject;
284/// 3. when given, the root credential is a valid trust credential issued by
285///    `trusted_root` about itself;
286/// 4. when `has_action`, the action credential verifies and its issuer is the
287///    agent the identity names.
288///
289/// Keys, revocation and the action verdict come from the host, one question
290/// at a time, so it is asked only what the reference would ask, in the
291/// reference's order. A replay check of the action credential stays with the
292/// host (its store), after a result that is ok.
293#[allow(clippy::too_many_arguments)]
294pub fn walk_identity_chain(
295    identity_credential: &Value,
296    recognized_issuer_credential: &Value,
297    trusted_root: &str,
298    root_credential: Option<&Value>,
299    has_action: bool,
300    required_action: &Value,
301    now_iso: &str,
302    clock_skew_seconds: i64,
303    host: &mut dyn ChainHost,
304) -> ChainWalk {
305    crate::nesting::deep_guard!(ChainWalk::Done(IdentityChainResult::fail(crate::nesting::TOO_DEEP)); identity_credential, recognized_issuer_credential, root_credential, required_action);
306    let fail = |r: &str| ChainWalk::Done(IdentityChainResult::fail(r));
307    // A skew outside 0..120 is a caller error: the chain is refused.
308    if crate::time::check_clock_skew(clock_skew_seconds).is_err() {
309        return fail("invalid_clock_skew");
310    }
311    if trusted_root.is_empty() {
312        return fail("no_trusted_root");
313    }
314    macro_rules! check {
315        ($cred:expr, $ty:expr, $slot:expr, $prefix:expr) => {
316            match verify_trust_credential($cred, $ty, $slot, now_iso, clock_skew_seconds, host) {
317                Ok(()) => {}
318                Err(Stop::Ask(ask)) => return ChainWalk::Ask(ask),
319                Err(Stop::Reason(r)) => return fail(&format!("{}{r}", $prefix)),
320            }
321        };
322    }
323
324    // 1. The recognition must be signed by the pinned root.
325    check!(
326        recognized_issuer_credential,
327        RECOGNIZED_ISSUER_TYPE,
328        "recognized",
329        "recognized_issuer_"
330    );
331    if issuer_of(recognized_issuer_credential).as_deref() != Some(trusted_root) {
332        return fail("recognized_issuer_not_from_root");
333    }
334    let rec_subject = match recognized_issuer_credential.get("credentialSubject") {
335        Some(Value::Object(o)) => o,
336        _ => return fail("recognized_issuer_bad_subject"),
337    };
338    let recognized_did = match rec_subject.get("id").and_then(|v| v.as_str()) {
339        Some(s) if !s.is_empty() => s.to_string(),
340        _ => return fail("recognized_issuer_no_subject"),
341    };
342    let actions_ok = rec_subject
343        .get("recognizedActions")
344        .and_then(|v| v.as_array())
345        // Any JSON value the caller names, compared as the reference's `in`
346        // compares it: a value that is not one of the actions matches none.
347        .map(|a| a.iter().any(|x| x == required_action))
348        .unwrap_or(false)
349        // An action the host could not hand over (no JSON form) is one no
350        // issuer holds.
351        && !host.unreadable("requiredAction");
352    if !actions_ok {
353        return fail("issuer_not_recognized_for_action");
354    }
355    match host.revoked("recognized") {
356        None => return ChainWalk::Ask(ChainAsk::Revoked("recognized")),
357        Some(true) => return fail("recognized_issuer_revoked"),
358        Some(false) => {}
359    }
360
361    // 2. The identity must be signed by the recognized issuer.
362    check!(
363        identity_credential,
364        AGENT_IDENTITY_TYPE,
365        "identity",
366        "identity_"
367    );
368    if issuer_of(identity_credential).as_deref() != Some(recognized_did.as_str()) {
369        return fail("identity_not_from_recognized_issuer");
370    }
371    match host.revoked("identity") {
372        None => return ChainWalk::Ask(ChainAsk::Revoked("identity")),
373        Some(true) => return fail("identity_revoked"),
374        Some(false) => {}
375    }
376    let id_subject = match identity_credential.get("credentialSubject") {
377        Some(Value::Object(o)) => o,
378        _ => return fail("identity_bad_subject"),
379    };
380    let agent_did = match id_subject.get("id").and_then(|v| v.as_str()) {
381        Some(s) if !s.is_empty() => s.to_string(),
382        _ => return fail("identity_no_subject"),
383    };
384    let attributes = id_subject.get("identity").cloned();
385
386    // 3. Optional: confirm the root credential is genuinely self-issued.
387    if let Some(root_cred) = root_credential {
388        check!(root_cred, ROOT_OF_TRUST_TYPE, "root", "root_");
389        let root_sub = match root_cred.get("credentialSubject") {
390            Some(Value::Object(o)) => o,
391            _ => return fail("root_bad_subject"),
392        };
393        if issuer_of(root_cred).as_deref() != Some(trusted_root)
394            || root_sub.get("id").and_then(|v| v.as_str()) != Some(trusted_root)
395        {
396            return fail("root_not_self_issued");
397        }
398    }
399
400    // 4. Optional: bind the agent's own action to this identity.
401    if has_action {
402        match host.action() {
403            None => return ChainWalk::Ask(ChainAsk::Action),
404            Some((false, _)) => return fail("action_proof_invalid"),
405            Some((true, issuer)) => {
406                if issuer.as_deref() != Some(agent_did.as_str()) {
407                    return fail("action_not_from_agent");
408                }
409            }
410        }
411    }
412
413    ChainWalk::Done(IdentityChainResult {
414        ok: true,
415        reason: None,
416        agent_did: Some(agent_did),
417        issuer_did: Some(recognized_did),
418        root_did: Some(trusted_root.to_string()),
419        attributes,
420    })
421}
422
423/// The offline host: did:key issuers only, no revocation check.
424struct DidKeyHost;
425
426impl ChainHost for DidKeyHost {
427    fn key(&mut self, did: &str, _vm: &str) -> Option<Option<Vec<u8>>> {
428        Some(resolve_key(did))
429    }
430    fn revoked(&mut self, _which: &'static str) -> Option<bool> {
431        Some(false)
432    }
433    fn action(&mut self) -> Option<(bool, Option<String>)> {
434        None
435    }
436}
437
438/// Verify an agent identity against a pinned Vouch root, fully offline for
439/// did:key issuers (see [`walk_identity_chain`] for a host that resolves
440/// other DIDs, checks revocation, and verifies the action credential with its
441/// verifier). `action_credential`, when given, must verify under its did:key
442/// issuer inside its window and be issued by the agent.
443#[allow(clippy::too_many_arguments)]
444pub fn verify_identity_chain(
445    identity_credential: &Value,
446    recognized_issuer_credential: &Value,
447    trusted_root: &str,
448    root_credential: Option<&Value>,
449    action_credential: Option<&Value>,
450    required_action: &str,
451    now_iso: &str,
452    clock_skew_seconds: i64,
453) -> IdentityChainResult {
454    crate::nesting::deep_guard!(IdentityChainResult::fail(crate::nesting::TOO_DEEP); identity_credential, recognized_issuer_credential, root_credential, action_credential);
455    let walked = walk_identity_chain(
456        identity_credential,
457        recognized_issuer_credential,
458        trusted_root,
459        root_credential,
460        false,
461        &Value::String(required_action.to_string()),
462        now_iso,
463        clock_skew_seconds,
464        &mut DidKeyHost,
465    );
466    let result = match walked {
467        ChainWalk::Done(r) => r,
468        // The offline host answers every question.
469        ChainWalk::Ask(_) => return IdentityChainResult::fail("unresolved_key"),
470    };
471    let Some(action_cred) = action_credential.filter(|_| result.ok) else {
472        return result;
473    };
474    let action_issuer = match issuer_of(action_cred) {
475        Some(i) => i,
476        None => return IdentityChainResult::fail("action_proof_invalid"),
477    };
478    match resolve_key(&action_issuer) {
479        Some(pk) => match data_integrity::verify_proof(action_cred, &pk) {
480            Ok(true) => {}
481            _ => return IdentityChainResult::fail("action_proof_invalid"),
482        },
483        None => return IdentityChainResult::fail("action_proof_invalid"),
484    }
485    if !within_window(action_cred, now_iso, clock_skew_seconds) {
486        return IdentityChainResult::fail("action_proof_invalid");
487    }
488    if Some(action_issuer.as_str()) != result.agent_did.as_deref() {
489        return IdentityChainResult::fail("action_not_from_agent");
490    }
491    result
492}
493
494// ---------------------------------------------------------------------------
495// Module-private helpers
496// ---------------------------------------------------------------------------
497
498/// Build the unsigned VC envelope shared by all three credential types.
499#[allow(clippy::too_many_arguments)]
500fn envelope(
501    credential_id: &str,
502    types: &[&str],
503    issuer: &str,
504    subject: Value,
505    valid_from: &str,
506    valid_seconds: i64,
507    credential_status: Option<Value>,
508) -> Result<Value> {
509    let from = iso_to_epoch_seconds(valid_from)?;
510    // The last instant a protocol time can name.
511    const LAST_SECOND: i64 = 253_402_300_799; // 9999-12-31T23:59:59Z
512    let until = from
513        .checked_add(valid_seconds)
514        .filter(|u| *u <= LAST_SECOND)
515        .ok_or_else(|| {
516            CoreError::Json("valid_seconds puts validUntil past 9999-12-31T23:59:59Z".into())
517        })?;
518    let valid_until = epoch_to_iso(until);
519    let types_val: Vec<Value> = types.iter().map(|t| json!(t)).collect();
520
521    let mut vc = Map::new();
522    vc.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
523    vc.insert("id".into(), json!(credential_id));
524    vc.insert("type".into(), Value::Array(types_val));
525    vc.insert("issuer".into(), json!(issuer));
526    vc.insert("validFrom".into(), json!(valid_from));
527    vc.insert("validUntil".into(), json!(valid_until));
528    vc.insert("credentialSubject".into(), subject);
529    if let Some(status) = credential_status {
530        vc.insert("credentialStatus".into(), status);
531    }
532    Ok(Value::Object(vc))
533}
534
535/// Attach an eddsa-jcs-2022 Data Integrity proof to `credential`.
536fn sign(credential: &Value, seed: &[u8], issuer_did: &str, created: &str) -> Result<Value> {
537    let opts = BuildProofOptions::new(verification_method_of(issuer_did), created);
538    data_integrity::sign(credential, seed, &opts)
539}
540
541/// did:key DID for a raw 32-byte Ed25519 seed.
542fn did_of_seed(seed: &[u8]) -> Result<String> {
543    let kp = Ed25519KeyPair::from_seed_slice(seed)?;
544    ed25519_to_did_key(&kp.public_key())
545}
546
547/// Verify a trust-layer credential (root, recognized-issuer, or identity).
548///
549/// Checks the type (exactly one trust type), the issuer, the proof purpose,
550/// that the verification method belongs to the issuer, the issuer's key
551/// (from the host), the proof, and the validity window. Returns the Python
552/// reason code on failure.
553fn verify_trust_credential(
554    credential: &Value,
555    expected_type: &str,
556    slot: &'static str,
557    now_iso: &str,
558    clock_skew_seconds: i64,
559    host: &mut dyn ChainHost,
560) -> core::result::Result<(), Stop> {
561    let reason = |r: &'static str| Err(Stop::Reason(r));
562    let Some(obj) = credential.as_object() else {
563        return reason("not_a_credential");
564    };
565    let types = match obj.get("type").and_then(|v| v.as_array()) {
566        Some(t) if t.iter().any(|t| t.as_str() == Some(expected_type)) => t,
567        _ => return reason("wrong_type"),
568    };
569    // Exactly one trust-layer type, so the credential cannot double as another
570    // link in the chain.
571    let trust_count = TRUST_TYPES
572        .iter()
573        .filter(|tt| types.iter().any(|t| t.as_str() == Some(**tt)))
574        .count();
575    // A list or object inside `type` cannot be compared with the trust types
576    // (the reference stops there): never one clear type.
577    let nested = types.iter().any(|t| t.is_array() || t.is_object());
578    if trust_count != 1 || nested {
579        return reason("ambiguous_type");
580    }
581    let issuer = match issuer_of(credential) {
582        Some(i) if !i.is_empty() => i,
583        _ => return reason("no_issuer"),
584    };
585    let Some(proof) = obj.get("proof").and_then(|p| p.as_object()) else {
586        return reason("no_proof");
587    };
588    if proof.get("proofPurpose").and_then(|v| v.as_str()) != Some("assertionMethod") {
589        return reason("bad_proof_purpose");
590    }
591    let vm = match proof.get("verificationMethod").and_then(|v| v.as_str()) {
592        Some(vm) if crate::verification_method::proof_method_names(proof, &issuer) => vm,
593        _ => return reason("vm_mismatch"),
594    };
595    let public_key = match host.key(&issuer, vm) {
596        None => {
597            return Err(Stop::Ask(ChainAsk::Key {
598                did: issuer,
599                vm: vm.to_string(),
600            }))
601        }
602        Some(None) => return reason("unresolved_key"),
603        Some(Some(k)) => k,
604    };
605    // A credential with no JSON form has no signing input: its proof is
606    // malformed, as the reference finds when it cannot canonicalize it.
607    if host.unreadable(slot) {
608        return reason("proof_malformed");
609    }
610    match crate::proof_json::verify_eddsa(credential, &public_key) {
611        Ok(true) => {}
612        Ok(false) => return reason("proof_invalid"),
613        Err(_) => return reason("proof_malformed"),
614    }
615
616    // Temporal window.
617    let time = |name: &str| {
618        obj.get(name)
619            .and_then(|v| v.as_str())
620            .and_then(|t| parse_protocol_time_ns(t).ok())
621    };
622    let (Some(valid_from), Some(valid_until)) = (time("validFrom"), time("validUntil")) else {
623        return reason("no_validity_window");
624    };
625    let Ok(now) = parse_protocol_time_ns(now_iso) else {
626        return reason("no_validity_window");
627    };
628    let skew = seconds_to_ns(clock_skew_seconds);
629    if now - valid_until > skew {
630        return reason("expired");
631    }
632    if valid_from - now > skew {
633        return reason("not_yet_valid");
634    }
635    Ok(())
636}
637
638/// Whether `now_iso` falls inside the credential's validity window (used for the
639/// optional action credential check).
640fn within_window(credential: &Value, now_iso: &str, clock_skew_seconds: i64) -> bool {
641    let obj = match credential.as_object() {
642        Some(o) => o,
643        None => return false,
644    };
645    let vf = obj.get("validFrom").and_then(|v| v.as_str());
646    let vu = obj.get("validUntil").and_then(|v| v.as_str());
647    let (vf, vu) = match (vf, vu) {
648        (Some(a), Some(b)) => (a, b),
649        _ => return false,
650    };
651    let now = match parse_protocol_time_ns(now_iso) {
652        Ok(n) => n,
653        Err(_) => return false,
654    };
655    let from = match parse_protocol_time_ns(vf) {
656        Ok(t) => t,
657        Err(_) => return false,
658    };
659    let until = match parse_protocol_time_ns(vu) {
660        Ok(t) => t,
661        Err(_) => return false,
662    };
663    let skew = seconds_to_ns(clock_skew_seconds);
664    from <= until && now >= from - skew && now <= until + skew
665}
666
667/// Resolve an issuer's Ed25519 public key. Offline for did:key issuers, which is
668/// all the vector and the current core support.
669fn resolve_key(did: &str) -> Option<Vec<u8>> {
670    if did.starts_with("did:key:") {
671        did_key_to_ed25519(did).ok()
672    } else {
673        None
674    }
675}
676
677/// Return the issuer DID, tolerating the list form used by multi-issuer VCs.
678fn issuer_of(credential: &Value) -> Option<String> {
679    match credential.get("issuer") {
680        Some(Value::String(s)) => Some(s.clone()),
681        Some(Value::Array(a)) => a.first().and_then(|v| v.as_str()).map(|s| s.to_string()),
682        _ => None,
683    }
684}
685
686/// Format Unix epoch seconds as "YYYY-MM-DDTHH:MM:SSZ" (inverse of
687/// [`iso_to_epoch_seconds`] for whole-second UTC instants).
688fn epoch_to_iso(epoch: i64) -> String {
689    let days = epoch.div_euclid(86400);
690    let secs = epoch.rem_euclid(86400);
691    let (y, m, d) = civil_from_days(days);
692    let hh = secs / 3600;
693    let mm = (secs % 3600) / 60;
694    let ss = secs % 60;
695    format!("{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}Z")
696}
697
698/// Civil date (year, month, day) from days since the Unix epoch. Howard
699/// Hinnant's algorithm; the inverse of `time::days_from_civil`.
700fn civil_from_days(z: i64) -> (i64, i64, i64) {
701    let z = z + 719468;
702    let era = (if z >= 0 { z } else { z - 146096 }) / 146097;
703    let doe = z - era * 146097;
704    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
705    let y = yoe + era * 400;
706    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
707    let mp = (5 * doy + 2) / 153;
708    let d = doy - (153 * mp + 2) / 5 + 1;
709    let m = if mp < 10 { mp + 3 } else { mp - 9 };
710    (if m <= 2 { y + 1 } else { y }, m, d)
711}
712
713// ---------------------------------------------------------------------------
714// JSON entry (for the language SDKs)
715// ---------------------------------------------------------------------------
716
717/// The answers a host has given so far, read from a JSON request.
718struct JsonHost<'a> {
719    unreadable: &'a [Value],
720    keys: &'a [Value],
721    check_revoked: bool,
722    revoked: Option<&'a Map<String, Value>>,
723    action: Option<&'a Value>,
724}
725
726impl ChainHost for JsonHost<'_> {
727    fn key(&mut self, did: &str, vm: &str) -> Option<Option<Vec<u8>>> {
728        use base64::{engine::general_purpose::STANDARD, Engine};
729        let entry = self.keys.iter().find(|k| {
730            k.get("did").and_then(Value::as_str) == Some(did)
731                && k.get("vm").and_then(Value::as_str) == Some(vm)
732        })?;
733        Some(
734            entry
735                .get("publicKey")
736                .and_then(Value::as_str)
737                .and_then(|k| STANDARD.decode(k).ok()),
738        )
739    }
740    fn revoked(&mut self, which: &'static str) -> Option<bool> {
741        if !self.check_revoked {
742            return Some(false);
743        }
744        self.revoked?.get(which).and_then(Value::as_bool)
745    }
746    fn unreadable(&mut self, slot: &'static str) -> bool {
747        self.unreadable.iter().any(|v| v.as_str() == Some(slot))
748    }
749    fn action(&mut self) -> Option<(bool, Option<String>)> {
750        let a = self.action.filter(|a| a.is_object())?;
751        Some((
752            a.get("valid").and_then(Value::as_bool) == Some(true),
753            a.get("issuer").and_then(Value::as_str).map(String::from),
754        ))
755    }
756}
757
758fn ask_json(ask: &ChainAsk) -> Value {
759    match ask {
760        ChainAsk::Key { did, vm } => json!({"kind": "key", "did": did, "vm": vm}),
761        ChainAsk::Revoked(which) => json!({"kind": "revoked", "which": which}),
762        ChainAsk::Action => json!({"kind": "action"}),
763    }
764}
765
766fn chain_json(r: &IdentityChainResult) -> Value {
767    json!({
768        "ok": r.ok, "reason": r.reason, "agentDid": r.agent_did,
769        "issuerDid": r.issuer_did, "rootDid": r.root_did, "attributes": r.attributes,
770    })
771}
772
773/// The pinned root as the reference reads it: a root that is not given (or
774/// false, zero, empty) pins nothing; a value that is not text pins a root no
775/// issuer can be.
776fn trusted_root_of(request: &Value) -> String {
777    match request.get("trustedRoot") {
778        Some(Value::String(s)) => s.clone(),
779        None | Some(Value::Null) | Some(Value::Bool(false)) => String::new(),
780        Some(Value::Number(n)) if n.as_f64() == Some(0.0) => String::new(),
781        Some(Value::Array(a)) if a.is_empty() => String::new(),
782        Some(Value::Object(o)) if o.is_empty() => String::new(),
783        // NUL never appears in a DID.
784        Some(_) => "\u{0}not a DID".to_string(),
785    }
786}
787
788/// A true-or-false member: absent or null is false; anything else that is
789/// not a boolean is a malformed request.
790fn optional_bool(request: &Value, name: &str) -> Result<bool> {
791    match request.get(name) {
792        None | Some(Value::Null) => Ok(false),
793        Some(Value::Bool(b)) => Ok(*b),
794        Some(_) => Err(CoreError::Json(format!("{name} must be true or false"))),
795    }
796}
797
798fn optional_array<'a>(request: &'a Value, name: &str) -> Result<Option<&'a Vec<Value>>> {
799    match request.get(name) {
800        None | Some(Value::Null) => Ok(None),
801        Some(Value::Array(a)) => Ok(Some(a)),
802        Some(_) => Err(CoreError::Json(format!("{name} must be a list"))),
803    }
804}
805
806fn required_text<'a>(request: &'a Value, name: &str) -> Result<&'a str> {
807    request
808        .get(name)
809        .and_then(Value::as_str)
810        .ok_or_else(|| CoreError::Json(format!("{name} must be text")))
811}
812
813fn optional_object<'a>(request: &'a Value, name: &str) -> Option<&'a Value> {
814    request.get(name).filter(|v| !v.is_null())
815}
816
817/// The valid_seconds rule every builder applies, with the reference's text.
818fn valid_seconds_of(request: &Value, default: i64) -> Result<i64> {
819    let refused = || {
820        CoreError::Json("valid_seconds must be a whole number of seconds greater than zero".into())
821    };
822    match request.get("validSeconds") {
823        None => Ok(default),
824        Some(v) => v
825            .as_i64()
826            .filter(|n| *n > 0 && !v.is_f64())
827            .ok_or_else(refused),
828    }
829}
830
831fn walk_json(
832    request: &Value,
833    identity: &Value,
834    recognized: &Value,
835    required_action: &Value,
836    has_action: bool,
837) -> Result<core::result::Result<IdentityChainResult, Value>> {
838    let skew = match request.get("clockSkewSeconds") {
839        None | Some(Value::Null) => 30,
840        Some(v) => crate::time_json::check_skew(v)?,
841    };
842    let empty = Vec::new();
843    let unreadable = optional_array(request, "unreadable")?.unwrap_or(&empty);
844    // A root credential the host could not hand over is still a root
845    // credential given: it is checked (and is not a credential when its
846    // copy is not an object), never skipped as absent.
847    let root = if unreadable.iter().any(|v| v.as_str() == Some("root")) {
848        Some(request.get("root").unwrap_or(&Value::Null))
849    } else {
850        optional_object(request, "root")
851    };
852    let mut host = JsonHost {
853        unreadable,
854        keys: request
855            .get("keys")
856            .and_then(Value::as_array)
857            .unwrap_or(&empty),
858        check_revoked: optional_bool(request, "checkRevoked")?,
859        revoked: request.get("revoked").and_then(Value::as_object),
860        action: optional_object(request, "action"),
861    };
862    let walked = walk_identity_chain(
863        identity,
864        recognized,
865        &trusted_root_of(request),
866        root,
867        has_action,
868        required_action,
869        required_text(request, "now")?,
870        skew,
871        &mut host,
872    );
873    Ok(match walked {
874        ChainWalk::Done(r) => Ok(r),
875        ChainWalk::Ask(ask) => Err(json!({ "ask": ask_json(&ask) })),
876    })
877}
878
879/// The root of trust rules, `{"op": ...}` in:
880///
881/// * `verifyChain` `{identity, recognized, trustedRoot, root?, hasAction?,
882///   requiredAction? (issueAgentIdentity), now, clockSkewSeconds? (30),
883///   keys?: [{did, vm, publicKey (standard base64) or null}],
884///   checkRevoked?, revoked?: {recognized?, identity?}, action?: {valid,
885///   issuer}}` -> `{"ask": {kind: "key" (did, vm) | "revoked" (which) |
886///   "action"}}` or `{"result": {ok, reason, agentDid, issuerDid, rootDid,
887///   attributes}}`. `requiredAction`, when given, is compared as given (a
888///   value that is not one of the issuer's actions matches none);
889///   `checkRevoked` and `hasAction` must be true or false. `unreadable`
890///   names the slots ("recognized", "identity", "root", and for a robot
891///   chain "hardwareCredential") whose credential had no JSON form: the host
892///   sends them with those values as null and their proof is malformed. An
893///   unreadable "requiredAction" is one no issuer holds. The host answers the ask (adds the key, null when it
894///   cannot resolve one; the revocation answer; the action verdict from its
895///   verifier) and calls again with the same request plus the answer. A
896///   replay check of the action stays with the host, after an ok result.
897/// * `verifyRobotChain` `{authorityIdentity, recognized, hardwareCredential,
898///   robotPublicKey (standard base64 raw Ed25519), trustedRoot, root?, now,
899///   clockSkewSeconds?, keys?, checkRevoked?, revoked?}` -> an ask, or
900///   `{"result": {ok, reason, robotDid, issuerDid, rootDid, attributes,
901///   hardwareRooted}}`: the chain for `issueRobotIdentity`, then the robot's
902///   own credential, its subject, its key and the hardware root.
903/// * `build` `{kind: "root" | "recognizedIssuer" | "agentIdentity" |
904///   "robotIdentity", issuerDid, credentialId, validFrom, validSeconds?,
905///   credentialStatus?, ...}` -> `{credential}`: the unsigned credential, for
906///   the host to sign with the issuer's key (proof rules `prepare` and
907///   `attach`). `root`: `name`, `scope?`; `recognizedIssuer`:
908///   `subjectDid`, `recognizedActions?`; `agentIdentity`: `subjectDid`,
909///   `attributes`; `robotIdentity`: `robotDid`, `hardwareKeyMultibase`,
910///   `attributes`, `hardwareRootKeyMultibase?`.
911pub fn rules_json(request: &Value) -> Result<Value> {
912    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
913    let op = required_text(request, "op")?;
914    let field = |name: &str| request.get(name).unwrap_or(&Value::Null);
915    match op {
916        "verifyChain" => {
917            // Absent: the default action. Present: compared as given, so a
918            // value that is not an action the issuer holds matches none.
919            let default_action = Value::String(ACTION_ISSUE_AGENT_IDENTITY.into());
920            let required = request.get("requiredAction").unwrap_or(&default_action);
921            let has_action = optional_bool(request, "hasAction")?;
922            Ok(
923                match walk_json(
924                    request,
925                    field("identity"),
926                    field("recognized"),
927                    required,
928                    has_action,
929                )? {
930                    Ok(r) => json!({ "result": chain_json(&r) }),
931                    Err(ask) => ask,
932                },
933            )
934        }
935        "verifyRobotChain" => {
936            use base64::{engine::general_purpose::STANDARD, Engine};
937            let root = request
938                .get("trustedRoot")
939                .and_then(Value::as_str)
940                .unwrap_or("");
941            let robot_action = Value::String(ACTION_ISSUE_ROBOT_IDENTITY.into());
942            let chain = match walk_json(
943                request,
944                field("authorityIdentity"),
945                field("recognized"),
946                &robot_action,
947                false,
948            )? {
949                Ok(r) => r,
950                Err(ask) => return Ok(ask),
951            };
952            let key = request
953                .get("robotPublicKey")
954                .and_then(Value::as_str)
955                .and_then(|k| STANDARD.decode(k).ok())
956                .unwrap_or_default();
957            let r = crate::robotics::robot_identity_chain_tail(
958                chain,
959                // A robot credential with no JSON form cannot verify.
960                if optional_array(request, "unreadable")?
961                    .is_some_and(|u| u.iter().any(|v| v.as_str() == Some("hardwareCredential")))
962                {
963                    &Value::Null
964                } else {
965                    field("hardwareCredential")
966                },
967                root,
968                &key,
969                required_text(request, "now")?,
970            );
971            Ok(json!({"result": {
972                "ok": r.ok, "reason": r.reason, "robotDid": r.robot_did,
973                "issuerDid": r.issuer_did, "rootDid": r.root_did,
974                "attributes": r.attributes, "hardwareRooted": r.hardware_rooted,
975            }}))
976        }
977        "build" => {
978            let issuer = required_text(request, "issuerDid")?;
979            let status = optional_object(request, "credentialStatus").cloned();
980            // The reference checks the lifetime first, except for a robot
981            // identity, whose own checks come before it.
982            if request.get("kind").and_then(Value::as_str) != Some("robotIdentity") {
983                valid_seconds_of(request, 1)?;
984            }
985            let (types, subject, default_seconds, status) = match required_text(request, "kind")? {
986                "root" => {
987                    let scope = match list_or_default(request, "scope", "scope")? {
988                        Some(a) => Value::Array(a.clone()),
989                        None => json!(["ai-agent", "robot"]),
990                    };
991                    let mut subject = Map::new();
992                    subject.insert("id".into(), json!(issuer));
993                    subject.insert("vouchVersion".into(), json!(PROTOCOL_VERSION));
994                    subject.insert(
995                        "rootOfTrust".into(),
996                        json!({"name": field("name"), "scope": scope}),
997                    );
998                    (ROOT_OF_TRUST_TYPE, subject, ROOT_VALID_SECONDS, None)
999                }
1000                "recognizedIssuer" => {
1001                    let subject_did = request
1002                        .get("subjectDid")
1003                        .and_then(Value::as_str)
1004                        .filter(|d| !d.is_empty())
1005                        .ok_or_else(|| CoreError::Json("issuer_did is required".into()))?;
1006                    let actions = match list_or_default(
1007                        request,
1008                        "recognizedActions",
1009                        "recognized_actions",
1010                    )? {
1011                        Some(a) => Value::Array(a.clone()),
1012                        None => json!([ACTION_ISSUE_AGENT_IDENTITY]),
1013                    };
1014                    let mut subject = Map::new();
1015                    subject.insert("id".into(), json!(subject_did));
1016                    subject.insert("recognizedActions".into(), actions);
1017                    subject.insert("recognizedIn".into(), json!(issuer));
1018                    (
1019                        RECOGNIZED_ISSUER_TYPE,
1020                        subject,
1021                        ISSUER_VALID_SECONDS,
1022                        status,
1023                    )
1024                }
1025                kind @ ("agentIdentity" | "robotIdentity") => {
1026                    let robot = kind == "robotIdentity";
1027                    let name = if robot { "robotDid" } else { "subjectDid" };
1028                    let subject_did = request
1029                        .get(name)
1030                        .and_then(Value::as_str)
1031                        .filter(|d| !d.is_empty())
1032                        .ok_or_else(|| {
1033                            CoreError::Json(if robot {
1034                                "robot_did is required".into()
1035                            } else {
1036                                "subject_did is required".into()
1037                            })
1038                        })?;
1039                    let attributes = if robot {
1040                        let hw = request
1041                            .get("hardwareKeyMultibase")
1042                            .and_then(Value::as_str)
1043                            .filter(|k| !k.is_empty())
1044                            .ok_or_else(|| {
1045                                CoreError::Json("hardware_key_multibase is required".into())
1046                            })?;
1047                        let mut attributes = attribute_map(field("attributes"))?;
1048                        attributes.insert("kind".into(), json!("robot"));
1049                        attributes.insert("hardwareKey".into(), json!(hw));
1050                        match optional_object(request, "hardwareRootKeyMultibase") {
1051                            None => {}
1052                            Some(Value::String(k)) if !k.is_empty() => {
1053                                attributes.insert("hardwareRootKey".into(), json!(k));
1054                            }
1055                            Some(_) => {
1056                                return Err(CoreError::Json(
1057                                    "hardware_root_key_multibase must be a multikey string".into(),
1058                                ))
1059                            }
1060                        }
1061                        attributes
1062                    } else {
1063                        attribute_map(field("attributes"))?
1064                    };
1065                    let mut subject = Map::new();
1066                    subject.insert("id".into(), json!(subject_did));
1067                    subject.insert("identity".into(), Value::Object(attributes));
1068                    (AGENT_IDENTITY_TYPE, subject, IDENTITY_VALID_SECONDS, status)
1069                }
1070                other => {
1071                    return Err(CoreError::Json(format!(
1072                        "no root of trust credential of kind {other:?}"
1073                    )))
1074                }
1075            };
1076            let valid_seconds = valid_seconds_of(request, default_seconds)?;
1077            let credential = envelope(
1078                required_text(request, "credentialId")?,
1079                &[VC_TYPE, types],
1080                issuer,
1081                Value::Object(subject),
1082                required_text(request, "validFrom")?,
1083                valid_seconds,
1084                status,
1085            )?;
1086            Ok(json!({ "credential": credential }))
1087        }
1088        other => Err(CoreError::Json(format!(
1089            "unknown root of trust op {other:?}"
1090        ))),
1091    }
1092}
1093
1094/// [`rules_json`] on request text, read with the nesting the reference's
1095/// canonical form allows (see [`crate::jcs::parse_deep`]), so a credential
1096/// nested 130 levels is judged by its proof, not refused unread.
1097pub fn rules_json_text(text: &str) -> Result<Value> {
1098    rules_json(&crate::jcs::parse_deep(text)?)
1099}
1100
1101/// A list member that falls back to its default when absent, null or empty
1102/// (as the reference's `x or default`); any other type is refused.
1103fn list_or_default<'a>(
1104    request: &'a Value,
1105    name: &str,
1106    text: &str,
1107) -> Result<Option<&'a Vec<Value>>> {
1108    match request.get(name) {
1109        None | Some(Value::Null) => Ok(None),
1110        Some(Value::Array(a)) if a.is_empty() => Ok(None),
1111        Some(Value::Array(a)) => Ok(Some(a)),
1112        Some(_) => Err(CoreError::Json(format!("{text} must be a list"))),
1113    }
1114}
1115
1116fn attribute_map(v: &Value) -> Result<Map<String, Value>> {
1117    match v.as_object() {
1118        Some(o) if !o.is_empty() => Ok(o.clone()),
1119        _ => Err(CoreError::Json(
1120            "attributes must be a non-empty dict".into(),
1121        )),
1122    }
1123}
1124
1125#[cfg(test)]
1126mod tests {
1127    use super::*;
1128    use std::path::PathBuf;
1129
1130    const ROOT_SEED: [u8; 32] = [0x01; 32];
1131    const ISSUER_SEED: [u8; 32] = [0x02; 32];
1132    const AGENT_SEED: [u8; 32] = [0x03; 32];
1133
1134    const VALID_FROM: &str = "2026-01-01T00:00:00Z";
1135    const CREATED: &str = "2026-01-01T00:00:00Z";
1136    const VALID_SECONDS: i64 = 100 * 365 * 24 * 3600;
1137    const NOW: &str = "2026-07-01T00:00:00Z";
1138
1139    const ROOT_ID: &str = "urn:uuid:11111111-1111-1111-1111-111111111111";
1140    const RECOGNITION_ID: &str = "urn:uuid:22222222-2222-2222-2222-222222222222";
1141    const IDENTITY_ID: &str = "urn:uuid:33333333-3333-3333-3333-333333333333";
1142
1143    fn load_vector() -> Value {
1144        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1145            .join("../../test-vectors/root-of-trust/vector.json");
1146        let text = std::fs::read_to_string(&path)
1147            .unwrap_or_else(|e| panic!("read vector {}: {e}", path.display()));
1148        serde_json::from_str(&text).expect("vector is valid JSON")
1149    }
1150
1151    fn agent_attributes() -> Value {
1152        json!({ "owner": "Acme", "model": "gpt-x", "capabilityClass": "shopping" })
1153    }
1154
1155    fn build_all() -> (Value, Value, Value) {
1156        let issuer_did = did_of_seed(&ISSUER_SEED).unwrap();
1157        let agent_did = did_of_seed(&AGENT_SEED).unwrap();
1158
1159        let root = build_root_of_trust(
1160            &ROOT_SEED,
1161            "Vouch Machine Identity Root",
1162            None,
1163            VALID_SECONDS,
1164            VALID_FROM,
1165            CREATED,
1166            ROOT_ID,
1167        )
1168        .unwrap();
1169
1170        let recognition = build_recognized_issuer(
1171            &ROOT_SEED,
1172            &issuer_did,
1173            Some(&[ACTION_ISSUE_AGENT_IDENTITY]),
1174            VALID_SECONDS,
1175            VALID_FROM,
1176            CREATED,
1177            None,
1178            RECOGNITION_ID,
1179        )
1180        .unwrap();
1181
1182        let identity = build_agent_identity(
1183            &ISSUER_SEED,
1184            &agent_did,
1185            &agent_attributes(),
1186            VALID_SECONDS,
1187            VALID_FROM,
1188            CREATED,
1189            None,
1190            IDENTITY_ID,
1191        )
1192        .unwrap();
1193
1194        (root, recognition, identity)
1195    }
1196
1197    // (a) Verify Python-signed credentials from the committed interop vector.
1198    #[test]
1199    fn verifies_python_signed_vector() {
1200        let vector = load_vector();
1201        let trusted_root = vector["trustedRoot"].as_str().unwrap();
1202        let result = verify_identity_chain(
1203            &vector["agentIdentity"],
1204            &vector["recognizedIssuer"],
1205            trusted_root,
1206            Some(&vector["rootOfTrust"]),
1207            None,
1208            ACTION_ISSUE_AGENT_IDENTITY,
1209            NOW,
1210            30,
1211        );
1212        assert!(result.ok, "chain must verify: {:?}", result.reason);
1213        assert_eq!(
1214            result.agent_did.as_deref(),
1215            vector["expected"]["agentDid"].as_str()
1216        );
1217        assert_eq!(
1218            result.issuer_did.as_deref(),
1219            vector["expected"]["issuerDid"].as_str()
1220        );
1221        assert_eq!(result.root_did.as_deref(), Some(trusted_root));
1222    }
1223
1224    // (b) Reproduce every proofValue byte-for-byte from the same fixed inputs.
1225    #[test]
1226    fn reproduces_vector_byte_for_byte() {
1227        let vector = load_vector();
1228        let (root, recognition, identity) = build_all();
1229
1230        assert_eq!(
1231            root["proof"]["proofValue"], vector["rootOfTrust"]["proof"]["proofValue"],
1232            "root of trust proofValue diverges from Python"
1233        );
1234        assert_eq!(
1235            recognition["proof"]["proofValue"], vector["recognizedIssuer"]["proof"]["proofValue"],
1236            "recognized issuer proofValue diverges from Python"
1237        );
1238        assert_eq!(
1239            identity["proof"]["proofValue"], vector["agentIdentity"]["proof"]["proofValue"],
1240            "agent identity proofValue diverges from Python"
1241        );
1242
1243        // The derived DIDs and validity window must also match the vector.
1244        assert_eq!(root["issuer"], vector["trustedRoot"]);
1245        assert_eq!(root["validUntil"], vector["rootOfTrust"]["validUntil"]);
1246        assert_eq!(identity["issuer"], vector["agentIdentity"]["issuer"]);
1247    }
1248
1249    // Round-trip: credentials we build verify through our own chain walker.
1250    #[test]
1251    fn self_built_chain_verifies() {
1252        let (root, recognition, identity) = build_all();
1253        let root_did = did_of_seed(&ROOT_SEED).unwrap();
1254        let agent_did = did_of_seed(&AGENT_SEED).unwrap();
1255        let issuer_did = did_of_seed(&ISSUER_SEED).unwrap();
1256
1257        let result = verify_identity_chain(
1258            &identity,
1259            &recognition,
1260            &root_did,
1261            Some(&root),
1262            None,
1263            ACTION_ISSUE_AGENT_IDENTITY,
1264            NOW,
1265            30,
1266        );
1267        assert!(
1268            result.ok,
1269            "self-built chain must verify: {:?}",
1270            result.reason
1271        );
1272        assert_eq!(result.agent_did.as_deref(), Some(agent_did.as_str()));
1273        assert_eq!(result.issuer_did.as_deref(), Some(issuer_did.as_str()));
1274        assert_eq!(result.attributes, Some(agent_attributes()));
1275    }
1276
1277    #[test]
1278    fn skew_outside_zero_to_120_is_refused() {
1279        let (root, recognition, identity) = build_all();
1280        let root_did = did_of_seed(&ROOT_SEED).unwrap();
1281        for skew in [-1, 121, 300, 1_000_000_000] {
1282            let result = verify_identity_chain(
1283                &identity,
1284                &recognition,
1285                &root_did,
1286                Some(&root),
1287                None,
1288                ACTION_ISSUE_AGENT_IDENTITY,
1289                NOW,
1290                skew,
1291            );
1292            assert!(!result.ok, "skew {skew} must be refused");
1293            assert_eq!(result.reason.as_deref(), Some("invalid_clock_skew"));
1294        }
1295    }
1296
1297    // (c) Adversarial: a tampered identity proof must break the chain.
1298    #[test]
1299    fn tampered_identity_proof_is_rejected() {
1300        let vector = load_vector();
1301        let mut identity = vector["agentIdentity"].clone();
1302        // Edit a signed attribute: the proof no longer matches. (A changed
1303        // proofValue whose S is no longer below the group order is a
1304        // malformed proof instead, as in the reference.)
1305        identity["credentialSubject"]["identity"]["capabilityClass"] = json!("admin");
1306        let result = verify_identity_chain(
1307            &identity,
1308            &vector["recognizedIssuer"],
1309            vector["trustedRoot"].as_str().unwrap(),
1310            Some(&vector["rootOfTrust"]),
1311            None,
1312            ACTION_ISSUE_AGENT_IDENTITY,
1313            NOW,
1314            30,
1315        );
1316        assert!(!result.ok, "tampered proof must be rejected");
1317        assert_eq!(
1318            result.reason.as_deref(),
1319            Some("identity_proof_invalid"),
1320            "unexpected reason for tampered proof"
1321        );
1322    }
1323
1324    // A recognition that does not grant the required action is rejected.
1325    #[test]
1326    fn wrong_action_is_rejected() {
1327        let (root, _recognition, identity) = build_all();
1328        let root_did = did_of_seed(&ROOT_SEED).unwrap();
1329        let issuer_did = did_of_seed(&ISSUER_SEED).unwrap();
1330        let recognition = build_recognized_issuer(
1331            &ROOT_SEED,
1332            &issuer_did,
1333            Some(&[ACTION_ISSUE_ROBOT_IDENTITY]),
1334            VALID_SECONDS,
1335            VALID_FROM,
1336            CREATED,
1337            None,
1338            RECOGNITION_ID,
1339        )
1340        .unwrap();
1341        let result = verify_identity_chain(
1342            &identity,
1343            &recognition,
1344            &root_did,
1345            Some(&root),
1346            None,
1347            ACTION_ISSUE_AGENT_IDENTITY,
1348            NOW,
1349            30,
1350        );
1351        assert!(!result.ok);
1352        assert_eq!(
1353            result.reason.as_deref(),
1354            Some("issuer_not_recognized_for_action")
1355        );
1356    }
1357
1358    // A credential carrying two trust types is ambiguous and rejected.
1359    #[test]
1360    fn ambiguous_type_is_rejected() {
1361        let (_root, recognition, mut identity) = build_all();
1362        identity["type"] = json!([VC_TYPE, AGENT_IDENTITY_TYPE, RECOGNIZED_ISSUER_TYPE]);
1363        let root_did = did_of_seed(&ROOT_SEED).unwrap();
1364        let result = verify_identity_chain(
1365            &identity,
1366            &recognition,
1367            &root_did,
1368            None,
1369            None,
1370            ACTION_ISSUE_AGENT_IDENTITY,
1371            NOW,
1372            30,
1373        );
1374        assert!(!result.ok);
1375        assert_eq!(result.reason.as_deref(), Some("identity_ambiguous_type"));
1376    }
1377
1378    #[test]
1379    fn epoch_iso_roundtrip() {
1380        assert_eq!(epoch_to_iso(0), "1970-01-01T00:00:00Z");
1381        let from = iso_to_epoch_seconds(VALID_FROM).unwrap();
1382        assert_eq!(epoch_to_iso(from + VALID_SECONDS), "2125-12-08T00:00:00Z");
1383    }
1384
1385    fn walk_request(extra: Value) -> Value {
1386        let (root, recognition, identity) = build_all();
1387        let mut req = json!({
1388            "op": "verifyChain",
1389            "identity": identity,
1390            "recognized": recognition,
1391            "trustedRoot": did_of_seed(&ROOT_SEED).unwrap(),
1392            "root": root,
1393            "now": NOW,
1394        });
1395        for (k, v) in extra.as_object().unwrap() {
1396            req[k] = v.clone();
1397        }
1398        req
1399    }
1400
1401    /// Walk with the offline keys: answer every key ask from the did:key.
1402    fn walk(mut req: Value) -> Value {
1403        use base64::{engine::general_purpose::STANDARD, Engine};
1404        for _ in 0..8 {
1405            let out = rules_json(&req).unwrap();
1406            let Some(ask) = out.get("ask") else {
1407                return out["result"].clone();
1408            };
1409            assert_eq!(ask["kind"], "key", "{out}");
1410            let did = ask["did"].as_str().unwrap();
1411            let key = did_key_to_ed25519(did).unwrap();
1412            let keys = req
1413                .as_object_mut()
1414                .unwrap()
1415                .entry("keys")
1416                .or_insert(json!([]));
1417            keys.as_array_mut()
1418                .unwrap()
1419                .push(json!({"did": did, "vm": ask["vm"], "publicKey": STANDARD.encode(key)}));
1420        }
1421        panic!("the walk did not finish");
1422    }
1423
1424    #[test]
1425    fn a_required_action_is_compared_as_given() {
1426        assert_eq!(walk(walk_request(json!({})))["ok"], json!(true));
1427        for odd in [
1428            json!(null),
1429            json!(5),
1430            json!(["issueAgentIdentity"]),
1431            json!(""),
1432        ] {
1433            let got = walk(walk_request(json!({ "requiredAction": odd })));
1434            assert_eq!(
1435                got["reason"],
1436                json!("issuer_not_recognized_for_action"),
1437                "{odd}"
1438            );
1439        }
1440    }
1441
1442    #[test]
1443    fn flags_that_are_not_true_or_false_are_refused() {
1444        for (name, value) in [("checkRevoked", json!(1)), ("hasAction", json!("true"))] {
1445            let err = rules_json(&walk_request(json!({ name: value }))).unwrap_err();
1446            assert_eq!(
1447                err,
1448                CoreError::Json(format!("{name} must be true or false"))
1449            );
1450        }
1451    }
1452
1453    #[test]
1454    fn an_unreadable_credential_has_a_malformed_proof() {
1455        let got = walk(walk_request(json!({"unreadable": ["identity"]})));
1456        assert_eq!(got["reason"], json!("identity_proof_malformed"));
1457        let got = walk(walk_request(json!({"unreadable": ["recognized"]})));
1458        assert_eq!(got["reason"], json!("recognized_issuer_proof_malformed"));
1459    }
1460
1461    #[test]
1462    fn an_unreadable_required_action_matches_no_action() {
1463        let got = walk(walk_request(json!({
1464            "requiredAction": null, "unreadable": ["requiredAction"]
1465        })));
1466        assert_eq!(got["reason"], json!("issuer_not_recognized_for_action"));
1467        let got = walk(walk_request(json!({
1468            "requiredAction": "issueAgentIdentity", "unreadable": ["requiredAction"]
1469        })));
1470        assert_eq!(got["reason"], json!("issuer_not_recognized_for_action"));
1471    }
1472
1473    #[test]
1474    fn an_unreadable_root_that_is_not_an_object_is_not_a_credential() {
1475        // The host's copy of a root with no JSON form (a NaN, a lone
1476        // surrogate) is null: the root was still given, so it is checked.
1477        let got = walk(walk_request(json!({"root": null, "unreadable": ["root"]})));
1478        assert_eq!(got["reason"], json!("root_not_a_credential"));
1479        let got = walk(walk_request(json!({"root": null})));
1480        assert_eq!(got["ok"], json!(true));
1481    }
1482
1483    #[test]
1484    fn a_trust_type_list_with_a_nested_list_is_ambiguous() {
1485        let (_, mut recognition, identity) = build_all();
1486        recognition["type"]
1487            .as_array_mut()
1488            .unwrap()
1489            .push(json!(["VouchRootOfTrust"]));
1490        let got = walk(walk_request(
1491            json!({"recognized": recognition, "identity": identity}),
1492        ));
1493        assert_eq!(got["reason"], json!("recognized_issuer_ambiguous_type"));
1494    }
1495
1496    #[test]
1497    fn a_trusted_root_that_is_not_text_pins_nothing_an_issuer_can_be() {
1498        let got = walk(walk_request(json!({"trustedRoot": 5})));
1499        assert_eq!(got["reason"], json!("recognized_issuer_not_from_root"));
1500        let got = walk(walk_request(json!({"trustedRoot": ""})));
1501        assert_eq!(got["reason"], json!("no_trusted_root"));
1502    }
1503
1504    #[test]
1505    #[cfg_attr(not(feature = "std"), ignore = "the std build's 512-level allowance")]
1506    fn a_deep_credential_is_read_and_judged_by_its_proof() {
1507        let (_, recognition, mut identity) = build_all();
1508        let deep =
1509            crate::jcs::parse_deep(&format!("{}{}", "[".repeat(130), "]".repeat(130))).unwrap();
1510        identity["x"] = deep;
1511        let mut req = walk_request(json!({"recognized": recognition}));
1512        req["identity"] = identity;
1513        let text = req.to_string();
1514        assert!(
1515            serde_json::from_str::<Value>(&text).is_err(),
1516            "deeper than the default reader"
1517        );
1518        let out = rules_json_text(&text).unwrap();
1519        assert!(out.get("ask").is_some() || out.get("result").is_some());
1520    }
1521
1522    #[test]
1523    #[cfg_attr(feature = "std", ignore = "checks the no_std build")]
1524    fn no_std_text_entry_refuses_past_the_cap_before_parsing() {
1525        let (_, recognition, _) = build_all();
1526        let req = walk_request(json!({"recognized": recognition})).to_string();
1527        for n in [32, 129, 600] {
1528            let deep = format!("{}{}", "[".repeat(n), "]".repeat(n));
1529            let text = format!("{{\"x\":{deep},{}", &req[1..]);
1530            assert_eq!(
1531                rules_json_text(&text).unwrap_err(),
1532                crate::nesting::too_deep(),
1533                "{n} levels"
1534            );
1535        }
1536    }
1537
1538    #[test]
1539    fn build_refuses_wrong_types_and_a_window_past_year_9999() {
1540        let base = json!({"op": "build", "issuerDid": "did:web:a.example", "credentialId": "urn:x",
1541                          "validFrom": "2026-01-01T00:00:00Z"});
1542        let with = |k: &str, v: Value, kind: &str| {
1543            let mut r = base.clone();
1544            r["kind"] = json!(kind);
1545            r["name"] = json!("n");
1546            r["subjectDid"] = json!("did:web:b.example");
1547            r[k] = v;
1548            rules_json(&r)
1549        };
1550        assert_eq!(
1551            with("scope", json!("robot"), "root").unwrap_err(),
1552            CoreError::Json("scope must be a list".into())
1553        );
1554        assert_eq!(
1555            with("recognizedActions", json!({"a": 1}), "recognizedIssuer").unwrap_err(),
1556            CoreError::Json("recognized_actions must be a list".into())
1557        );
1558        assert!(with("validSeconds", json!(null), "root").is_err());
1559        let err = with("validSeconds", json!(i64::MAX), "root").unwrap_err();
1560        assert_eq!(
1561            err,
1562            CoreError::Json("valid_seconds puts validUntil past 9999-12-31T23:59:59Z".into())
1563        );
1564        let mut r = base.clone();
1565        r["kind"] = json!("root");
1566        r["validFrom"] = json!("9999-12-31T23:59:58Z");
1567        r["validSeconds"] = json!(1);
1568        assert_eq!(
1569            rules_json(&r).unwrap()["credential"]["validUntil"],
1570            json!("9999-12-31T23:59:59Z")
1571        );
1572    }
1573}