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
23use serde_json::{json, Map, Value};
24
25use crate::credentials::{PROTOCOL_VERSION, VC_CONTEXT_V2, VC_TYPE, VOUCH_CONTEXT_V1};
26use crate::data_integrity::{self, BuildProofOptions};
27use crate::error::{CoreError, Result};
28use crate::keys::{did_key_to_ed25519, ed25519_to_did_key, Ed25519KeyPair};
29use crate::time::{iso_to_epoch_seconds, parse_protocol_time_ns, seconds_to_ns};
30
31/// Credential type identifiers (the second entry in each `type` array).
32pub const ROOT_OF_TRUST_TYPE: &str = "VouchRootOfTrust";
33pub const RECOGNIZED_ISSUER_TYPE: &str = "RecognizedIssuerCredential";
34pub const AGENT_IDENTITY_TYPE: &str = "AgentIdentityCredential";
35
36/// Actions an issuer can be recognized to perform.
37pub const ACTION_ISSUE_AGENT_IDENTITY: &str = "issueAgentIdentity";
38pub const ACTION_ISSUE_ROBOT_IDENTITY: &str = "issueRobotIdentity";
39
40/// The three trust-layer credential types. A single credential must carry exactly
41/// one of these, otherwise one signed object could be replayed into a different
42/// slot of the chain (type confusion).
43const TRUST_TYPES: [&str; 3] = [
44    ROOT_OF_TRUST_TYPE,
45    RECOGNIZED_ISSUER_TYPE,
46    AGENT_IDENTITY_TYPE,
47];
48
49/// Default validity windows. Roots are long lived; issuer and identity
50/// credentials rotate more often. All are overridable per call.
51pub const ROOT_VALID_SECONDS: i64 = 10 * 365 * 24 * 3600;
52pub const ISSUER_VALID_SECONDS: i64 = 365 * 24 * 3600;
53pub const IDENTITY_VALID_SECONDS: i64 = 365 * 24 * 3600;
54
55/// The proof verification method is always `{did}#key-1` for a did:key signer.
56fn verification_method_of(did: &str) -> String {
57    format!("{did}#key-1")
58}
59
60/// Outcome of [`verify_identity_chain`].
61///
62/// `ok` is true only if every link verified and anchored to the pinned root.
63/// On failure `reason` carries a structured code matching the Python reference.
64#[derive(Debug, Clone, PartialEq, Eq)]
65pub struct IdentityChainResult {
66    pub ok: bool,
67    pub reason: Option<String>,
68    pub agent_did: Option<String>,
69    pub issuer_did: Option<String>,
70    pub root_did: Option<String>,
71    pub attributes: Option<Value>,
72}
73
74impl IdentityChainResult {
75    fn fail(reason: impl Into<String>) -> Self {
76        Self {
77            ok: false,
78            reason: Some(reason.into()),
79            agent_did: None,
80            issuer_did: None,
81            root_did: None,
82            attributes: None,
83        }
84    }
85}
86
87// ---------------------------------------------------------------------------
88// Credential builders
89// ---------------------------------------------------------------------------
90
91/// Self-issue the Vouch Root of Trust credential.
92///
93/// Issuer and subject are both the root's own DID (derived from `root_seed`).
94/// `scope` defaults to `["ai-agent", "robot"]` when None. `valid_from` and
95/// `created` are ISO-8601 instants ("YYYY-MM-DDTHH:MM:SSZ"); the core does not
96/// read a clock.
97#[allow(clippy::too_many_arguments)]
98pub fn build_root_of_trust(
99    root_seed: &[u8],
100    name: &str,
101    scope: Option<&[&str]>,
102    valid_seconds: i64,
103    valid_from: &str,
104    created: &str,
105    credential_id: &str,
106) -> Result<Value> {
107    let root_did = did_of_seed(root_seed)?;
108    let scope_val: Vec<Value> = match scope {
109        Some(s) => s.iter().map(|x| json!(x)).collect(),
110        None => vec![json!("ai-agent"), json!("robot")],
111    };
112    let mut subject = Map::new();
113    subject.insert("id".into(), json!(root_did));
114    subject.insert("vouchVersion".into(), json!(PROTOCOL_VERSION));
115    subject.insert(
116        "rootOfTrust".into(),
117        json!({ "name": name, "scope": scope_val }),
118    );
119
120    let credential = envelope(
121        credential_id,
122        &[VC_TYPE, ROOT_OF_TRUST_TYPE],
123        &root_did,
124        Value::Object(subject),
125        valid_from,
126        valid_seconds,
127        None,
128    )?;
129    sign(&credential, root_seed, &root_did, created)
130}
131
132/// Issue a recognized-issuer credential from the root.
133///
134/// The root attests that `issuer_did` may perform `recognized_actions`
135/// (default `["issueAgentIdentity"]`). `recognizedIn` chains back to the root
136/// DID so a verifier can trace the recognition to the anchor it pinned.
137#[allow(clippy::too_many_arguments)]
138pub fn build_recognized_issuer(
139    root_seed: &[u8],
140    issuer_did: &str,
141    recognized_actions: Option<&[&str]>,
142    valid_seconds: i64,
143    valid_from: &str,
144    created: &str,
145    credential_status: Option<Value>,
146    credential_id: &str,
147) -> Result<Value> {
148    if issuer_did.is_empty() {
149        return Err(CoreError::Json("issuer_did is required".into()));
150    }
151    let root_did = did_of_seed(root_seed)?;
152    let actions: Vec<Value> = match recognized_actions {
153        Some(a) => a.iter().map(|x| json!(x)).collect(),
154        None => vec![json!(ACTION_ISSUE_AGENT_IDENTITY)],
155    };
156    let mut subject = Map::new();
157    subject.insert("id".into(), json!(issuer_did));
158    subject.insert("recognizedActions".into(), Value::Array(actions));
159    subject.insert("recognizedIn".into(), json!(root_did));
160
161    let credential = envelope(
162        credential_id,
163        &[VC_TYPE, RECOGNIZED_ISSUER_TYPE],
164        &root_did,
165        Value::Object(subject),
166        valid_from,
167        valid_seconds,
168        credential_status,
169    )?;
170    sign(&credential, root_seed, &root_did, created)
171}
172
173/// Issue an authority-issued identity credential for an agent.
174///
175/// Here the issuer (derived from `issuer_seed`) differs from the subject: a
176/// recognized issuer binds `subject_did` to real `attributes` (owner, model,
177/// capability class, and so on). `attributes` MUST be a non-empty JSON object.
178#[allow(clippy::too_many_arguments)]
179pub fn build_agent_identity(
180    issuer_seed: &[u8],
181    subject_did: &str,
182    attributes: &Value,
183    valid_seconds: i64,
184    valid_from: &str,
185    created: &str,
186    credential_status: Option<Value>,
187    credential_id: &str,
188) -> Result<Value> {
189    if subject_did.is_empty() {
190        return Err(CoreError::Json("subject_did is required".into()));
191    }
192    match attributes.as_object() {
193        Some(o) if !o.is_empty() => {}
194        _ => {
195            return Err(CoreError::Json(
196                "attributes must be a non-empty object".into(),
197            ))
198        }
199    }
200    let issuer_did = did_of_seed(issuer_seed)?;
201    let mut subject = Map::new();
202    subject.insert("id".into(), json!(subject_did));
203    subject.insert("identity".into(), attributes.clone());
204
205    let credential = envelope(
206        credential_id,
207        &[VC_TYPE, AGENT_IDENTITY_TYPE],
208        &issuer_did,
209        Value::Object(subject),
210        valid_from,
211        valid_seconds,
212        credential_status,
213    )?;
214    sign(&credential, issuer_seed, &issuer_did, created)
215}
216
217// ---------------------------------------------------------------------------
218// Verification
219// ---------------------------------------------------------------------------
220
221/// Verify an agent identity against a pinned Vouch root, fully offline for
222/// did:key issuers.
223///
224/// Walks the chain: the recognized-issuer credential must be signed by the
225/// pinned root and grant `required_action`; the identity credential must be
226/// signed by that recognized issuer. Everything anchors at `trusted_root`, the
227/// ONE DID the verifier trusts up front. `now_iso` is the current instant used
228/// for the temporal window; `clock_skew_seconds` is the allowed drift.
229///
230/// The reason codes returned on failure match the Python reference exactly.
231#[allow(clippy::too_many_arguments)]
232pub fn verify_identity_chain(
233    identity_credential: &Value,
234    recognized_issuer_credential: &Value,
235    trusted_root: &str,
236    root_credential: Option<&Value>,
237    action_credential: Option<&Value>,
238    required_action: &str,
239    now_iso: &str,
240    clock_skew_seconds: i64,
241) -> IdentityChainResult {
242    if trusted_root.is_empty() {
243        return IdentityChainResult::fail("no_trusted_root");
244    }
245
246    // 1. The recognition must be signed by the pinned root.
247    if let Err(reason) = verify_trust_credential(
248        recognized_issuer_credential,
249        RECOGNIZED_ISSUER_TYPE,
250        now_iso,
251        clock_skew_seconds,
252    ) {
253        return IdentityChainResult::fail(format!("recognized_issuer_{reason}"));
254    }
255    if issuer_of(recognized_issuer_credential).as_deref() != Some(trusted_root) {
256        return IdentityChainResult::fail("recognized_issuer_not_from_root");
257    }
258
259    let rec_subject = match recognized_issuer_credential.get("credentialSubject") {
260        Some(Value::Object(o)) => o,
261        _ => return IdentityChainResult::fail("recognized_issuer_bad_subject"),
262    };
263    let recognized_did = match rec_subject.get("id").and_then(|v| v.as_str()) {
264        Some(s) if !s.is_empty() => s.to_string(),
265        _ => return IdentityChainResult::fail("recognized_issuer_no_subject"),
266    };
267    let actions_ok = rec_subject
268        .get("recognizedActions")
269        .and_then(|v| v.as_array())
270        .map(|a| a.iter().any(|x| x.as_str() == Some(required_action)))
271        .unwrap_or(false);
272    if !actions_ok {
273        return IdentityChainResult::fail("issuer_not_recognized_for_action");
274    }
275
276    // 2. The identity must be signed by the recognized issuer.
277    if let Err(reason) = verify_trust_credential(
278        identity_credential,
279        AGENT_IDENTITY_TYPE,
280        now_iso,
281        clock_skew_seconds,
282    ) {
283        return IdentityChainResult::fail(format!("identity_{reason}"));
284    }
285    if issuer_of(identity_credential).as_deref() != Some(recognized_did.as_str()) {
286        return IdentityChainResult::fail("identity_not_from_recognized_issuer");
287    }
288
289    let id_subject = match identity_credential.get("credentialSubject") {
290        Some(Value::Object(o)) => o,
291        _ => return IdentityChainResult::fail("identity_bad_subject"),
292    };
293    let agent_did = match id_subject.get("id").and_then(|v| v.as_str()) {
294        Some(s) if !s.is_empty() => s.to_string(),
295        _ => return IdentityChainResult::fail("identity_no_subject"),
296    };
297    let attributes = id_subject.get("identity").cloned();
298
299    // 3. Optional: confirm the root credential is genuinely self-issued.
300    if let Some(root_cred) = root_credential {
301        if let Err(reason) =
302            verify_trust_credential(root_cred, ROOT_OF_TRUST_TYPE, now_iso, clock_skew_seconds)
303        {
304            return IdentityChainResult::fail(format!("root_{reason}"));
305        }
306        let root_sub = match root_cred.get("credentialSubject") {
307            Some(Value::Object(o)) => o,
308            _ => return IdentityChainResult::fail("root_bad_subject"),
309        };
310        let root_sub_id = root_sub.get("id").and_then(|v| v.as_str());
311        if issuer_of(root_cred).as_deref() != Some(trusted_root)
312            || root_sub_id != Some(trusted_root)
313        {
314            return IdentityChainResult::fail("root_not_self_issued");
315        }
316    }
317
318    // 4. Optional: bind the agent's own action to this identity.
319    if let Some(action_cred) = action_credential {
320        let action_issuer = match issuer_of(action_cred) {
321            Some(i) => i,
322            None => return IdentityChainResult::fail("action_proof_invalid"),
323        };
324        match resolve_key(&action_issuer) {
325            Some(pk) => match data_integrity::verify_proof(action_cred, &pk) {
326                Ok(true) => {}
327                _ => return IdentityChainResult::fail("action_proof_invalid"),
328            },
329            None => return IdentityChainResult::fail("action_proof_invalid"),
330        }
331        if !within_window(action_cred, now_iso, clock_skew_seconds) {
332            return IdentityChainResult::fail("action_proof_invalid");
333        }
334        if action_issuer != agent_did {
335            return IdentityChainResult::fail("action_not_from_agent");
336        }
337    }
338
339    IdentityChainResult {
340        ok: true,
341        reason: None,
342        agent_did: Some(agent_did),
343        issuer_did: Some(recognized_did),
344        root_did: Some(trusted_root.to_string()),
345        attributes,
346    }
347}
348
349// ---------------------------------------------------------------------------
350// Module-private helpers
351// ---------------------------------------------------------------------------
352
353/// Build the unsigned VC envelope shared by all three credential types.
354#[allow(clippy::too_many_arguments)]
355fn envelope(
356    credential_id: &str,
357    types: &[&str],
358    issuer: &str,
359    subject: Value,
360    valid_from: &str,
361    valid_seconds: i64,
362    credential_status: Option<Value>,
363) -> Result<Value> {
364    let from = iso_to_epoch_seconds(valid_from)?;
365    let valid_until = epoch_to_iso(from + valid_seconds);
366    let types_val: Vec<Value> = types.iter().map(|t| json!(t)).collect();
367
368    let mut vc = Map::new();
369    vc.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
370    vc.insert("id".into(), json!(credential_id));
371    vc.insert("type".into(), Value::Array(types_val));
372    vc.insert("issuer".into(), json!(issuer));
373    vc.insert("validFrom".into(), json!(valid_from));
374    vc.insert("validUntil".into(), json!(valid_until));
375    vc.insert("credentialSubject".into(), subject);
376    if let Some(status) = credential_status {
377        vc.insert("credentialStatus".into(), status);
378    }
379    Ok(Value::Object(vc))
380}
381
382/// Attach an eddsa-jcs-2022 Data Integrity proof to `credential`.
383fn sign(credential: &Value, seed: &[u8], issuer_did: &str, created: &str) -> Result<Value> {
384    let opts = BuildProofOptions::new(verification_method_of(issuer_did), created);
385    data_integrity::sign(credential, seed, &opts)
386}
387
388/// did:key DID for a raw 32-byte Ed25519 seed.
389fn did_of_seed(seed: &[u8]) -> Result<String> {
390    let kp = Ed25519KeyPair::from_seed_slice(seed)?;
391    ed25519_to_did_key(&kp.public_key())
392}
393
394/// Verify a trust-layer credential (root, recognized-issuer, or identity).
395///
396/// Checks the type (exactly one trust type), the proof, the proof purpose, that
397/// the verification method belongs to the issuer, and the validity window.
398/// Returns the Python reason code on failure.
399fn verify_trust_credential(
400    credential: &Value,
401    expected_type: &str,
402    now_iso: &str,
403    clock_skew_seconds: i64,
404) -> std::result::Result<(), &'static str> {
405    let obj = match credential.as_object() {
406        Some(o) => o,
407        None => return Err("not_a_credential"),
408    };
409
410    let types = match obj.get("type").and_then(|v| v.as_array()) {
411        Some(t) => t,
412        None => return Err("wrong_type"),
413    };
414    if !types.iter().any(|t| t.as_str() == Some(expected_type)) {
415        return Err("wrong_type");
416    }
417    // Exactly one trust-layer type, so the credential cannot double as another
418    // link in the chain.
419    let trust_count = TRUST_TYPES
420        .iter()
421        .filter(|tt| types.iter().any(|t| t.as_str() == Some(**tt)))
422        .count();
423    if trust_count != 1 {
424        return Err("ambiguous_type");
425    }
426
427    let issuer = match issuer_of(credential) {
428        Some(i) if !i.is_empty() => i,
429        _ => return Err("no_issuer"),
430    };
431
432    let proof = match obj.get("proof").and_then(|p| p.as_object()) {
433        Some(p) => p,
434        None => return Err("no_proof"),
435    };
436    if proof.get("proofPurpose").and_then(|v| v.as_str()) != Some("assertionMethod") {
437        return Err("bad_proof_purpose");
438    }
439    match proof.get("verificationMethod").and_then(|v| v.as_str()) {
440        Some(vm) if !vm.is_empty() && vm.split('#').next() == Some(issuer.as_str()) => {}
441        _ => return Err("vm_mismatch"),
442    }
443
444    let public_key = match resolve_key(&issuer) {
445        Some(k) => k,
446        None => return Err("unresolved_key"),
447    };
448    match data_integrity::verify_proof(credential, &public_key) {
449        Ok(true) => {}
450        Ok(false) => return Err("proof_invalid"),
451        Err(_) => return Err("proof_malformed"),
452    }
453
454    // Temporal window.
455    let vf = obj.get("validFrom").and_then(|v| v.as_str());
456    let vu = obj.get("validUntil").and_then(|v| v.as_str());
457    let (vf, vu) = match (vf, vu) {
458        (Some(a), Some(b)) => (a, b),
459        _ => return Err("no_validity_window"),
460    };
461    let now = match parse_protocol_time_ns(now_iso) {
462        Ok(n) => n,
463        Err(_) => return Err("no_validity_window"),
464    };
465    let valid_from = match parse_protocol_time_ns(vf) {
466        Ok(t) => t,
467        Err(_) => return Err("no_validity_window"),
468    };
469    let valid_until = match parse_protocol_time_ns(vu) {
470        Ok(t) => t,
471        Err(_) => return Err("no_validity_window"),
472    };
473    let skew = seconds_to_ns(clock_skew_seconds);
474    if now - valid_until > skew {
475        return Err("expired");
476    }
477    if valid_from - now > skew {
478        return Err("not_yet_valid");
479    }
480    Ok(())
481}
482
483/// Whether `now_iso` falls inside the credential's validity window (used for the
484/// optional action credential check).
485fn within_window(credential: &Value, now_iso: &str, clock_skew_seconds: i64) -> bool {
486    let obj = match credential.as_object() {
487        Some(o) => o,
488        None => return false,
489    };
490    let vf = obj.get("validFrom").and_then(|v| v.as_str());
491    let vu = obj.get("validUntil").and_then(|v| v.as_str());
492    let (vf, vu) = match (vf, vu) {
493        (Some(a), Some(b)) => (a, b),
494        _ => return false,
495    };
496    let now = match parse_protocol_time_ns(now_iso) {
497        Ok(n) => n,
498        Err(_) => return false,
499    };
500    let from = match parse_protocol_time_ns(vf) {
501        Ok(t) => t,
502        Err(_) => return false,
503    };
504    let until = match parse_protocol_time_ns(vu) {
505        Ok(t) => t,
506        Err(_) => return false,
507    };
508    let skew = seconds_to_ns(clock_skew_seconds);
509    from <= until && now >= from - skew && now <= until + skew
510}
511
512/// Resolve an issuer's Ed25519 public key. Offline for did:key issuers, which is
513/// all the vector and the current core support.
514fn resolve_key(did: &str) -> Option<Vec<u8>> {
515    if did.starts_with("did:key:") {
516        did_key_to_ed25519(did).ok()
517    } else {
518        None
519    }
520}
521
522/// Return the issuer DID, tolerating the list form used by multi-issuer VCs.
523fn issuer_of(credential: &Value) -> Option<String> {
524    match credential.get("issuer") {
525        Some(Value::String(s)) => Some(s.clone()),
526        Some(Value::Array(a)) => a.first().and_then(|v| v.as_str()).map(|s| s.to_string()),
527        _ => None,
528    }
529}
530
531/// Format Unix epoch seconds as "YYYY-MM-DDTHH:MM:SSZ" (inverse of
532/// [`iso_to_epoch_seconds`] for whole-second UTC instants).
533fn epoch_to_iso(epoch: i64) -> String {
534    let days = epoch.div_euclid(86400);
535    let secs = epoch.rem_euclid(86400);
536    let (y, m, d) = civil_from_days(days);
537    let hh = secs / 3600;
538    let mm = (secs % 3600) / 60;
539    let ss = secs % 60;
540    format!("{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}Z")
541}
542
543/// Civil date (year, month, day) from days since the Unix epoch. Howard
544/// Hinnant's algorithm; the inverse of `time::days_from_civil`.
545fn civil_from_days(z: i64) -> (i64, i64, i64) {
546    let z = z + 719468;
547    let era = (if z >= 0 { z } else { z - 146096 }) / 146097;
548    let doe = z - era * 146097;
549    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
550    let y = yoe + era * 400;
551    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
552    let mp = (5 * doy + 2) / 153;
553    let d = doy - (153 * mp + 2) / 5 + 1;
554    let m = if mp < 10 { mp + 3 } else { mp - 9 };
555    (if m <= 2 { y + 1 } else { y }, m, d)
556}
557
558#[cfg(test)]
559mod tests {
560    use super::*;
561    use std::path::PathBuf;
562
563    const ROOT_SEED: [u8; 32] = [0x01; 32];
564    const ISSUER_SEED: [u8; 32] = [0x02; 32];
565    const AGENT_SEED: [u8; 32] = [0x03; 32];
566
567    const VALID_FROM: &str = "2026-01-01T00:00:00Z";
568    const CREATED: &str = "2026-01-01T00:00:00Z";
569    const VALID_SECONDS: i64 = 100 * 365 * 24 * 3600;
570    const NOW: &str = "2026-07-01T00:00:00Z";
571
572    const ROOT_ID: &str = "urn:uuid:11111111-1111-1111-1111-111111111111";
573    const RECOGNITION_ID: &str = "urn:uuid:22222222-2222-2222-2222-222222222222";
574    const IDENTITY_ID: &str = "urn:uuid:33333333-3333-3333-3333-333333333333";
575
576    fn load_vector() -> Value {
577        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
578            .join("../../test-vectors/root-of-trust/vector.json");
579        let text = std::fs::read_to_string(&path)
580            .unwrap_or_else(|e| panic!("read vector {}: {e}", path.display()));
581        serde_json::from_str(&text).expect("vector is valid JSON")
582    }
583
584    fn agent_attributes() -> Value {
585        json!({ "owner": "Acme", "model": "gpt-x", "capabilityClass": "shopping" })
586    }
587
588    fn build_all() -> (Value, Value, Value) {
589        let issuer_did = did_of_seed(&ISSUER_SEED).unwrap();
590        let agent_did = did_of_seed(&AGENT_SEED).unwrap();
591
592        let root = build_root_of_trust(
593            &ROOT_SEED,
594            "Vouch Machine Identity Root",
595            None,
596            VALID_SECONDS,
597            VALID_FROM,
598            CREATED,
599            ROOT_ID,
600        )
601        .unwrap();
602
603        let recognition = build_recognized_issuer(
604            &ROOT_SEED,
605            &issuer_did,
606            Some(&[ACTION_ISSUE_AGENT_IDENTITY]),
607            VALID_SECONDS,
608            VALID_FROM,
609            CREATED,
610            None,
611            RECOGNITION_ID,
612        )
613        .unwrap();
614
615        let identity = build_agent_identity(
616            &ISSUER_SEED,
617            &agent_did,
618            &agent_attributes(),
619            VALID_SECONDS,
620            VALID_FROM,
621            CREATED,
622            None,
623            IDENTITY_ID,
624        )
625        .unwrap();
626
627        (root, recognition, identity)
628    }
629
630    // (a) Verify Python-signed credentials from the committed interop vector.
631    #[test]
632    fn verifies_python_signed_vector() {
633        let vector = load_vector();
634        let trusted_root = vector["trustedRoot"].as_str().unwrap();
635        let result = verify_identity_chain(
636            &vector["agentIdentity"],
637            &vector["recognizedIssuer"],
638            trusted_root,
639            Some(&vector["rootOfTrust"]),
640            None,
641            ACTION_ISSUE_AGENT_IDENTITY,
642            NOW,
643            30,
644        );
645        assert!(result.ok, "chain must verify: {:?}", result.reason);
646        assert_eq!(
647            result.agent_did.as_deref(),
648            vector["expected"]["agentDid"].as_str()
649        );
650        assert_eq!(
651            result.issuer_did.as_deref(),
652            vector["expected"]["issuerDid"].as_str()
653        );
654        assert_eq!(result.root_did.as_deref(), Some(trusted_root));
655    }
656
657    // (b) Reproduce every proofValue byte-for-byte from the same fixed inputs.
658    #[test]
659    fn reproduces_vector_byte_for_byte() {
660        let vector = load_vector();
661        let (root, recognition, identity) = build_all();
662
663        assert_eq!(
664            root["proof"]["proofValue"], vector["rootOfTrust"]["proof"]["proofValue"],
665            "root of trust proofValue diverges from Python"
666        );
667        assert_eq!(
668            recognition["proof"]["proofValue"], vector["recognizedIssuer"]["proof"]["proofValue"],
669            "recognized issuer proofValue diverges from Python"
670        );
671        assert_eq!(
672            identity["proof"]["proofValue"], vector["agentIdentity"]["proof"]["proofValue"],
673            "agent identity proofValue diverges from Python"
674        );
675
676        // The derived DIDs and validity window must also match the vector.
677        assert_eq!(root["issuer"], vector["trustedRoot"]);
678        assert_eq!(root["validUntil"], vector["rootOfTrust"]["validUntil"]);
679        assert_eq!(identity["issuer"], vector["agentIdentity"]["issuer"]);
680    }
681
682    // Round-trip: credentials we build verify through our own chain walker.
683    #[test]
684    fn self_built_chain_verifies() {
685        let (root, recognition, identity) = build_all();
686        let root_did = did_of_seed(&ROOT_SEED).unwrap();
687        let agent_did = did_of_seed(&AGENT_SEED).unwrap();
688        let issuer_did = did_of_seed(&ISSUER_SEED).unwrap();
689
690        let result = verify_identity_chain(
691            &identity,
692            &recognition,
693            &root_did,
694            Some(&root),
695            None,
696            ACTION_ISSUE_AGENT_IDENTITY,
697            NOW,
698            30,
699        );
700        assert!(
701            result.ok,
702            "self-built chain must verify: {:?}",
703            result.reason
704        );
705        assert_eq!(result.agent_did.as_deref(), Some(agent_did.as_str()));
706        assert_eq!(result.issuer_did.as_deref(), Some(issuer_did.as_str()));
707        assert_eq!(result.attributes, Some(agent_attributes()));
708    }
709
710    // (c) Adversarial: a tampered identity proof must break the chain.
711    #[test]
712    fn tampered_identity_proof_is_rejected() {
713        let vector = load_vector();
714        let mut identity = vector["agentIdentity"].clone();
715        let original = identity["proof"]["proofValue"]
716            .as_str()
717            .unwrap()
718            .to_string();
719        // Flip one base58 character so the value still decodes but the signature
720        // no longer matches.
721        let mut chars: Vec<char> = original.chars().collect();
722        let idx = chars.len() - 1;
723        chars[idx] = if chars[idx] == 'A' { 'B' } else { 'A' };
724        identity["proof"]["proofValue"] = json!(chars.into_iter().collect::<String>());
725
726        let result = verify_identity_chain(
727            &identity,
728            &vector["recognizedIssuer"],
729            vector["trustedRoot"].as_str().unwrap(),
730            Some(&vector["rootOfTrust"]),
731            None,
732            ACTION_ISSUE_AGENT_IDENTITY,
733            NOW,
734            30,
735        );
736        assert!(!result.ok, "tampered proof must be rejected");
737        assert_eq!(
738            result.reason.as_deref(),
739            Some("identity_proof_invalid"),
740            "unexpected reason for tampered proof"
741        );
742    }
743
744    // A recognition that does not grant the required action is rejected.
745    #[test]
746    fn wrong_action_is_rejected() {
747        let (root, _recognition, identity) = build_all();
748        let root_did = did_of_seed(&ROOT_SEED).unwrap();
749        let issuer_did = did_of_seed(&ISSUER_SEED).unwrap();
750        let recognition = build_recognized_issuer(
751            &ROOT_SEED,
752            &issuer_did,
753            Some(&[ACTION_ISSUE_ROBOT_IDENTITY]),
754            VALID_SECONDS,
755            VALID_FROM,
756            CREATED,
757            None,
758            RECOGNITION_ID,
759        )
760        .unwrap();
761        let result = verify_identity_chain(
762            &identity,
763            &recognition,
764            &root_did,
765            Some(&root),
766            None,
767            ACTION_ISSUE_AGENT_IDENTITY,
768            NOW,
769            30,
770        );
771        assert!(!result.ok);
772        assert_eq!(
773            result.reason.as_deref(),
774            Some("issuer_not_recognized_for_action")
775        );
776    }
777
778    // A credential carrying two trust types is ambiguous and rejected.
779    #[test]
780    fn ambiguous_type_is_rejected() {
781        let (_root, recognition, mut identity) = build_all();
782        identity["type"] = json!([VC_TYPE, AGENT_IDENTITY_TYPE, RECOGNIZED_ISSUER_TYPE]);
783        let root_did = did_of_seed(&ROOT_SEED).unwrap();
784        let result = verify_identity_chain(
785            &identity,
786            &recognition,
787            &root_did,
788            None,
789            None,
790            ACTION_ISSUE_AGENT_IDENTITY,
791            NOW,
792            30,
793        );
794        assert!(!result.ok);
795        assert_eq!(result.reason.as_deref(), Some("identity_ambiguous_type"));
796    }
797
798    #[test]
799    fn epoch_iso_roundtrip() {
800        assert_eq!(epoch_to_iso(0), "1970-01-01T00:00:00Z");
801        let from = iso_to_epoch_seconds(VALID_FROM).unwrap();
802        assert_eq!(epoch_to_iso(from + VALID_SECONDS), "2125-12-08T00:00:00Z");
803    }
804}