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 proof verification method is always `{did}#key-1` for a did:key signer.
59fn verification_method_of(did: &str) -> String {
60    format!("{did}#key-1")
61}
62
63/// Outcome of [`verify_identity_chain`].
64///
65/// `ok` is true only if every link verified and anchored to the pinned root.
66/// On failure `reason` carries a structured code matching the Python reference.
67#[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// ---------------------------------------------------------------------------
91// Credential builders
92// ---------------------------------------------------------------------------
93
94/// Self-issue the Vouch Root of Trust credential.
95///
96/// Issuer and subject are both the root's own DID (derived from `root_seed`).
97/// `scope` defaults to `["ai-agent", "robot"]` when None. `valid_from` and
98/// `created` are ISO-8601 instants ("YYYY-MM-DDTHH:MM:SSZ"); the core does not
99/// read a clock.
100#[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/// Issue a recognized-issuer credential from the root.
136///
137/// The root attests that `issuer_did` may perform `recognized_actions`
138/// (default `["issueAgentIdentity"]`). `recognizedIn` chains back to the root
139/// DID so a verifier can trace the recognition to the anchor it pinned.
140#[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/// Issue an authority-issued identity credential for an agent.
178///
179/// Here the issuer (derived from `issuer_seed`) differs from the subject: a
180/// recognized issuer binds `subject_did` to real `attributes` (owner, model,
181/// capability class, and so on). `attributes` MUST be a non-empty JSON object.
182#[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// ---------------------------------------------------------------------------
223// Verification
224// ---------------------------------------------------------------------------
225
226/// What a host is asked for while a chain is walked (see [`walk_identity_chain`]).
227#[derive(Debug, Clone, PartialEq, Eq)]
228pub enum ChainAsk {
229    /// The Ed25519 public key of `did` for the proof's verification method.
230    Key { did: String, vm: String },
231    /// Whether the recognized-issuer ("recognized") or the identity
232    /// ("identity") credential is revoked.
233    Revoked(&'static str),
234    /// The action credential's verdict: does it verify (the host's verifier,
235    /// which runs the core decision), and who issued it.
236    Action,
237}
238
239/// A host's answers. Each method answers None when it has not been asked
240/// before: the walk then stops with that [`ChainAsk`], the host finds the
241/// answer, and the walk runs again from the start with it.
242pub trait ChainHost {
243    /// The issuer's key: Some(Some(key)), Some(None) when it cannot be
244    /// resolved, None when not yet asked.
245    fn key(&mut self, did: &str, vm: &str) -> Option<Option<Vec<u8>>>;
246    /// Whether a credential is revoked; a host with no revocation check
247    /// answers Some(false).
248    fn revoked(&mut self, which: &'static str) -> Option<bool>;
249    /// The action credential's (verifies, issuer).
250    fn action(&mut self) -> Option<(bool, Option<String>)>;
251    /// Whether the credential in a slot ("recognized", "identity", "root")
252    /// has no JSON form the host could hand over (a NaN, an infinity, a lone
253    /// surrogate, a number out of range, nesting too deep): the host sends a
254    /// copy with those values as null, and its proof is malformed. The slot
255    /// "requiredAction" names a required action with no JSON form, which no
256    /// issuer holds.
257    fn unreadable(&mut self, _slot: &'static str) -> bool {
258        false
259    }
260}
261
262/// Where a walk stopped.
263#[derive(Debug, Clone, PartialEq)]
264pub enum ChainWalk {
265    Done(IdentityChainResult),
266    Ask(ChainAsk),
267}
268
269/// Why a trust credential check stopped: a reason code, or a question.
270enum Stop {
271    Reason(&'static str),
272    Ask(ChainAsk),
273}
274
275/// Walk an agent identity to a pinned Vouch root, the reference's checks in
276/// the reference's order:
277///
278/// 1. the recognized-issuer credential is a valid trust credential, issued
279///    by `trusted_root`, with a subject that is recognized for
280///    `required_action`, and not revoked;
281/// 2. the identity credential is a valid trust credential issued by that
282///    recognized issuer, not revoked, with a subject;
283/// 3. when given, the root credential is a valid trust credential issued by
284///    `trusted_root` about itself;
285/// 4. when `has_action`, the action credential verifies and its issuer is the
286///    agent the identity names.
287///
288/// Keys, revocation and the action verdict come from the host, one question
289/// at a time, so it is asked only what the reference would ask, in the
290/// reference's order. A replay check of the action credential stays with the
291/// host (its store), after a result that is ok.
292#[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    // A skew outside 0..120 is a caller error: the chain is refused.
307    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    // 1. The recognition must be signed by the pinned root.
324    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        // Any JSON value the caller names, compared as the reference's `in`
345        // compares it: a value that is not one of the actions matches none.
346        .map(|a| a.iter().any(|x| x == required_action))
347        .unwrap_or(false)
348        // An action the host could not hand over (no JSON form) is one no
349        // issuer holds.
350        && !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    // 2. The identity must be signed by the recognized issuer.
361    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    // 3. Optional: confirm the root credential is genuinely self-issued.
386    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    // 4. Optional: bind the agent's own action to this identity.
400    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
422/// The offline host: did:key issuers only, no revocation check.
423struct 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/// Verify an agent identity against a pinned Vouch root, fully offline for
438/// did:key issuers (see [`walk_identity_chain`] for a host that resolves
439/// other DIDs, checks revocation, and verifies the action credential with its
440/// verifier). `action_credential`, when given, must verify under its did:key
441/// issuer inside its window and be issued by the agent.
442#[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        // The offline host answers every question.
468        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// ---------------------------------------------------------------------------
494// Module-private helpers
495// ---------------------------------------------------------------------------
496
497/// Build the unsigned VC envelope shared by all three credential types.
498#[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    // The last instant a protocol time can name.
510    const LAST_SECOND: i64 = 253_402_300_799; // 9999-12-31T23:59:59Z
511    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
534/// Attach an eddsa-jcs-2022 Data Integrity proof to `credential`.
535fn 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
540/// did:key DID for a raw 32-byte Ed25519 seed.
541fn 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
546/// Verify a trust-layer credential (root, recognized-issuer, or identity).
547///
548/// Checks the type (exactly one trust type), the issuer, the proof purpose,
549/// that the verification method belongs to the issuer, the issuer's key
550/// (from the host), the proof, and the validity window. Returns the Python
551/// reason code on failure.
552fn 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    // Exactly one trust-layer type, so the credential cannot double as another
569    // link in the chain.
570    let trust_count = TRUST_TYPES
571        .iter()
572        .filter(|tt| types.iter().any(|t| t.as_str() == Some(**tt)))
573        .count();
574    // A list or object inside `type` cannot be compared with the trust types
575    // (the reference stops there): never one clear type.
576    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    // A credential with no JSON form has no signing input: its proof is
605    // malformed, as the reference finds when it cannot canonicalize it.
606    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    // Temporal window.
616    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
637/// Whether `now_iso` falls inside the credential's validity window (used for the
638/// optional action credential check).
639fn 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
666/// Resolve an issuer's Ed25519 public key. Offline for did:key issuers, which is
667/// all the vector and the current core support.
668fn 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
676/// Return the issuer DID, tolerating the list form used by multi-issuer VCs.
677fn 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
685/// Format Unix epoch seconds as "YYYY-MM-DDTHH:MM:SSZ" (inverse of
686/// [`iso_to_epoch_seconds`] for whole-second UTC instants).
687fn 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
697/// Civil date (year, month, day) from days since the Unix epoch. Howard
698/// Hinnant's algorithm; the inverse of `time::days_from_civil`.
699fn 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
712// ---------------------------------------------------------------------------
713// JSON entry (for the language SDKs)
714// ---------------------------------------------------------------------------
715
716/// The answers a host has given so far, read from a JSON request.
717struct 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
772/// The pinned root as the reference reads it: a root that is not given (or
773/// false, zero, empty) pins nothing; a value that is not text pins a root no
774/// issuer can be.
775fn 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        // NUL never appears in a DID.
783        Some(_) => "\u{0}not a DID".to_string(),
784    }
785}
786
787/// A true-or-false member: absent or null is false; anything else that is
788/// not a boolean is a malformed request.
789fn 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
816/// The valid_seconds rule every builder applies, with the reference's text.
817fn 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    // A root credential the host could not hand over is still a root
844    // credential given: it is checked (and is not a credential when its
845    // copy is not an object), never skipped as absent.
846    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
878/// The root of trust rules, `{"op": ...}` in:
879///
880/// * `verifyChain` `{identity, recognized, trustedRoot, root?, hasAction?,
881///   requiredAction? (issueAgentIdentity), now, clockSkewSeconds? (30),
882///   keys?: [{did, vm, publicKey (standard base64) or null}],
883///   checkRevoked?, revoked?: {recognized?, identity?}, action?: {valid,
884///   issuer}}` -> `{"ask": {kind: "key" (did, vm) | "revoked" (which) |
885///   "action"}}` or `{"result": {ok, reason, agentDid, issuerDid, rootDid,
886///   attributes}}`. `requiredAction`, when given, is compared as given (a
887///   value that is not one of the issuer's actions matches none);
888///   `checkRevoked` and `hasAction` must be true or false. `unreadable`
889///   names the slots ("recognized", "identity", "root", and for a robot
890///   chain "hardwareCredential") whose credential had no JSON form: the host
891///   sends them with those values as null and their proof is malformed. An
892///   unreadable "requiredAction" is one no issuer holds. The host answers the ask (adds the key, null when it
893///   cannot resolve one; the revocation answer; the action verdict from its
894///   verifier) and calls again with the same request plus the answer. A
895///   replay check of the action stays with the host, after an ok result.
896/// * `verifyRobotChain` `{authorityIdentity, recognized, hardwareCredential,
897///   robotPublicKey (standard base64 raw Ed25519), trustedRoot, root?, now,
898///   clockSkewSeconds?, keys?, checkRevoked?, revoked?}` -> an ask, or
899///   `{"result": {ok, reason, robotDid, issuerDid, rootDid, attributes,
900///   hardwareRooted}}`: the chain for `issueRobotIdentity`, then the robot's
901///   own credential, its subject, its key and the hardware root.
902/// * `build` `{kind: "root" | "recognizedIssuer" | "agentIdentity" |
903///   "robotIdentity", issuerDid, credentialId, validFrom, validSeconds?,
904///   credentialStatus?, ...}` -> `{credential}`: the unsigned credential, for
905///   the host to sign with the issuer's key (proof rules `prepare` and
906///   `attach`). `root`: `name`, `scope?`; `recognizedIssuer`:
907///   `subjectDid`, `recognizedActions?`; `agentIdentity`: `subjectDid`,
908///   `attributes`; `robotIdentity`: `robotDid`, `hardwareKeyMultibase`,
909///   `attributes`, `hardwareRootKeyMultibase?`.
910pub 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            // Absent: the default action. Present: compared as given, so a
917            // value that is not an action the issuer holds matches none.
918            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                // A robot credential with no JSON form cannot verify.
959                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            // The reference checks the lifetime first, except for a robot
980            // identity, whose own checks come before it.
981            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
1093/// [`rules_json`] on request text, read with the nesting the reference's
1094/// canonical form allows (see [`crate::jcs::parse_deep`]), so a credential
1095/// nested 130 levels is judged by its proof, not refused unread.
1096pub fn rules_json_text(text: &str) -> Result<Value> {
1097    rules_json(&crate::jcs::parse_deep(text)?)
1098}
1099
1100/// A list member that falls back to its default when absent, null or empty
1101/// (as the reference's `x or default`); any other type is refused.
1102fn 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    // (a) Verify Python-signed credentials from the committed interop vector.
1197    #[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    // (b) Reproduce every proofValue byte-for-byte from the same fixed inputs.
1224    #[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        // The derived DIDs and validity window must also match the vector.
1243        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    // Round-trip: credentials we build verify through our own chain walker.
1249    #[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    // (c) Adversarial: a tampered identity proof must break the chain.
1297    #[test]
1298    fn tampered_identity_proof_is_rejected() {
1299        let vector = load_vector();
1300        let mut identity = vector["agentIdentity"].clone();
1301        // Edit a signed attribute: the proof no longer matches. (A changed
1302        // proofValue whose S is no longer below the group order is a
1303        // malformed proof instead, as in the reference.)
1304        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    // A recognition that does not grant the required action is rejected.
1324    #[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    // A credential carrying two trust types is ambiguous and rejected.
1358    #[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    /// Walk with the offline keys: answer every key ask from the did:key.
1401    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        // The host's copy of a root with no JSON form (a NaN, a lone
1475        // surrogate) is null: the root was still given, so it is checked.
1476        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}