Skip to main content

vouch_core/
robotics.rs

1//! Robotics primitives (Phase 5), one byte-exact implementation in the core.
2//!
3//! Mirrors the Python `vouch.robotics` package and the TypeScript/Go SDKs so that
4//! a robotics credential built in any language verifies in every other. Exposing
5//! this module through the UniFFI and WASM wrappers gives Swift, Kotlin/JVM,
6//! .NET, C/C++, and the browser the same robotics surface without re-deriving it.
7//!
8//! This file covers hardware-rooted robot identity (Phase 5.1). The remaining
9//! capabilities (provenance, capability scope, handshake, black box, passport)
10//! are added alongside it.
11//!
12//! Design: the core is hardware-agnostic and deterministic. A robot self-issues
13//! its `RobotIdentityCredential` with its own Ed25519 key; the hardware root (a
14//! TPM, secure element, or a software root in development) signs a binding over
15//! the robot DID and key, supplied to [`mint_robot_identity`] as the attestation
16//! bytes. Timestamps are caller-supplied, matching the rest of the core, so the
17//! output is reproducible and the wrappers control the clock.
18
19use serde_json::{json, Map, Value};
20
21use crate::data_integrity::{self, BuildProofOptions};
22use crate::error::{CoreError, Result};
23use crate::keys;
24use crate::pq::{MlDsa44KeyPair, MLDSA44_PUBLIC_LEN};
25use crate::root_of_trust::{self, ACTION_ISSUE_ROBOT_IDENTITY};
26use crate::{hybrid, jcs, multikey};
27
28use aes_gcm::aead::Aead;
29use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
30use base64::engine::general_purpose::URL_SAFE_NO_PAD;
31use base64::Engine;
32use sha2::{Digest, Sha256};
33use std::collections::HashSet;
34
35pub const VC_CONTEXT_V2: &str = "https://www.w3.org/ns/credentials/v2";
36pub const VOUCH_CONTEXT_V1: &str = "https://vouch-protocol.com/contexts/v1";
37pub const ROBOT_IDENTITY_TYPE: &str = "RobotIdentityCredential";
38
39/// Multibase ('u') base64url-no-pad encoding, matching the Python/TS/Go `mb64`.
40pub(crate) fn mb64(bytes: &[u8]) -> String {
41    format!("u{}", URL_SAFE_NO_PAD.encode(bytes))
42}
43
44/// Decode a multibase ('u') base64url-no-pad string.
45pub(crate) fn unmb64(s: &str) -> Result<Vec<u8>> {
46    let body = s
47        .strip_prefix('u')
48        .ok_or_else(|| CoreError::Json("expected multibase 'u' prefix".into()))?;
49    URL_SAFE_NO_PAD
50        .decode(body)
51        .map_err(|e| CoreError::Json(format!("bad base64url: {e}")))
52}
53
54/// True if `type_field` (a JSON string or array of strings) contains `want`.
55pub(crate) fn has_type(type_field: Option<&Value>, want: &str) -> bool {
56    match type_field {
57        Some(Value::String(s)) => s == want,
58        Some(Value::Array(items)) => items.iter().any(|v| v.as_str() == Some(want)),
59        _ => false,
60    }
61}
62
63/// The canonical bytes a hardware root signs to bind a robot's identity key to
64/// its hardware: JCS of `{"key": robot_key_multibase, "robotDid": robot_did}`.
65pub fn robot_identity_binding(robot_did: &str, robot_key_multibase: &str) -> Vec<u8> {
66    jcs::canonicalize(&json!({
67        "key": robot_key_multibase,
68        "robotDid": robot_did,
69    }))
70}
71
72/// Parameters for [`mint_robot_identity`]. Timestamps are ISO-8601 strings the
73/// caller supplies. `attestation` is the hardware root's signature over
74/// [`robot_identity_binding`]; `root_public_multibase` is that root's public key.
75#[derive(Debug, Clone)]
76pub struct MintRobotIdentity {
77    pub robot_did: String,
78    pub make: String,
79    pub model: String,
80    pub serial: String,
81    pub owner: Option<String>,
82    pub root_kind: String,
83    pub root_public_multibase: String,
84    pub attestation: Vec<u8>,
85    /// Optional explicit lifecycle array; defaults to a single "commissioned" entry.
86    pub lifecycle: Option<Value>,
87    pub valid_from: String,
88    pub valid_until: Option<String>,
89}
90
91/// Mint a hardware-attested `RobotIdentityCredential`, signed by the robot's own
92/// Ed25519 seed. The hardware-root attestation is embedded as
93/// `credentialSubject.hardwareRoot.attestation`.
94pub fn mint_robot_identity(robot_seed: &[u8], params: &MintRobotIdentity) -> Result<Value> {
95    let lifecycle = params
96        .lifecycle
97        .clone()
98        .unwrap_or_else(|| json!([{ "event": "commissioned", "timestamp": params.valid_from }]));
99
100    let mut subject = Map::new();
101    subject.insert("id".into(), json!(params.robot_did));
102    subject.insert("make".into(), json!(params.make));
103    subject.insert("model".into(), json!(params.model));
104    subject.insert("serial".into(), json!(params.serial));
105    subject.insert(
106        "hardwareRoot".into(),
107        json!({
108            "kind": params.root_kind,
109            "publicKeyMultibase": params.root_public_multibase,
110            "attestation": mb64(&params.attestation),
111        }),
112    );
113    subject.insert("lifecycle".into(), lifecycle);
114    if let Some(owner) = &params.owner {
115        subject.insert("owner".into(), json!(owner));
116    }
117
118    let mut cred = Map::new();
119    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
120    cred.insert(
121        "type".into(),
122        json!(["VerifiableCredential", ROBOT_IDENTITY_TYPE]),
123    );
124    cred.insert("issuer".into(), json!(params.robot_did));
125    cred.insert("validFrom".into(), json!(params.valid_from));
126    if let Some(vu) = &params.valid_until {
127        cred.insert("validUntil".into(), json!(vu));
128    }
129    cred.insert("credentialSubject".into(), Value::Object(subject));
130
131    let opts = BuildProofOptions::new(
132        format!("{}#key-1", params.robot_did),
133        params.valid_from.clone(),
134    );
135    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
136}
137
138/// Verify a `RobotIdentityCredential`: both the credential proof (under
139/// `robot_public_key`) AND the hardware-root attestation binding the robot key to
140/// the hardware. Returns the credentialSubject on success, `None` if invalid.
141pub fn verify_robot_identity(credential: &Value, robot_public_key: &[u8]) -> Result<Option<Value>> {
142    let obj = credential
143        .as_object()
144        .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?;
145    if !has_type(obj.get("type"), ROBOT_IDENTITY_TYPE) {
146        return Ok(None);
147    }
148    if !data_integrity::verify_proof(credential, robot_public_key)? {
149        return Ok(None);
150    }
151
152    let subject = match obj.get("credentialSubject").and_then(|s| s.as_object()) {
153        Some(s) => s,
154        None => return Ok(None),
155    };
156    let hw = match subject.get("hardwareRoot").and_then(|h| h.as_object()) {
157        Some(h) => h,
158        None => return Ok(None),
159    };
160    let hw_mb = match hw.get("publicKeyMultibase").and_then(|v| v.as_str()) {
161        Some(s) => s,
162        None => return Ok(None),
163    };
164    let attestation_mb = match hw.get("attestation").and_then(|v| v.as_str()) {
165        Some(s) => s,
166        None => return Ok(None),
167    };
168
169    let decoded = match multikey::decode(hw_mb) {
170        Ok(d) if d.algorithm == "Ed25519" && d.raw_key.len() == 32 => d,
171        _ => return Ok(None),
172    };
173    let attestation = match unmb64(attestation_mb) {
174        Ok(a) => a,
175        Err(_) => return Ok(None),
176    };
177
178    let robot_key_mb = multikey::encode_ed25519_public(robot_public_key)?;
179    let robot_did = subject.get("id").and_then(|v| v.as_str()).unwrap_or("");
180    let binding = robot_identity_binding(robot_did, &robot_key_mb);
181
182    if !keys::verify(&decoded.raw_key, &binding, &attestation)? {
183        return Ok(None);
184    }
185    Ok(Some(Value::Object(subject.clone())))
186}
187
188// ---------------------------------------------------------------------------
189// Root of Trust for robot identity (Phase 5.1, authority binding)
190// ---------------------------------------------------------------------------
191//
192// Byte-exact port of the Python reference `vouch/robotics/root_identity.py`.
193//
194// The Root of Trust for Machine Identity lets one pinned Vouch root recognize
195// issuers, and a recognized issuer bind a subject DID to attributes, verified
196// offline against that one pinned root. This extends it to robots. A recognized
197// manufacturer (an issuer the root granted the `issueRobotIdentity` action)
198// issues an identity that binds a robot's DID and its hardware-rooted key to
199// attributes such as make, model, serial, and owner. The robot separately holds
200// a hardware-attested `RobotIdentityCredential` proving its key is bound to a
201// secure element.
202//
203// [`verify_robot_identity_chain`] closes the loop: from one pinned root a
204// verifier confirms both that the robot is a legitimate robot from a recognized
205// manufacturer (the authority chain via [`root_of_trust::verify_identity_chain`])
206// and that the key the manufacturer vouched for is genuinely hardware-rooted (the
207// secure-element attestation via [`verify_robot_identity`]), and that the two
208// name the same robot and the same key. It follows the anchor-once model and the
209// reason-code style of the underlying root_of_trust.
210
211/// Outcome of [`verify_robot_identity_chain`].
212///
213/// `ok` is true only if the authority chain verified against the pinned root AND
214/// the vouched key is hardware-rooted for the same robot. On failure `reason`
215/// carries a structured code matching the Python reference exactly.
216#[derive(Debug, Clone, PartialEq, Eq)]
217pub struct RobotIdentityChainResult {
218    pub ok: bool,
219    pub reason: Option<String>,
220    pub robot_did: Option<String>,
221    pub issuer_did: Option<String>,
222    pub root_did: Option<String>,
223    pub attributes: Option<Value>,
224    pub hardware_rooted: bool,
225}
226
227impl RobotIdentityChainResult {
228    /// A failure result carrying the reason code and the pinned root that was in
229    /// force when the check failed.
230    fn fail(reason: impl Into<String>, root_did: &str) -> Self {
231        Self {
232            ok: false,
233            reason: Some(reason.into()),
234            robot_did: None,
235            issuer_did: None,
236            root_did: Some(root_did.to_string()),
237            attributes: None,
238            hardware_rooted: false,
239        }
240    }
241}
242
243/// Issue an authority robot identity: a recognized manufacturer binds `robot_did`,
244/// its hardware-rooted key (`hardware_key_multibase`, the robot's Ed25519 key as a
245/// multikey), and identity `attributes` (make, model, serial, owner). The
246/// manufacturer (derived from `issuer_seed`) must be a recognized issuer for the
247/// `issueRobotIdentity` action.
248///
249/// The credential is an `AgentIdentityCredential` so the shared identity-chain
250/// verification applies, with a `kind` of "robot" and the hardware key carried in
251/// the bound identity attributes.
252#[allow(clippy::too_many_arguments)]
253pub fn build_robot_identity(
254    issuer_seed: &[u8],
255    robot_did: &str,
256    hardware_key_multibase: &str,
257    attributes: &Value,
258    valid_seconds: i64,
259    valid_from: &str,
260    created: &str,
261    credential_status: Option<Value>,
262    credential_id: &str,
263) -> Result<Value> {
264    if robot_did.is_empty() {
265        return Err(CoreError::Json("robot_did is required".into()));
266    }
267    if hardware_key_multibase.is_empty() {
268        return Err(CoreError::Json("hardware_key_multibase is required".into()));
269    }
270    let bound = match attributes.as_object() {
271        Some(o) if !o.is_empty() => {
272            let mut m = o.clone();
273            m.insert("kind".into(), json!("robot"));
274            m.insert("hardwareKey".into(), json!(hardware_key_multibase));
275            Value::Object(m)
276        }
277        _ => {
278            return Err(CoreError::Json(
279                "attributes must be a non-empty object".into(),
280            ))
281        }
282    };
283    root_of_trust::build_agent_identity(
284        issuer_seed,
285        robot_did,
286        &bound,
287        valid_seconds,
288        valid_from,
289        created,
290        credential_status,
291        credential_id,
292    )
293}
294
295/// Verify a robot's identity against a single pinned Vouch root, confirming both
296/// provenance and hardware-rooting.
297///
298/// From `trusted_root`, the pinned root DID:
299///
300///   1. The authority chain: the recognized manufacturer must be recognized by
301///      the pinned root for the `issueRobotIdentity` action, and the authority
302///      identity must be signed by that manufacturer (shared identity-chain verify).
303///   2. The vouched key: the authority identity must carry a hardware key.
304///   3. The hardware root: the robot's own `RobotIdentityCredential` must verify
305///      under `robot_public_key` and its secure-element attestation, name the same
306///      robot, and its key must equal the key the manufacturer vouched for.
307///
308/// `robot_public_key` is the robot's raw 32-byte Ed25519 public key. `now_iso` is
309/// the current instant used for the temporal window; `clock_skew_seconds` is the
310/// allowed drift. Reason codes on failure match the Python reference exactly.
311#[allow(clippy::too_many_arguments)]
312pub fn verify_robot_identity_chain(
313    authority_identity: &Value,
314    recognized_issuer_credential: &Value,
315    robot_hardware_credential: &Value,
316    trusted_root: &str,
317    robot_public_key: &[u8],
318    root_credential: Option<&Value>,
319    now_iso: &str,
320    clock_skew_seconds: i64,
321) -> RobotIdentityChainResult {
322    let chain = root_of_trust::verify_identity_chain(
323        authority_identity,
324        recognized_issuer_credential,
325        trusted_root,
326        root_credential,
327        None,
328        ACTION_ISSUE_ROBOT_IDENTITY,
329        now_iso,
330        clock_skew_seconds,
331    );
332    if !chain.ok {
333        return RobotIdentityChainResult {
334            ok: false,
335            reason: chain.reason,
336            robot_did: None,
337            issuer_did: None,
338            root_did: Some(trusted_root.to_string()),
339            attributes: None,
340            hardware_rooted: false,
341        };
342    }
343
344    let attributes = match &chain.attributes {
345        Some(v @ Value::Object(_)) => v.clone(),
346        _ => json!({}),
347    };
348    let hardware_key = match attributes.get("hardwareKey").and_then(|v| v.as_str()) {
349        Some(s) if !s.is_empty() => s.to_string(),
350        _ => return RobotIdentityChainResult::fail("identity_no_hardware_key", trusted_root),
351    };
352
353    let hw_subject = match verify_robot_identity(robot_hardware_credential, robot_public_key) {
354        Ok(Some(s)) => s,
355        _ => return RobotIdentityChainResult::fail("hardware_root_invalid", trusted_root),
356    };
357    if hw_subject.get("id").and_then(|v| v.as_str()) != chain.agent_did.as_deref() {
358        return RobotIdentityChainResult::fail("hardware_subject_mismatch", trusted_root);
359    }
360
361    let robot_key_mb = match multikey::encode_ed25519_public(robot_public_key) {
362        Ok(mb) => mb,
363        Err(_) => return RobotIdentityChainResult::fail("hardware_key_unresolvable", trusted_root),
364    };
365    if robot_key_mb != hardware_key {
366        return RobotIdentityChainResult::fail("hardware_key_mismatch", trusted_root);
367    }
368
369    RobotIdentityChainResult {
370        ok: true,
371        reason: None,
372        robot_did: chain.agent_did,
373        issuer_did: chain.issuer_did,
374        root_did: Some(trusted_root.to_string()),
375        attributes: Some(attributes),
376        hardware_rooted: true,
377    }
378}
379
380// ---------------------------------------------------------------------------
381// Model and config provenance (Phase 5.2)
382// ---------------------------------------------------------------------------
383
384pub const MODEL_PROVENANCE_TYPE: &str = "ModelProvenanceAttestation";
385
386/// Multibase SHA-256 of the JCS-canonical config object. Python, TypeScript, Go,
387/// and Rust all canonicalize identically, so the digest is the same byte string
388/// in every language.
389pub fn config_hash(config: &Value) -> String {
390    let digest = Sha256::digest(jcs::canonicalize(config));
391    mb64(&digest)
392}
393
394/// Parameters for [`build_provenance_attestation`]. The issuer is the signer (the
395/// robot itself or an authority); `robot_did` names the robot the attestation is
396/// about.
397#[derive(Debug, Clone)]
398pub struct BuildProvenance {
399    pub issuer_did: String,
400    pub robot_did: String,
401    pub model_name: String,
402    pub weights_hash: String,
403    pub safety_policy: String,
404    pub config: Option<Value>,
405    pub version: Option<String>,
406    pub supersedes: Option<String>,
407    pub valid_from: String,
408    pub valid_until: Option<String>,
409}
410
411/// Build a signed `ModelProvenanceAttestation` for the software on a robot.
412pub fn build_provenance_attestation(signer_seed: &[u8], params: &BuildProvenance) -> Result<Value> {
413    let mut vla = Map::new();
414    vla.insert("modelName".into(), json!(params.model_name));
415    vla.insert("weightsHash".into(), json!(params.weights_hash));
416    vla.insert("safetyPolicy".into(), json!(params.safety_policy));
417    if let Some(v) = &params.version {
418        vla.insert("version".into(), json!(v));
419    }
420    if let Some(cfg) = &params.config {
421        vla.insert("configHash".into(), json!(config_hash(cfg)));
422    }
423
424    let mut subject = Map::new();
425    subject.insert("id".into(), json!(params.robot_did));
426    subject.insert("vla".into(), Value::Object(vla));
427    if let Some(s) = &params.supersedes {
428        subject.insert("supersedes".into(), json!(s));
429    }
430
431    let mut cred = Map::new();
432    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
433    cred.insert(
434        "type".into(),
435        json!(["VerifiableCredential", MODEL_PROVENANCE_TYPE]),
436    );
437    cred.insert("issuer".into(), json!(params.issuer_did));
438    cred.insert("validFrom".into(), json!(params.valid_from));
439    if let Some(vu) = &params.valid_until {
440        cred.insert("validUntil".into(), json!(vu));
441    }
442    cred.insert("credentialSubject".into(), Value::Object(subject));
443
444    let opts = BuildProofOptions::new(
445        format!("{}#key-1", params.issuer_did),
446        params.valid_from.clone(),
447    );
448    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
449}
450
451/// Verify a `ModelProvenanceAttestation`. When `config` is supplied, also check
452/// the recorded configHash reproduces. Returns the subject on success, `None`
453/// otherwise.
454pub fn verify_provenance_attestation(
455    attestation: &Value,
456    public_key: &[u8],
457    config: Option<&Value>,
458) -> Result<Option<Value>> {
459    let obj = attestation
460        .as_object()
461        .ok_or_else(|| CoreError::Json("attestation must be a JSON object".into()))?;
462    if !has_type(obj.get("type"), MODEL_PROVENANCE_TYPE) {
463        return Ok(None);
464    }
465    if !data_integrity::verify_proof(attestation, public_key)? {
466        return Ok(None);
467    }
468    let subject = match obj.get("credentialSubject").and_then(|s| s.as_object()) {
469        Some(s) => s,
470        None => return Ok(None),
471    };
472    if let Some(cfg) = config {
473        let want = config_hash(cfg);
474        let got = subject
475            .get("vla")
476            .and_then(|v| v.as_object())
477            .and_then(|v| v.get("configHash"))
478            .and_then(|v| v.as_str())
479            .unwrap_or("");
480        if got != want {
481            return Ok(None);
482        }
483    }
484    Ok(Some(Value::Object(subject.clone())))
485}
486
487// ---------------------------------------------------------------------------
488// Physical capability scope (Phase 5.3)
489// ---------------------------------------------------------------------------
490
491pub const PHYSICAL_SCOPE_TYPE: &str = "PhysicalCapabilityScope";
492
493/// An allowed time-of-day window, "HH:MM" start and end.
494#[derive(Debug, Clone)]
495pub struct ShiftWindow {
496    pub start: String,
497    pub end: String,
498}
499
500/// A proposed actuation to check against a scope. `None` numerics mean "not
501/// specified" (a meaningful zero is still `Some(0.0)`).
502#[derive(Debug, Clone, Default)]
503pub struct PhysicalAction {
504    pub force_n: Option<f64>,
505    pub speed_mps: Option<f64>,
506    pub near_humans: bool,
507    pub zone: Option<String>,
508    pub time_hm: Option<String>,
509}
510
511/// The outcome of [`check_physical_action`].
512#[derive(Debug, Clone)]
513pub struct CheckResult {
514    pub ok: bool,
515    pub reasons: Vec<String>,
516}
517
518/// Parameters for [`build_physical_scope_credential`]. The issuer is the signer
519/// (a fleet authority); `subject_did` is the robot the scope is granted to.
520#[derive(Debug, Clone, Default)]
521pub struct BuildPhysicalScope {
522    pub issuer_did: String,
523    pub subject_did: String,
524    pub max_force_n: Option<f64>,
525    pub max_speed_mps: Option<f64>,
526    pub max_speed_near_humans_mps: Option<f64>,
527    pub allowed_zones: Option<Vec<String>>,
528    pub shift_windows: Option<Vec<ShiftWindow>>,
529    pub valid_from: String,
530    pub valid_until: Option<String>,
531}
532
533/// Build a signed `PhysicalCapabilityScope` credential.
534pub fn build_physical_scope_credential(
535    signer_seed: &[u8],
536    params: &BuildPhysicalScope,
537) -> Result<Value> {
538    let mut scope = Map::new();
539    if let Some(v) = params.max_force_n {
540        scope.insert("maxForceN".into(), json!(v));
541    }
542    if let Some(v) = params.max_speed_mps {
543        scope.insert("maxSpeedMps".into(), json!(v));
544    }
545    if let Some(v) = params.max_speed_near_humans_mps {
546        scope.insert("maxSpeedNearHumansMps".into(), json!(v));
547    }
548    if let Some(zones) = &params.allowed_zones {
549        scope.insert("allowedZones".into(), json!(zones));
550    }
551    if let Some(ws) = &params.shift_windows {
552        let arr: Vec<Value> = ws
553            .iter()
554            .map(|w| json!({"start": w.start, "end": w.end}))
555            .collect();
556        scope.insert("shiftWindows".into(), Value::Array(arr));
557    }
558
559    let mut subject = Map::new();
560    subject.insert("id".into(), json!(params.subject_did));
561    subject.insert("physicalScope".into(), Value::Object(scope));
562
563    let mut cred = Map::new();
564    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
565    cred.insert(
566        "type".into(),
567        json!(["VerifiableCredential", PHYSICAL_SCOPE_TYPE]),
568    );
569    cred.insert("issuer".into(), json!(params.issuer_did));
570    cred.insert("validFrom".into(), json!(params.valid_from));
571    if let Some(vu) = &params.valid_until {
572        cred.insert("validUntil".into(), json!(vu));
573    }
574    cred.insert("credentialSubject".into(), Value::Object(subject));
575
576    let opts = BuildProofOptions::new(
577        format!("{}#key-1", params.issuer_did),
578        params.valid_from.clone(),
579    );
580    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
581}
582
583fn scope_num(scope: &Map<String, Value>, key: &str) -> Option<f64> {
584    scope.get(key).and_then(|v| v.as_f64())
585}
586
587fn window_bounds(w: &Value) -> (String, String) {
588    let start = w
589        .get("start")
590        .and_then(|v| v.as_str())
591        .filter(|s| !s.is_empty())
592        .unwrap_or("00:00")
593        .to_string();
594    let end = w
595        .get("end")
596        .and_then(|v| v.as_str())
597        .filter(|s| !s.is_empty())
598        .unwrap_or("23:59")
599        .to_string();
600    (start, end)
601}
602
603fn in_window(hm: &str, w: &Value) -> bool {
604    let (start, end) = window_bounds(w);
605    start.as_str() <= hm && hm <= end.as_str()
606}
607
608/// Check a proposed physical action against a physical scope object, returning ok
609/// plus a reason for each violated dimension. Accepts both native and
610/// JSON-decoded scope shapes.
611pub fn check_physical_action(scope: &Value, action: &PhysicalAction) -> CheckResult {
612    let empty = Map::new();
613    let scope = scope.as_object().unwrap_or(&empty);
614    let mut reasons = Vec::new();
615
616    if let Some(force) = action.force_n {
617        if let Some(cap) = scope_num(scope, "maxForceN") {
618            if force > cap {
619                reasons.push(format!("force_exceeded: {force}N > {cap}N"));
620            }
621        }
622    }
623
624    if let Some(speed) = action.speed_mps {
625        let mut cap = scope_num(scope, "maxSpeedMps");
626        if action.near_humans {
627            if let Some(nh) = scope_num(scope, "maxSpeedNearHumansMps") {
628                cap = Some(nh);
629            }
630        }
631        if let Some(c) = cap {
632            if speed > c {
633                let label = if action.near_humans {
634                    "near_humans "
635                } else {
636                    ""
637                };
638                reasons.push(format!("{label}speed_exceeded: {speed} m/s > {c} m/s"));
639            }
640        }
641    }
642
643    if let Some(zone) = &action.zone {
644        if let Some(zones) = scope.get("allowedZones").and_then(|v| v.as_array()) {
645            if !zones.iter().any(|z| z.as_str() == Some(zone.as_str())) {
646                reasons.push(format!("zone_not_allowed: {zone}"));
647            }
648        }
649    }
650
651    if let Some(time_hm) = &action.time_hm {
652        if let Some(windows) = scope.get("shiftWindows").and_then(|v| v.as_array()) {
653            if !windows.is_empty() && !windows.iter().any(|w| in_window(time_hm, w)) {
654                reasons.push(format!("outside_shift_window: {time_hm}"));
655            }
656        }
657    }
658
659    CheckResult {
660        ok: reasons.is_empty(),
661        reasons,
662    }
663}
664
665/// Report whether `child` is a valid attenuation of `parent`: never broader on
666/// any physical dimension. The privilege-escalation guard for delegated scopes.
667pub fn attenuates(parent: &Value, child: &Value) -> bool {
668    let empty = Map::new();
669    let p = parent.as_object().unwrap_or(&empty);
670    let c = child.as_object().unwrap_or(&empty);
671
672    for key in ["maxForceN", "maxSpeedMps", "maxSpeedNearHumansMps"] {
673        if let Some(pv) = scope_num(p, key) {
674            match scope_num(c, key) {
675                Some(cv) if cv <= pv => {}
676                _ => return false,
677            }
678        }
679    }
680
681    if let Some(pz) = p.get("allowedZones").and_then(|v| v.as_array()) {
682        let pset: Vec<&str> = pz.iter().filter_map(|z| z.as_str()).collect();
683        let cz: Vec<&str> = c
684            .get("allowedZones")
685            .and_then(|v| v.as_array())
686            .map(|a| a.iter().filter_map(|z| z.as_str()).collect())
687            .unwrap_or_default();
688        if cz.is_empty() || !cz.iter().all(|z| pset.contains(z)) {
689            return false;
690        }
691    }
692
693    if let Some(pw) = p.get("shiftWindows").and_then(|v| v.as_array()) {
694        let empty_arr = Vec::new();
695        let cw = c
696            .get("shiftWindows")
697            .and_then(|v| v.as_array())
698            .unwrap_or(&empty_arr);
699        for cwin in cw {
700            let (cs, ce) = window_bounds(cwin);
701            let fits = pw.iter().any(|pwin| {
702                let (ps, pe) = window_bounds(pwin);
703                ps.as_str() <= cs.as_str() && ce.as_str() <= pe.as_str()
704            });
705            if !fits {
706                return false;
707            }
708        }
709    }
710
711    true
712}
713
714// ---------------------------------------------------------------------------
715// Robot-to-robot trust handshake (Phase 5.4)
716// ---------------------------------------------------------------------------
717
718pub const HELLO: &str = "handshake_hello";
719pub const ACCEPT: &str = "handshake_accept";
720pub const CONFIRM: &str = "handshake_confirm";
721
722/// Decides whether a peer DID is trusted: its did:web domain must be allowed, or
723/// `accept_unknown` is set.
724#[derive(Debug, Clone, Default)]
725pub struct TrustPolicy {
726    pub trusted_domains: HashSet<String>,
727    pub accept_unknown: bool,
728}
729
730impl TrustPolicy {
731    pub fn new(domains: impl IntoIterator<Item = String>, accept_unknown: bool) -> Self {
732        Self {
733            trusted_domains: domains.into_iter().collect(),
734            accept_unknown,
735        }
736    }
737
738    pub fn is_trusted(&self, did: &str) -> bool {
739        if self.accept_unknown {
740            return true;
741        }
742        match did_web_domain(did) {
743            Some(d) => self.trusted_domains.contains(d),
744            None => false,
745        }
746    }
747}
748
749/// The agreed cooperation session after a successful handshake.
750#[derive(Debug, Clone)]
751pub struct BoundedSession {
752    pub session_id: String,
753    pub initiator: String,
754    pub responder: String,
755    pub scope: Vec<String>,
756    pub nonce: String,
757    pub valid_until: Option<String>,
758}
759
760fn did_web_domain(did: &str) -> Option<&str> {
761    let rest = did.strip_prefix("did:web:")?;
762    let domain = rest.split(':').next().unwrap_or("");
763    if domain.is_empty() {
764        None
765    } else {
766        Some(domain)
767    }
768}
769
770/// Parameters for [`build_hello`]. `nonce` and `issued_at` are caller-supplied so
771/// the core stays deterministic; the wrapper SDKs generate them.
772#[derive(Debug, Clone, Default)]
773pub struct BuildHello {
774    pub from_did: String,
775    pub proposed_scope: Vec<String>,
776    pub nonce: String,
777    pub peer_did: Option<String>,
778    pub issued_at: String,
779}
780
781/// Open the handshake (initiator A): a proposed scope and a fresh nonce, signed.
782pub fn build_hello(signer_seed: &[u8], params: &BuildHello) -> Result<Value> {
783    let mut hello = Map::new();
784    hello.insert("type".into(), json!(HELLO));
785    hello.insert("from".into(), json!(params.from_did));
786    hello.insert(
787        "to".into(),
788        match &params.peer_did {
789            Some(p) => json!(p),
790            None => Value::Null,
791        },
792    );
793    hello.insert("nonce".into(), json!(params.nonce));
794    hello.insert("proposedScope".into(), json!(params.proposed_scope));
795    hello.insert("issuedAt".into(), json!(params.issued_at));
796    let opts = BuildProofOptions::new(format!("{}#key-1", params.from_did), &params.issued_at);
797    data_integrity::sign(&Value::Object(hello), signer_seed, &opts)
798}
799
800/// Parameters for [`build_accept`].
801#[derive(Debug, Clone, Default)]
802pub struct BuildAccept {
803    pub from_did: String,
804    pub offered_scope: Vec<String>,
805    pub session_id: String,
806    pub valid_until: String,
807    pub created: String,
808}
809
810/// Verify A's HELLO and identity domain, intersect the scope, and sign an
811/// acceptance (responder B). Errors if A is untrusted or the HELLO is invalid.
812pub fn build_accept(
813    signer_seed: &[u8],
814    hello: &Value,
815    hello_public_key: &[u8],
816    policy: &TrustPolicy,
817    params: &BuildAccept,
818) -> Result<Value> {
819    if hello.get("type").and_then(|v| v.as_str()) != Some(HELLO) {
820        return Err(CoreError::Json("not a HELLO message".into()));
821    }
822    if !data_integrity::verify_proof(hello, hello_public_key)? {
823        return Err(CoreError::Json("HELLO signature invalid".into()));
824    }
825    let initiator = hello.get("from").and_then(|v| v.as_str()).unwrap_or("");
826    if !policy.is_trusted(initiator) {
827        return Err(CoreError::Json(format!(
828            "peer {initiator} is not in this trust domain's policy"
829        )));
830    }
831
832    let offered: HashSet<&str> = params.offered_scope.iter().map(|s| s.as_str()).collect();
833    let empty = Vec::new();
834    let proposed = hello
835        .get("proposedScope")
836        .and_then(|v| v.as_array())
837        .unwrap_or(&empty);
838    let mut seen: HashSet<String> = HashSet::new();
839    let mut bounded: Vec<String> = Vec::new();
840    for item in proposed {
841        if let Some(s) = item.as_str() {
842            if offered.contains(s) && seen.insert(s.to_string()) {
843                bounded.push(s.to_string());
844            }
845        }
846    }
847    bounded.sort();
848
849    let mut accept = Map::new();
850    accept.insert("type".into(), json!(ACCEPT));
851    accept.insert("from".into(), json!(params.from_did));
852    accept.insert("to".into(), json!(initiator));
853    accept.insert("sessionId".into(), json!(params.session_id));
854    accept.insert(
855        "nonce".into(),
856        hello.get("nonce").cloned().unwrap_or(Value::Null),
857    );
858    accept.insert("boundedScope".into(), json!(bounded));
859    accept.insert("validUntil".into(), json!(params.valid_until));
860    let opts = BuildProofOptions::new(format!("{}#key-1", params.from_did), &params.created);
861    data_integrity::sign(&Value::Object(accept), signer_seed, &opts)
862}
863
864/// Verify B's ACCEPT (initiator A): signature, nonce echo, and optional responder
865/// trust. Returns the bounded session on success.
866pub fn verify_accept(
867    accept: &Value,
868    accept_public_key: &[u8],
869    expected_nonce: &str,
870    policy: Option<&TrustPolicy>,
871) -> Result<Option<BoundedSession>> {
872    if accept.get("type").and_then(|v| v.as_str()) != Some(ACCEPT) {
873        return Ok(None);
874    }
875    if !data_integrity::verify_proof(accept, accept_public_key)? {
876        return Ok(None);
877    }
878    if accept.get("nonce").and_then(|v| v.as_str()) != Some(expected_nonce) {
879        return Ok(None);
880    }
881    let responder = accept.get("from").and_then(|v| v.as_str()).unwrap_or("");
882    if let Some(p) = policy {
883        if !p.is_trusted(responder) {
884            return Ok(None);
885        }
886    }
887    let scope = accept
888        .get("boundedScope")
889        .and_then(|v| v.as_array())
890        .map(|a| {
891            a.iter()
892                .filter_map(|s| s.as_str().map(String::from))
893                .collect()
894        })
895        .unwrap_or_default();
896    Ok(Some(BoundedSession {
897        session_id: accept
898            .get("sessionId")
899            .and_then(|v| v.as_str())
900            .unwrap_or("")
901            .to_string(),
902        initiator: accept
903            .get("to")
904            .and_then(|v| v.as_str())
905            .unwrap_or("")
906            .to_string(),
907        responder: responder.to_string(),
908        scope,
909        nonce: expected_nonce.to_string(),
910        valid_until: accept
911            .get("validUntil")
912            .and_then(|v| v.as_str())
913            .map(String::from),
914    }))
915}
916
917/// Sign A's confirmation of the bounded session to B.
918pub fn build_confirm(
919    signer_seed: &[u8],
920    from_did: &str,
921    session: &BoundedSession,
922    created: &str,
923) -> Result<Value> {
924    let mut confirm = Map::new();
925    confirm.insert("type".into(), json!(CONFIRM));
926    confirm.insert("from".into(), json!(from_did));
927    confirm.insert("to".into(), json!(session.responder));
928    confirm.insert("sessionId".into(), json!(session.session_id));
929    confirm.insert("nonce".into(), json!(session.nonce));
930    confirm.insert("acceptedScope".into(), json!(session.scope));
931    let opts = BuildProofOptions::new(format!("{from_did}#key-1"), created);
932    data_integrity::sign(&Value::Object(confirm), signer_seed, &opts)
933}
934
935/// Verify A's CONFIRM closes the agreed session (responder B): signature plus a
936/// matching session id and nonce.
937pub fn verify_confirm(
938    confirm: &Value,
939    confirm_public_key: &[u8],
940    session_id: &str,
941    expected_nonce: &str,
942) -> Result<bool> {
943    if confirm.get("type").and_then(|v| v.as_str()) != Some(CONFIRM) {
944        return Ok(false);
945    }
946    if !data_integrity::verify_proof(confirm, confirm_public_key)? {
947        return Ok(false);
948    }
949    let sid = confirm
950        .get("sessionId")
951        .and_then(|v| v.as_str())
952        .unwrap_or("");
953    let nonce = confirm.get("nonce").and_then(|v| v.as_str()).unwrap_or("");
954    Ok(sid == session_id && nonce == expected_nonce)
955}
956
957// ---------------------------------------------------------------------------
958// Black box and kill switch (Phase 5.5)
959// ---------------------------------------------------------------------------
960
961pub const BLACKBOX_VERSION: &str = "1.0";
962pub const KILLSWITCH_TYPE: &str = "KillSwitchCredential";
963pub const EMERGENCY_STOP: &str = "emergency_stop";
964
965/// The prevHash of the first entry: multibase of 32 zero bytes.
966pub fn genesis_prev_hash() -> String {
967    mb64(&[0u8; 32])
968}
969
970fn entry_hash(body: &Map<String, Value>) -> Result<String> {
971    let mut clean = body.clone();
972    clean.remove("entryHash");
973    let canonical = jcs::canonicalize(&Value::Object(clean));
974    Ok(mb64(&Sha256::digest(canonical)))
975}
976
977/// Build one black-box entry statelessly: encrypt `payload` under `key`, link it
978/// to `prev_hash` at `seq`, and return the entry with its `entryHash`. The
979/// stateful [`BlackBoxLog`] and the FFI layer both build on this. The encrypted
980/// blob is nonce(12) || ciphertext || tag(16).
981pub fn blackbox_append_entry(
982    key: &[u8],
983    seq: u64,
984    event: &str,
985    payload: &Value,
986    timestamp: &str,
987    prev_hash: &str,
988) -> Result<Value> {
989    if key.len() != 32 {
990        return Err(CoreError::Crypto(
991            "black box key must be 32 bytes (AES-256)".into(),
992        ));
993    }
994    let mut nonce = [0u8; 12];
995    getrandom::getrandom(&mut nonce).map_err(|e| CoreError::Crypto(format!("rng: {e}")))?;
996    let plaintext = jcs::canonicalize(payload);
997    let cipher =
998        Aes256Gcm::new_from_slice(key).map_err(|e| CoreError::Crypto(format!("aes key: {e}")))?;
999    let ct = cipher
1000        .encrypt(Nonce::from_slice(&nonce), plaintext.as_ref())
1001        .map_err(|e| CoreError::Crypto(format!("encrypt: {e}")))?;
1002    let mut blob = Vec::with_capacity(nonce.len() + ct.len());
1003    blob.extend_from_slice(&nonce);
1004    blob.extend_from_slice(&ct);
1005
1006    let mut body = Map::new();
1007    body.insert("version".into(), json!(BLACKBOX_VERSION));
1008    body.insert("seq".into(), json!(seq));
1009    body.insert("timestamp".into(), json!(timestamp));
1010    body.insert("event".into(), json!(event));
1011    body.insert("ciphertext".into(), json!(mb64(&blob)));
1012    body.insert("prevHash".into(), json!(prev_hash));
1013    let h = entry_hash(&body)?;
1014    body.insert("entryHash".into(), json!(h));
1015    Ok(Value::Object(body))
1016}
1017
1018/// An append-only, AES-256-GCM-encrypted, JCS hash-linked event log. The key is
1019/// 32 bytes. The encrypted blob is nonce(12) || ciphertext || tag(16), matching
1020/// Python, TypeScript, and Go.
1021pub struct BlackBoxLog {
1022    key: Vec<u8>,
1023    genesis: String,
1024    entries: Vec<Value>,
1025    head: String,
1026}
1027
1028impl BlackBoxLog {
1029    /// Build a log. A `None` genesis uses [`genesis_prev_hash`].
1030    pub fn new(key: &[u8], genesis_prev_hash_override: Option<&str>) -> Result<Self> {
1031        if key.len() != 32 {
1032            return Err(CoreError::Crypto(
1033                "black box key must be 32 bytes (AES-256)".into(),
1034            ));
1035        }
1036        let genesis = genesis_prev_hash_override
1037            .map(String::from)
1038            .unwrap_or_else(genesis_prev_hash);
1039        Ok(Self {
1040            key: key.to_vec(),
1041            head: genesis.clone(),
1042            genesis,
1043            entries: Vec::new(),
1044        })
1045    }
1046
1047    /// Encrypt `payload`, link it to the chain head, and return the new entry.
1048    pub fn append(&mut self, event: &str, payload: &Value, timestamp: &str) -> Result<Value> {
1049        let entry = blackbox_append_entry(
1050            &self.key,
1051            self.entries.len() as u64,
1052            event,
1053            payload,
1054            timestamp,
1055            &self.head,
1056        )?;
1057        self.head = entry
1058            .get("entryHash")
1059            .and_then(|v| v.as_str())
1060            .unwrap_or("")
1061            .to_string();
1062        self.entries.push(entry.clone());
1063        Ok(entry)
1064    }
1065
1066    pub fn head(&self) -> &str {
1067        &self.head
1068    }
1069
1070    pub fn genesis(&self) -> &str {
1071        &self.genesis
1072    }
1073
1074    pub fn entries(&self) -> &[Value] {
1075        &self.entries
1076    }
1077
1078    pub fn open(&self, entry: &Value) -> Result<Value> {
1079        open_entry(entry, &self.key)
1080    }
1081}
1082
1083/// Decrypt a black-box entry payload with the log key.
1084pub fn open_entry(entry: &Value, key: &[u8]) -> Result<Value> {
1085    let ct_mb = entry
1086        .get("ciphertext")
1087        .and_then(|v| v.as_str())
1088        .ok_or_else(|| CoreError::Json("entry has no ciphertext".into()))?;
1089    let blob = unmb64(ct_mb)?;
1090    if blob.len() < 12 + 16 {
1091        return Err(CoreError::Crypto("ciphertext too short".into()));
1092    }
1093    let cipher =
1094        Aes256Gcm::new_from_slice(key).map_err(|e| CoreError::Crypto(format!("aes key: {e}")))?;
1095    let (nonce, rest) = blob.split_at(12);
1096    let pt = cipher
1097        .decrypt(Nonce::from_slice(nonce), rest)
1098        .map_err(|_| CoreError::Crypto("decryption failed".into()))?;
1099    serde_json::from_slice(&pt).map_err(|e| CoreError::Json(format!("payload decode: {e}")))
1100}
1101
1102/// The outcome of [`verify_blackbox_chain`].
1103#[derive(Debug, Clone)]
1104pub struct ChainResult {
1105    pub ok: bool,
1106    pub reason: Option<String>,
1107}
1108
1109/// Verify the hash chain over the (still-encrypted) entries. Tamper-evident
1110/// without the key. A `None` genesis uses [`genesis_prev_hash`].
1111pub fn verify_blackbox_chain(
1112    entries: &[Value],
1113    genesis_prev_hash_override: Option<&str>,
1114) -> ChainResult {
1115    let mut prev = genesis_prev_hash_override
1116        .map(String::from)
1117        .unwrap_or_else(genesis_prev_hash);
1118    for (i, entry) in entries.iter().enumerate() {
1119        if entry.get("seq").and_then(|v| v.as_u64()) != Some(i as u64) {
1120            return ChainResult {
1121                ok: false,
1122                reason: Some(format!("entry {i} seq mismatch")),
1123            };
1124        }
1125        if entry.get("prevHash").and_then(|v| v.as_str()).unwrap_or("") != prev {
1126            return ChainResult {
1127                ok: false,
1128                reason: Some(format!("entry {i} prevHash does not link")),
1129            };
1130        }
1131        let obj = match entry.as_object() {
1132            Some(o) => o,
1133            None => {
1134                return ChainResult {
1135                    ok: false,
1136                    reason: Some(format!("entry {i} is not an object")),
1137                }
1138            }
1139        };
1140        let want = match entry_hash(obj) {
1141            Ok(w) => w,
1142            Err(_) => {
1143                return ChainResult {
1144                    ok: false,
1145                    reason: Some(format!("entry {i} hash error")),
1146                }
1147            }
1148        };
1149        let eh = entry
1150            .get("entryHash")
1151            .and_then(|v| v.as_str())
1152            .unwrap_or("");
1153        if eh != want {
1154            return ChainResult {
1155                ok: false,
1156                reason: Some(format!("entry {i} entryHash mismatch (tampered)")),
1157            };
1158        }
1159        prev = eh.to_string();
1160    }
1161    ChainResult {
1162        ok: true,
1163        reason: None,
1164    }
1165}
1166
1167/// Parameters for [`build_killswitch_credential`].
1168#[derive(Debug, Clone, Default)]
1169pub struct BuildKillswitch {
1170    pub issuer_did: String,
1171    pub target: String,
1172    pub reason: String,
1173    pub command: Option<String>,
1174    pub scope: Option<Vec<String>>,
1175    pub valid_from: String,
1176    pub valid_until: Option<String>,
1177}
1178
1179/// Build a signed `KillSwitchCredential` proving who issued an emergency stop.
1180pub fn build_killswitch_credential(
1181    authority_seed: &[u8],
1182    params: &BuildKillswitch,
1183) -> Result<Value> {
1184    let command = params
1185        .command
1186        .clone()
1187        .unwrap_or_else(|| EMERGENCY_STOP.to_string());
1188    let mut subject = Map::new();
1189    subject.insert("id".into(), json!(params.target));
1190    subject.insert("command".into(), json!(command));
1191    subject.insert("reason".into(), json!(params.reason));
1192    subject.insert("issuedBy".into(), json!(params.issuer_did));
1193    if let Some(scope) = &params.scope {
1194        subject.insert("scope".into(), json!(scope));
1195    }
1196
1197    let mut cred = Map::new();
1198    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
1199    cred.insert(
1200        "type".into(),
1201        json!(["VerifiableCredential", KILLSWITCH_TYPE]),
1202    );
1203    cred.insert("issuer".into(), json!(params.issuer_did));
1204    cred.insert("validFrom".into(), json!(params.valid_from));
1205    if let Some(vu) = &params.valid_until {
1206        cred.insert("validUntil".into(), json!(vu));
1207    }
1208    cred.insert("credentialSubject".into(), Value::Object(subject));
1209
1210    let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), &params.valid_from);
1211    data_integrity::sign(&Value::Object(cred), authority_seed, &opts)
1212}
1213
1214/// Verify a `KillSwitchCredential`. When `trusted_authorities` is supplied, the
1215/// issuer DID MUST be in it. Returns the subject on success.
1216pub fn verify_killswitch_credential(
1217    credential: &Value,
1218    public_key: &[u8],
1219    trusted_authorities: Option<&HashSet<String>>,
1220) -> Result<Option<Value>> {
1221    if !has_type(credential.get("type"), KILLSWITCH_TYPE) {
1222        return Ok(None);
1223    }
1224    if !data_integrity::verify_proof(credential, public_key)? {
1225        return Ok(None);
1226    }
1227    if let Some(trusted) = trusted_authorities {
1228        let issuer = credential
1229            .get("issuer")
1230            .and_then(|v| v.as_str())
1231            .unwrap_or("");
1232        if !trusted.contains(issuer) {
1233            return Ok(None);
1234        }
1235    }
1236    Ok(credential.get("credentialSubject").cloned())
1237}
1238
1239// ---------------------------------------------------------------------------
1240// Halos safety-evidence recorder (NVIDIA Halos integration)
1241// ---------------------------------------------------------------------------
1242//
1243// Byte-exact port of the Python reference `vouch/robotics/halos.py`.
1244//
1245// Halos certifies that a robot's stack is functionally safe and secure by design.
1246// It does not, on its own, produce a verifiable record of what a specific robot
1247// did or bind that record to the robot's identity. This is the evidence layer
1248// under a Halos-certified stack: the robot seals its black-box chain head and
1249// entry count into a signed `HalosSafetyEvidenceCredential` that binds them to its
1250// identity, to the Halos stack elements it ran on, and to a time window. A
1251// verifier that holds the credential and the entries confirms, without the
1252// black-box key, that the record is unaltered, was not truncated or extended since
1253// it was sealed, and is attributable to that robot. This composes the existing
1254// black-box and credential primitives and adds no new cryptography.
1255
1256pub const HALOS_SAFETY_EVIDENCE_TYPE: &str = "HalosSafetyEvidenceCredential";
1257
1258/// Format Unix epoch seconds as "YYYY-MM-DDTHH:MM:SSZ" for a whole-second UTC
1259/// instant. Howard Hinnant's civil-from-days algorithm, matching the rest of the
1260/// core so a `valid_seconds` lifetime renders identically across languages.
1261fn halos_epoch_to_iso(epoch: i64) -> String {
1262    let days = epoch.div_euclid(86400);
1263    let secs = epoch.rem_euclid(86400);
1264    let z = days + 719468;
1265    let era = (if z >= 0 { z } else { z - 146096 }) / 146097;
1266    let doe = z - era * 146097;
1267    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
1268    let y = yoe + era * 400;
1269    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1270    let mp = (5 * doy + 2) / 153;
1271    let d = doy - (153 * mp + 2) / 5 + 1;
1272    let m = if mp < 10 { mp + 3 } else { mp - 9 };
1273    let year = if m <= 2 { y + 1 } else { y };
1274    let hh = secs / 3600;
1275    let mm = (secs % 3600) / 60;
1276    let ss = secs % 60;
1277    format!("{year:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}Z")
1278}
1279
1280/// Parameters for [`build_safety_evidence`]. The robot DID is derived from
1281/// `signer_seed` (a did:key), mirroring the Python signer. `blackbox_head` and
1282/// `entry_count` seal the robot's black-box chain; `halos_stack` names the
1283/// certified configuration; `window` covers the recorded events. Timestamps are
1284/// caller-supplied ISO-8601 strings.
1285#[derive(Debug, Clone)]
1286pub struct BuildSafetyEvidence {
1287    pub halos_stack: Value,
1288    pub window_from: String,
1289    pub window_to: String,
1290    pub blackbox_head: String,
1291    pub entry_count: u64,
1292    pub robot_identity: Option<String>,
1293    pub valid_seconds: Option<i64>,
1294    pub valid_from: String,
1295    pub created: String,
1296}
1297
1298/// Seal a robot's Halos safety-event record into a signed
1299/// `HalosSafetyEvidenceCredential`. The robot signs a credential binding the
1300/// black-box chain head and entry count to its identity, to the Halos stack
1301/// elements it ran on, and to the time window.
1302pub fn build_safety_evidence(signer_seed: &[u8], params: &BuildSafetyEvidence) -> Result<Value> {
1303    match params.halos_stack.as_object() {
1304        Some(o) if !o.is_empty() => {}
1305        _ => return Err(CoreError::Json("halos_stack is required".into())),
1306    }
1307    if params.window_from.is_empty() || params.window_to.is_empty() {
1308        return Err(CoreError::Json(
1309            "window with 'from' and 'to' is required".into(),
1310        ));
1311    }
1312
1313    let kp = keys::Ed25519KeyPair::from_seed_slice(signer_seed)?;
1314    let robot_did = keys::ed25519_to_did_key(&kp.public_key())?;
1315
1316    let mut subject = Map::new();
1317    subject.insert("id".into(), json!(robot_did));
1318    subject.insert("blackboxHead".into(), json!(params.blackbox_head));
1319    subject.insert("entryCount".into(), json!(params.entry_count));
1320    subject.insert("halosStack".into(), params.halos_stack.clone());
1321    subject.insert(
1322        "window".into(),
1323        json!({ "from": params.window_from, "to": params.window_to }),
1324    );
1325    if let Some(robot_identity) = &params.robot_identity {
1326        subject.insert("robotIdentity".into(), json!(robot_identity));
1327    }
1328
1329    let mut cred = Map::new();
1330    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
1331    cred.insert(
1332        "type".into(),
1333        json!(["VerifiableCredential", HALOS_SAFETY_EVIDENCE_TYPE]),
1334    );
1335    cred.insert("issuer".into(), json!(robot_did));
1336    cred.insert("validFrom".into(), json!(params.valid_from));
1337    if let Some(valid_seconds) = params.valid_seconds {
1338        let from = crate::time::iso_to_epoch_seconds(&params.valid_from)?;
1339        cred.insert(
1340            "validUntil".into(),
1341            json!(halos_epoch_to_iso(from + valid_seconds)),
1342        );
1343    }
1344    cred.insert("credentialSubject".into(), Value::Object(subject));
1345
1346    let opts = BuildProofOptions::new(format!("{robot_did}#key-1"), &params.created);
1347    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
1348}
1349
1350/// Verify a `HalosSafetyEvidenceCredential`: the robot's proof and that the issuer
1351/// is the robot (`credentialSubject.id`). When `entries` is supplied, also checks
1352/// that the black-box chain is intact, that its length matches the sealed entry
1353/// count, and that its head matches the sealed head, so a truncated, extended,
1354/// reordered, or tampered record is rejected. Returns `(ok, credentialSubject)`.
1355pub fn verify_safety_evidence(
1356    credential: &Value,
1357    robot_public_key: &[u8],
1358    entries: Option<&[Value]>,
1359) -> Result<(bool, Option<Value>)> {
1360    if !has_type(credential.get("type"), HALOS_SAFETY_EVIDENCE_TYPE) {
1361        return Ok((false, None));
1362    }
1363    if !data_integrity::verify_proof(credential, robot_public_key)? {
1364        return Ok((false, None));
1365    }
1366
1367    let subject = match credential.get("credentialSubject") {
1368        Some(s) if s.is_object() => s.clone(),
1369        _ => return Ok((false, None)),
1370    };
1371    let subject_id = subject.get("id").and_then(|v| v.as_str());
1372    if subject_id.is_none() || subject_id != credential.get("issuer").and_then(|v| v.as_str()) {
1373        return Ok((false, None));
1374    }
1375
1376    if let Some(entries) = entries {
1377        if !verify_blackbox_chain(entries, None).ok {
1378            return Ok((false, None));
1379        }
1380        if subject.get("entryCount").and_then(|v| v.as_u64()) != Some(entries.len() as u64) {
1381            return Ok((false, None));
1382        }
1383        let head = match entries.last() {
1384            Some(last) => last
1385                .get("entryHash")
1386                .and_then(|v| v.as_str())
1387                .unwrap_or("")
1388                .to_string(),
1389            None => genesis_prev_hash(),
1390        };
1391        if Some(head.as_str()) != subject.get("blackboxHead").and_then(|v| v.as_str()) {
1392            return Ok((false, None));
1393        }
1394    }
1395
1396    Ok((true, Some(subject)))
1397}
1398
1399// ---------------------------------------------------------------------------
1400// Scannable robot passport (Phase 5.6)
1401// ---------------------------------------------------------------------------
1402
1403pub const ROBOT_PASSPORT_TYPE: &str = "RobotPassport";
1404pub const PASSPORT_URI_SCHEME: &str = "vouch-passport:";
1405pub const STATUS_ACTIVE: &str = "active";
1406pub const STATUS_SUSPENDED: &str = "suspended";
1407pub const STATUS_DECOMMISSIONED: &str = "decommissioned";
1408
1409/// Parameters for [`build_passport`]. The issuer is the signer (the robot or an
1410/// authority); `robot_did` is the robot the passport describes.
1411#[derive(Debug, Clone, Default)]
1412pub struct BuildPassport {
1413    pub issuer_did: String,
1414    pub robot_did: String,
1415    pub make: String,
1416    pub model: String,
1417    pub owner: String,
1418    pub authorized_actions: Vec<String>,
1419    pub certification: Option<String>,
1420    pub status: Option<String>,
1421    pub valid_from: String,
1422    pub valid_until: Option<String>,
1423}
1424
1425/// Build a signed `RobotPassport` credential.
1426pub fn build_passport(signer_seed: &[u8], params: &BuildPassport) -> Result<Value> {
1427    let status = params
1428        .status
1429        .clone()
1430        .unwrap_or_else(|| STATUS_ACTIVE.to_string());
1431    let mut subject = Map::new();
1432    subject.insert("id".into(), json!(params.robot_did));
1433    subject.insert("make".into(), json!(params.make));
1434    subject.insert("model".into(), json!(params.model));
1435    subject.insert("owner".into(), json!(params.owner));
1436    subject.insert("authorizedActions".into(), json!(params.authorized_actions));
1437    subject.insert("status".into(), json!(status));
1438    if let Some(c) = &params.certification {
1439        subject.insert("certification".into(), json!(c));
1440    }
1441
1442    let mut cred = Map::new();
1443    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
1444    cred.insert(
1445        "type".into(),
1446        json!(["VerifiableCredential", ROBOT_PASSPORT_TYPE]),
1447    );
1448    cred.insert("issuer".into(), json!(params.issuer_did));
1449    cred.insert("validFrom".into(), json!(params.valid_from));
1450    if let Some(vu) = &params.valid_until {
1451        cred.insert("validUntil".into(), json!(vu));
1452    }
1453    cred.insert("credentialSubject".into(), Value::Object(subject));
1454
1455    let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), &params.valid_from);
1456    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
1457}
1458
1459/// Encode a passport into a compact `vouch-passport:` URI for a QR or NFC tag.
1460pub fn encode_passport(passport: &Value) -> String {
1461    format!(
1462        "{}{}",
1463        PASSPORT_URI_SCHEME,
1464        mb64(&jcs::canonicalize(passport))
1465    )
1466}
1467
1468/// Decode a `vouch-passport:` URI back into the passport credential.
1469pub fn decode_passport(uri: &str) -> Result<Value> {
1470    let body = uri
1471        .strip_prefix(PASSPORT_URI_SCHEME)
1472        .ok_or_else(|| CoreError::Json(format!("not a {PASSPORT_URI_SCHEME} URI")))?;
1473    let raw = unmb64(body)?;
1474    serde_json::from_slice(&raw).map_err(|e| CoreError::Json(format!("passport decode: {e}")))
1475}
1476
1477/// Verify a passport credential. A suspended or decommissioned status still
1478/// verifies but is surfaced in the subject so a scanner can refuse; an expired
1479/// passport fails. `now_iso` is the verifier's clock. Returns the subject.
1480pub fn verify_passport(
1481    passport: &Value,
1482    public_key: &[u8],
1483    now_iso: &str,
1484) -> Result<Option<Value>> {
1485    if !has_type(passport.get("type"), ROBOT_PASSPORT_TYPE) {
1486        return Ok(None);
1487    }
1488    if !data_integrity::verify_proof(passport, public_key)? {
1489        return Ok(None);
1490    }
1491    if let Some(vu) = passport.get("validUntil").and_then(|v| v.as_str()) {
1492        if let (Ok(vu_e), Ok(now_e)) = (
1493            crate::time::iso_to_epoch_seconds(vu),
1494            crate::time::iso_to_epoch_seconds(now_iso),
1495        ) {
1496            if now_e > vu_e {
1497                return Ok(None);
1498            }
1499        }
1500    }
1501    Ok(passport.get("credentialSubject").cloned())
1502}
1503
1504/// Decode a `vouch-passport:` URI and verify it. Returns `None` on a malformed URI.
1505pub fn verify_passport_uri(uri: &str, public_key: &[u8], now_iso: &str) -> Result<Option<Value>> {
1506    match decode_passport(uri) {
1507        Ok(p) => verify_passport(&p, public_key, now_iso),
1508        Err(_) => Ok(None),
1509    }
1510}
1511
1512// ---------------------------------------------------------------------------
1513// Liveness heartbeat with safety-envelope conformance (Phase 5.7)
1514// ---------------------------------------------------------------------------
1515
1516pub const ROBOT_HEARTBEAT_TYPE: &str = "RobotHeartbeatCredential";
1517
1518/// Default number of missed intervals tolerated before trust is considered stale.
1519pub const DEFAULT_GRACE_INTERVALS: i64 = 2;
1520
1521/// One observed motion sample. `None` numerics mean "not specified" (a meaningful
1522/// zero is still `Some(0.0)`), matching [`PhysicalAction`].
1523#[derive(Debug, Clone, Default)]
1524pub struct MotionSample {
1525    pub force_n: Option<f64>,
1526    pub speed_mps: Option<f64>,
1527    pub near_humans: bool,
1528    pub zone: Option<String>,
1529    pub time_hm: Option<String>,
1530}
1531
1532/// Collector for per-interval motion telemetry. It accumulates aggregates of what
1533/// the robot physically did over a heartbeat interval and, when given a physical
1534/// scope, counts how many samples fell outside the declared envelope. The
1535/// physical analogue of the agent behavioral digest.
1536///
1537/// With `scope` set to `None` the digest still reports observed maxima but cannot
1538/// judge conformance, so it reports `withinEnvelope` true with a zero breach
1539/// count, mirroring the Python `MotionCollector`.
1540#[derive(Debug, Clone, Default)]
1541pub struct MotionCollector {
1542    scope: Option<Value>,
1543    samples: u64,
1544    max_force: f64,
1545    max_speed: f64,
1546    max_speed_near: f64,
1547    zone_breaches: u64,
1548    breaches: u64,
1549}
1550
1551impl MotionCollector {
1552    /// A collector that judges samples against `scope` (the
1553    /// `credentialSubject.physicalScope` object). Pass `None` to only aggregate.
1554    pub fn new(scope: Option<Value>) -> Self {
1555        Self {
1556            scope,
1557            ..Default::default()
1558        }
1559    }
1560
1561    /// Record a single observed motion sample, updating the running aggregates and
1562    /// (when a scope is set) the breach counts.
1563    pub fn record(&mut self, sample: &MotionSample) -> Result<()> {
1564        if let Some(f) = sample.force_n {
1565            if f < 0.0 {
1566                return Err(CoreError::Json(format!(
1567                    "force_n must be non-negative, got {f}"
1568                )));
1569            }
1570        }
1571        if let Some(s) = sample.speed_mps {
1572            if s < 0.0 {
1573                return Err(CoreError::Json(format!(
1574                    "speed_mps must be non-negative, got {s}"
1575                )));
1576            }
1577        }
1578
1579        self.samples += 1;
1580        if let Some(f) = sample.force_n {
1581            self.max_force = self.max_force.max(f);
1582        }
1583        if let Some(s) = sample.speed_mps {
1584            self.max_speed = self.max_speed.max(s);
1585            if sample.near_humans {
1586                self.max_speed_near = self.max_speed_near.max(s);
1587            }
1588        }
1589
1590        if let Some(scope) = &self.scope {
1591            let action = PhysicalAction {
1592                force_n: sample.force_n,
1593                speed_mps: sample.speed_mps,
1594                near_humans: sample.near_humans,
1595                zone: sample.zone.clone(),
1596                time_hm: sample.time_hm.clone(),
1597            };
1598            let result = check_physical_action(scope, &action);
1599            if !result.ok {
1600                self.breaches += 1;
1601                if result
1602                    .reasons
1603                    .iter()
1604                    .any(|r| r.starts_with("zone_not_allowed"))
1605                {
1606                    self.zone_breaches += 1;
1607                }
1608            }
1609        }
1610        Ok(())
1611    }
1612
1613    /// Return the `motionDigest` object for embedding in a heartbeat credential.
1614    pub fn digest(&self) -> Value {
1615        json!({
1616            "samples": self.samples,
1617            "maxForceN": self.max_force,
1618            "maxSpeedMps": self.max_speed,
1619            "maxSpeedNearHumansMps": self.max_speed_near,
1620            "zoneBreaches": self.zone_breaches,
1621            "breachCount": self.breaches,
1622            "withinEnvelope": self.breaches == 0,
1623        })
1624    }
1625
1626    /// Clear all state. Call after submitting a heartbeat to start fresh.
1627    pub fn reset(&mut self) {
1628        self.samples = 0;
1629        self.max_force = 0.0;
1630        self.max_speed = 0.0;
1631        self.max_speed_near = 0.0;
1632        self.zone_breaches = 0;
1633        self.breaches = 0;
1634    }
1635}
1636
1637fn digest_non_negative_int(digest: &Map<String, Value>, name: &str) -> Result<()> {
1638    match digest.get(name) {
1639        Some(v) if v.is_u64() => Ok(()),
1640        Some(Value::Number(n)) if n.as_i64().map(|i| i >= 0).unwrap_or(false) => Ok(()),
1641        Some(_) => Err(CoreError::Json(format!(
1642            "motionDigest.{name} must be a non-negative integer"
1643        ))),
1644        None => Err(CoreError::Json(format!("motionDigest.{name} is required"))),
1645    }
1646}
1647
1648/// Structural validation of a `motionDigest` object. Does not judge whether the
1649/// values are acceptable; that is policy, expressed through [`is_live`].
1650pub fn validate_motion_digest(digest: &Value) -> Result<()> {
1651    let obj = digest
1652        .as_object()
1653        .ok_or_else(|| CoreError::Json("motionDigest must be an object".into()))?;
1654
1655    for name in ["samples", "zoneBreaches", "breachCount"] {
1656        digest_non_negative_int(obj, name)?;
1657    }
1658    for name in ["maxForceN", "maxSpeedMps", "maxSpeedNearHumansMps"] {
1659        match obj.get(name) {
1660            Some(Value::Bool(_)) | None => {
1661                return Err(CoreError::Json(format!("motionDigest.{name} is required")))
1662            }
1663            Some(v) => {
1664                let n = v.as_f64().ok_or_else(|| {
1665                    CoreError::Json(format!("motionDigest.{name} must be a number"))
1666                })?;
1667                if n < 0.0 {
1668                    return Err(CoreError::Json(format!(
1669                        "motionDigest.{name} must be non-negative"
1670                    )));
1671                }
1672            }
1673        }
1674    }
1675    match obj.get("withinEnvelope") {
1676        Some(Value::Bool(_)) => Ok(()),
1677        Some(_) => Err(CoreError::Json(
1678            "motionDigest.withinEnvelope must be a boolean".into(),
1679        )),
1680        None => Err(CoreError::Json(
1681            "motionDigest.withinEnvelope is required".into(),
1682        )),
1683    }
1684}
1685
1686/// Parameters for [`build_robot_heartbeat`]. The robot self-issues the credential
1687/// with its own Ed25519 seed; `motion_digest` is produced by a [`MotionCollector`]
1688/// over the interval and `interval_seconds` is the declared heartbeat cadence.
1689#[derive(Debug, Clone)]
1690pub struct BuildRobotHeartbeat {
1691    pub robot_did: String,
1692    pub session_id: String,
1693    pub interval_index: i64,
1694    pub interval_seconds: i64,
1695    pub motion_digest: Value,
1696    pub valid_from: String,
1697}
1698
1699/// Build a signed `RobotHeartbeatCredential`.
1700pub fn build_robot_heartbeat(robot_seed: &[u8], params: &BuildRobotHeartbeat) -> Result<Value> {
1701    if params.interval_index < 0 {
1702        return Err(CoreError::Json(
1703            "interval_index must be non-negative".into(),
1704        ));
1705    }
1706    if params.interval_seconds <= 0 {
1707        return Err(CoreError::Json("interval_seconds must be positive".into()));
1708    }
1709    validate_motion_digest(&params.motion_digest)?;
1710
1711    let mut subject = Map::new();
1712    subject.insert("id".into(), json!(params.robot_did));
1713    subject.insert("sessionId".into(), json!(params.session_id));
1714    subject.insert("intervalIndex".into(), json!(params.interval_index));
1715    subject.insert("intervalSeconds".into(), json!(params.interval_seconds));
1716    subject.insert("motionDigest".into(), params.motion_digest.clone());
1717
1718    let mut cred = Map::new();
1719    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
1720    cred.insert(
1721        "type".into(),
1722        json!(["VerifiableCredential", ROBOT_HEARTBEAT_TYPE]),
1723    );
1724    cred.insert("issuer".into(), json!(params.robot_did));
1725    cred.insert("validFrom".into(), json!(params.valid_from));
1726    cred.insert("credentialSubject".into(), Value::Object(subject));
1727
1728    let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), &params.valid_from);
1729    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
1730}
1731
1732/// Verify a `RobotHeartbeatCredential`: the credential proof (robot key) and the
1733/// structural validity of the embedded motion digest. Returns the subject on
1734/// success. Whether the robot is currently trusted is a separate, time-dependent
1735/// question answered by [`is_live`].
1736pub fn verify_robot_heartbeat(
1737    credential: &Value,
1738    robot_public_key: &[u8],
1739) -> Result<Option<Value>> {
1740    if !has_type(credential.get("type"), ROBOT_HEARTBEAT_TYPE) {
1741        return Ok(None);
1742    }
1743    if !data_integrity::verify_proof(credential, robot_public_key)? {
1744        return Ok(None);
1745    }
1746    let subject = match credential.get("credentialSubject") {
1747        Some(s) if s.is_object() => s,
1748        _ => return Ok(None),
1749    };
1750    let digest = subject.get("motionDigest").cloned().unwrap_or(Value::Null);
1751    if validate_motion_digest(&digest).is_err() {
1752        return Ok(None);
1753    }
1754    Ok(Some(subject.clone()))
1755}
1756
1757/// Decide whether a robot is currently trusted, given its most recent heartbeat.
1758/// A robot is live only if BOTH hold: the digest reports `withinEnvelope` true,
1759/// and the heartbeat was issued within `grace_intervals` cadence periods of
1760/// `now_iso`. `interval_seconds` (when `Some`) overrides the heartbeat's
1761/// self-declared cadence.
1762pub fn is_live(
1763    credential: &Value,
1764    now_iso: &str,
1765    interval_seconds: Option<i64>,
1766    grace_intervals: i64,
1767) -> Result<bool> {
1768    let subject = credential
1769        .get("credentialSubject")
1770        .and_then(|s| s.as_object());
1771    let digest = subject
1772        .and_then(|s| s.get("motionDigest"))
1773        .and_then(|d| d.as_object());
1774    let within = digest
1775        .and_then(|d| d.get("withinEnvelope"))
1776        .and_then(|v| v.as_bool())
1777        .unwrap_or(false);
1778    if !within {
1779        return Ok(false);
1780    }
1781
1782    let cadence = match interval_seconds {
1783        Some(c) => c,
1784        None => subject
1785            .and_then(|s| s.get("intervalSeconds"))
1786            .and_then(|v| v.as_i64())
1787            .unwrap_or(0),
1788    };
1789    if cadence <= 0 {
1790        return Ok(false);
1791    }
1792    if grace_intervals < 1 {
1793        return Err(CoreError::Json("grace_intervals must be at least 1".into()));
1794    }
1795
1796    let raw = match credential.get("validFrom").and_then(|v| v.as_str()) {
1797        Some(s) if !s.is_empty() => s,
1798        _ => return Ok(false),
1799    };
1800    let issued = match crate::time::iso_to_epoch_seconds(raw) {
1801        Ok(t) => t,
1802        Err(_) => return Ok(false),
1803    };
1804    let moment = match crate::time::iso_to_epoch_seconds(now_iso) {
1805        Ok(t) => t,
1806        Err(_) => return Ok(false),
1807    };
1808    let deadline = issued + cadence * grace_intervals;
1809    // A heartbeat from the future (clock skew beyond one cadence) is not trusted.
1810    if moment + cadence < issued {
1811        return Ok(false);
1812    }
1813    Ok(moment <= deadline)
1814}
1815
1816// ---------------------------------------------------------------------------
1817// Per-credential revocation (Phase 5.8)
1818// ---------------------------------------------------------------------------
1819
1820pub use crate::status_list::{BITSTRING_STATUS_LIST_ENTRY_TYPE, STATUS_PURPOSE_REVOCATION};
1821
1822/// Build a BitstringStatusList `credentialStatus` entry referencing a bit index in
1823/// a published status list credential. Mirrors the agent-side
1824/// `status_list.build_status_list_entry`. `entry_id`, when `None`, defaults to
1825/// `{status_list_credential}#{status_list_index}`.
1826pub fn build_status_list_entry(
1827    status_list_credential: &str,
1828    status_list_index: i64,
1829    status_purpose: &str,
1830    entry_id: Option<&str>,
1831) -> Result<Value> {
1832    if !matches!(status_purpose, "revocation" | "suspension" | "message") {
1833        return Err(CoreError::Json(format!(
1834            "status_purpose must be one of revocation, suspension, message, got {status_purpose:?}"
1835        )));
1836    }
1837    if status_list_index < 0 {
1838        return Err(CoreError::Json(
1839            "status_list_index must be non-negative".into(),
1840        ));
1841    }
1842    if status_list_credential.is_empty() {
1843        return Err(CoreError::Json(
1844            "status_list_credential URL is required".into(),
1845        ));
1846    }
1847    let id = entry_id
1848        .map(String::from)
1849        .unwrap_or_else(|| format!("{status_list_credential}#{status_list_index}"));
1850    Ok(json!({
1851        "id": id,
1852        "type": BITSTRING_STATUS_LIST_ENTRY_TYPE,
1853        "statusPurpose": status_purpose,
1854        "statusListIndex": status_list_index.to_string(),
1855        "statusListCredential": status_list_credential,
1856    }))
1857}
1858
1859/// Parameters for [`attach_credential_status`].
1860#[derive(Debug, Clone)]
1861pub struct AttachCredentialStatus {
1862    pub status_list_credential: String,
1863    pub status_list_index: i64,
1864    pub status_purpose: String,
1865    pub entry_id: Option<String>,
1866    /// `validFrom`-style timestamp used as the proof `created` when re-signing.
1867    pub created: String,
1868}
1869
1870/// Add a BitstringStatusList `credentialStatus` entry to a robot credential and
1871/// re-sign it under `signer_seed`, so the proof covers the status binding. If the
1872/// credential already carries a `credentialStatus`, the new entry is appended (the
1873/// field becomes a list), matching the Verifiable Credentials data model. Any
1874/// pre-existing proof is replaced.
1875pub fn attach_credential_status(
1876    credential: &Value,
1877    signer_seed: &[u8],
1878    params: &AttachCredentialStatus,
1879) -> Result<Value> {
1880    let entry = build_status_list_entry(
1881        &params.status_list_credential,
1882        params.status_list_index,
1883        &params.status_purpose,
1884        params.entry_id.as_deref(),
1885    )?;
1886
1887    let mut obj = credential
1888        .as_object()
1889        .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
1890        .clone();
1891
1892    match obj.get("credentialStatus").cloned() {
1893        None => {
1894            obj.insert("credentialStatus".into(), entry);
1895        }
1896        Some(Value::Array(mut existing)) => {
1897            existing.push(entry);
1898            obj.insert("credentialStatus".into(), Value::Array(existing));
1899        }
1900        Some(existing) => {
1901            obj.insert("credentialStatus".into(), json!([existing, entry]));
1902        }
1903    }
1904
1905    // Re-sign: the proof must cover the credentialStatus we just added.
1906    obj.remove("proof");
1907    let issuer = obj.get("issuer").and_then(|v| v.as_str()).unwrap_or("");
1908    let opts = BuildProofOptions::new(format!("{issuer}#key-1"), &params.created);
1909    data_integrity::sign(&Value::Object(obj), signer_seed, &opts)
1910}
1911
1912fn status_entries(credential: &Value) -> Result<Vec<Value>> {
1913    match credential.get("credentialStatus") {
1914        None => Ok(Vec::new()),
1915        Some(Value::Array(a)) => Ok(a.iter().filter(|e| e.is_object()).cloned().collect()),
1916        Some(v) if v.is_object() => Ok(vec![v.clone()]),
1917        Some(_) => Err(CoreError::Json(
1918            "credentialStatus must be an object or a list of objects".into(),
1919        )),
1920    }
1921}
1922
1923/// Return true if the robot credential's status bit for `status_purpose` is set
1924/// (for example, the credential has been revoked) in the supplied status list. The
1925/// caller MUST verify the Data Integrity proof on `status_list_credential` first.
1926/// Returns false when the credential carries no matching status entry.
1927pub fn check_credential_status(
1928    credential: &Value,
1929    status_list_credential: &Value,
1930    status_purpose: &str,
1931) -> Result<bool> {
1932    let referenced_id = status_list_credential.get("id").and_then(|v| v.as_str());
1933    for entry in status_entries(credential)? {
1934        if entry.get("statusPurpose").and_then(|v| v.as_str()) != Some(status_purpose) {
1935            continue;
1936        }
1937        if entry.get("statusListCredential").and_then(|v| v.as_str()) != referenced_id {
1938            continue;
1939        }
1940        return crate::status_list::verify_status(&entry, status_list_credential);
1941    }
1942    Ok(false)
1943}
1944
1945// ---------------------------------------------------------------------------
1946// Accountable safety record (Phase 5.9)
1947// ---------------------------------------------------------------------------
1948
1949pub const SAFETY_RECORD_TYPE: &str = "RobotSafetyRecordCredential";
1950pub const SAFETY_LOG_VERSION: &str = "1.0";
1951
1952/// Standard safety event types: the interoperable set a verifier and an insurer
1953/// can rely on. Implementers MAY use additional types.
1954pub const EVENT_TYPES: [&str; 6] = [
1955    "incident",
1956    "near_miss",
1957    "manual_override",
1958    "kill_switch",
1959    "envelope_breach",
1960    "maintenance",
1961];
1962
1963/// Severity bands, ordered from least to most serious.
1964pub const SEVERITIES: [&str; 5] = ["info", "low", "medium", "high", "critical"];
1965
1966/// Append-only, plaintext, hash-linked safety event ledger. Reuses the black-box
1967/// chain semantics ([`entry_hash`], [`genesis_prev_hash`]) so the two logs verify
1968/// the same way, but entries are plaintext: a safety record is meant to be read
1969/// and trusted by third parties.
1970pub struct SafetyEventLog {
1971    genesis: String,
1972    entries: Vec<Value>,
1973    head: String,
1974}
1975
1976impl SafetyEventLog {
1977    /// Build a log. A `None` genesis uses [`genesis_prev_hash`].
1978    pub fn new(genesis_prev_hash_override: Option<&str>) -> Self {
1979        let genesis = genesis_prev_hash_override
1980            .map(String::from)
1981            .unwrap_or_else(genesis_prev_hash);
1982        Self {
1983            head: genesis.clone(),
1984            genesis,
1985            entries: Vec::new(),
1986        }
1987    }
1988
1989    /// Append one safety event, link it to the chain head, and return the entry.
1990    pub fn append(
1991        &mut self,
1992        event_type: &str,
1993        severity: &str,
1994        details: Option<&Value>,
1995        actor: Option<&str>,
1996        timestamp: &str,
1997    ) -> Result<Value> {
1998        if !EVENT_TYPES.contains(&event_type) {
1999            return Err(CoreError::Json(format!(
2000                "event_type must be one of {EVENT_TYPES:?}, got {event_type:?}"
2001            )));
2002        }
2003        if !SEVERITIES.contains(&severity) {
2004            return Err(CoreError::Json(format!(
2005                "severity must be one of {SEVERITIES:?}, got {severity:?}"
2006            )));
2007        }
2008
2009        let mut body = Map::new();
2010        body.insert("version".into(), json!(SAFETY_LOG_VERSION));
2011        body.insert("seq".into(), json!(self.entries.len() as u64));
2012        body.insert("timestamp".into(), json!(timestamp));
2013        body.insert("eventType".into(), json!(event_type));
2014        body.insert("severity".into(), json!(severity));
2015        body.insert("prevHash".into(), json!(self.head));
2016        if let Some(d) = details {
2017            body.insert("details".into(), d.clone());
2018        }
2019        if let Some(a) = actor {
2020            body.insert("actor".into(), json!(a));
2021        }
2022        let h = entry_hash(&body)?;
2023        body.insert("entryHash".into(), json!(h));
2024        self.head = h;
2025        let entry = Value::Object(body);
2026        self.entries.push(entry.clone());
2027        Ok(entry)
2028    }
2029
2030    pub fn head(&self) -> &str {
2031        &self.head
2032    }
2033
2034    pub fn genesis(&self) -> &str {
2035        &self.genesis
2036    }
2037
2038    pub fn entries(&self) -> &[Value] {
2039        &self.entries
2040    }
2041
2042    /// Produce a summary object for embedding in a safety-record credential.
2043    pub fn summarize(&self) -> Value {
2044        summarize_entries(&self.entries, Some(&self.head))
2045    }
2046}
2047
2048/// Verify the hash chain over the ledger entries. Tamper-evident. Shares the
2049/// black-box chain verifier so the two logs verify identically.
2050pub fn verify_safety_log(
2051    entries: &[Value],
2052    genesis_prev_hash_override: Option<&str>,
2053) -> ChainResult {
2054    verify_blackbox_chain(entries, genesis_prev_hash_override)
2055}
2056
2057/// Summarize ledger entries into counts by event type (sorted) and by severity
2058/// (info..critical), the total event count, and (when supplied) the ledger head
2059/// hash that anchors the summary to a specific chain state.
2060pub fn summarize_entries(entries: &[Value], head: Option<&str>) -> Value {
2061    let mut sorted_types: Vec<&str> = EVENT_TYPES.to_vec();
2062    sorted_types.sort_unstable();
2063
2064    let mut event_counts = Map::new();
2065    for t in &sorted_types {
2066        event_counts.insert((*t).to_string(), json!(0));
2067    }
2068    let mut severity_counts = Map::new();
2069    for s in SEVERITIES {
2070        severity_counts.insert(s.to_string(), json!(0));
2071    }
2072
2073    for e in entries {
2074        if let Some(et) = e.get("eventType").and_then(|v| v.as_str()) {
2075            if let Some(c) = event_counts.get_mut(et).and_then(|v| v.as_u64()) {
2076                event_counts.insert(et.to_string(), json!(c + 1));
2077            }
2078        }
2079        if let Some(sv) = e.get("severity").and_then(|v| v.as_str()) {
2080            if let Some(c) = severity_counts.get_mut(sv).and_then(|v| v.as_u64()) {
2081                severity_counts.insert(sv.to_string(), json!(c + 1));
2082            }
2083        }
2084    }
2085
2086    let mut summary = Map::new();
2087    summary.insert("eventCounts".into(), Value::Object(event_counts));
2088    summary.insert("severityCounts".into(), Value::Object(severity_counts));
2089    summary.insert("totalEvents".into(), json!(entries.len() as u64));
2090    if let Some(h) = head {
2091        summary.insert("logHead".into(), json!(h));
2092    }
2093    Value::Object(summary)
2094}
2095
2096/// Structural validation of a safety summary.
2097pub fn validate_safety_summary(summary: &Value) -> Result<()> {
2098    let obj = summary
2099        .as_object()
2100        .ok_or_else(|| CoreError::Json("summary must be an object".into()))?;
2101    for name in ["eventCounts", "severityCounts"] {
2102        let block = obj
2103            .get(name)
2104            .and_then(|v| v.as_object())
2105            .ok_or_else(|| CoreError::Json(format!("summary.{name} must be an object")))?;
2106        for (k, v) in block {
2107            let ok = v.is_u64() || v.as_i64().map(|i| i >= 0).unwrap_or(false);
2108            if v.is_boolean() || !ok {
2109                return Err(CoreError::Json(format!(
2110                    "summary.{name}[{k:?}] must be a non-negative integer"
2111                )));
2112            }
2113        }
2114    }
2115    let total_ok = obj
2116        .get("totalEvents")
2117        .map(|v| (v.is_u64() || v.as_i64().map(|i| i >= 0).unwrap_or(false)) && !v.is_boolean())
2118        .unwrap_or(false);
2119    if !total_ok {
2120        return Err(CoreError::Json(
2121            "summary.totalEvents must be a non-negative integer".into(),
2122        ));
2123    }
2124    Ok(())
2125}
2126
2127/// Parameters for [`build_safety_record`]. The issuer (an owner, an auditor, or
2128/// the robot itself) attests `summary`, produced by [`SafetyEventLog::summarize`]
2129/// or [`summarize_entries`].
2130#[derive(Debug, Clone)]
2131pub struct BuildSafetyRecord {
2132    pub issuer_did: String,
2133    pub robot_did: String,
2134    pub summary: Value,
2135    pub period_start: Option<String>,
2136    pub period_end: Option<String>,
2137    pub valid_from: String,
2138    pub valid_until: Option<String>,
2139}
2140
2141/// Build a signed `RobotSafetyRecordCredential` summarizing a robot's safety
2142/// ledger.
2143pub fn build_safety_record(signer_seed: &[u8], params: &BuildSafetyRecord) -> Result<Value> {
2144    validate_safety_summary(&params.summary)?;
2145
2146    let mut subject = Map::new();
2147    subject.insert("id".into(), json!(params.robot_did));
2148    if let Some(s) = params.summary.as_object() {
2149        for (k, v) in s {
2150            subject.insert(k.clone(), v.clone());
2151        }
2152    }
2153    if params.period_start.is_some() || params.period_end.is_some() {
2154        let mut period = Map::new();
2155        if let Some(start) = &params.period_start {
2156            period.insert("start".into(), json!(start));
2157        }
2158        if let Some(end) = &params.period_end {
2159            period.insert("end".into(), json!(end));
2160        }
2161        subject.insert("period".into(), Value::Object(period));
2162    }
2163
2164    let mut cred = Map::new();
2165    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
2166    cred.insert(
2167        "type".into(),
2168        json!(["VerifiableCredential", SAFETY_RECORD_TYPE]),
2169    );
2170    cred.insert("issuer".into(), json!(params.issuer_did));
2171    cred.insert("validFrom".into(), json!(params.valid_from));
2172    if let Some(vu) = &params.valid_until {
2173        cred.insert("validUntil".into(), json!(vu));
2174    }
2175    cred.insert("credentialSubject".into(), Value::Object(subject));
2176
2177    let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), &params.valid_from);
2178    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
2179}
2180
2181/// Verify a `RobotSafetyRecordCredential`: the issuer's proof and the structural
2182/// validity of the embedded summary. Returns the credentialSubject on success.
2183pub fn verify_safety_record(credential: &Value, public_key: &[u8]) -> Result<Option<Value>> {
2184    if !has_type(credential.get("type"), SAFETY_RECORD_TYPE) {
2185        return Ok(None);
2186    }
2187    if !data_integrity::verify_proof(credential, public_key)? {
2188        return Ok(None);
2189    }
2190    let subject = match credential.get("credentialSubject") {
2191        Some(s) if s.is_object() => s,
2192        _ => return Ok(None),
2193    };
2194    if validate_safety_summary(subject).is_err() {
2195        return Ok(None);
2196    }
2197    Ok(Some(subject.clone()))
2198}
2199
2200// ---------------------------------------------------------------------------
2201// Perception provenance (Phase 5.10)
2202// ---------------------------------------------------------------------------
2203
2204pub const PERCEPTION_TYPE: &str = "PerceptionProvenanceCredential";
2205pub const PERCEPTION_LOG_VERSION: &str = "1.0";
2206
2207/// Standard sensor modalities: the interoperable set a verifier can rely on.
2208/// Implementers MAY use additional values.
2209pub const MODALITIES: [&str; 6] = ["camera", "lidar", "radar", "depth", "audio", "thermal"];
2210
2211/// Multibase (base64url) SHA-256 of a raw sensor frame. Only the hash travels in
2212/// the log and the attestation; the frame stays wherever the deployment keeps it.
2213pub fn hash_frame(frame: &[u8]) -> String {
2214    mb64(&Sha256::digest(frame))
2215}
2216
2217/// Append-only, plaintext, hash-linked log of sensor-frame provenance records.
2218/// Reuses the black-box chain semantics ([`entry_hash`], [`genesis_prev_hash`]),
2219/// so a perception log verifies the same way as the safety ledger. Each entry
2220/// binds a sequence number, a timestamp, the sensor id, the modality, the frame
2221/// hash, and the hash of the previous entry; the frames are not stored.
2222pub struct PerceptionLog {
2223    genesis: String,
2224    entries: Vec<Value>,
2225    head: String,
2226}
2227
2228impl PerceptionLog {
2229    /// Build a log. A `None` genesis uses [`genesis_prev_hash`].
2230    pub fn new(genesis_prev_hash_override: Option<&str>) -> Self {
2231        let genesis = genesis_prev_hash_override
2232            .map(String::from)
2233            .unwrap_or_else(genesis_prev_hash);
2234        Self {
2235            head: genesis.clone(),
2236            genesis,
2237            entries: Vec::new(),
2238        }
2239    }
2240
2241    /// Append one frame-provenance record, link it to the chain head, and return
2242    /// the entry. Provide either the raw `frame` (it is hashed) or a precomputed
2243    /// `frame_hash`, not both.
2244    pub fn record(
2245        &mut self,
2246        sensor_id: &str,
2247        modality: &str,
2248        frame: Option<&[u8]>,
2249        frame_hash: Option<&str>,
2250        timestamp: &str,
2251    ) -> Result<Value> {
2252        if !MODALITIES.contains(&modality) {
2253            return Err(CoreError::Json(format!(
2254                "modality must be one of {MODALITIES:?}, got {modality:?}"
2255            )));
2256        }
2257        if sensor_id.is_empty() {
2258            return Err(CoreError::Json("sensor_id is required".into()));
2259        }
2260        if frame.is_some() && frame_hash.is_some() {
2261            return Err(CoreError::Json(
2262                "provide either frame or frame_hash, not both".into(),
2263            ));
2264        }
2265        let resolved = match (frame, frame_hash) {
2266            (Some(f), None) => hash_frame(f),
2267            (None, Some(h)) if !h.is_empty() => h.to_string(),
2268            _ => return Err(CoreError::Json("frame or frame_hash is required".into())),
2269        };
2270
2271        let mut body = Map::new();
2272        body.insert("version".into(), json!(PERCEPTION_LOG_VERSION));
2273        body.insert("seq".into(), json!(self.entries.len() as u64));
2274        body.insert("timestamp".into(), json!(timestamp));
2275        body.insert("sensorId".into(), json!(sensor_id));
2276        body.insert("modality".into(), json!(modality));
2277        body.insert("frameHash".into(), json!(resolved));
2278        body.insert("prevHash".into(), json!(self.head));
2279        let h = entry_hash(&body)?;
2280        body.insert("entryHash".into(), json!(h));
2281        self.head = h;
2282        let entry = Value::Object(body);
2283        self.entries.push(entry.clone());
2284        Ok(entry)
2285    }
2286
2287    pub fn head(&self) -> &str {
2288        &self.head
2289    }
2290
2291    pub fn genesis(&self) -> &str {
2292        &self.genesis
2293    }
2294
2295    pub fn entries(&self) -> &[Value] {
2296        &self.entries
2297    }
2298}
2299
2300/// Verify the hash chain over the perception log entries. Tamper-evident. Shares
2301/// the black-box chain verifier so every hash-linked log verifies identically.
2302pub fn verify_perception_log(
2303    entries: &[Value],
2304    genesis_prev_hash_override: Option<&str>,
2305) -> ChainResult {
2306    verify_blackbox_chain(entries, genesis_prev_hash_override)
2307}
2308
2309/// Parameters for [`build_perception_attestation`]. The robot self-issues the
2310/// credential with its own Ed25519 seed. `captured_at`, when `None`, defaults to
2311/// `valid_from`. When `log_head` is supplied, the attestation also anchors the
2312/// segment of frames up to that chain head.
2313#[derive(Debug, Clone)]
2314pub struct BuildPerception {
2315    pub robot_did: String,
2316    pub sensor_id: String,
2317    pub modality: String,
2318    pub frame_hash: String,
2319    pub captured_at: Option<String>,
2320    pub log_head: Option<String>,
2321    pub valid_from: String,
2322    pub valid_until: Option<String>,
2323}
2324
2325/// Build a signed `PerceptionProvenanceCredential` attesting that a robot's sensor
2326/// captured a specific frame. Software frame-hash signing: the robot signs the
2327/// provenance of the captured frame with its own key.
2328pub fn build_perception_attestation(robot_seed: &[u8], params: &BuildPerception) -> Result<Value> {
2329    if !MODALITIES.contains(&params.modality.as_str()) {
2330        return Err(CoreError::Json(format!(
2331            "modality must be one of {MODALITIES:?}, got {:?}",
2332            params.modality
2333        )));
2334    }
2335    if params.frame_hash.is_empty() {
2336        return Err(CoreError::Json("frame_hash is required".into()));
2337    }
2338
2339    let captured = params
2340        .captured_at
2341        .clone()
2342        .unwrap_or_else(|| params.valid_from.clone());
2343
2344    let mut subject = Map::new();
2345    subject.insert("id".into(), json!(params.robot_did));
2346    subject.insert("sensorId".into(), json!(params.sensor_id));
2347    subject.insert("modality".into(), json!(params.modality));
2348    subject.insert("frameHash".into(), json!(params.frame_hash));
2349    subject.insert("capturedAt".into(), json!(captured));
2350    if let Some(head) = &params.log_head {
2351        subject.insert("logHead".into(), json!(head));
2352    }
2353
2354    let mut cred = Map::new();
2355    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
2356    cred.insert(
2357        "type".into(),
2358        json!(["VerifiableCredential", PERCEPTION_TYPE]),
2359    );
2360    cred.insert("issuer".into(), json!(params.robot_did));
2361    cred.insert("validFrom".into(), json!(params.valid_from));
2362    if let Some(vu) = &params.valid_until {
2363        cred.insert("validUntil".into(), json!(vu));
2364    }
2365    cred.insert("credentialSubject".into(), Value::Object(subject));
2366
2367    let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), &params.valid_from);
2368    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
2369}
2370
2371/// Verify a `PerceptionProvenanceCredential`: the robot's proof and, when the raw
2372/// `frame` is supplied, that its hash reproduces the attested `frameHash`. Returns
2373/// the credentialSubject on success, `None` if invalid.
2374pub fn verify_perception_attestation(
2375    credential: &Value,
2376    public_key: &[u8],
2377    frame: Option<&[u8]>,
2378) -> Result<Option<Value>> {
2379    if !has_type(credential.get("type"), PERCEPTION_TYPE) {
2380        return Ok(None);
2381    }
2382    if !data_integrity::verify_proof(credential, public_key)? {
2383        return Ok(None);
2384    }
2385    let subject = match credential
2386        .get("credentialSubject")
2387        .and_then(|s| s.as_object())
2388    {
2389        Some(s) => s,
2390        None => return Ok(None),
2391    };
2392    let frame_hash = subject.get("frameHash").and_then(|v| v.as_str());
2393    let modality = subject.get("modality").and_then(|v| v.as_str());
2394    match (frame_hash, modality) {
2395        (Some(fh), Some(m)) if !fh.is_empty() && MODALITIES.contains(&m) => {}
2396        _ => return Ok(None),
2397    }
2398    if let Some(f) = frame {
2399        if hash_frame(f) != frame_hash.unwrap_or("") {
2400            return Ok(None);
2401        }
2402    }
2403    Ok(Some(Value::Object(subject.clone())))
2404}
2405
2406// ---------------------------------------------------------------------------
2407// Delegation lease (Phase 5.11)
2408// ---------------------------------------------------------------------------
2409
2410pub const DELEGATION_LEASE_TYPE: &str = "DelegationLeaseCredential";
2411
2412/// Parameters for [`build_delegation_lease`]. The issuer is the signer (an
2413/// authority or the holder of a parent lease); `robot_did` is the subject the
2414/// lease is granted to. `scope` is a physicalScope object (the same shape as a
2415/// `PhysicalCapabilityScope` credentialSubject.physicalScope). Leases are
2416/// short-lived by design, so the window is bounded by `valid_from`/`valid_until`.
2417/// Set `parent_lease_id` when sub-granting from another lease.
2418#[derive(Debug, Clone)]
2419pub struct BuildDelegationLease {
2420    pub issuer_did: String,
2421    pub robot_did: String,
2422    pub lease_id: String,
2423    pub scope: Value,
2424    pub parent_lease_id: Option<String>,
2425    pub valid_from: String,
2426    pub valid_until: String,
2427}
2428
2429/// Build a signed `DelegationLeaseCredential` granting `robot_did` a bounded
2430/// physical scope for a fixed window. The window is verifiable entirely offline.
2431pub fn build_delegation_lease(signer_seed: &[u8], params: &BuildDelegationLease) -> Result<Value> {
2432    if params.lease_id.is_empty() {
2433        return Err(CoreError::Json("lease_id is required".into()));
2434    }
2435    if !params.scope.is_object() {
2436        return Err(CoreError::Json(
2437            "scope must be a physicalScope object".into(),
2438        ));
2439    }
2440
2441    let mut subject = Map::new();
2442    subject.insert("id".into(), json!(params.robot_did));
2443    subject.insert("leaseId".into(), json!(params.lease_id));
2444    subject.insert("physicalScope".into(), params.scope.clone());
2445    if let Some(parent) = &params.parent_lease_id {
2446        subject.insert("parentLeaseId".into(), json!(parent));
2447    }
2448
2449    let mut cred = Map::new();
2450    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
2451    cred.insert(
2452        "type".into(),
2453        json!(["VerifiableCredential", DELEGATION_LEASE_TYPE]),
2454    );
2455    cred.insert("issuer".into(), json!(params.issuer_did));
2456    cred.insert("validFrom".into(), json!(params.valid_from));
2457    cred.insert("validUntil".into(), json!(params.valid_until));
2458    cred.insert("credentialSubject".into(), Value::Object(subject));
2459
2460    let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), &params.valid_from);
2461    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
2462}
2463
2464/// True if the credential's `validFrom`/`validUntil` window contains `now_iso`.
2465/// A `None` clock skips the check (the deterministic core leaves the wall clock
2466/// to the wrapper), so the window is treated as current.
2467fn lease_window_current(credential: &Value, now_iso: Option<&str>) -> bool {
2468    let now = match now_iso {
2469        Some(n) => n,
2470        None => return true,
2471    };
2472    let moment = match crate::time::iso_to_epoch_seconds(now) {
2473        Ok(t) => t,
2474        Err(_) => return false,
2475    };
2476    if let Some(vf) = credential.get("validFrom").and_then(|v| v.as_str()) {
2477        match crate::time::iso_to_epoch_seconds(vf) {
2478            Ok(t) if moment < t => return false,
2479            Err(_) => return false,
2480            _ => {}
2481        }
2482    }
2483    if let Some(vu) = credential.get("validUntil").and_then(|v| v.as_str()) {
2484        match crate::time::iso_to_epoch_seconds(vu) {
2485            Ok(t) if moment > t => return false,
2486            Err(_) => return false,
2487            _ => {}
2488        }
2489    }
2490    true
2491}
2492
2493/// Verify a `DelegationLeaseCredential` offline: the issuer's proof, that the
2494/// window is current (when `now_iso` is supplied), and (when `parent_scope` is
2495/// supplied) that this lease's scope attenuates the parent. No network call.
2496/// Returns the credentialSubject on success, `None` if invalid.
2497pub fn verify_delegation_lease(
2498    credential: &Value,
2499    public_key: &[u8],
2500    now_iso: Option<&str>,
2501    parent_scope: Option<&Value>,
2502) -> Result<Option<Value>> {
2503    if !has_type(credential.get("type"), DELEGATION_LEASE_TYPE) {
2504        return Ok(None);
2505    }
2506    if !data_integrity::verify_proof(credential, public_key)? {
2507        return Ok(None);
2508    }
2509    if !lease_window_current(credential, now_iso) {
2510        return Ok(None);
2511    }
2512
2513    let subject = match credential
2514        .get("credentialSubject")
2515        .and_then(|s| s.as_object())
2516    {
2517        Some(s) => s,
2518        None => return Ok(None),
2519    };
2520    let scope = match subject.get("physicalScope") {
2521        Some(s) if s.is_object() => s,
2522        _ => return Ok(None),
2523    };
2524    if let Some(parent) = parent_scope {
2525        if !attenuates(parent, scope) {
2526            return Ok(None);
2527        }
2528    }
2529    Ok(Some(Value::Object(subject.clone())))
2530}
2531
2532/// Decide whether a verified lease permits a proposed physical action: the
2533/// action must fit the lease scope, and (when the full `credential` is supplied)
2534/// the window must still be current.
2535pub fn lease_permits(
2536    subject: &Value,
2537    action: &PhysicalAction,
2538    credential: Option<&Value>,
2539    now_iso: Option<&str>,
2540) -> bool {
2541    if let Some(cred) = credential {
2542        if !lease_window_current(cred, now_iso) {
2543            return false;
2544        }
2545    }
2546    let empty = json!({});
2547    let scope = subject.get("physicalScope").unwrap_or(&empty);
2548    check_physical_action(scope, action).ok
2549}
2550
2551// ---------------------------------------------------------------------------
2552// Physical quorum (Phase 5.12)
2553// ---------------------------------------------------------------------------
2554
2555pub const ACTION_APPROVAL_TYPE: &str = "PhysicalActionApprovalCredential";
2556pub const APPROVE: &str = "approve";
2557pub const REJECT: &str = "reject";
2558
2559/// Parameters for [`build_action_approval`]. The approver is the signer; the
2560/// approval is over a specific physical action `action_id` that `robot_did`
2561/// would perform. `decision` is "approve" or "reject".
2562#[derive(Debug, Clone)]
2563pub struct BuildActionApproval {
2564    pub approver_did: String,
2565    pub action_id: String,
2566    pub robot_did: String,
2567    pub decision: String,
2568    pub valid_from: String,
2569    pub valid_until: Option<String>,
2570}
2571
2572/// Build a signed `PhysicalActionApprovalCredential` by one approver for a
2573/// specific physical action.
2574pub fn build_action_approval(approver_seed: &[u8], params: &BuildActionApproval) -> Result<Value> {
2575    if params.decision != APPROVE && params.decision != REJECT {
2576        return Err(CoreError::Json(format!(
2577            "decision must be {APPROVE:?} or {REJECT:?}, got {:?}",
2578            params.decision
2579        )));
2580    }
2581    if params.action_id.is_empty() {
2582        return Err(CoreError::Json("action_id is required".into()));
2583    }
2584
2585    let mut subject = Map::new();
2586    subject.insert("id".into(), json!(params.approver_did));
2587    subject.insert("actionId".into(), json!(params.action_id));
2588    subject.insert("robotDid".into(), json!(params.robot_did));
2589    subject.insert("decision".into(), json!(params.decision));
2590
2591    let mut cred = Map::new();
2592    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
2593    cred.insert(
2594        "type".into(),
2595        json!(["VerifiableCredential", ACTION_APPROVAL_TYPE]),
2596    );
2597    cred.insert("issuer".into(), json!(params.approver_did));
2598    cred.insert("validFrom".into(), json!(params.valid_from));
2599    if let Some(vu) = &params.valid_until {
2600        cred.insert("validUntil".into(), json!(vu));
2601    }
2602    cred.insert("credentialSubject".into(), Value::Object(subject));
2603
2604    let opts = BuildProofOptions::new(format!("{}#key-1", params.approver_did), &params.valid_from);
2605    data_integrity::sign(&Value::Object(cred), approver_seed, &opts)
2606}
2607
2608/// One approver's public key, looked up by issuer DID, for
2609/// [`verify_action_authorization`].
2610#[derive(Debug, Clone)]
2611pub struct ApproverKey {
2612    pub did: String,
2613    pub public_key: Vec<u8>,
2614}
2615
2616/// Verify that a high-consequence physical action is authorized by a quorum.
2617///
2618/// Each approval must be the right type, carry an in-date proof signed by the
2619/// approver's key (looked up in `approver_keys` by issuer DID), match `action_id`
2620/// and `robot_did`, and carry an `approve` decision. When `approver_set` is
2621/// supplied, the approver must be in it. The action is authorized when at least
2622/// `threshold` DISTINCT valid approvers have approved; a single approver counts
2623/// once even if it submits several approvals. Returns `(authorized, sorted list
2624/// of the distinct approving DIDs)`.
2625pub fn verify_action_authorization(
2626    approvals: &[Value],
2627    action_id: &str,
2628    robot_did: &str,
2629    approver_keys: &[ApproverKey],
2630    threshold: i64,
2631    approver_set: Option<&HashSet<String>>,
2632    now_iso: Option<&str>,
2633) -> Result<(bool, Vec<String>)> {
2634    if threshold < 1 {
2635        return Err(CoreError::Json("threshold must be at least 1".into()));
2636    }
2637
2638    let mut approvers: HashSet<String> = HashSet::new();
2639    for approval in approvals {
2640        if !has_type(approval.get("type"), ACTION_APPROVAL_TYPE) {
2641            continue;
2642        }
2643        let subject = match approval
2644            .get("credentialSubject")
2645            .and_then(|s| s.as_object())
2646        {
2647            Some(s) => s,
2648            None => continue,
2649        };
2650        let issuer = approval
2651            .get("issuer")
2652            .and_then(|v| v.as_str())
2653            .unwrap_or("");
2654        if subject.get("actionId").and_then(|v| v.as_str()) != Some(action_id)
2655            || subject.get("robotDid").and_then(|v| v.as_str()) != Some(robot_did)
2656        {
2657            continue;
2658        }
2659        if subject.get("decision").and_then(|v| v.as_str()) != Some(APPROVE) {
2660            continue;
2661        }
2662        if let Some(set) = approver_set {
2663            if !set.contains(issuer) {
2664                continue;
2665            }
2666        }
2667        let key = match approver_keys.iter().find(|k| k.did == issuer) {
2668            Some(k) => k,
2669            None => continue,
2670        };
2671        if !lease_window_current(approval, now_iso) {
2672            continue;
2673        }
2674        if !data_integrity::verify_proof(approval, &key.public_key)? {
2675            continue;
2676        }
2677        approvers.insert(issuer.to_string());
2678    }
2679
2680    let mut sorted: Vec<String> = approvers.into_iter().collect();
2681    sorted.sort();
2682    Ok((sorted.len() as i64 >= threshold, sorted))
2683}
2684
2685// ---------------------------------------------------------------------------
2686// Robot lifecycle: ownership transfer, key rotation, decommission (Phase 5.13)
2687// ---------------------------------------------------------------------------
2688
2689pub const OWNERSHIP_TRANSFER_TYPE: &str = "RobotOwnershipTransferCredential";
2690pub const KEY_ROTATION_TYPE: &str = "RobotKeyRotationCredential";
2691pub const DECOMMISSION_TYPE: &str = "RobotDecommissionCredential";
2692
2693/// Verify a typed lifecycle credential: the credential carries `expected_type`
2694/// and its Data Integrity proof verifies under `public_key`. Returns the
2695/// credentialSubject on success, `None` otherwise. The per-credential rules
2696/// (issuer equals fromOwner, required subject fields) are applied by the caller.
2697fn verify_typed(
2698    credential: &Value,
2699    public_key: &[u8],
2700    expected_type: &str,
2701) -> Result<Option<Value>> {
2702    if !has_type(credential.get("type"), expected_type) {
2703        return Ok(None);
2704    }
2705    if !data_integrity::verify_proof(credential, public_key)? {
2706        return Ok(None);
2707    }
2708    match credential
2709        .get("credentialSubject")
2710        .and_then(|s| s.as_object())
2711    {
2712        Some(s) => Ok(Some(Value::Object(s.clone()))),
2713        None => Ok(None),
2714    }
2715}
2716
2717/// Parameters for [`build_ownership_transfer`]. The signer is the current owner;
2718/// `from_owner` defaults to `issuer_did` (the current owner's DID). Setting
2719/// `prev_transfer_id` links this transfer to the previous one, forming a chain.
2720#[derive(Debug, Clone)]
2721pub struct BuildOwnershipTransfer {
2722    pub issuer_did: String,
2723    pub robot_did: String,
2724    pub to_owner: String,
2725    pub from_owner: Option<String>,
2726    pub prev_transfer_id: Option<String>,
2727    pub valid_from: String,
2728}
2729
2730/// Build a signed transfer of `robot_did` from the current owner to `to_owner`.
2731/// The signer is the current owner; `from_owner` defaults to `issuer_did`.
2732pub fn build_ownership_transfer(
2733    current_owner_seed: &[u8],
2734    params: &BuildOwnershipTransfer,
2735) -> Result<Value> {
2736    if params.robot_did.is_empty() || params.to_owner.is_empty() {
2737        return Err(CoreError::Json(
2738            "robot_did and to_owner are required".into(),
2739        ));
2740    }
2741    let seller = params
2742        .from_owner
2743        .clone()
2744        .unwrap_or_else(|| params.issuer_did.clone());
2745
2746    let mut subject = Map::new();
2747    subject.insert("id".into(), json!(params.robot_did));
2748    subject.insert("fromOwner".into(), json!(seller));
2749    subject.insert("toOwner".into(), json!(params.to_owner));
2750    if let Some(prev) = &params.prev_transfer_id {
2751        subject.insert("prevTransferId".into(), json!(prev));
2752    }
2753
2754    let mut cred = Map::new();
2755    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
2756    cred.insert(
2757        "type".into(),
2758        json!(["VerifiableCredential", OWNERSHIP_TRANSFER_TYPE]),
2759    );
2760    cred.insert("issuer".into(), json!(params.issuer_did));
2761    cred.insert("validFrom".into(), json!(params.valid_from));
2762    cred.insert("credentialSubject".into(), Value::Object(subject));
2763
2764    let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), &params.valid_from);
2765    data_integrity::sign(&Value::Object(cred), current_owner_seed, &opts)
2766}
2767
2768/// Verify a transfer: the current owner's proof and that the issuer is the
2769/// `fromOwner` (only the current owner can transfer the robot). Returns the
2770/// credentialSubject on success, `None` if invalid.
2771pub fn verify_ownership_transfer(
2772    credential: &Value,
2773    current_owner_public_key: &[u8],
2774) -> Result<Option<Value>> {
2775    let subject = match verify_typed(
2776        credential,
2777        current_owner_public_key,
2778        OWNERSHIP_TRANSFER_TYPE,
2779    )? {
2780        Some(s) => s,
2781        None => return Ok(None),
2782    };
2783    let to_owner = subject.get("toOwner").and_then(|v| v.as_str());
2784    let from_owner = subject.get("fromOwner").and_then(|v| v.as_str());
2785    match (to_owner, from_owner) {
2786        (Some(t), Some(f)) if !t.is_empty() && !f.is_empty() => {
2787            if credential.get("issuer").and_then(|v| v.as_str()) != Some(f) {
2788                return Ok(None);
2789            }
2790        }
2791        _ => return Ok(None),
2792    }
2793    Ok(Some(subject))
2794}
2795
2796/// One owner's public key, looked up by owner DID, for [`verify_custody_chain`].
2797#[derive(Debug, Clone)]
2798pub struct OwnerKey {
2799    pub did: String,
2800    pub public_key: Vec<u8>,
2801}
2802
2803/// Verify an ordered list of transfer credentials forms a valid chain of custody:
2804/// each transfer's proof verifies under the owner who signed it, every link's
2805/// `toOwner` matches the next link's `fromOwner`, and (when given) the first
2806/// `fromOwner` is `origin_owner`. `public_keys` maps an owner DID to its key.
2807/// Returns `(ok, current_owner)`.
2808pub fn verify_custody_chain(
2809    transfers: &[Value],
2810    public_keys: &[OwnerKey],
2811    origin_owner: Option<&str>,
2812) -> Result<(bool, Option<String>)> {
2813    let mut expected_from: Option<String> = origin_owner.map(String::from);
2814    let mut current_owner: Option<String> = origin_owner.map(String::from);
2815    for transfer in transfers {
2816        let issuer = transfer
2817            .get("issuer")
2818            .and_then(|v| v.as_str())
2819            .unwrap_or("");
2820        let key = match public_keys.iter().find(|k| k.did == issuer) {
2821            Some(k) => k,
2822            None => return Ok((false, None)),
2823        };
2824        let subject = match verify_ownership_transfer(transfer, &key.public_key)? {
2825            Some(s) => s,
2826            None => return Ok((false, None)),
2827        };
2828        if let Some(expected) = &expected_from {
2829            if subject.get("fromOwner").and_then(|v| v.as_str()) != Some(expected.as_str()) {
2830                return Ok((false, None));
2831            }
2832        }
2833        current_owner = subject
2834            .get("toOwner")
2835            .and_then(|v| v.as_str())
2836            .map(String::from);
2837        expected_from = current_owner.clone();
2838    }
2839    Ok((true, current_owner))
2840}
2841
2842/// Parameters for [`build_key_rotation`]. The credential is signed by the old key
2843/// (the `signer_seed`) and issued under `robot_did`; the old key's public multibase
2844/// is recorded as `previousKey` and `new_key_multibase` as the authorized successor.
2845#[derive(Debug, Clone)]
2846pub struct BuildKeyRotation {
2847    pub robot_did: String,
2848    pub new_key_multibase: String,
2849    pub reason: Option<String>,
2850    pub valid_from: String,
2851}
2852
2853/// Build a key-rotation credential in which the robot's current (old) key
2854/// authorizes a new key. Signed by the old key, so anyone trusting the old key
2855/// can trust the new one. `old_key_seed` is the seed of the current key.
2856pub fn build_key_rotation(old_key_seed: &[u8], params: &BuildKeyRotation) -> Result<Value> {
2857    if params.new_key_multibase.is_empty() {
2858        return Err(CoreError::Json("new_key_multibase is required".into()));
2859    }
2860    let old_kp = keys::Ed25519KeyPair::from_seed_slice(old_key_seed)?;
2861
2862    let mut subject = Map::new();
2863    subject.insert("id".into(), json!(params.robot_did));
2864    subject.insert("previousKey".into(), json!(old_kp.public_multikey()));
2865    subject.insert("newKey".into(), json!(params.new_key_multibase));
2866    if let Some(reason) = &params.reason {
2867        subject.insert("reason".into(), json!(reason));
2868    }
2869
2870    let mut cred = Map::new();
2871    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
2872    cred.insert(
2873        "type".into(),
2874        json!(["VerifiableCredential", KEY_ROTATION_TYPE]),
2875    );
2876    cred.insert("issuer".into(), json!(params.robot_did));
2877    cred.insert("validFrom".into(), json!(params.valid_from));
2878    cred.insert("credentialSubject".into(), Value::Object(subject));
2879
2880    let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), &params.valid_from);
2881    data_integrity::sign(&Value::Object(cred), old_key_seed, &opts)
2882}
2883
2884/// Verify a key rotation: the OLD key signed it, binding the new key. Returns the
2885/// credentialSubject (with `newKey` the authorized successor) on success.
2886pub fn verify_key_rotation(credential: &Value, old_public_key: &[u8]) -> Result<Option<Value>> {
2887    let subject = match verify_typed(credential, old_public_key, KEY_ROTATION_TYPE)? {
2888        Some(s) => s,
2889        None => return Ok(None),
2890    };
2891    let previous = subject.get("previousKey").and_then(|v| v.as_str());
2892    let new_key = subject.get("newKey").and_then(|v| v.as_str());
2893    match (previous, new_key) {
2894        (Some(p), Some(n)) if !p.is_empty() && !n.is_empty() => {}
2895        _ => return Ok(None),
2896    }
2897    Ok(Some(subject))
2898}
2899
2900/// One key's public bytes, looked up by key multibase, for [`verify_key_history`].
2901#[derive(Debug, Clone)]
2902pub struct KeyEntry {
2903    pub multibase: String,
2904    pub public_key: Vec<u8>,
2905}
2906
2907/// Verify an ordered list of key rotations forms a valid key history starting from
2908/// `origin_key_multibase`: each rotation's `previousKey` matches the current key,
2909/// and each is signed by the key it rotates from. `public_keys` maps a key
2910/// multibase to the corresponding public key. Returns `(ok, current_key)`.
2911pub fn verify_key_history(
2912    rotations: &[Value],
2913    origin_key_multibase: &str,
2914    public_keys: &[KeyEntry],
2915) -> Result<(bool, Option<String>)> {
2916    let mut current_key = origin_key_multibase.to_string();
2917    for rotation in rotations {
2918        let previous = rotation
2919            .get("credentialSubject")
2920            .and_then(|s| s.get("previousKey"))
2921            .and_then(|v| v.as_str())
2922            .unwrap_or("");
2923        if previous != current_key {
2924            return Ok((false, None));
2925        }
2926        let key = match public_keys.iter().find(|k| k.multibase == current_key) {
2927            Some(k) => k,
2928            None => return Ok((false, None)),
2929        };
2930        let subject = match verify_key_rotation(rotation, &key.public_key)? {
2931            Some(s) => s,
2932            None => return Ok((false, None)),
2933        };
2934        current_key = subject
2935            .get("newKey")
2936            .and_then(|v| v.as_str())
2937            .unwrap_or("")
2938            .to_string();
2939    }
2940    Ok((true, Some(current_key)))
2941}
2942
2943/// Parameters for [`build_decommission`]. The signer is the owner or an authority;
2944/// `final_disposition` records the outcome (for example recycled, destroyed, or
2945/// transferred to parts). When `valid_until` is set it bounds the credential.
2946#[derive(Debug, Clone)]
2947pub struct BuildDecommission {
2948    pub issuer_did: String,
2949    pub robot_did: String,
2950    pub reason: String,
2951    pub final_disposition: Option<String>,
2952    pub valid_from: String,
2953    pub valid_until: Option<String>,
2954}
2955
2956/// Build a signed decommission credential retiring `robot_did`. After
2957/// decommissioning, a verifier should refuse to trust the robot. `decommissionedBy`
2958/// is the issuer DID.
2959pub fn build_decommission(signer_seed: &[u8], params: &BuildDecommission) -> Result<Value> {
2960    if params.reason.is_empty() {
2961        return Err(CoreError::Json("reason is required".into()));
2962    }
2963    let mut subject = Map::new();
2964    subject.insert("id".into(), json!(params.robot_did));
2965    subject.insert("reason".into(), json!(params.reason));
2966    subject.insert("decommissionedBy".into(), json!(params.issuer_did));
2967    if let Some(disposition) = &params.final_disposition {
2968        subject.insert("finalDisposition".into(), json!(disposition));
2969    }
2970
2971    let mut cred = Map::new();
2972    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
2973    cred.insert(
2974        "type".into(),
2975        json!(["VerifiableCredential", DECOMMISSION_TYPE]),
2976    );
2977    cred.insert("issuer".into(), json!(params.issuer_did));
2978    cred.insert("validFrom".into(), json!(params.valid_from));
2979    if let Some(vu) = &params.valid_until {
2980        cred.insert("validUntil".into(), json!(vu));
2981    }
2982    cred.insert("credentialSubject".into(), Value::Object(subject));
2983
2984    let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), &params.valid_from);
2985    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
2986}
2987
2988/// Verify a decommission credential. When `trusted_authorities` is supplied, the
2989/// issuer DID MUST be in it, so only an attested authority can retire the robot.
2990/// Returns the credentialSubject on success.
2991pub fn verify_decommission(
2992    credential: &Value,
2993    public_key: &[u8],
2994    trusted_authorities: Option<&HashSet<String>>,
2995) -> Result<Option<Value>> {
2996    let subject = match verify_typed(credential, public_key, DECOMMISSION_TYPE)? {
2997        Some(s) => s,
2998        None => return Ok(None),
2999    };
3000    if let Some(trusted) = trusted_authorities {
3001        let issuer = credential
3002            .get("issuer")
3003            .and_then(|v| v.as_str())
3004            .unwrap_or("");
3005        if !trusted.contains(issuer) {
3006            return Ok(None);
3007        }
3008    }
3009    Ok(Some(subject))
3010}
3011
3012// ---------------------------------------------------------------------------
3013// Regulatory conformance profiles (Phase 5.14)
3014// ---------------------------------------------------------------------------
3015//
3016// A conformance profile is a machine-checkable mapping from Vouch robotics
3017// credentials to the clauses of a public safety or AI regulation. Given the
3018// credentials a robot presents, the checker reports which clauses are satisfied
3019// and cites each one, and an issuer can sign a point-in-time conformance
3020// attestation an auditor or notified body can consume. The profiles are plain
3021// data so every language reproduces them identically.
3022//
3023// This is the open layer: declarative profiles, a deterministic checker, and a
3024// signed point-in-time attestation over the full report. It is a reference
3025// crosswalk to make conformance verifiable in the open, not legal advice.
3026
3027pub const CONFORMANCE_ATTESTATION_TYPE: &str = "RobotConformanceAttestation";
3028
3029/// How well-sourced a requirement's clause citation is. A profile can be a
3030/// useful crosswalk while its citations are only as good as the sources that
3031/// were available, and a reader is entitled to know which. Every report and
3032/// every signed attestation carries these, so a conformance result never
3033/// implies more authority over the regulation than it has.
3034///
3035/// The clause text was read from the official published source.
3036pub const CITATION_VERIFIED_PRIMARY: &str = "verified-primary";
3037/// The mapping is believed sound, but the clause number comes from secondary
3038/// sources rather than the standard or official journal itself. The default,
3039/// because it is the honest default.
3040pub const CITATION_UNVERIFIED_SECONDARY: &str = "unverified-secondary";
3041/// Not a clause reference at all, only a description of the topic. An assessor
3042/// cannot look it up.
3043pub const CITATION_DESCRIPTIVE: &str = "descriptive";
3044
3045/// Every citation provenance value, in report order.
3046pub const CITATION_STATUSES: &[&str] = &[
3047    CITATION_VERIFIED_PRIMARY,
3048    CITATION_UNVERIFIED_SECONDARY,
3049    CITATION_DESCRIPTIVE,
3050];
3051
3052// Citation notes shared by several requirements. Macros rather than consts so
3053// they can be `concat!`-ed into the longer per-requirement notes, byte-for-byte
3054// identical with the Python, TypeScript and Go profiles.
3055macro_rules! iso_paywall_note {
3056    () => {
3057        "Clause number taken from secondary sources; the standard is paywalled \
3058         and the text has not been read."
3059    };
3060}
3061
3062macro_rules! iso_10218_note {
3063    () => {
3064        concat!(
3065            iso_paywall_note!(),
3066            " ISO 10218-1/-2:2011 were superseded by the 2025 editions (in \
3067             force 1 April 2025); this mapping still cites the 2011 clause \
3068             numbering and has not been migrated."
3069        )
3070    };
3071}
3072
3073macro_rules! oj_note {
3074    () => {
3075        "Article number taken from a third-party reproduction of the Official \
3076         Journal text, not from EUR-Lex itself."
3077    };
3078}
3079
3080macro_rules! ul_note {
3081    () => {
3082        "UL 3300 (now ANSI/CAN/UL 3300:2024) is paywalled and no clause \
3083         numbering was available; this names the topic only and cannot be \
3084         looked up."
3085    };
3086}
3087
3088/// One requirement in a profile: a clause of a regulation mapped to the
3089/// credential type and field paths that satisfy it.
3090struct ProfileRequirement {
3091    id: &'static str,
3092    clause: &'static str,
3093    title: &'static str,
3094    credential: &'static str,
3095    fields: &'static [&'static str],
3096    /// Subject paths that must hold boolean `true`, for requirements where mere
3097    /// presence is not evidence: a heartbeat reporting an envelope breach is not
3098    /// evidence of having stayed inside the envelope. This is the boolean subset
3099    /// of the `expect` map the Python, TypeScript and Go profiles carry; the
3100    /// built-in profiles use only boolean expectations.
3101    expect_true: &'static [&'static str],
3102    /// Provenance of the `clause` reference above, one of [`CITATION_STATUSES`].
3103    citation: &'static str,
3104    /// Anything a reader should know about the citation, such as a known
3105    /// conflict between sources.
3106    citation_note: Option<&'static str>,
3107}
3108
3109/// A built-in conformance profile: a regime, a version, and its requirements.
3110struct ConformanceProfile {
3111    regime: &'static str,
3112    version: &'static str,
3113    requirements: &'static [ProfileRequirement],
3114}
3115
3116const ISO_10218_REQUIREMENTS: &[ProfileRequirement] = &[
3117    ProfileRequirement {
3118        id: "iso10218-identification",
3119        clause: "ISO 10218-1:2011, 5.2",
3120        title: "Robot identification bound to its hardware",
3121        credential: "RobotIdentityCredential",
3122        fields: &["hardwareRoot.kind", "hardwareRoot.attestation"],
3123        expect_true: &[],
3124        citation: CITATION_UNVERIFIED_SECONDARY,
3125        citation_note: Some(iso_10218_note!()),
3126    },
3127    ProfileRequirement {
3128        id: "iso10218-software-integrity",
3129        clause: "ISO 10218-1:2011, 5.3",
3130        title: "Control software and configuration integrity",
3131        credential: "ModelProvenanceAttestation",
3132        fields: &["vla.weightsHash"],
3133        expect_true: &[],
3134        citation: CITATION_UNVERIFIED_SECONDARY,
3135        citation_note: Some(iso_10218_note!()),
3136    },
3137    ProfileRequirement {
3138        id: "iso10218-limits",
3139        clause: "ISO 10218-1:2011, 5.6",
3140        title: "Limiting of speed, force, and workspace",
3141        credential: "PhysicalCapabilityScope",
3142        fields: &[
3143            "physicalScope.maxForceN",
3144            "physicalScope.maxSpeedMps",
3145            "physicalScope.allowedZones",
3146        ],
3147        expect_true: &[],
3148        citation: CITATION_UNVERIFIED_SECONDARY,
3149        citation_note: Some(iso_10218_note!()),
3150    },
3151    ProfileRequirement {
3152        id: "iso10218-records",
3153        clause: "ISO 10218-2:2011, 5.2",
3154        title: "Records of safety-relevant events",
3155        credential: "RobotSafetyRecordCredential",
3156        fields: &["totalEvents", "logHead"],
3157        expect_true: &[],
3158        citation: CITATION_UNVERIFIED_SECONDARY,
3159        citation_note: Some(iso_10218_note!()),
3160    },
3161];
3162
3163const ISO_TS_15066_REQUIREMENTS: &[ProfileRequirement] = &[
3164    ProfileRequirement {
3165        id: "iso15066-power-force-limiting",
3166        clause: "ISO/TS 15066:2016, 5.5.4",
3167        title: "Power and force limiting near humans",
3168        credential: "PhysicalCapabilityScope",
3169        fields: &[
3170            "physicalScope.maxSpeedNearHumansMps",
3171            "physicalScope.maxForceN",
3172        ],
3173        expect_true: &[],
3174        citation: CITATION_UNVERIFIED_SECONDARY,
3175        citation_note: Some(concat!(
3176            iso_paywall_note!(),
3177            " Secondary sources disagree on whether power and force limiting \
3178             is 5.5.4 or 5.5.2; confirm against the published table of \
3179             contents before relying on the number."
3180        )),
3181    },
3182    ProfileRequirement {
3183        id: "iso15066-collaborative-workspace",
3184        clause: "ISO/TS 15066:2016, 5.5.2",
3185        title: "Defined collaborative workspace",
3186        credential: "PhysicalCapabilityScope",
3187        fields: &["physicalScope.allowedZones"],
3188        expect_true: &[],
3189        citation: CITATION_UNVERIFIED_SECONDARY,
3190        citation_note: Some(concat!(
3191            iso_paywall_note!(),
3192            " Shares the unresolved 5.5.2/5.5.4 numbering conflict with \
3193             iso15066-power-force-limiting."
3194        )),
3195    },
3196    ProfileRequirement {
3197        id: "iso15066-monitoring",
3198        clause: "ISO/TS 15066:2016, 5.2",
3199        title: "Continuous monitoring of the collaborative operation",
3200        credential: "RobotHeartbeatCredential",
3201        fields: &["motionDigest"],
3202        expect_true: &["motionDigest.withinEnvelope"],
3203        citation: CITATION_UNVERIFIED_SECONDARY,
3204        citation_note: Some(iso_paywall_note!()),
3205    },
3206];
3207
3208const EU_MACHINERY_REQUIREMENTS: &[ProfileRequirement] = &[
3209    ProfileRequirement {
3210        id: "eu-mr-identification",
3211        clause: "Reg (EU) 2023/1230, Annex III 1.7.4",
3212        title: "Machinery identification and traceability",
3213        credential: "RobotIdentityCredential",
3214        fields: &["make", "model", "serial"],
3215        expect_true: &[],
3216        citation: CITATION_UNVERIFIED_SECONDARY,
3217        citation_note: Some(oj_note!()),
3218    },
3219    ProfileRequirement {
3220        id: "eu-mr-software-integrity",
3221        clause: "Reg (EU) 2023/1230, Annex III 1.1.9",
3222        title: "Protection against corruption of safety software",
3223        credential: "ModelProvenanceAttestation",
3224        fields: &["vla.weightsHash", "vla.safetyPolicy"],
3225        expect_true: &[],
3226        citation: CITATION_UNVERIFIED_SECONDARY,
3227        citation_note: Some(concat!(
3228            oj_note!(),
3229            " The Annex III subclause for protection against corruption has \
3230             not been confirmed and may need to be re-pointed."
3231        )),
3232    },
3233    ProfileRequirement {
3234        id: "eu-mr-safe-limits",
3235        clause: "Reg (EU) 2023/1230, Annex III 1.2.1",
3236        title: "Safety and reliability of control systems and limits",
3237        credential: "PhysicalCapabilityScope",
3238        fields: &["physicalScope.maxForceN"],
3239        expect_true: &[],
3240        citation: CITATION_UNVERIFIED_SECONDARY,
3241        citation_note: Some(oj_note!()),
3242    },
3243    ProfileRequirement {
3244        id: "eu-mr-records",
3245        clause: "Reg (EU) 2023/1230, Annex III 1.2.1",
3246        title: "Recording of safety-relevant data",
3247        credential: "RobotSafetyRecordCredential",
3248        fields: &["totalEvents", "logHead"],
3249        expect_true: &[],
3250        citation: CITATION_UNVERIFIED_SECONDARY,
3251        citation_note: Some(oj_note!()),
3252    },
3253];
3254
3255const EU_AI_ACT_REQUIREMENTS: &[ProfileRequirement] = &[
3256    ProfileRequirement {
3257        id: "eu-aia-record-keeping",
3258        clause: "Reg (EU) 2024/1689, Art. 12",
3259        title: "Automatic recording of events (logging)",
3260        credential: "RobotSafetyRecordCredential",
3261        fields: &["logHead"],
3262        expect_true: &[],
3263        citation: CITATION_UNVERIFIED_SECONDARY,
3264        citation_note: Some(oj_note!()),
3265    },
3266    ProfileRequirement {
3267        id: "eu-aia-transparency",
3268        clause: "Reg (EU) 2024/1689, Art. 13",
3269        title: "Model and configuration transparency",
3270        credential: "ModelProvenanceAttestation",
3271        fields: &["vla.modelName", "vla.configHash"],
3272        expect_true: &[],
3273        citation: CITATION_UNVERIFIED_SECONDARY,
3274        citation_note: Some(oj_note!()),
3275    },
3276    ProfileRequirement {
3277        id: "eu-aia-human-oversight",
3278        clause: "Reg (EU) 2024/1689, Art. 14",
3279        title: "Human oversight through enforced operating limits",
3280        credential: "PhysicalCapabilityScope",
3281        fields: &["physicalScope.maxSpeedNearHumansMps"],
3282        expect_true: &[],
3283        citation: CITATION_UNVERIFIED_SECONDARY,
3284        citation_note: Some(concat!(
3285            oj_note!(),
3286            " Art. 14 also requires a means for the overseer to intervene or \
3287             stop the system, which an operating-limit scope alone does not \
3288             evidence."
3289        )),
3290    },
3291    ProfileRequirement {
3292        id: "eu-aia-accuracy-robustness",
3293        clause: "Reg (EU) 2024/1689, Art. 15",
3294        title: "Accuracy and robustness traceable to a known build",
3295        credential: "ModelProvenanceAttestation",
3296        fields: &["vla.weightsHash"],
3297        expect_true: &[],
3298        citation: CITATION_UNVERIFIED_SECONDARY,
3299        citation_note: Some(oj_note!()),
3300    },
3301];
3302
3303const UL_3300_REQUIREMENTS: &[ProfileRequirement] = &[
3304    ProfileRequirement {
3305        id: "ul3300-identity",
3306        clause: "UL 3300, identification",
3307        title: "Robot identity bound to its hardware",
3308        credential: "RobotIdentityCredential",
3309        fields: &["hardwareRoot.kind", "hardwareRoot.attestation"],
3310        expect_true: &[],
3311        citation: CITATION_DESCRIPTIVE,
3312        citation_note: Some(ul_note!()),
3313    },
3314    ProfileRequirement {
3315        id: "ul3300-operating-limits",
3316        clause: "UL 3300, operating limits",
3317        title: "Enforced speed and zone limits",
3318        credential: "PhysicalCapabilityScope",
3319        fields: &["physicalScope.maxSpeedMps", "physicalScope.allowedZones"],
3320        expect_true: &[],
3321        citation: CITATION_DESCRIPTIVE,
3322        citation_note: Some(ul_note!()),
3323    },
3324    ProfileRequirement {
3325        id: "ul3300-perception-integrity",
3326        clause: "UL 3300, sensing integrity",
3327        title: "Integrity of perception used for safe operation",
3328        credential: "PerceptionProvenanceCredential",
3329        fields: &["frameHash"],
3330        expect_true: &[],
3331        citation: CITATION_DESCRIPTIVE,
3332        citation_note: Some(ul_note!()),
3333    },
3334    ProfileRequirement {
3335        id: "ul3300-records",
3336        clause: "UL 3300, incident records",
3337        title: "Records of safety-relevant incidents",
3338        credential: "RobotSafetyRecordCredential",
3339        fields: &["totalEvents", "logHead"],
3340        expect_true: &[],
3341        citation: CITATION_DESCRIPTIVE,
3342        citation_note: Some(ul_note!()),
3343    },
3344];
3345
3346/// Return a built-in profile by id, or `None` if it is unknown. The five profiles
3347/// cover ISO 10218-1/-2 (industrial), ISO/TS 15066 (collaborative), the EU
3348/// Machinery Regulation 2023/1230, the EU AI Act high-risk requirements, and
3349/// UL 3300 (service and mobile robots).
3350fn conformance_profile(profile_id: &str) -> Option<ConformanceProfile> {
3351    match profile_id {
3352        "iso-10218" => Some(ConformanceProfile {
3353            regime: "ISO 10218-1/-2 industrial robots",
3354            version: "2011 (superseded by the 2025 editions; mapping not yet migrated)",
3355            requirements: ISO_10218_REQUIREMENTS,
3356        }),
3357        "iso-ts-15066" => Some(ConformanceProfile {
3358            regime: "ISO/TS 15066 collaborative robots",
3359            version: "2016",
3360            requirements: ISO_TS_15066_REQUIREMENTS,
3361        }),
3362        "eu-machinery-2023-1230" => Some(ConformanceProfile {
3363            regime: "EU Machinery Regulation 2023/1230",
3364            version: "2023",
3365            requirements: EU_MACHINERY_REQUIREMENTS,
3366        }),
3367        "eu-ai-act-high-risk" => Some(ConformanceProfile {
3368            regime: "EU AI Act high-risk systems",
3369            version: "2024",
3370            requirements: EU_AI_ACT_REQUIREMENTS,
3371        }),
3372        "ul-3300" => Some(ConformanceProfile {
3373            regime: "UL 3300 service, communication, and mobile robots",
3374            version: "2022 (see ANSI/CAN/UL 3300:2024)",
3375            requirements: UL_3300_REQUIREMENTS,
3376        }),
3377        _ => None,
3378    }
3379}
3380
3381/// The type array of a credential, accepting a JSON string or an array of strings.
3382fn credential_types(credential: &Value) -> Vec<&str> {
3383    match credential.get("type") {
3384        Some(Value::String(s)) => vec![s.as_str()],
3385        Some(Value::Array(items)) => items.iter().filter_map(|v| v.as_str()).collect(),
3386        _ => Vec::new(),
3387    }
3388}
3389
3390/// Follow a dot-separated path from the credentialSubject, returning the value at
3391/// the leaf or `None` if any segment is missing or not an object.
3392fn path_value<'a>(subject: &'a Value, path: &str) -> Option<&'a Value> {
3393    let mut node = subject;
3394    for part in path.split('.') {
3395        match node {
3396            Value::Object(map) => match map.get(part) {
3397                Some(v) => node = v,
3398                None => return None,
3399            },
3400            _ => return None,
3401        }
3402    }
3403    Some(node)
3404}
3405
3406/// True when a value is present and non-empty: not null, and not an empty array
3407/// or empty object. Any other value (including `false`, `0`, or `""`) counts.
3408fn value_present(value: &Value) -> bool {
3409    match value {
3410        Value::Null => false,
3411        Value::Array(a) => !a.is_empty(),
3412        Value::Object(o) => !o.is_empty(),
3413        _ => true,
3414    }
3415}
3416
3417/// True when `credential` satisfies `requirement`: its type array includes the
3418/// requirement's credential type, its credentialSubject has a non-null,
3419/// non-empty value at every field path, and every `expect_true` path holds
3420/// boolean `true`. Presence alone is not evidence: a heartbeat that reports an
3421/// envelope breach does not evidence having stayed inside the envelope.
3422fn credential_satisfies(credential: &Value, requirement: &ProfileRequirement) -> bool {
3423    if !credential_types(credential).contains(&requirement.credential) {
3424        return false;
3425    }
3426    let empty = Value::Object(Map::new());
3427    let subject = credential.get("credentialSubject").unwrap_or(&empty);
3428    for path in requirement.fields {
3429        match path_value(subject, path) {
3430            Some(v) if value_present(v) => {}
3431            _ => return false,
3432        }
3433    }
3434    for path in requirement.expect_true {
3435        if path_value(subject, path) != Some(&Value::Bool(true)) {
3436            return false;
3437        }
3438    }
3439    true
3440}
3441
3442/// Check the presented `credentials` against the named profile and return a
3443/// deterministic report. Each requirement is satisfied when some presented
3444/// credential matches its type and has every required field. The caller is
3445/// expected to have verified the credentials' signatures first; this checks
3446/// structure and coverage, not proofs.
3447///
3448/// Every requirement carries the provenance of its clause citation, and the
3449/// report totals them, so a result never reads as more authoritative about the
3450/// regulation than its sources are.
3451///
3452/// The report has exactly `{profileId, regime, version, conforms,
3453/// satisfiedCount, totalCount, citations:{...},
3454/// requirements:[{id, clause, title, satisfied, citation, citationNote?}]}`.
3455pub fn check_conformance(credentials: &[Value], profile_id: &str) -> Result<Value> {
3456    let prof = conformance_profile(profile_id)
3457        .ok_or_else(|| CoreError::Json(format!("unknown conformance profile: {profile_id}")))?;
3458
3459    let mut results: Vec<Value> = Vec::with_capacity(prof.requirements.len());
3460    let mut satisfied = 0i64;
3461    let mut citations = Map::new();
3462    for status in CITATION_STATUSES {
3463        citations.insert((*status).into(), json!(0i64));
3464    }
3465    for requirement in prof.requirements {
3466        let ok = credentials
3467            .iter()
3468            .any(|c| credential_satisfies(c, requirement));
3469        if ok {
3470            satisfied += 1;
3471        }
3472        let seen = citations
3473            .get(requirement.citation)
3474            .and_then(|v| v.as_i64())
3475            .unwrap_or(0);
3476        citations.insert(requirement.citation.into(), json!(seen + 1));
3477        let mut result = Map::new();
3478        result.insert("id".into(), json!(requirement.id));
3479        result.insert("clause".into(), json!(requirement.clause));
3480        result.insert("title".into(), json!(requirement.title));
3481        result.insert("satisfied".into(), json!(ok));
3482        result.insert("citation".into(), json!(requirement.citation));
3483        if let Some(note) = requirement.citation_note {
3484            result.insert("citationNote".into(), json!(note));
3485        }
3486        results.push(Value::Object(result));
3487    }
3488    let total = prof.requirements.len() as i64;
3489
3490    let mut report = Map::new();
3491    report.insert("profileId".into(), json!(profile_id));
3492    report.insert("regime".into(), json!(prof.regime));
3493    report.insert("version".into(), json!(prof.version));
3494    report.insert("conforms".into(), json!(satisfied == total));
3495    report.insert("satisfiedCount".into(), json!(satisfied));
3496    report.insert("totalCount".into(), json!(total));
3497    report.insert("citations".into(), Value::Object(citations));
3498    report.insert("requirements".into(), Value::Array(results));
3499    Ok(Value::Object(report))
3500}
3501
3502/// Multibase SHA-256 of the JCS-canonical report, for binding into an
3503/// attestation. Every language canonicalizes identically, so the digest is the
3504/// same byte string everywhere.
3505pub fn report_digest(report: &Value) -> String {
3506    mb64(&Sha256::digest(jcs::canonicalize(report)))
3507}
3508
3509/// Parameters for [`build_conformance_attestation`]. The signer is the robot, its
3510/// owner, or an assessing authority; `robot_did` names the robot the attestation
3511/// is about. `report` is produced by [`check_conformance`] and is embedded and
3512/// bound by digest. When `valid_seconds` is set it bounds the attestation.
3513#[derive(Debug, Clone)]
3514pub struct BuildConformanceAttestation {
3515    pub issuer_did: String,
3516    pub robot_did: String,
3517    pub report: Value,
3518    pub valid_from: String,
3519    pub valid_until: Option<String>,
3520}
3521
3522/// Build a signed point-in-time `RobotConformanceAttestation` for `robot_did`
3523/// over a `report` produced by [`check_conformance`]. The report is embedded and
3524/// bound by digest.
3525pub fn build_conformance_attestation(
3526    signer_seed: &[u8],
3527    params: &BuildConformanceAttestation,
3528) -> Result<Value> {
3529    if params.robot_did.is_empty() {
3530        return Err(CoreError::Json("robot_did is required".into()));
3531    }
3532    let report = params
3533        .report
3534        .as_object()
3535        .ok_or_else(|| CoreError::Json("report must come from check_conformance".into()))?;
3536    if !report.contains_key("profileId") || !report.contains_key("conforms") {
3537        return Err(CoreError::Json(
3538            "report must come from check_conformance".into(),
3539        ));
3540    }
3541
3542    let mut subject = Map::new();
3543    subject.insert("id".into(), json!(params.robot_did));
3544    subject.insert(
3545        "profileId".into(),
3546        report.get("profileId").cloned().unwrap_or(Value::Null),
3547    );
3548    subject.insert(
3549        "regime".into(),
3550        report.get("regime").cloned().unwrap_or(Value::Null),
3551    );
3552    subject.insert(
3553        "conforms".into(),
3554        report.get("conforms").cloned().unwrap_or(Value::Null),
3555    );
3556    subject.insert(
3557        "satisfiedCount".into(),
3558        report.get("satisfiedCount").cloned().unwrap_or(Value::Null),
3559    );
3560    subject.insert(
3561        "totalCount".into(),
3562        report.get("totalCount").cloned().unwrap_or(Value::Null),
3563    );
3564    subject.insert(
3565        "citations".into(),
3566        report
3567            .get("citations")
3568            .cloned()
3569            .unwrap_or_else(|| Value::Object(Map::new())),
3570    );
3571    subject.insert("reportDigest".into(), json!(report_digest(&params.report)));
3572    subject.insert("report".into(), params.report.clone());
3573
3574    let mut cred = Map::new();
3575    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
3576    cred.insert(
3577        "type".into(),
3578        json!(["VerifiableCredential", CONFORMANCE_ATTESTATION_TYPE]),
3579    );
3580    cred.insert("issuer".into(), json!(params.issuer_did));
3581    cred.insert("validFrom".into(), json!(params.valid_from));
3582    if let Some(vu) = &params.valid_until {
3583        cred.insert("validUntil".into(), json!(vu));
3584    }
3585    cred.insert("credentialSubject".into(), Value::Object(subject));
3586
3587    let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), &params.valid_from);
3588    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
3589}
3590
3591/// Verify a conformance attestation: the issuer's proof, that the embedded report
3592/// matches its bound digest, and that the subject's `conforms` matches the report.
3593/// Returns the credentialSubject on success, `None` if invalid.
3594pub fn verify_conformance_attestation(
3595    credential: &Value,
3596    public_key: &[u8],
3597) -> Result<Option<Value>> {
3598    if !has_type(credential.get("type"), CONFORMANCE_ATTESTATION_TYPE) {
3599        return Ok(None);
3600    }
3601    if !data_integrity::verify_proof(credential, public_key)? {
3602        return Ok(None);
3603    }
3604    let subject = match credential
3605        .get("credentialSubject")
3606        .and_then(|s| s.as_object())
3607    {
3608        Some(s) => s,
3609        None => return Ok(None),
3610    };
3611    let embedded = match subject.get("report") {
3612        Some(r) if r.is_object() => r,
3613        _ => return Ok(None),
3614    };
3615    if subject.get("reportDigest").and_then(|v| v.as_str())
3616        != Some(report_digest(embedded).as_str())
3617    {
3618        return Ok(None);
3619    }
3620    if subject.get("conforms") != embedded.get("conforms") {
3621        return Ok(None);
3622    }
3623    Ok(Some(Value::Object(subject.clone())))
3624}
3625
3626// ---------------------------------------------------------------------------
3627// Post-quantum robot credentials (Phase 5.13)
3628// ---------------------------------------------------------------------------
3629//
3630// A robot fielded today lives for ten to twenty years, longer than classical
3631// Ed25519 is expected to stay safe, so a robot identity signed now could be
3632// forged once a quantum computer arrives. This section makes the hybrid
3633// post-quantum cryptosuite (`hybrid-eddsa-mldsa44-jcs-2026`, a classical
3634// Ed25519 signature alongside an ML-DSA-44 signature) available for robot
3635// credentials so they stay unforgeable across the robot's whole service life.
3636//
3637//   - sign_pq: attach a hybrid proof to a robot credential.
3638//   - verify_robot_credential: verify a robot credential whether it carries a
3639//     classical or a hybrid proof, auto-detected from the proof, so a fleet can
3640//     move to PQ gradually without breaking the classical credentials already in
3641//     the field.
3642//   - migrate_to_pq: re-sign a fielded robot's classical credential under PQ.
3643//
3644// This is the open layer: hybrid signing, backward-compatible verification, and
3645// a software re-signing migration path. It reuses the existing hybrid composite
3646// path ([`crate::hybrid`]) and the ML-DSA-44 and multikey helpers rather than
3647// re-deriving any cryptography.
3648
3649/// The classical (Ed25519-only) robot credential cryptosuite.
3650pub const CLASSICAL_CRYPTOSUITE: &str = data_integrity::CRYPTOSUITE_ID;
3651/// The hybrid post-quantum robot credential cryptosuite.
3652pub const HYBRID_CRYPTOSUITE: &str = hybrid::HYBRID_COMPOSITE_CRYPTOSUITE_ID;
3653
3654/// Coerce an ML-DSA-44 public key supplied either as raw 1312-byte bytes or as a
3655/// Multikey string into raw bytes. Errors on the wrong length or a non-ML-DSA
3656/// multikey.
3657pub fn coerce_mldsa44_public(mldsa44_public: &[u8]) -> Result<Vec<u8>> {
3658    if mldsa44_public.len() != MLDSA44_PUBLIC_LEN {
3659        return Err(CoreError::InvalidKeyLength {
3660            expected: MLDSA44_PUBLIC_LEN,
3661            got: mldsa44_public.len(),
3662        });
3663    }
3664    Ok(mldsa44_public.to_vec())
3665}
3666
3667/// Coerce an ML-DSA-44 Multikey string into raw public-key bytes. Errors if the
3668/// multikey does not carry an ML-DSA-44 key.
3669pub fn mldsa44_public_from_multikey(multikey_str: &str) -> Result<Vec<u8>> {
3670    let decoded = multikey::decode(multikey_str)?;
3671    if decoded.algorithm != "ML-DSA-44" {
3672        return Err(CoreError::InvalidMultikey(format!(
3673            "expected an ML-DSA-44 multikey, got {}",
3674            decoded.algorithm
3675        )));
3676    }
3677    coerce_mldsa44_public(&decoded.raw_key)
3678}
3679
3680fn pq_verification_method(credential: &Value) -> String {
3681    let issuer = credential
3682        .as_object()
3683        .and_then(|o| o.get("issuer"))
3684        .and_then(|v| v.as_str())
3685        .unwrap_or("");
3686    format!("{issuer}#key-1")
3687}
3688
3689/// The ML-DSA-44 verification method slot, matching the `#key-2` convention the
3690/// language SDKs derive for the post-quantum member of a proof set.
3691fn pq_mldsa_verification_method(credential: &Value) -> String {
3692    let issuer = credential
3693        .as_object()
3694        .and_then(|o| o.get("issuer"))
3695        .and_then(|v| v.as_str())
3696        .unwrap_or("");
3697    format!("{issuer}#key-2")
3698}
3699
3700/// Attach a hybrid (classical Ed25519 plus post-quantum ML-DSA-44) Data Integrity
3701/// proof to a pre-built robot `credential`. Any existing proof is replaced. The
3702/// robot signs with its Ed25519 seed and its ML-DSA-44 key pair; `created` is the
3703/// caller-supplied ISO-8601 instant, keeping the core deterministic.
3704pub fn sign_pq(
3705    credential: &Value,
3706    ed25519_seed: &[u8],
3707    mldsa: &MlDsa44KeyPair,
3708    created: &str,
3709) -> Result<Value> {
3710    let ed_vm = pq_verification_method(credential);
3711    let ml_vm = pq_mldsa_verification_method(credential);
3712    hybrid::sign_dual(credential, ed25519_seed, mldsa, &ed_vm, &ml_vm, created)
3713}
3714
3715/// Return true if `credential` carries a post-quantum proof, in either the
3716/// proof-set shape (a `proof` array holding an ML-DSA-44 proof) or the
3717/// pre-alignment composite shape.
3718pub fn is_pq(credential: &Value) -> bool {
3719    let proof = match credential.as_object().and_then(|o| o.get("proof")) {
3720        Some(p) => p,
3721        None => return false,
3722    };
3723    match proof {
3724        Value::Array(proofs) => proofs.iter().any(|p| {
3725            matches!(
3726                p.get("cryptosuite").and_then(|v| v.as_str()),
3727                Some(hybrid::MLDSA44_CRYPTOSUITE_ID) | Some(hybrid::MLDSA44_LEGACY_CRYPTOSUITE_ID)
3728            )
3729        }),
3730        Value::Object(o) => {
3731            o.get("cryptosuite").and_then(|v| v.as_str()) == Some(HYBRID_CRYPTOSUITE)
3732        }
3733        _ => false,
3734    }
3735}
3736
3737/// Verify a post-quantum robot credential in whichever shape it carries. Both
3738/// the Ed25519 and the ML-DSA-44 signatures MUST validate in either shape.
3739fn verify_pq_either_shape(
3740    credential: &Value,
3741    ed25519_public_key: &[u8],
3742    mldsa44_public_key: &[u8],
3743) -> Result<bool> {
3744    match credential.as_object().and_then(|o| o.get("proof")) {
3745        Some(Value::Array(_)) => {
3746            hybrid::verify_dual(credential, ed25519_public_key, mldsa44_public_key)
3747        }
3748        _ => hybrid::verify_composite(credential, ed25519_public_key, mldsa44_public_key),
3749    }
3750}
3751
3752/// Verify a hybrid robot credential. Both the Ed25519 and the ML-DSA-44 signature
3753/// MUST validate. `mldsa44_public_key` is raw 1312-byte bytes or an ML-DSA-44
3754/// Multikey string (pass `mldsa44_multikey` for the string form).
3755pub fn verify_pq(
3756    credential: &Value,
3757    ed25519_public_key: &[u8],
3758    mldsa44_public_key: &[u8],
3759) -> Result<bool> {
3760    let resolved_ml = coerce_mldsa44_public(mldsa44_public_key)?;
3761    verify_pq_either_shape(credential, ed25519_public_key, &resolved_ml)
3762}
3763
3764/// Verify a robot credential whether it carries a classical or a hybrid proof,
3765/// auto-detected from the proof cryptosuite. A hybrid credential REQUIRES
3766/// `mldsa44_public_key` (returns Ok(false) if absent); a classical credential
3767/// ignores it and is verified under `eddsa-jcs-2022`. This is the
3768/// backward-compatible verify a fleet uses while migrating to PQ.
3769///
3770/// `mldsa44_public_key` accepts raw 1312-byte bytes or an ML-DSA-44 Multikey
3771/// string, matched by length: a 1312-byte input is treated as raw, anything else
3772/// is parsed as a UTF-8 Multikey string.
3773pub fn verify_robot_credential(
3774    credential: &Value,
3775    ed25519_public_key: &[u8],
3776    mldsa44_public_key: Option<&[u8]>,
3777) -> Result<bool> {
3778    if is_pq(credential) {
3779        let ml = match mldsa44_public_key {
3780            Some(k) => k,
3781            None => return Ok(false),
3782        };
3783        let resolved_ml = resolve_mldsa44_public(ml)?;
3784        return verify_pq_either_shape(credential, ed25519_public_key, &resolved_ml);
3785    }
3786    // Supplying an ML-DSA-44 key means the caller requires the post-quantum
3787    // proof. A credential that is not a post-quantum proof set is rejected here
3788    // rather than verified under Ed25519 alone, so a post-quantum credential
3789    // whose ML-DSA proof was stripped cannot be accepted as a classical one. A
3790    // caller that intends to accept classical credentials passes no ML-DSA key.
3791    if mldsa44_public_key.is_some() {
3792        return Ok(false);
3793    }
3794    data_integrity::verify_proof(credential, ed25519_public_key)
3795}
3796
3797/// Resolve an ML-DSA-44 public key given either raw bytes or a Multikey string.
3798/// A 1312-byte input is the raw key; otherwise it is parsed as a UTF-8 Multikey.
3799pub fn resolve_mldsa44_public(mldsa44_public_key: &[u8]) -> Result<Vec<u8>> {
3800    if mldsa44_public_key.len() == MLDSA44_PUBLIC_LEN {
3801        return Ok(mldsa44_public_key.to_vec());
3802    }
3803    let s = std::str::from_utf8(mldsa44_public_key).map_err(|_| {
3804        CoreError::InvalidMultikey("ML-DSA-44 key must be raw bytes or a Multikey string".into())
3805    })?;
3806    mldsa44_public_from_multikey(s)
3807}
3808
3809/// Re-sign a fielded robot's classical `credential` under the hybrid PQ
3810/// cryptosuite, preserving its body. The robot holds its current Ed25519 seed and
3811/// an ML-DSA-44 key pair; `created` is the caller-supplied re-signing instant.
3812pub fn migrate_to_pq(
3813    credential: &Value,
3814    ed25519_seed: &[u8],
3815    mldsa: &MlDsa44KeyPair,
3816    created: &str,
3817) -> Result<Value> {
3818    sign_pq(credential, ed25519_seed, mldsa, created)
3819}
3820
3821// ---------------------------------------------------------------------------
3822// Cross-embodiment identity continuity (Phase 5.15)
3823// ---------------------------------------------------------------------------
3824//
3825// An AI agent (a policy with its own Vouch identity) can run on one robot body
3826// today and a different body tomorrow. An embodiment credential binds the agent
3827// identity to a specific body (a hardware-rooted robot identity) and that body's
3828// hardware root for a period, signed by the agent's own persistent key. Linking
3829// each embodiment to the previous forms a continuity chain a verifier walks to
3830// confirm the same accountable agent persisted across bodies, re-binding to each
3831// body's hardware root as it moved. A fork check confirms the agent was never
3832// actively embodied in two bodies at once.
3833//
3834// This is the inverse of the ownership custody chain: there one body passes
3835// between owners; here one mind passes between bodies, and the constant that
3836// signs every link is the agent identity itself.
3837//
3838// This is the open layer: plain signed embodiment credentials, continuity-chain
3839// verification, and software fork detection. It reuses the core proof path
3840// ([`data_integrity`]) rather than re-deriving any cryptography.
3841
3842pub const EMBODIMENT_TYPE: &str = "AgentEmbodimentCredential";
3843
3844/// Parameters for [`build_embodiment`]. The signer is the agent's own persistent
3845/// key; `agent_did` is both issuer and subject id, so the whole continuity chain
3846/// is signed by one accountable identity. `from_body`, when set, links this
3847/// embodiment to the body the agent left, forming the chain. `valid_until`, when
3848/// set, bounds the active window (used by [`check_no_fork`]).
3849#[derive(Debug, Clone)]
3850pub struct BuildEmbodiment {
3851    pub agent_did: String,
3852    pub body_did: String,
3853    pub body_hardware_root: String,
3854    pub from_body: Option<String>,
3855    pub embodied_at: String,
3856    pub valid_until: Option<String>,
3857}
3858
3859/// Build a signed embodiment credential: the agent `agent_did` authorizes running
3860/// on `body_did`, re-binding to that body's hardware root `body_hardware_root`.
3861/// Signed by the agent's own persistent key. `from_body` links this embodiment to
3862/// the body the agent left.
3863pub fn build_embodiment(agent_seed: &[u8], params: &BuildEmbodiment) -> Result<Value> {
3864    if params.agent_did.is_empty()
3865        || params.body_did.is_empty()
3866        || params.body_hardware_root.is_empty()
3867    {
3868        return Err(CoreError::Json(
3869            "agent_did, body_did, and body_hardware_root are required".into(),
3870        ));
3871    }
3872
3873    let mut subject = Map::new();
3874    subject.insert("id".into(), json!(params.agent_did));
3875    subject.insert("body".into(), json!(params.body_did));
3876    subject.insert("bodyHardwareRoot".into(), json!(params.body_hardware_root));
3877    if let Some(from_body) = &params.from_body {
3878        subject.insert("fromBody".into(), json!(from_body));
3879    }
3880
3881    let mut cred = Map::new();
3882    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
3883    cred.insert(
3884        "type".into(),
3885        json!(["VerifiableCredential", EMBODIMENT_TYPE]),
3886    );
3887    cred.insert("issuer".into(), json!(params.agent_did));
3888    cred.insert("validFrom".into(), json!(params.embodied_at));
3889    if let Some(vu) = &params.valid_until {
3890        cred.insert("validUntil".into(), json!(vu));
3891    }
3892    cred.insert("credentialSubject".into(), Value::Object(subject));
3893
3894    let opts = BuildProofOptions::new(format!("{}#key-1", params.agent_did), &params.embodied_at);
3895    data_integrity::sign(&Value::Object(cred), agent_seed, &opts)
3896}
3897
3898/// Verify an embodiment credential: the agent's proof, that the issuer is the
3899/// agent itself (a mind authorizes its own embodiment), and that the subject
3900/// carries a `body` and a `bodyHardwareRoot`. Returns the credentialSubject on
3901/// success, `None` if invalid.
3902pub fn verify_embodiment(credential: &Value, agent_public_key: &[u8]) -> Result<Option<Value>> {
3903    let subject = match verify_typed(credential, agent_public_key, EMBODIMENT_TYPE)? {
3904        Some(s) => s,
3905        None => return Ok(None),
3906    };
3907    let has_body = subject
3908        .get("body")
3909        .and_then(|v| v.as_str())
3910        .map(|s| !s.is_empty())
3911        .unwrap_or(false);
3912    let has_root = subject
3913        .get("bodyHardwareRoot")
3914        .and_then(|v| v.as_str())
3915        .map(|s| !s.is_empty())
3916        .unwrap_or(false);
3917    if !has_body || !has_root {
3918        return Ok(None);
3919    }
3920    let subject_id = subject.get("id").and_then(|v| v.as_str());
3921    if credential.get("issuer").and_then(|v| v.as_str()) != subject_id {
3922        return Ok(None);
3923    }
3924    Ok(Some(subject))
3925}
3926
3927/// Verify an ordered list of embodiment credentials forms a valid continuity chain
3928/// for one agent: every link verifies under the SAME agent key (the persistent
3929/// mind), each link's `fromBody` matches the previous link's `body`, and (when
3930/// given) the first `fromBody` is `origin_body`. Returns `(ok, current_body)`.
3931pub fn verify_continuity_chain(
3932    embodiments: &[Value],
3933    agent_public_key: &[u8],
3934    origin_body: Option<&str>,
3935) -> Result<(bool, Option<String>)> {
3936    let mut expected_from: Option<String> = origin_body.map(String::from);
3937    let mut current_body: Option<String> = origin_body.map(String::from);
3938    for embodiment in embodiments {
3939        let subject = match verify_embodiment(embodiment, agent_public_key)? {
3940            Some(s) => s,
3941            None => return Ok((false, None)),
3942        };
3943        if let Some(expected) = &expected_from {
3944            if subject.get("fromBody").and_then(|v| v.as_str()) != Some(expected.as_str()) {
3945                return Ok((false, None));
3946            }
3947        }
3948        current_body = subject
3949            .get("body")
3950            .and_then(|v| v.as_str())
3951            .map(String::from);
3952        expected_from = current_body.clone();
3953    }
3954    Ok((true, current_body))
3955}
3956
3957/// Two conflicting bodies surfaced by [`check_no_fork`].
3958#[derive(Debug, Clone, PartialEq, Eq)]
3959pub struct ForkConflict {
3960    pub body_a: String,
3961    pub body_b: String,
3962}
3963
3964/// Half-open intervals [start, end); a missing end is open-ended (+infinity). A
3965/// clean handover sets one window's end to the next window's start, which does not
3966/// overlap.
3967fn windows_overlap(start_a: i64, end_a: Option<i64>, start_b: i64, end_b: Option<i64>) -> bool {
3968    let a_before_b = end_a.map(|e| e <= start_b).unwrap_or(false);
3969    let b_before_a = end_b.map(|e| e <= start_a).unwrap_or(false);
3970    !(a_before_b || b_before_a)
3971}
3972
3973/// Confirm no two embodiments place the agent in different bodies with overlapping
3974/// active windows. Each embodiment is active from `validFrom` to `validUntil` (a
3975/// missing `validUntil` is treated as open-ended). Two embodiments on different
3976/// bodies whose windows overlap are a fork. Returns `(ok, conflict)` where
3977/// conflict, when present, names the two conflicting bodies.
3978pub fn check_no_fork(embodiments: &[Value]) -> Result<(bool, Option<ForkConflict>)> {
3979    let mut windows: Vec<(String, i64, Option<i64>)> = Vec::with_capacity(embodiments.len());
3980    for embodiment in embodiments {
3981        let subject = embodiment
3982            .get("credentialSubject")
3983            .and_then(|s| s.as_object());
3984        let body = subject
3985            .and_then(|s| s.get("body"))
3986            .and_then(|v| v.as_str())
3987            .filter(|s| !s.is_empty());
3988        let start = embodiment
3989            .get("validFrom")
3990            .and_then(|v| v.as_str())
3991            .and_then(|s| crate::time::iso_to_epoch_seconds(s).ok());
3992        let (body, start) = match (body, start) {
3993            (Some(b), Some(s)) => (b.to_string(), s),
3994            _ => return Ok((false, None)),
3995        };
3996        let end = embodiment
3997            .get("validUntil")
3998            .and_then(|v| v.as_str())
3999            .and_then(|s| crate::time::iso_to_epoch_seconds(s).ok());
4000        windows.push((body, start, end));
4001    }
4002
4003    for i in 0..windows.len() {
4004        let (body_i, start_i, end_i) = &windows[i];
4005        for window_j in windows.iter().skip(i + 1) {
4006            let (body_j, start_j, end_j) = window_j;
4007            if body_i == body_j {
4008                continue;
4009            }
4010            if windows_overlap(*start_i, *end_i, *start_j, *end_j) {
4011                return Ok((
4012                    false,
4013                    Some(ForkConflict {
4014                        body_a: body_i.clone(),
4015                        body_b: body_j.clone(),
4016                    }),
4017                ));
4018            }
4019        }
4020    }
4021    Ok((true, None))
4022}
4023
4024// ---------------------------------------------------------------------------
4025// Physical custody handoff (Phase 5.16)
4026// ---------------------------------------------------------------------------
4027//
4028// A physical task or object passes across a chain of actors, human and robot: a
4029// person picks an item, hands it to a robot, that robot hands it to another
4030// robot, which places it. Each handoff is a signed custody transition, so a
4031// physical-world event traces to the exact hop and the actor responsible.
4032//
4033// A custody handoff credential records that a receiving actor accepted custody
4034// of a task or object from a releasing actor, signed by the receiver. Linking
4035// each handoff to the previous forms a chain a verifier walks to establish who
4036// held the task at any time. A condition attested at each handoff lets a state
4037// change be localized to the specific hop whose holder was responsible.
4038//
4039// This is the open layer: signed handoff credentials, chain verification, a
4040// holder-at-time helper, and software condition localization. It reuses the core
4041// proof path ([`data_integrity`]) rather than re-deriving any cryptography.
4042
4043pub const CUSTODY_HANDOFF_TYPE: &str = "CustodyHandoffCredential";
4044
4045/// Parameters for [`build_handoff`]. The signer is the receiver (`to_actor`), the
4046/// party taking responsibility. `condition`, when set, attests the state of the
4047/// task or object as received (for example a status, a quantity, or a hash of an
4048/// inspection), which lets a later state change be localized to a hop.
4049/// `from_actor` and `to_actor` may be human or robot DIDs. `valid_until`, when
4050/// set, bounds the handoff's active window (the wrapper derives it from a
4051/// `valid_seconds` lifetime added to `handoff_at`, keeping the core's clock
4052/// caller-supplied).
4053#[derive(Debug, Clone)]
4054pub struct BuildHandoff {
4055    pub task_id: String,
4056    pub from_actor: String,
4057    pub to_actor: String,
4058    pub condition: Option<String>,
4059    pub handoff_at: String,
4060    pub valid_until: Option<String>,
4061}
4062
4063/// Build a signed custody handoff: the receiving actor `to_actor` accepts custody
4064/// of `task_id` from `from_actor`, signed by the receiver. The issuer is the
4065/// receiver, so a party attests its own acceptance of custody.
4066pub fn build_handoff(receiver_seed: &[u8], params: &BuildHandoff) -> Result<Value> {
4067    if params.task_id.is_empty() || params.from_actor.is_empty() || params.to_actor.is_empty() {
4068        return Err(CoreError::Json(
4069            "task_id, from_actor, and to_actor are required".into(),
4070        ));
4071    }
4072
4073    let mut subject = Map::new();
4074    subject.insert("id".into(), json!(params.task_id));
4075    subject.insert("fromActor".into(), json!(params.from_actor));
4076    subject.insert("toActor".into(), json!(params.to_actor));
4077    if let Some(condition) = &params.condition {
4078        subject.insert("condition".into(), json!(condition));
4079    }
4080
4081    let mut cred = Map::new();
4082    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
4083    cred.insert(
4084        "type".into(),
4085        json!(["VerifiableCredential", CUSTODY_HANDOFF_TYPE]),
4086    );
4087    cred.insert("issuer".into(), json!(params.to_actor));
4088    cred.insert("validFrom".into(), json!(params.handoff_at));
4089    if let Some(vu) = &params.valid_until {
4090        cred.insert("validUntil".into(), json!(vu));
4091    }
4092    cred.insert("credentialSubject".into(), Value::Object(subject));
4093
4094    let opts = BuildProofOptions::new(format!("{}#key-1", params.to_actor), &params.handoff_at);
4095    data_integrity::sign(&Value::Object(cred), receiver_seed, &opts)
4096}
4097
4098/// Verify a custody handoff: the receiver's proof, that the subject carries both a
4099/// `fromActor` and a `toActor`, and that the issuer is the receiving actor (a
4100/// party attests its own acceptance of custody). Returns the credentialSubject on
4101/// success, `None` if invalid.
4102pub fn verify_handoff(credential: &Value, receiver_public_key: &[u8]) -> Result<Option<Value>> {
4103    let subject = match verify_typed(credential, receiver_public_key, CUSTODY_HANDOFF_TYPE)? {
4104        Some(s) => s,
4105        None => return Ok(None),
4106    };
4107    let from_actor = subject.get("fromActor").and_then(|v| v.as_str());
4108    let to_actor = subject.get("toActor").and_then(|v| v.as_str());
4109    match (from_actor, to_actor) {
4110        (Some(f), Some(t)) if !f.is_empty() && !t.is_empty() => {
4111            if credential.get("issuer").and_then(|v| v.as_str()) != Some(t) {
4112                return Ok(None);
4113            }
4114        }
4115        _ => return Ok(None),
4116    }
4117    Ok(Some(subject))
4118}
4119
4120/// One actor's public key, looked up by actor DID, for [`verify_handoff_chain`].
4121#[derive(Debug, Clone)]
4122pub struct ActorKey {
4123    pub did: String,
4124    pub public_key: Vec<u8>,
4125}
4126
4127/// Verify an ordered list of handoff credentials forms a valid custody chain: each
4128/// handoff verifies under its receiver's key, every link's `toActor` matches the
4129/// next link's `fromActor`, and (when given) the first `fromActor` is
4130/// `origin_actor`. `public_keys` maps an actor DID (human or robot) to its key.
4131/// Returns `(ok, current_holder)`.
4132pub fn verify_handoff_chain(
4133    handoffs: &[Value],
4134    public_keys: &[ActorKey],
4135    origin_actor: Option<&str>,
4136) -> Result<(bool, Option<String>)> {
4137    let mut expected_from: Option<String> = origin_actor.map(String::from);
4138    let mut current_holder: Option<String> = origin_actor.map(String::from);
4139    for handoff in handoffs {
4140        let receiver = handoff.get("issuer").and_then(|v| v.as_str()).unwrap_or("");
4141        let key = match public_keys.iter().find(|k| k.did == receiver) {
4142            Some(k) => k,
4143            None => return Ok((false, None)),
4144        };
4145        let subject = match verify_handoff(handoff, &key.public_key)? {
4146            Some(s) => s,
4147            None => return Ok((false, None)),
4148        };
4149        if let Some(expected) = &expected_from {
4150            if subject.get("fromActor").and_then(|v| v.as_str()) != Some(expected.as_str()) {
4151                return Ok((false, None));
4152            }
4153        }
4154        current_holder = subject
4155            .get("toActor")
4156            .and_then(|v| v.as_str())
4157            .map(String::from);
4158        expected_from = current_holder.clone();
4159    }
4160    Ok((true, current_holder))
4161}
4162
4163/// Return the actor holding the task at ISO time `at`: the receiver (`toActor`) of
4164/// the most recent handoff whose `validFrom` is at or before `at`. Returns `None`
4165/// if no handoff had occurred yet or `at` is unparseable. `handoffs` is assumed in
4166/// chain order.
4167pub fn holder_at(handoffs: &[Value], at: &str) -> Option<String> {
4168    let when = crate::time::iso_to_epoch_seconds(at).ok()?;
4169    let mut holder: Option<String> = None;
4170    for handoff in handoffs {
4171        let start = handoff
4172            .get("validFrom")
4173            .and_then(|v| v.as_str())
4174            .and_then(|s| crate::time::iso_to_epoch_seconds(s).ok());
4175        if let Some(start) = start {
4176            if start <= when {
4177                holder = handoff
4178                    .get("credentialSubject")
4179                    .and_then(|s| s.get("toActor"))
4180                    .and_then(|v| v.as_str())
4181                    .map(String::from);
4182            }
4183        }
4184    }
4185    holder
4186}
4187
4188/// A condition change localized to the hop responsible for it, surfaced by
4189/// [`locate_condition_change`].
4190#[derive(Debug, Clone, PartialEq, Eq)]
4191pub struct ConditionChange {
4192    pub responsible_holder: Option<String>,
4193    pub from_condition: String,
4194    pub to_condition: String,
4195}
4196
4197/// Find the first hop where the attested condition differs from the previous
4198/// handoff. The holder responsible for the change is the actor who held the task
4199/// during it (the previous handoff's receiver). Returns the change, or `None` if
4200/// the condition never changed. Handoffs without a condition are skipped for the
4201/// comparison.
4202pub fn locate_condition_change(handoffs: &[Value]) -> Option<ConditionChange> {
4203    let mut prev_condition: Option<String> = None;
4204    let mut prev_holder: Option<String> = None;
4205    for handoff in handoffs {
4206        let subject = handoff.get("credentialSubject");
4207        let condition = subject
4208            .and_then(|s| s.get("condition"))
4209            .and_then(|v| v.as_str());
4210        let condition = match condition {
4211            Some(c) => c,
4212            None => continue,
4213        };
4214        if let Some(prev) = &prev_condition {
4215            if condition != prev {
4216                return Some(ConditionChange {
4217                    responsible_holder: prev_holder,
4218                    from_condition: prev.clone(),
4219                    to_condition: condition.to_string(),
4220                });
4221            }
4222        }
4223        prev_condition = Some(condition.to_string());
4224        prev_holder = subject
4225            .and_then(|s| s.get("toActor"))
4226            .and_then(|v| v.as_str())
4227            .map(String::from);
4228    }
4229    None
4230}
4231
4232// ---------------------------------------------------------------------------
4233// Robot-to-infrastructure bounded access (Phase 5.17)
4234// ---------------------------------------------------------------------------
4235//
4236// A robot in a warehouse, hospital, or building needs to open doors, call
4237// elevators, dock at chargers, and operate machines. This gives it a bounded,
4238// revocable, auditable way to do so. The infrastructure operator issues an access
4239// grant naming a resource, the permitted operations, an optional zone, and a time
4240// window, signed by the operator. The robot presents a signed access request for a
4241// specific operation on a specific resource, and the resource authorizes it
4242// offline: the grant must be valid and operator-signed, the request valid and
4243// robot-signed, the operation permitted, and the moment inside the window. The
4244// grant plus the request is a tamper-evident, attributable record of the access.
4245//
4246// This is the open layer: signed grants and requests, an offline authorize
4247// decision, shrink-only attenuation, and the audit record. Hardware-enforced
4248// actuation in the resource and managed fleet access-policy orchestration are out
4249// of scope for the open layer.
4250
4251pub const ACCESS_GRANT_TYPE: &str = "InfrastructureAccessGrant";
4252pub const ACCESS_REQUEST_TYPE: &str = "InfrastructureAccessRequest";
4253
4254/// Parameters for [`build_access_grant`]. The signer is the operator; the grant
4255/// names the robot, the resource, the permitted operations, an optional zone, and
4256/// a validity window. `valid_until`, when set, bounds the window (the wrapper
4257/// derives it from a `valid_seconds` lifetime added to `granted_at`, keeping the
4258/// core's clock caller-supplied).
4259#[derive(Debug, Clone)]
4260pub struct BuildAccessGrant {
4261    pub operator_did: String,
4262    pub robot_did: String,
4263    pub resource: String,
4264    pub operations: Vec<String>,
4265    pub zone: Option<String>,
4266    pub granted_at: String,
4267    pub valid_until: Option<String>,
4268}
4269
4270/// Build a signed access grant: the operator grants `robot_did` permission to
4271/// perform `operations` on `resource` (optionally within `zone`) for the window.
4272/// Signed by the operator.
4273pub fn build_access_grant(operator_seed: &[u8], params: &BuildAccessGrant) -> Result<Value> {
4274    if params.robot_did.is_empty() || params.resource.is_empty() {
4275        return Err(CoreError::Json(
4276            "robot_did and resource are required".into(),
4277        ));
4278    }
4279    if params.operations.is_empty() {
4280        return Err(CoreError::Json(
4281            "operations must be a non-empty list".into(),
4282        ));
4283    }
4284
4285    let mut subject = Map::new();
4286    subject.insert("id".into(), json!(params.robot_did));
4287    subject.insert("resource".into(), json!(params.resource));
4288    subject.insert("operations".into(), json!(params.operations));
4289    if let Some(zone) = &params.zone {
4290        subject.insert("zone".into(), json!(zone));
4291    }
4292
4293    let mut cred = Map::new();
4294    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
4295    cred.insert(
4296        "type".into(),
4297        json!(["VerifiableCredential", ACCESS_GRANT_TYPE]),
4298    );
4299    cred.insert("issuer".into(), json!(params.operator_did));
4300    cred.insert("validFrom".into(), json!(params.granted_at));
4301    if let Some(vu) = &params.valid_until {
4302        cred.insert("validUntil".into(), json!(vu));
4303    }
4304    cred.insert("credentialSubject".into(), Value::Object(subject));
4305
4306    let opts = BuildProofOptions::new(format!("{}#key-1", params.operator_did), &params.granted_at);
4307    data_integrity::sign(&Value::Object(cred), operator_seed, &opts)
4308}
4309
4310/// Verify an access grant: the operator's proof, that the subject carries a
4311/// `resource` and non-empty `operations`, and that the grant is within its window
4312/// at `now_iso` (a `None` clock skips the window check). Returns the
4313/// credentialSubject on success, `None` if invalid.
4314pub fn verify_access_grant(
4315    credential: &Value,
4316    operator_public_key: &[u8],
4317    now_iso: Option<&str>,
4318) -> Result<Option<Value>> {
4319    let subject = match verify_typed(credential, operator_public_key, ACCESS_GRANT_TYPE)? {
4320        Some(s) => s,
4321        None => return Ok(None),
4322    };
4323    let resource = subject.get("resource").and_then(|v| v.as_str());
4324    let operations = subject.get("operations").and_then(|v| v.as_array());
4325    match (resource, operations) {
4326        (Some(r), Some(ops)) if !r.is_empty() && !ops.is_empty() => {}
4327        _ => return Ok(None),
4328    }
4329    if !lease_window_current(credential, now_iso) {
4330        return Ok(None);
4331    }
4332    Ok(Some(subject))
4333}
4334
4335/// Parameters for [`build_access_request`]. The signer is the robot; the request
4336/// names the resource and the single operation the robot wants to perform.
4337#[derive(Debug, Clone)]
4338pub struct BuildAccessRequest {
4339    pub robot_did: String,
4340    pub resource: String,
4341    pub operation: String,
4342    pub requested_at: String,
4343}
4344
4345/// Build a signed access request: the robot requests to perform `operation` on
4346/// `resource`. Signed by the robot.
4347pub fn build_access_request(robot_seed: &[u8], params: &BuildAccessRequest) -> Result<Value> {
4348    if params.robot_did.is_empty() || params.resource.is_empty() || params.operation.is_empty() {
4349        return Err(CoreError::Json(
4350            "robot_did, resource, and operation are required".into(),
4351        ));
4352    }
4353
4354    let mut subject = Map::new();
4355    subject.insert("id".into(), json!(params.robot_did));
4356    subject.insert("resource".into(), json!(params.resource));
4357    subject.insert("operation".into(), json!(params.operation));
4358
4359    let mut cred = Map::new();
4360    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
4361    cred.insert(
4362        "type".into(),
4363        json!(["VerifiableCredential", ACCESS_REQUEST_TYPE]),
4364    );
4365    cred.insert("issuer".into(), json!(params.robot_did));
4366    cred.insert("validFrom".into(), json!(params.requested_at));
4367    cred.insert("credentialSubject".into(), Value::Object(subject));
4368
4369    let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), &params.requested_at);
4370    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
4371}
4372
4373/// The outcome of an offline access authorization: `ok` plus any reasons it
4374/// failed. Surfaced by [`authorize_access`].
4375#[derive(Debug, Clone)]
4376pub struct AuthorizeResult {
4377    pub ok: bool,
4378    pub reasons: Vec<String>,
4379}
4380
4381/// Decide, offline, whether to allow the requested access. The grant must verify
4382/// under the operator's key and be in window, the request must verify under the
4383/// robot's key and be issued by the robot it names, the grant and request must
4384/// name the same robot and resource, and the requested operation must be permitted
4385/// by the grant. Returns an [`AuthorizeResult`] with the reasons for any refusal.
4386pub fn authorize_access(
4387    grant: &Value,
4388    request: &Value,
4389    operator_public_key: &[u8],
4390    robot_public_key: &[u8],
4391    now_iso: Option<&str>,
4392) -> Result<AuthorizeResult> {
4393    let mut reasons: Vec<String> = Vec::new();
4394
4395    let grant_subject = match verify_access_grant(grant, operator_public_key, now_iso)? {
4396        Some(s) => s,
4397        None => {
4398            reasons.push("grant invalid or out of window".into());
4399            return Ok(AuthorizeResult { ok: false, reasons });
4400        }
4401    };
4402
4403    let req_subject = match verify_typed(request, robot_public_key, ACCESS_REQUEST_TYPE)? {
4404        Some(s) => s,
4405        None => {
4406            reasons.push("request invalid".into());
4407            return Ok(AuthorizeResult { ok: false, reasons });
4408        }
4409    };
4410    let req_id = req_subject.get("id").and_then(|v| v.as_str());
4411    if request.get("issuer").and_then(|v| v.as_str()) != req_id {
4412        reasons.push("request invalid".into());
4413        return Ok(AuthorizeResult { ok: false, reasons });
4414    }
4415
4416    if grant_subject.get("id").and_then(|v| v.as_str()) != req_id {
4417        reasons.push("grant and request name different robots".into());
4418    }
4419    if grant_subject.get("resource").and_then(|v| v.as_str())
4420        != req_subject.get("resource").and_then(|v| v.as_str())
4421    {
4422        reasons.push("grant and request name different resources".into());
4423    }
4424    let operation = req_subject.get("operation").and_then(|v| v.as_str());
4425    let permitted = grant_subject
4426        .get("operations")
4427        .and_then(|v| v.as_array())
4428        .map(|ops| operation.is_some() && ops.iter().any(|o| o.as_str() == operation))
4429        .unwrap_or(false);
4430    if !permitted {
4431        reasons.push("operation not permitted by the grant".into());
4432    }
4433
4434    Ok(AuthorizeResult {
4435        ok: reasons.is_empty(),
4436        reasons,
4437    })
4438}
4439
4440/// Return true if `child` is a valid attenuation of `parent`: the same resource, a
4441/// subset of the operations, and the same zone (or the parent had no zone). A
4442/// sub-grant may only narrow, never widen, the access it inherits.
4443pub fn attenuates_grant(parent: &Value, child: &Value) -> bool {
4444    let p = parent.get("credentialSubject");
4445    let c = child.get("credentialSubject");
4446    let p_resource = p.and_then(|s| s.get("resource")).and_then(|v| v.as_str());
4447    let c_resource = c.and_then(|s| s.get("resource")).and_then(|v| v.as_str());
4448    if p_resource != c_resource {
4449        return false;
4450    }
4451    let p_ops: HashSet<&str> = p
4452        .and_then(|s| s.get("operations"))
4453        .and_then(|v| v.as_array())
4454        .map(|a| a.iter().filter_map(|o| o.as_str()).collect())
4455        .unwrap_or_default();
4456    let c_ops: HashSet<&str> = c
4457        .and_then(|s| s.get("operations"))
4458        .and_then(|v| v.as_array())
4459        .map(|a| a.iter().filter_map(|o| o.as_str()).collect())
4460        .unwrap_or_default();
4461    if !c_ops.is_subset(&p_ops) {
4462        return false;
4463    }
4464    let p_zone = p.and_then(|s| s.get("zone")).and_then(|v| v.as_str());
4465    let c_zone = c.and_then(|s| s.get("zone")).and_then(|v| v.as_str());
4466    if p_zone.is_some() && c_zone != p_zone {
4467        return false;
4468    }
4469    true
4470}
4471
4472// ---------------------------------------------------------------------------
4473// Fused-sensor provenance (Phase 5.18)
4474// ---------------------------------------------------------------------------
4475//
4476// Perception provenance signs individual sensor frames. A robot rarely acts on
4477// one frame, though: it fuses many frames, from cameras, lidar, radar, and other
4478// sensors, into a single world model, an object set, an occupancy grid, or a
4479// pose estimate, and acts on that. This binds a fused output to the exact set of
4480// input frames that produced it and the fusion method that produced it, signed by
4481// the robot, so a manipulated fusion result or a silently dropped or substituted
4482// input is detectable at the provenance layer.
4483//
4484// A fused-perception attestation carries the hash of the fused output, an ordered
4485// list of the input frame hashes, a digest over those inputs, and a fusion method
4486// identifier, signed by the robot. A verifier reproduces the input digest from the
4487// listed inputs and, when it holds the raw fused output, reproduces its hash, so
4488// the attestation commits to exactly those inputs and that output. Checking each
4489// listed input against the robot's signed perception log confirms every fused
4490// input traces to a frame the robot actually recorded.
4491//
4492// This is the open layer: the robot signs the binding of a fused output to its
4493// inputs in software, reusing the perception frame hashes. Hardware sensor
4494// attestation and managed sensor-fusion orchestration are out of scope for the
4495// open layer.
4496
4497pub const FUSED_PERCEPTION_TYPE: &str = "FusedPerceptionAttestation";
4498
4499/// Multibase (base64url) SHA-256 of a raw fused output. Only the hash travels in
4500/// the attestation; the fused output stays wherever the deployment keeps it.
4501pub fn hash_fused_output(output: &[u8]) -> String {
4502    mb64(&Sha256::digest(output))
4503}
4504
4505/// Return a deterministic multibase digest over an ordered list of input frame
4506/// hashes. The digest commits to the exact inputs and their order, so adding,
4507/// removing, or reordering an input changes it. Reproduced byte-identically
4508/// across language SDKs by hashing the input hashes joined with newlines.
4509pub fn fusion_inputs_digest(input_frame_hashes: &[String]) -> Result<String> {
4510    if input_frame_hashes.is_empty() {
4511        return Err(CoreError::Json(
4512            "input_frame_hashes must be a non-empty list".into(),
4513        ));
4514    }
4515    for h in input_frame_hashes {
4516        if h.is_empty() {
4517            return Err(CoreError::Json(
4518                "each input frame hash must be a non-empty string".into(),
4519            ));
4520        }
4521    }
4522    let joined = input_frame_hashes.join("\n");
4523    Ok(mb64(&Sha256::digest(joined.as_bytes())))
4524}
4525
4526/// Parameters for [`build_fused_attestation`]. The robot self-issues the
4527/// credential with its own Ed25519 seed. Provide either the raw `fused_output` (it
4528/// is hashed) or a precomputed `fused_output_hash`, not both. `captured_at`, when
4529/// `None`, defaults to `valid_from`.
4530#[derive(Debug, Clone)]
4531pub struct BuildFusedAttestation {
4532    pub robot_did: String,
4533    pub fusion_method: String,
4534    pub input_frame_hashes: Vec<String>,
4535    pub fused_output: Option<Vec<u8>>,
4536    pub fused_output_hash: Option<String>,
4537    pub captured_at: Option<String>,
4538    pub valid_from: String,
4539    pub valid_until: Option<String>,
4540}
4541
4542/// Build a signed `FusedPerceptionAttestation`: the robot attests that a fused
4543/// output was produced by `fusion_method` from the frames named in
4544/// `input_frame_hashes`. The attestation carries a digest over the ordered inputs,
4545/// so the set of inputs is tamper-evident. Signed by the robot.
4546pub fn build_fused_attestation(robot_seed: &[u8], params: &BuildFusedAttestation) -> Result<Value> {
4547    if params.robot_did.is_empty() {
4548        return Err(CoreError::Json("robot_did is required".into()));
4549    }
4550    if params.fusion_method.is_empty() {
4551        return Err(CoreError::Json("fusion_method is required".into()));
4552    }
4553    if params.input_frame_hashes.is_empty() {
4554        return Err(CoreError::Json(
4555            "input_frame_hashes must be a non-empty list".into(),
4556        ));
4557    }
4558    if params.fused_output.is_some() && params.fused_output_hash.is_some() {
4559        return Err(CoreError::Json(
4560            "provide either fused_output or fused_output_hash, not both".into(),
4561        ));
4562    }
4563    let fused_output_hash = match (&params.fused_output, &params.fused_output_hash) {
4564        (Some(o), None) => hash_fused_output(o),
4565        (None, Some(h)) if !h.is_empty() => h.clone(),
4566        _ => {
4567            return Err(CoreError::Json(
4568                "fused_output or fused_output_hash is required".into(),
4569            ))
4570        }
4571    };
4572
4573    let captured = params
4574        .captured_at
4575        .clone()
4576        .unwrap_or_else(|| params.valid_from.clone());
4577
4578    let mut subject = Map::new();
4579    subject.insert("id".into(), json!(params.robot_did));
4580    subject.insert("fusionMethod".into(), json!(params.fusion_method));
4581    subject.insert("fusedOutputHash".into(), json!(fused_output_hash));
4582    subject.insert("inputFrameHashes".into(), json!(params.input_frame_hashes));
4583    subject.insert(
4584        "inputsDigest".into(),
4585        json!(fusion_inputs_digest(&params.input_frame_hashes)?),
4586    );
4587    subject.insert("capturedAt".into(), json!(captured));
4588
4589    let mut cred = Map::new();
4590    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
4591    cred.insert(
4592        "type".into(),
4593        json!(["VerifiableCredential", FUSED_PERCEPTION_TYPE]),
4594    );
4595    cred.insert("issuer".into(), json!(params.robot_did));
4596    cred.insert("validFrom".into(), json!(params.valid_from));
4597    if let Some(vu) = &params.valid_until {
4598        cred.insert("validUntil".into(), json!(vu));
4599    }
4600    cred.insert("credentialSubject".into(), Value::Object(subject));
4601
4602    let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), &params.valid_from);
4603    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
4604}
4605
4606/// Verify a `FusedPerceptionAttestation`: the robot's proof, that the digest over
4607/// the listed inputs reproduces the attested `inputsDigest` (so the inputs are
4608/// internally consistent and tamper-evident), and, when the raw `fused_output` is
4609/// supplied, that its hash reproduces the attested `fusedOutputHash`. Returns the
4610/// credentialSubject on success, `None` if invalid.
4611pub fn verify_fused_attestation(
4612    credential: &Value,
4613    public_key: &[u8],
4614    fused_output: Option<&[u8]>,
4615) -> Result<Option<Value>> {
4616    let subject = match verify_typed(credential, public_key, FUSED_PERCEPTION_TYPE)? {
4617        Some(s) => s,
4618        None => return Ok(None),
4619    };
4620    let fused_output_hash = subject.get("fusedOutputHash").and_then(|v| v.as_str());
4621    let inputs: Vec<String> = subject
4622        .get("inputFrameHashes")
4623        .and_then(|v| v.as_array())
4624        .map(|a| {
4625            a.iter()
4626                .filter_map(|e| e.as_str().map(String::from))
4627                .collect()
4628        })
4629        .unwrap_or_default();
4630    match fused_output_hash {
4631        Some(h) if !h.is_empty() && !inputs.is_empty() => {}
4632        _ => return Ok(None),
4633    }
4634    match fusion_inputs_digest(&inputs) {
4635        Ok(d) => {
4636            if Some(d.as_str()) != subject.get("inputsDigest").and_then(|v| v.as_str()) {
4637                return Ok(None);
4638            }
4639        }
4640        Err(_) => return Ok(None),
4641    }
4642    if let Some(o) = fused_output {
4643        if hash_fused_output(o) != fused_output_hash.unwrap_or("") {
4644            return Ok(None);
4645        }
4646    }
4647    Ok(Some(subject))
4648}
4649
4650/// The outcome of confirming an attestation's inputs against a perception log:
4651/// `ok` plus the input frame hashes not found. Surfaced by [`verify_fusion_inputs`].
4652#[derive(Debug, Clone)]
4653pub struct FusionInputsResult {
4654    pub ok: bool,
4655    pub missing: Vec<String>,
4656}
4657
4658/// Confirm every input frame the attestation names was actually recorded in the
4659/// robot's perception log. Returns `ok` plus `missing`, the input frame hashes that
4660/// do not appear as a recorded frame, so a dropped or substituted fused input is
4661/// named rather than hidden.
4662pub fn verify_fusion_inputs(credential: &Value, log_entries: &[Value]) -> FusionInputsResult {
4663    let recorded: HashSet<&str> = log_entries
4664        .iter()
4665        .filter_map(|e| e.get("frameHash").and_then(|v| v.as_str()))
4666        .collect();
4667    let inputs: Vec<String> = credential
4668        .get("credentialSubject")
4669        .and_then(|s| s.get("inputFrameHashes"))
4670        .and_then(|v| v.as_array())
4671        .map(|a| {
4672            a.iter()
4673                .filter_map(|e| e.as_str().map(String::from))
4674                .collect()
4675        })
4676        .unwrap_or_default();
4677    let missing: Vec<String> = inputs
4678        .into_iter()
4679        .filter(|h| !recorded.contains(h.as_str()))
4680        .collect();
4681    FusionInputsResult {
4682        ok: missing.is_empty(),
4683        missing,
4684    }
4685}
4686
4687// ---------------------------------------------------------------------------
4688// Wear and degradation attestation (Phase 5.19)
4689// ---------------------------------------------------------------------------
4690//
4691// A robot does not stay as capable as it left the factory. Actuators wear, joints
4692// develop backlash, sensors drift out of calibration, and error rates creep up.
4693// This lets a robot sign its own degradation state, bound to its identity and
4694// hash-linked over time so the history is tamper-evident, and derives a narrowed
4695// physical capability scope from that state, so a worn robot operates inside a
4696// tighter, verifiable envelope instead of trusting the static limit it shipped
4697// with.
4698//
4699// A wear attestation carries a normalized wear level (0 for as-new, 1 for fully
4700// worn) and optional detailed metrics, signed by the robot. Linking each
4701// attestation to the previous one by its proof value forms a chain a verifier
4702// walks to see how the robot degraded over its life. `attenuate_for_wear` derives
4703// a physical scope whose numeric caps are scaled down by the wear level, and the
4704// result is a valid attenuation of the original scope, so the same attenuation
4705// rule the rest of Vouch uses carries the derating.
4706//
4707// This is the open layer: the robot signs its wear state and derives the narrowed
4708// scope credential in software. Firmware-level enforcement of the narrowed
4709// envelope and managed predictive-maintenance modeling are out of scope for the
4710// open layer.
4711
4712pub const WEAR_ATTESTATION_TYPE: &str = "RobotWearAttestation";
4713
4714/// Numeric caps that scale down with wear. Zones and shift windows are preserved
4715/// unchanged, so the derived scope stays a valid attenuation of the original.
4716const WEAR_DERATED_CAPS: [&str; 3] = ["maxForceN", "maxSpeedMps", "maxSpeedNearHumansMps"];
4717
4718/// Parameters for [`build_wear_attestation`]. The robot self-issues the credential
4719/// with its own Ed25519 seed. `metrics`, when present, is carried through into the
4720/// subject unchanged. `prev_proof`, when present, links this attestation to the
4721/// previous one, forming a wear history. `attested_at`, when `None`, defaults to
4722/// `valid_from`.
4723#[derive(Debug, Clone)]
4724pub struct BuildWearAttestation {
4725    pub robot_did: String,
4726    pub wear_level: f64,
4727    pub metrics: Option<Value>,
4728    pub prev_proof: Option<String>,
4729    pub attested_at: Option<String>,
4730    pub valid_from: String,
4731    pub valid_until: Option<String>,
4732}
4733
4734/// Build a signed `RobotWearAttestation`: the robot attests its own degradation as
4735/// a normalized `wear_level` in `[0, 1]`, optionally with detailed `metrics`. When
4736/// `prev_proof` is the proof value of the previous attestation, the new one links
4737/// to it, forming a tamper-evident wear history. Signed by the robot.
4738pub fn build_wear_attestation(robot_seed: &[u8], params: &BuildWearAttestation) -> Result<Value> {
4739    if params.robot_did.is_empty() {
4740        return Err(CoreError::Json("robot_did is required".into()));
4741    }
4742    if params.wear_level < 0.0 || params.wear_level > 1.0 {
4743        return Err(CoreError::Json(
4744            "wear_level must be between 0.0 and 1.0".into(),
4745        ));
4746    }
4747
4748    let attested = params
4749        .attested_at
4750        .clone()
4751        .unwrap_or_else(|| params.valid_from.clone());
4752
4753    let mut subject = Map::new();
4754    subject.insert("id".into(), json!(params.robot_did));
4755    subject.insert("wearLevel".into(), json!(params.wear_level));
4756    subject.insert("attestedAt".into(), json!(attested));
4757    if let Some(m) = &params.metrics {
4758        subject.insert("metrics".into(), m.clone());
4759    }
4760    if let Some(prev) = &params.prev_proof {
4761        subject.insert("prevProof".into(), json!(prev));
4762    }
4763
4764    let mut cred = Map::new();
4765    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
4766    cred.insert(
4767        "type".into(),
4768        json!(["VerifiableCredential", WEAR_ATTESTATION_TYPE]),
4769    );
4770    cred.insert("issuer".into(), json!(params.robot_did));
4771    cred.insert("validFrom".into(), json!(params.valid_from));
4772    if let Some(vu) = &params.valid_until {
4773        cred.insert("validUntil".into(), json!(vu));
4774    }
4775    cred.insert("credentialSubject".into(), Value::Object(subject));
4776
4777    let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), &params.valid_from);
4778    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
4779}
4780
4781/// Verify a `RobotWearAttestation`: the robot's proof, that the issuer is the
4782/// robot, and that the wear level is in range. Returns the credentialSubject on
4783/// success, `None` if invalid.
4784pub fn verify_wear_attestation(credential: &Value, public_key: &[u8]) -> Result<Option<Value>> {
4785    let subject = match verify_typed(credential, public_key, WEAR_ATTESTATION_TYPE)? {
4786        Some(s) => s,
4787        None => return Ok(None),
4788    };
4789    if credential.get("issuer") != subject.get("id") {
4790        return Ok(None);
4791    }
4792    match subject.get("wearLevel").and_then(|v| v.as_f64()) {
4793        Some(level) if (0.0..=1.0).contains(&level) => {}
4794        _ => return Ok(None),
4795    }
4796    Ok(Some(subject))
4797}
4798
4799/// Verify an ordered wear history: each attestation verifies under the robot's
4800/// key, and each one after the first links to the previous by its proof value.
4801/// Returns the latest credentialSubject on success, `None` if any link is invalid.
4802pub fn verify_wear_chain(attestations: &[Value], public_key: &[u8]) -> Result<Option<Value>> {
4803    if attestations.is_empty() {
4804        return Ok(None);
4805    }
4806    let mut prev_proof: Option<String> = None;
4807    let mut latest: Option<Value> = None;
4808    for att in attestations {
4809        let subject = match verify_wear_attestation(att, public_key)? {
4810            Some(s) => s,
4811            None => return Ok(None),
4812        };
4813        if let Some(prev) = &prev_proof {
4814            let linked = subject.get("prevProof").and_then(|v| v.as_str());
4815            if linked != Some(prev.as_str()) {
4816                return Ok(None);
4817            }
4818        }
4819        prev_proof = att
4820            .get("proof")
4821            .and_then(|p| p.get("proofValue"))
4822            .and_then(|v| v.as_str())
4823            .map(String::from);
4824        latest = Some(subject);
4825    }
4826    Ok(latest)
4827}
4828
4829/// Derive a physical scope narrowed for the given wear level: each numeric cap is
4830/// scaled by `(1 - wear_level)`, and the allowed zones and shift windows are
4831/// carried through unchanged. The result is a valid attenuation of `scope` (never
4832/// broader on any dimension), so the same attenuation check the rest of Vouch uses
4833/// accepts it. A wear level of 0 returns the caps unchanged.
4834pub fn attenuate_for_wear(scope: &Value, wear_level: f64) -> Result<Value> {
4835    if wear_level < 0.0 || wear_level > 1.0 {
4836        return Err(CoreError::Json(
4837            "wear_level must be between 0.0 and 1.0".into(),
4838        ));
4839    }
4840    let factor = 1.0 - wear_level;
4841    let empty = Map::new();
4842    let src = scope.as_object().unwrap_or(&empty);
4843    let mut narrowed = Map::new();
4844    for (key, value) in src {
4845        if WEAR_DERATED_CAPS.contains(&key.as_str()) {
4846            if let Some(n) = value.as_f64() {
4847                narrowed.insert(key.clone(), json!(n * factor));
4848                continue;
4849            }
4850        }
4851        narrowed.insert(key.clone(), value.clone());
4852    }
4853    Ok(Value::Object(narrowed))
4854}
4855
4856// ---------------------------------------------------------------------------
4857// Bystander-consent evidence (Phase 5.20)
4858// ---------------------------------------------------------------------------
4859//
4860// A robot working in a shared or public space captures people incidentally
4861// through its cameras and microphones. This lets the robot record, at capture
4862// time, the basis on which a capture was permitted, bound to the specific capture
4863// and to the robot's identity, and lets a bystander (or their device) sign a
4864// consent token bound to that one capture. Only hashes and a consent basis are
4865// stored, never an image or a bystander's identifying data, so the evidence is
4866// verifiable without retaining anyone's biometrics.
4867//
4868// A bystander consent token is signed by the bystander over the hash of the
4869// capture and the robot's DID, so it verifies only against the capture it was
4870// given for and cannot be replayed to a different recording. A bystander-consent
4871// evidence credential is signed by the robot, binding the capture hash to a
4872// consent basis (an explicit token, posted notice, a legitimate interest, or a
4873// redaction that was applied) and, when the basis is explicit consent, to the
4874// tokens that cover it.
4875//
4876// This is the open layer: the cryptographic binding of a consent basis to a
4877// capture, and its verification, holding only hashes. On-device biometric
4878// detection and redaction, and managed consent-registry orchestration, are out of
4879// scope for the open layer.
4880
4881pub const CONSENT_EVIDENCE_TYPE: &str = "BystanderConsentEvidence";
4882pub const CONSENT_TOKEN_TYPE: &str = "BystanderConsentToken";
4883
4884/// Accepted consent bases: the interoperable set a verifier can rely on.
4885/// Implementers MAY use additional values.
4886pub const CONSENT_BASES: [&str; 4] = [
4887    "explicit-consent",
4888    "posted-notice",
4889    "legitimate-interest",
4890    "redacted",
4891];
4892
4893/// Multibase (base64url) SHA-256 of a raw capture. Only the hash travels in the
4894/// token and the evidence; the capture stays wherever the deployment keeps it.
4895pub fn hash_capture(capture: &[u8]) -> String {
4896    mb64(&Sha256::digest(capture))
4897}
4898
4899/// Parameters for [`build_consent_token`]. The signer is the bystander; the token
4900/// binds their consent to one capture (named by `capture_hash`) by one robot
4901/// (`robot_did`). `valid_until`, when set, bounds the window (the wrapper derives
4902/// it from a `valid_seconds` lifetime added to `granted_at`, keeping the core's
4903/// clock caller-supplied). `scope`, when set, records what the consent covers.
4904#[derive(Debug, Clone)]
4905pub struct BuildConsentToken {
4906    pub bystander_did: String,
4907    pub capture_hash: String,
4908    pub robot_did: String,
4909    pub scope: Option<String>,
4910    pub granted_at: String,
4911    pub valid_until: Option<String>,
4912}
4913
4914/// Build a signed `BystanderConsentToken`: a bystander grants consent for a
4915/// specific capture (named by `capture_hash`) by a specific robot (`robot_did`),
4916/// signed by the bystander. Binding the token to the capture hash means it cannot
4917/// be replayed to a different recording. Signed by the bystander.
4918pub fn build_consent_token(bystander_seed: &[u8], params: &BuildConsentToken) -> Result<Value> {
4919    if params.bystander_did.is_empty()
4920        || params.capture_hash.is_empty()
4921        || params.robot_did.is_empty()
4922    {
4923        return Err(CoreError::Json(
4924            "bystander_did, capture_hash, and robot_did are required".into(),
4925        ));
4926    }
4927
4928    let mut subject = Map::new();
4929    subject.insert("id".into(), json!(params.bystander_did));
4930    subject.insert("captureHash".into(), json!(params.capture_hash));
4931    subject.insert("robotDid".into(), json!(params.robot_did));
4932    if let Some(scope) = &params.scope {
4933        subject.insert("scope".into(), json!(scope));
4934    }
4935
4936    let mut cred = Map::new();
4937    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
4938    cred.insert(
4939        "type".into(),
4940        json!(["VerifiableCredential", CONSENT_TOKEN_TYPE]),
4941    );
4942    cred.insert("issuer".into(), json!(params.bystander_did));
4943    cred.insert("validFrom".into(), json!(params.granted_at));
4944    if let Some(vu) = &params.valid_until {
4945        cred.insert("validUntil".into(), json!(vu));
4946    }
4947    cred.insert("credentialSubject".into(), Value::Object(subject));
4948
4949    let opts = BuildProofOptions::new(
4950        format!("{}#key-1", params.bystander_did),
4951        &params.granted_at,
4952    );
4953    data_integrity::sign(&Value::Object(cred), bystander_seed, &opts)
4954}
4955
4956/// Verify a `BystanderConsentToken`: the bystander's proof, that the issuer is the
4957/// bystander, that the token is bound to this capture and this robot, and that it
4958/// is within its window at `now_iso` (a `None` clock skips the window check).
4959/// Returns the credentialSubject on success, `None` if invalid.
4960pub fn verify_consent_token(
4961    token: &Value,
4962    bystander_public_key: &[u8],
4963    capture_hash: &str,
4964    robot_did: &str,
4965    now_iso: Option<&str>,
4966) -> Result<Option<Value>> {
4967    let subject = match verify_typed(token, bystander_public_key, CONSENT_TOKEN_TYPE)? {
4968        Some(s) => s,
4969        None => return Ok(None),
4970    };
4971    if token.get("issuer") != subject.get("id") {
4972        return Ok(None);
4973    }
4974    if subject.get("captureHash").and_then(|v| v.as_str()) != Some(capture_hash)
4975        || subject.get("robotDid").and_then(|v| v.as_str()) != Some(robot_did)
4976    {
4977        return Ok(None);
4978    }
4979    if !lease_window_current(token, now_iso) {
4980        return Ok(None);
4981    }
4982    Ok(Some(subject))
4983}
4984
4985/// Parameters for [`build_consent_evidence`]. The signer is the robot; the
4986/// evidence records that a capture (named by `capture_hash`) was permitted on
4987/// `basis`, one of [`CONSENT_BASES`]. `consent_tokens`, when the basis is explicit
4988/// consent, are the bystander tokens that cover it, committed by their proof value.
4989/// `redaction_hash`, when set, records that a redacted output was produced.
4990/// `valid_until`, when set, bounds the window.
4991#[derive(Debug, Clone)]
4992pub struct BuildConsentEvidence {
4993    pub robot_did: String,
4994    pub capture_hash: String,
4995    pub basis: String,
4996    pub consent_tokens: Vec<Value>,
4997    pub redaction_hash: Option<String>,
4998    pub valid_from: String,
4999    pub valid_until: Option<String>,
5000}
5001
5002/// A privacy-preserving reference to a token: its proof value. Never embeds a
5003/// bystander's identifying data.
5004fn consent_token_ref(token: &Value) -> Result<String> {
5005    token
5006        .get("proof")
5007        .and_then(|p| p.get("proofValue"))
5008        .and_then(|v| v.as_str())
5009        .map(String::from)
5010        .ok_or_else(|| CoreError::Json("consent token is missing a proof value".into()))
5011}
5012
5013/// Build a signed `BystanderConsentEvidence` credential: the robot records that a
5014/// capture (named by `capture_hash`) was permitted on `basis`, one of
5015/// [`CONSENT_BASES`]. When the basis is explicit consent, the `consent_tokens` are
5016/// the bystander tokens that cover it, and the evidence commits to them by their
5017/// proof value (never embedding a bystander's identifying data). Signed by the
5018/// robot.
5019pub fn build_consent_evidence(robot_seed: &[u8], params: &BuildConsentEvidence) -> Result<Value> {
5020    if params.robot_did.is_empty() || params.capture_hash.is_empty() {
5021        return Err(CoreError::Json(
5022            "robot_did and capture_hash are required".into(),
5023        ));
5024    }
5025    if !CONSENT_BASES.contains(&params.basis.as_str()) {
5026        return Err(CoreError::Json(format!(
5027            "basis must be one of {:?}, got {:?}",
5028            CONSENT_BASES, params.basis
5029        )));
5030    }
5031    if params.basis == "explicit-consent" && params.consent_tokens.is_empty() {
5032        return Err(CoreError::Json(
5033            "explicit-consent basis requires at least one consent token".into(),
5034        ));
5035    }
5036
5037    let mut subject = Map::new();
5038    subject.insert("id".into(), json!(params.robot_did));
5039    subject.insert("captureHash".into(), json!(params.capture_hash));
5040    subject.insert("basis".into(), json!(params.basis));
5041    if !params.consent_tokens.is_empty() {
5042        let mut refs = Vec::with_capacity(params.consent_tokens.len());
5043        for t in &params.consent_tokens {
5044            refs.push(consent_token_ref(t)?);
5045        }
5046        subject.insert("consentTokenRefs".into(), json!(refs));
5047    }
5048    if let Some(rh) = &params.redaction_hash {
5049        subject.insert("redactionHash".into(), json!(rh));
5050    }
5051
5052    let mut cred = Map::new();
5053    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
5054    cred.insert(
5055        "type".into(),
5056        json!(["VerifiableCredential", CONSENT_EVIDENCE_TYPE]),
5057    );
5058    cred.insert("issuer".into(), json!(params.robot_did));
5059    cred.insert("validFrom".into(), json!(params.valid_from));
5060    if let Some(vu) = &params.valid_until {
5061        cred.insert("validUntil".into(), json!(vu));
5062    }
5063    cred.insert("credentialSubject".into(), Value::Object(subject));
5064
5065    let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), &params.valid_from);
5066    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
5067}
5068
5069/// One bystander's public key, looked up by bystander DID, for
5070/// [`verify_consent_evidence`].
5071#[derive(Debug, Clone)]
5072pub struct BystanderKey {
5073    pub did: String,
5074    pub public_key: Vec<u8>,
5075}
5076
5077/// Verify a `BystanderConsentEvidence` credential: the robot's proof, that the
5078/// issuer is the robot, and that the basis is accepted. When `capture` is supplied,
5079/// its hash must reproduce the attested capture hash. When `consent_tokens` and
5080/// `bystander_keys` are supplied, every token must verify, be bound to this capture
5081/// and this robot, and match a committed reference, and an explicit-consent
5082/// evidence must carry at least one token. Returns the credentialSubject on
5083/// success, `None` if invalid.
5084pub fn verify_consent_evidence(
5085    evidence: &Value,
5086    robot_public_key: &[u8],
5087    capture: Option<&[u8]>,
5088    consent_tokens: Option<&[Value]>,
5089    bystander_keys: Option<&[BystanderKey]>,
5090    now_iso: Option<&str>,
5091) -> Result<Option<Value>> {
5092    let subject = match verify_typed(evidence, robot_public_key, CONSENT_EVIDENCE_TYPE)? {
5093        Some(s) => s,
5094        None => return Ok(None),
5095    };
5096    if evidence.get("issuer") != subject.get("id") {
5097        return Ok(None);
5098    }
5099    let basis = subject.get("basis").and_then(|v| v.as_str());
5100    match basis {
5101        Some(b) if CONSENT_BASES.contains(&b) => {}
5102        _ => return Ok(None),
5103    }
5104    let capture_hash = match subject.get("captureHash").and_then(|v| v.as_str()) {
5105        Some(h) if !h.is_empty() => h,
5106        _ => return Ok(None),
5107    };
5108
5109    if let Some(c) = capture {
5110        if hash_capture(c) != capture_hash {
5111            return Ok(None);
5112        }
5113    }
5114
5115    let refs: HashSet<&str> = subject
5116        .get("consentTokenRefs")
5117        .and_then(|v| v.as_array())
5118        .map(|a| a.iter().filter_map(|r| r.as_str()).collect())
5119        .unwrap_or_default();
5120    if basis == Some("explicit-consent") && refs.is_empty() {
5121        return Ok(None);
5122    }
5123
5124    if let (Some(tokens), Some(keys)) = (consent_tokens, bystander_keys) {
5125        let robot_did = subject.get("id").and_then(|v| v.as_str()).unwrap_or("");
5126        for token in tokens {
5127            let issuer = token.get("issuer").and_then(|v| v.as_str());
5128            let key = match issuer.and_then(|i| keys.iter().find(|k| k.did == i)) {
5129                Some(k) => &k.public_key,
5130                None => return Ok(None),
5131            };
5132            let tok_ok =
5133                verify_consent_token(token, key, capture_hash, robot_did, now_iso)?.is_some();
5134            let committed = consent_token_ref(token)
5135                .map(|r| refs.contains(r.as_str()))
5136                .unwrap_or(false);
5137            if !tok_ok || !committed {
5138                return Ok(None);
5139            }
5140        }
5141    }
5142
5143    Ok(Some(subject))
5144}
5145
5146#[cfg(test)]
5147mod tests {
5148    use super::*;
5149    use crate::keys::Ed25519KeyPair;
5150    use std::fs;
5151
5152    fn load_vector() -> Value {
5153        let raw = fs::read_to_string("../../test-vectors/robotics/vector.json")
5154            .expect("interop vector present");
5155        serde_json::from_str(&raw).unwrap()
5156    }
5157
5158    fn software_root_attest(root_seed: &[u8], robot_did: &str, robot_key_mb: &str) -> Vec<u8> {
5159        let kp = Ed25519KeyPair::from_seed_slice(root_seed).unwrap();
5160        let binding = robot_identity_binding(robot_did, robot_key_mb);
5161        kp.sign(&binding).to_vec()
5162    }
5163
5164    // Cross-language interop: Go and TypeScript verify this same Python-minted
5165    // credential; the Rust core must too.
5166    #[test]
5167    fn verifies_python_interop_vector() {
5168        let raw = fs::read_to_string("../../test-vectors/robotics/vector.json")
5169            .expect("interop vector present");
5170        let vector: Value = serde_json::from_str(&raw).unwrap();
5171        let jwk_x = vector["robot_public_key_jwk"]["x"].as_str().unwrap();
5172        let robot_pub = URL_SAFE_NO_PAD.decode(jwk_x).unwrap();
5173        let cred = vector["robot_identity_credential"].clone();
5174
5175        let subject = verify_robot_identity(&cred, &robot_pub).unwrap();
5176        let subject = subject.expect("the Python interop vector must verify in Rust");
5177        assert_eq!(subject["make"], json!("Acme Robotics"));
5178    }
5179
5180    #[test]
5181    fn mint_verify_roundtrip() {
5182        let robot_seed = [3u8; 32];
5183        let root_seed = [7u8; 32];
5184        let robot_did = "did:web:robot.example.com";
5185        let robot_kp = Ed25519KeyPair::from_seed(&robot_seed);
5186        let root_kp = Ed25519KeyPair::from_seed(&root_seed);
5187
5188        let attestation = software_root_attest(&root_seed, robot_did, &robot_kp.public_multikey());
5189        let params = MintRobotIdentity {
5190            robot_did: robot_did.into(),
5191            make: "Acme".into(),
5192            model: "AR-7".into(),
5193            serial: "SN-1".into(),
5194            owner: Some("did:web:owner.example.com".into()),
5195            root_kind: "TPM".into(),
5196            root_public_multibase: root_kp.public_multikey(),
5197            attestation,
5198            lifecycle: None,
5199            valid_from: "2026-01-01T00:00:00Z".into(),
5200            valid_until: None,
5201        };
5202        let cred = mint_robot_identity(&robot_seed, &params).unwrap();
5203        let subject = verify_robot_identity(&cred, &robot_kp.public_key()).unwrap();
5204        assert!(subject.is_some(), "round-trip identity must verify");
5205    }
5206
5207    // Cross-language interop: this HalosSafetyEvidenceCredential, its black-box
5208    // entries, and the robot public key were produced by the Python reference
5209    // (vouch/robotics/halos.py) from a fixed Ed25519 seed (0x05 x32), a fixed
5210    // black-box key, and a fixed `created` timestamp. The Rust verify must accept
5211    // it, and must reject a tampered entry or a wrong entry count.
5212    const PY_HALOS_CREDENTIAL: &str = r#"{"@context":["https://www.w3.org/ns/credentials/v2","https://vouch-protocol.com/contexts/v1"],"type":["VerifiableCredential","HalosSafetyEvidenceCredential"],"issuer":"did:key:z6MkmtWtY63GQVBrpMyRJWEzsnxfsGkemu6CtMDwGTv4RYj2","validFrom":"2026-01-01T00:00:00Z","credentialSubject":{"id":"did:key:z6MkmtWtY63GQVBrpMyRJWEzsnxfsGkemu6CtMDwGTv4RYj2","blackboxHead":"utfv4sSWc6TH-n0HrNqB35Hacy3lYVksU0QYz6gbHol8","entryCount":3,"halosStack":{"igxSom":"IGX-Orin-64","halosCore":"1.4.0","blueprint":["SAIM","SEI","SDM"]},"window":{"from":"2026-01-01T00:00:00Z","to":"2026-01-01T00:00:10Z"},"robotIdentity":"urn:uuid:robot-identity-1"},"proof":{"type":"DataIntegrityProof","cryptosuite":"eddsa-jcs-2022","created":"2026-01-01T00:00:00Z","verificationMethod":"did:key:z6MkmtWtY63GQVBrpMyRJWEzsnxfsGkemu6CtMDwGTv4RYj2#key-1","proofPurpose":"assertionMethod","proofValue":"z5FjYsg9oQ543K8jtAsaYyYS3YG53ixoUYnhYop8oJWuLCoZp45uYos4416i13JR2bkt4tPtKB9hTk5xG9s8mQoQd"}}"#;
5213
5214    const PY_HALOS_ENTRIES: &str = r#"[{"version":"1.0","seq":0,"timestamp":"2026-01-01T00:00:01Z","event":"hazard_detected","ciphertext":"uzhrB2FNU_UNfM5ey2Dx1ogaX4_IuPx-0ylXC7022a7TqQ5ktnB9GmFqmrv9VzRx7ecoSyCAC6b6pcp1r7K2nQLSsDnmX2oar","prevHash":"uAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","entryHash":"uZm_cIGAA1kuQio4QWWwbE27xBVZE9QSuvAGweybxZZk"},{"version":"1.0","seq":1,"timestamp":"2026-01-01T00:00:02Z","event":"slow_stop","ciphertext":"ulQY1i5OnYlWdSJOS0Rp4esqwLIyh_4TM4WO-apHKoJde3AgFaGHgPIZ2GIb8q5sYKjtB9Az6kUnajkhzYA7VPQ6ChvF_3yQGfHuIM1lnaF5JEg","prevHash":"uZm_cIGAA1kuQio4QWWwbE27xBVZE9QSuvAGweybxZZk","entryHash":"uPulCLvRvEs_zV1R3koher2EMjyBZy5Rfe-Sv0Y64Tfk"},{"version":"1.0","seq":2,"timestamp":"2026-01-01T00:00:03Z","event":"cleared","ciphertext":"us7pdRfPVAGSeKCQU7RgEb1ee_2358wbs_P4epd4gPJoUUx9bw3hJSiVPGKwc2Xc3PjZySEaWKgK_F0h5mU2sxb0pEZ-E_FwwQQk3","prevHash":"uPulCLvRvEs_zV1R3koher2EMjyBZy5Rfe-Sv0Y64Tfk","entryHash":"utfv4sSWc6TH-n0HrNqB35Hacy3lYVksU0QYz6gbHol8"}]"#;
5215
5216    // Robot public key (raw 32-byte Ed25519) as base64url-no-pad.
5217    const PY_HALOS_ROBOT_PUB: &str = "bnoc3Smwt4_ROvTFWY_v9O8qlxZuPKby5Pv8zYBQW_E";
5218
5219    #[test]
5220    fn build_verify_safety_evidence_roundtrip() {
5221        let robot_seed = [5u8; 32];
5222        let robot_kp = Ed25519KeyPair::from_seed(&robot_seed);
5223
5224        // A black-box chain the robot recorded.
5225        let mut log = BlackBoxLog::new(&[9u8; 32], None).unwrap();
5226        log.append(
5227            "hazard_detected",
5228            &json!({"zone": "cell-3"}),
5229            "2026-01-01T00:00:01Z",
5230        )
5231        .unwrap();
5232        log.append(
5233            "slow_stop",
5234            &json!({"reason": "human"}),
5235            "2026-01-01T00:00:02Z",
5236        )
5237        .unwrap();
5238        let entries: Vec<Value> = log.entries().to_vec();
5239
5240        let params = BuildSafetyEvidence {
5241            halos_stack: json!({"igxSom": "IGX-Orin-64", "halosCore": "1.4.0"}),
5242            window_from: "2026-01-01T00:00:00Z".into(),
5243            window_to: "2026-01-01T00:00:10Z".into(),
5244            blackbox_head: log.head().to_string(),
5245            entry_count: entries.len() as u64,
5246            robot_identity: Some("urn:uuid:robot-identity-1".into()),
5247            valid_seconds: Some(3600),
5248            valid_from: "2026-01-01T00:00:00Z".into(),
5249            created: "2026-01-01T00:00:00Z".into(),
5250        };
5251        let cred = build_safety_evidence(&robot_seed, &params).unwrap();
5252
5253        // The issuer is the did:key derived from the seed and the validUntil is
5254        // rendered from the valid_seconds lifetime.
5255        assert_eq!(
5256            cred["issuer"],
5257            json!("did:key:z6MkmtWtY63GQVBrpMyRJWEzsnxfsGkemu6CtMDwGTv4RYj2")
5258        );
5259        assert_eq!(cred["validUntil"], json!("2026-01-01T01:00:00Z"));
5260
5261        let (ok, subject) =
5262            verify_safety_evidence(&cred, &robot_kp.public_key(), Some(&entries)).unwrap();
5263        assert!(ok, "a Rust-built evidence credential must verify in Rust");
5264        assert_eq!(subject.unwrap()["entryCount"], json!(2));
5265
5266        // A credential whose issuer is not the subject id is rejected.
5267        let mut forged = cred.clone();
5268        forged["issuer"] = json!("did:key:z6Mkother");
5269        let (ok_forged, _) = verify_safety_evidence(&forged, &robot_kp.public_key(), None).unwrap();
5270        assert!(!ok_forged, "issuer must equal credentialSubject.id");
5271    }
5272
5273    #[test]
5274    fn verifies_python_halos_evidence() {
5275        let credential: Value = serde_json::from_str(PY_HALOS_CREDENTIAL).unwrap();
5276        let entries: Vec<Value> = serde_json::from_str(PY_HALOS_ENTRIES).unwrap();
5277        let robot_pub = URL_SAFE_NO_PAD.decode(PY_HALOS_ROBOT_PUB).unwrap();
5278
5279        // The Python-produced credential and its entries verify in Rust.
5280        let (ok, subject) =
5281            verify_safety_evidence(&credential, &robot_pub, Some(&entries)).unwrap();
5282        assert!(ok, "the Python Halos evidence must verify in Rust");
5283        let subject = subject.expect("subject present on success");
5284        assert_eq!(subject["entryCount"], json!(3));
5285        assert_eq!(
5286            subject["blackboxHead"],
5287            json!("utfv4sSWc6TH-n0HrNqB35Hacy3lYVksU0QYz6gbHol8")
5288        );
5289
5290        // The proof and issuer binding hold even without the entries.
5291        let (ok_no_entries, _) = verify_safety_evidence(&credential, &robot_pub, None).unwrap();
5292        assert!(
5293            ok_no_entries,
5294            "proof and issuer binding verify without entries"
5295        );
5296
5297        // Tampering one entry breaks the chain, so verification fails.
5298        let mut tampered = entries.clone();
5299        tampered[1]["ciphertext"] = json!("utampered_ciphertext_value_that_does_not_match_hash");
5300        let (ok_tampered, subj_tampered) =
5301            verify_safety_evidence(&credential, &robot_pub, Some(&tampered)).unwrap();
5302        assert!(!ok_tampered, "a tampered entry must be rejected");
5303        assert!(subj_tampered.is_none());
5304
5305        // A wrong entry count (here a truncated log) is rejected against the seal.
5306        let truncated = entries[..2].to_vec();
5307        let (ok_truncated, _) =
5308            verify_safety_evidence(&credential, &robot_pub, Some(&truncated)).unwrap();
5309        assert!(!ok_truncated, "a wrong entry count must be rejected");
5310    }
5311
5312    #[test]
5313    fn forged_hardware_root_fails() {
5314        let robot_seed = [3u8; 32];
5315        let root_seed = [7u8; 32];
5316        let attacker_seed = [9u8; 32];
5317        let robot_did = "did:web:robot.example.com";
5318        let robot_kp = Ed25519KeyPair::from_seed(&robot_seed);
5319        let root_kp = Ed25519KeyPair::from_seed(&root_seed);
5320        let attacker_kp = Ed25519KeyPair::from_seed(&attacker_seed);
5321
5322        let attestation = software_root_attest(&root_seed, robot_did, &robot_kp.public_multikey());
5323        let params = MintRobotIdentity {
5324            robot_did: robot_did.into(),
5325            make: "Acme".into(),
5326            model: "AR-7".into(),
5327            serial: "SN-1".into(),
5328            owner: None,
5329            root_kind: "TPM".into(),
5330            root_public_multibase: root_kp.public_multikey(),
5331            attestation,
5332            lifecycle: None,
5333            valid_from: "2026-01-01T00:00:00Z".into(),
5334            valid_until: None,
5335        };
5336        let mut cred = mint_robot_identity(&robot_seed, &params).unwrap();
5337
5338        // Point the hardware-root key at an attacker's and re-sign the credential
5339        // proof; the attestation over the binding no longer matches.
5340        cred["credentialSubject"]["hardwareRoot"]["publicKeyMultibase"] =
5341            json!(attacker_kp.public_multikey());
5342        let resigned = {
5343            let mut bare = cred.clone();
5344            bare.as_object_mut().unwrap().remove("proof");
5345            let opts = BuildProofOptions::new(format!("{robot_did}#key-1"), "2026-01-01T00:00:00Z");
5346            data_integrity::sign(&bare, &robot_seed, &opts).unwrap()
5347        };
5348        assert!(verify_robot_identity(&resigned, &robot_kp.public_key())
5349            .unwrap()
5350            .is_none());
5351    }
5352
5353    // Cross-language interop: Rust reproduces the exact configHash Python pinned.
5354    #[test]
5355    fn config_hash_matches_interop_vector() {
5356        let vector = load_vector();
5357        let got = config_hash(&vector["config"]);
5358        assert_eq!(got, vector["expected_config_hash"].as_str().unwrap());
5359        assert_eq!(got, "uMh9_H2Lk51-m9SpBhiEa1oqIwwwA7yT27e2QFS0YKUs");
5360    }
5361
5362    #[test]
5363    fn provenance_roundtrip_and_config_tamper() {
5364        let seed = [4u8; 32];
5365        let kp = Ed25519KeyPair::from_seed(&seed);
5366        let config = load_vector()["config"].clone();
5367        let params = BuildProvenance {
5368            issuer_did: "did:web:robot.example.com".into(),
5369            robot_did: "did:web:robot.example.com".into(),
5370            model_name: "openvla-7b".into(),
5371            weights_hash: "uABCDEF".into(),
5372            safety_policy: "did:web:authority.example.com#policy-v3".into(),
5373            config: Some(config.clone()),
5374            version: Some("2026.06".into()),
5375            supersedes: None,
5376            valid_from: "2026-01-01T00:00:00Z".into(),
5377            valid_until: None,
5378        };
5379        let att = build_provenance_attestation(&seed, &params).unwrap();
5380        assert!(
5381            verify_provenance_attestation(&att, &kp.public_key(), Some(&config))
5382                .unwrap()
5383                .is_some()
5384        );
5385        // A different config than the one signed must be rejected.
5386        let tampered = json!({"temperature": 1.0, "max_torque": 99.0});
5387        assert!(
5388            verify_provenance_attestation(&att, &kp.public_key(), Some(&tampered))
5389                .unwrap()
5390                .is_none()
5391        );
5392    }
5393
5394    #[test]
5395    fn capability_build_check_attenuate() {
5396        let seed = [6u8; 32];
5397        let kp = Ed25519KeyPair::from_seed(&seed);
5398        let params = BuildPhysicalScope {
5399            issuer_did: "did:web:fleet.example.com".into(),
5400            subject_did: "did:web:robot.example.com".into(),
5401            max_force_n: Some(80.0),
5402            max_speed_mps: Some(2.0),
5403            max_speed_near_humans_mps: Some(0.5),
5404            allowed_zones: Some(vec!["warehouse-a".into(), "dock-3".into()]),
5405            shift_windows: Some(vec![ShiftWindow {
5406                start: "08:00".into(),
5407                end: "18:00".into(),
5408            }]),
5409            valid_from: "2026-01-01T00:00:00Z".into(),
5410            valid_until: None,
5411        };
5412        let cred = build_physical_scope_credential(&seed, &params).unwrap();
5413        assert!(has_type(cred.get("type"), PHYSICAL_SCOPE_TYPE));
5414        assert!(data_integrity::verify_proof(&cred, &kp.public_key()).unwrap());
5415
5416        let scope = cred["credentialSubject"]["physicalScope"].clone();
5417        let within = check_physical_action(
5418            &scope,
5419            &PhysicalAction {
5420                force_n: Some(50.0),
5421                speed_mps: Some(1.5),
5422                zone: Some("warehouse-a".into()),
5423                time_hm: Some("09:30".into()),
5424                ..Default::default()
5425            },
5426        );
5427        assert!(within.ok, "within-scope action: {:?}", within.reasons);
5428        assert!(
5429            !check_physical_action(
5430                &scope,
5431                &PhysicalAction {
5432                    force_n: Some(120.0),
5433                    ..Default::default()
5434                }
5435            )
5436            .ok
5437        );
5438        // Near humans the 0.5 m/s cap applies; 1.5 is fine away from them.
5439        assert!(
5440            !check_physical_action(
5441                &scope,
5442                &PhysicalAction {
5443                    speed_mps: Some(1.5),
5444                    near_humans: true,
5445                    ..Default::default()
5446                }
5447            )
5448            .ok
5449        );
5450        assert!(
5451            check_physical_action(
5452                &scope,
5453                &PhysicalAction {
5454                    speed_mps: Some(1.5),
5455                    near_humans: false,
5456                    ..Default::default()
5457                }
5458            )
5459            .ok
5460        );
5461        assert!(
5462            !check_physical_action(
5463                &scope,
5464                &PhysicalAction {
5465                    zone: Some("loading-bay-9".into()),
5466                    ..Default::default()
5467                }
5468            )
5469            .ok
5470        );
5471        assert!(
5472            !check_physical_action(
5473                &scope,
5474                &PhysicalAction {
5475                    time_hm: Some("23:00".into()),
5476                    ..Default::default()
5477                }
5478            )
5479            .ok
5480        );
5481    }
5482
5483    #[test]
5484    fn attenuation_rules() {
5485        let parent = json!({
5486            "maxForceN": 80.0, "maxSpeedMps": 2.0, "maxSpeedNearHumansMps": 0.5,
5487            "allowedZones": ["warehouse-a", "dock-3"],
5488            "shiftWindows": [{"start": "08:00", "end": "18:00"}]
5489        });
5490        let narrower = json!({
5491            "maxForceN": 50.0, "maxSpeedMps": 1.0, "maxSpeedNearHumansMps": 0.3,
5492            "allowedZones": ["warehouse-a"],
5493            "shiftWindows": [{"start": "09:00", "end": "17:00"}]
5494        });
5495        assert!(attenuates(&parent, &narrower));
5496        assert!(!attenuates(
5497            &parent,
5498            &json!({"maxForceN": 100.0, "maxSpeedMps": 1.0, "maxSpeedNearHumansMps": 0.3, "allowedZones": ["warehouse-a"]})
5499        ));
5500        assert!(!attenuates(
5501            &parent,
5502            &json!({"maxForceN": 50.0, "allowedZones": ["warehouse-a"]})
5503        ));
5504        assert!(!attenuates(
5505            &parent,
5506            &json!({"maxForceN": 50.0, "maxSpeedMps": 1.0, "maxSpeedNearHumansMps": 0.3, "allowedZones": ["loading-bay-9"]})
5507        ));
5508        assert!(!attenuates(
5509            &parent,
5510            &json!({"maxForceN": 50.0, "maxSpeedMps": 1.0, "maxSpeedNearHumansMps": 0.3, "allowedZones": ["warehouse-a"], "shiftWindows": [{"start": "06:00", "end": "20:00"}]})
5511        ));
5512    }
5513
5514    #[test]
5515    fn handshake_full_flow() {
5516        let a_seed = [11u8; 32];
5517        let b_seed = [12u8; 32];
5518        let a = Ed25519KeyPair::from_seed(&a_seed);
5519        let b = Ed25519KeyPair::from_seed(&b_seed);
5520        let a_did = "did:web:robot-a.example.com";
5521        let b_did = "did:web:robot-b.example.com";
5522        let policy_b = TrustPolicy::new(["robot-a.example.com".to_string()], false);
5523
5524        let hello = build_hello(
5525            &a_seed,
5526            &BuildHello {
5527                from_did: a_did.into(),
5528                proposed_scope: vec!["lift".into(), "carry".into(), "scan".into()],
5529                nonce: "abc123".into(),
5530                peer_did: Some(b_did.into()),
5531                issued_at: "2026-01-01T00:00:00Z".into(),
5532            },
5533        )
5534        .unwrap();
5535
5536        let accept = build_accept(
5537            &b_seed,
5538            &hello,
5539            &a.public_key(),
5540            &policy_b,
5541            &BuildAccept {
5542                from_did: b_did.into(),
5543                offered_scope: vec!["carry".into(), "scan".into(), "weld".into()],
5544                session_id: "urn:uuid:sess-1".into(),
5545                valid_until: "2026-01-01T00:05:00Z".into(),
5546                created: "2026-01-01T00:00:01Z".into(),
5547            },
5548        )
5549        .unwrap();
5550
5551        let session = verify_accept(&accept, &b.public_key(), "abc123", None)
5552            .unwrap()
5553            .expect("accept verifies");
5554        assert_eq!(session.scope, vec!["carry".to_string(), "scan".to_string()]);
5555        assert_eq!(session.initiator, a_did);
5556        assert_eq!(session.responder, b_did);
5557
5558        let confirm = build_confirm(&a_seed, a_did, &session, "2026-01-01T00:00:02Z").unwrap();
5559        assert!(verify_confirm(&confirm, &a.public_key(), &session.session_id, "abc123").unwrap());
5560    }
5561
5562    #[test]
5563    fn handshake_untrusted_tamper_and_nonce() {
5564        let a_seed = [11u8; 32];
5565        let b_seed = [12u8; 32];
5566        let a = Ed25519KeyPair::from_seed(&a_seed);
5567        let b = Ed25519KeyPair::from_seed(&b_seed);
5568        let a_did = "did:web:robot-a.example.com";
5569        let b_did = "did:web:robot-b.example.com";
5570
5571        let hello = build_hello(
5572            &a_seed,
5573            &BuildHello {
5574                from_did: a_did.into(),
5575                proposed_scope: vec!["lift".into()],
5576                nonce: "n1".into(),
5577                peer_did: None,
5578                issued_at: "2026-01-01T00:00:00Z".into(),
5579            },
5580        )
5581        .unwrap();
5582
5583        // Untrusted initiator.
5584        let strict = TrustPolicy::new(["someone-else.example.com".to_string()], false);
5585        assert!(build_accept(
5586            &b_seed,
5587            &hello,
5588            &a.public_key(),
5589            &strict,
5590            &BuildAccept {
5591                from_did: b_did.into(),
5592                offered_scope: vec!["lift".into()],
5593                session_id: "s".into(),
5594                valid_until: "2026-01-01T00:05:00Z".into(),
5595                created: "2026-01-01T00:00:01Z".into(),
5596            },
5597        )
5598        .is_err());
5599
5600        // Tampered HELLO (scope broadened after signing) fails signature check.
5601        let open = TrustPolicy::new(Vec::<String>::new(), true);
5602        let mut tampered = hello.clone();
5603        tampered["proposedScope"] = json!(["lift", "weld"]);
5604        assert!(build_accept(
5605            &b_seed,
5606            &tampered,
5607            &a.public_key(),
5608            &open,
5609            &BuildAccept {
5610                from_did: b_did.into(),
5611                offered_scope: vec!["lift".into(), "weld".into()],
5612                session_id: "s".into(),
5613                valid_until: "2026-01-01T00:05:00Z".into(),
5614                created: "2026-01-01T00:00:01Z".into(),
5615            },
5616        )
5617        .is_err());
5618
5619        // Nonce mismatch on a valid ACCEPT.
5620        let accept = build_accept(
5621            &b_seed,
5622            &hello,
5623            &a.public_key(),
5624            &open,
5625            &BuildAccept {
5626                from_did: b_did.into(),
5627                offered_scope: vec!["lift".into()],
5628                session_id: "s".into(),
5629                valid_until: "2026-01-01T00:05:00Z".into(),
5630                created: "2026-01-01T00:00:01Z".into(),
5631            },
5632        )
5633        .unwrap();
5634        assert!(verify_accept(&accept, &b.public_key(), "wrong-nonce", None)
5635            .unwrap()
5636            .is_none());
5637    }
5638
5639    #[test]
5640    fn did_web_domain_parsing() {
5641        assert_eq!(did_web_domain("did:web:example.com"), Some("example.com"));
5642        assert_eq!(
5643            did_web_domain("did:web:robot.example.com:agent"),
5644            Some("robot.example.com")
5645        );
5646        assert_eq!(did_web_domain("did:key:z6Mk"), None);
5647    }
5648
5649    #[test]
5650    fn blackbox_append_open_and_chain() {
5651        let key = [0x11u8; 32];
5652        let mut log = BlackBoxLog::new(&key, None).unwrap();
5653        let e0 = log
5654            .append(
5655                "motion",
5656                &json!({"speed": 1.5, "joint": "elbow"}),
5657                "2026-01-01T00:00:00Z",
5658            )
5659            .unwrap();
5660        log.append("stop", &json!({"reason": "human"}), "2026-01-01T00:00:01Z")
5661            .unwrap();
5662
5663        // Round-trip decrypt.
5664        let opened = log.open(&e0).unwrap();
5665        assert_eq!(opened["joint"], json!("elbow"));
5666
5667        // Chain verifies, in memory and after a JSON round trip.
5668        assert!(verify_blackbox_chain(log.entries(), None).ok);
5669        let wire: Vec<Value> =
5670            serde_json::from_str(&serde_json::to_string(log.entries()).unwrap()).unwrap();
5671        assert!(verify_blackbox_chain(&wire, None).ok);
5672        assert_eq!(open_entry(&wire[0], &key).unwrap()["joint"], json!("elbow"));
5673
5674        // Tamper detection.
5675        let mut tampered = wire.clone();
5676        tampered[1]["event"] = json!("tampered");
5677        assert!(!verify_blackbox_chain(&tampered, None).ok);
5678
5679        // Wrong key fails decryption; bad key length rejected.
5680        assert!(open_entry(&e0, &[0x22u8; 32]).is_err());
5681        assert!(BlackBoxLog::new(&[0u8; 16], None).is_err());
5682
5683        // Genesis constant matches the multibase of 32 zero bytes.
5684        assert_eq!(genesis_prev_hash(), format!("u{}", "A".repeat(43)));
5685    }
5686
5687    #[test]
5688    fn killswitch_build_verify_and_trust() {
5689        let seed = [13u8; 32];
5690        let kp = Ed25519KeyPair::from_seed(&seed);
5691        let cred = build_killswitch_credential(
5692            &seed,
5693            &BuildKillswitch {
5694                issuer_did: "did:web:safety.example.com".into(),
5695                target: "did:web:robot.example.com".into(),
5696                reason: "human in path".into(),
5697                command: None,
5698                scope: Some(vec!["arm".into(), "drive".into()]),
5699                valid_from: "2026-01-01T00:00:00Z".into(),
5700                valid_until: None,
5701            },
5702        )
5703        .unwrap();
5704
5705        let mut trusted = HashSet::new();
5706        trusted.insert("did:web:safety.example.com".to_string());
5707        let subject = verify_killswitch_credential(&cred, &kp.public_key(), Some(&trusted))
5708            .unwrap()
5709            .expect("trusted authority verifies");
5710        assert_eq!(subject["command"], json!(EMERGENCY_STOP));
5711
5712        // Untrusted issuer rejected though the signature is valid.
5713        let mut other = HashSet::new();
5714        other.insert("did:web:someone-else.example.com".to_string());
5715        assert!(
5716            verify_killswitch_credential(&cred, &kp.public_key(), Some(&other))
5717                .unwrap()
5718                .is_none()
5719        );
5720
5721        // Wrong type rejected.
5722        let mut wrong = cred.clone();
5723        wrong["type"] = json!(["VerifiableCredential"]);
5724        assert!(verify_killswitch_credential(&wrong, &kp.public_key(), None)
5725            .unwrap()
5726            .is_none());
5727    }
5728
5729    #[test]
5730    fn passport_build_encode_verify() {
5731        let seed = [14u8; 32];
5732        let kp = Ed25519KeyPair::from_seed(&seed);
5733        let did = "did:web:robot.example.com";
5734        let pass = build_passport(
5735            &seed,
5736            &BuildPassport {
5737                issuer_did: did.into(),
5738                robot_did: did.into(),
5739                make: "Acme Robotics".into(),
5740                model: "AR-7".into(),
5741                owner: "did:web:owner.example.com".into(),
5742                authorized_actions: vec!["lift".into(), "carry".into()],
5743                certification: Some("ISO-10218".into()),
5744                status: None,
5745                valid_from: "2026-01-01T00:00:00Z".into(),
5746                valid_until: None,
5747            },
5748        )
5749        .unwrap();
5750
5751        // Direct verify.
5752        let subject = verify_passport(&pass, &kp.public_key(), "2026-06-01T00:00:00Z")
5753            .unwrap()
5754            .expect("passport verifies");
5755        assert_eq!(subject["owner"], json!("did:web:owner.example.com"));
5756        assert_eq!(subject["status"], json!(STATUS_ACTIVE));
5757
5758        // Encode to a URI, decode, and verify the offline-scan path.
5759        let uri = encode_passport(&pass);
5760        assert!(uri.starts_with("vouch-passport:u"));
5761        let decoded = decode_passport(&uri).unwrap();
5762        assert!(
5763            verify_passport(&decoded, &kp.public_key(), "2026-06-01T00:00:00Z")
5764                .unwrap()
5765                .is_some()
5766        );
5767        assert!(
5768            verify_passport_uri(&uri, &kp.public_key(), "2026-06-01T00:00:00Z")
5769                .unwrap()
5770                .is_some()
5771        );
5772
5773        // Tamper and wrong type rejected.
5774        let mut tampered = pass.clone();
5775        tampered["credentialSubject"]["owner"] = json!("did:web:attacker.example.com");
5776        assert!(
5777            verify_passport(&tampered, &kp.public_key(), "2026-06-01T00:00:00Z")
5778                .unwrap()
5779                .is_none()
5780        );
5781
5782        // Malformed URI.
5783        assert!(decode_passport("https://example.com/x").is_err());
5784    }
5785
5786    #[test]
5787    fn passport_expiry_and_suspended() {
5788        let seed = [15u8; 32];
5789        let kp = Ed25519KeyPair::from_seed(&seed);
5790        let did = "did:web:robot.example.com";
5791
5792        // Expiry: valid inside the window, expired past validUntil.
5793        let timed = build_passport(
5794            &seed,
5795            &BuildPassport {
5796                issuer_did: did.into(),
5797                robot_did: did.into(),
5798                make: "Acme".into(),
5799                model: "AR-7".into(),
5800                owner: "did:web:owner.example.com".into(),
5801                authorized_actions: vec!["lift".into()],
5802                certification: None,
5803                status: None,
5804                valid_from: "2026-01-01T00:00:00Z".into(),
5805                valid_until: Some("2026-01-01T00:01:00Z".into()),
5806            },
5807        )
5808        .unwrap();
5809        assert!(
5810            verify_passport(&timed, &kp.public_key(), "2026-01-01T00:00:30Z")
5811                .unwrap()
5812                .is_some()
5813        );
5814        assert!(
5815            verify_passport(&timed, &kp.public_key(), "2026-01-01T00:02:00Z")
5816                .unwrap()
5817                .is_none()
5818        );
5819
5820        // Suspended still verifies but the status is surfaced.
5821        let suspended = build_passport(
5822            &seed,
5823            &BuildPassport {
5824                issuer_did: did.into(),
5825                robot_did: did.into(),
5826                make: "Acme".into(),
5827                model: "AR-7".into(),
5828                owner: "did:web:owner.example.com".into(),
5829                authorized_actions: vec!["lift".into()],
5830                certification: None,
5831                status: Some(STATUS_SUSPENDED.into()),
5832                valid_from: "2026-01-01T00:00:00Z".into(),
5833                valid_until: None,
5834            },
5835        )
5836        .unwrap();
5837        let subject = verify_passport(&suspended, &kp.public_key(), "2026-06-01T00:00:00Z")
5838            .unwrap()
5839            .expect("a suspended passport still verifies");
5840        assert_eq!(subject["status"], json!(STATUS_SUSPENDED));
5841    }
5842
5843    // Cross-language interop: Rust reproduces the exact motion digest Python
5844    // pinned from the same fixed samples against the same physical scope.
5845    #[test]
5846    fn motion_digest_matches_interop_vector() {
5847        let vector = load_vector();
5848        let scope = vector["physical_scope"].clone();
5849        let mut collector = MotionCollector::new(Some(scope));
5850        collector
5851            .record(&MotionSample {
5852                force_n: Some(12.0),
5853                speed_mps: Some(0.4),
5854                near_humans: false,
5855                zone: Some("cell-3".into()),
5856                time_hm: None,
5857            })
5858            .unwrap();
5859        collector
5860            .record(&MotionSample {
5861                force_n: Some(20.0),
5862                speed_mps: Some(0.2),
5863                near_humans: true,
5864                zone: Some("cell-3".into()),
5865                time_hm: None,
5866            })
5867            .unwrap();
5868        assert_eq!(collector.digest(), vector["expected_motion_digest"]);
5869    }
5870
5871    #[test]
5872    fn heartbeat_build_verify_and_liveness() {
5873        let seed = [21u8; 32];
5874        let kp = Ed25519KeyPair::from_seed(&seed);
5875        let did = "did:web:robot.example.com";
5876        let digest = json!({
5877            "samples": 2, "maxForceN": 20.0, "maxSpeedMps": 0.4,
5878            "maxSpeedNearHumansMps": 0.2, "zoneBreaches": 0, "breachCount": 0,
5879            "withinEnvelope": true
5880        });
5881        let hb = build_robot_heartbeat(
5882            &seed,
5883            &BuildRobotHeartbeat {
5884                robot_did: did.into(),
5885                session_id: "urn:uuid:sess-1".into(),
5886                interval_index: 0,
5887                interval_seconds: 60,
5888                motion_digest: digest,
5889                valid_from: "2026-01-01T00:00:00Z".into(),
5890            },
5891        )
5892        .unwrap();
5893
5894        let subject = verify_robot_heartbeat(&hb, &kp.public_key())
5895            .unwrap()
5896            .expect("heartbeat verifies");
5897        assert_eq!(subject["sessionId"], json!("urn:uuid:sess-1"));
5898
5899        // Fresh and in-envelope: live. Stale: not live.
5900        assert!(is_live(&hb, "2026-01-01T00:01:00Z", None, DEFAULT_GRACE_INTERVALS).unwrap());
5901        assert!(!is_live(&hb, "2026-01-01T01:00:00Z", None, DEFAULT_GRACE_INTERVALS).unwrap());
5902
5903        // Out-of-envelope heartbeat is never live, even when fresh.
5904        let breached = json!({
5905            "samples": 1, "maxForceN": 99.0, "maxSpeedMps": 0.4,
5906            "maxSpeedNearHumansMps": 0.2, "zoneBreaches": 0, "breachCount": 1,
5907            "withinEnvelope": false
5908        });
5909        let hb2 = build_robot_heartbeat(
5910            &seed,
5911            &BuildRobotHeartbeat {
5912                robot_did: did.into(),
5913                session_id: "s".into(),
5914                interval_index: 1,
5915                interval_seconds: 60,
5916                motion_digest: breached,
5917                valid_from: "2026-01-01T00:00:00Z".into(),
5918            },
5919        )
5920        .unwrap();
5921        assert!(!is_live(&hb2, "2026-01-01T00:00:30Z", None, DEFAULT_GRACE_INTERVALS).unwrap());
5922
5923        // Tamper and wrong type rejected.
5924        let mut tampered = hb.clone();
5925        tampered["credentialSubject"]["sessionId"] = json!("urn:uuid:other");
5926        assert!(verify_robot_heartbeat(&tampered, &kp.public_key())
5927            .unwrap()
5928            .is_none());
5929    }
5930
5931    // Cross-language interop: Rust reproduces the exact hash-linked ledger and
5932    // the summary Python pinned from the same fixed events and timestamps.
5933    #[test]
5934    fn safety_log_matches_interop_vector() {
5935        let vector = load_vector();
5936        let mut log = SafetyEventLog::new(None);
5937        log.append(
5938            "near_miss",
5939            "low",
5940            Some(&json!({"zone": "cell-3"})),
5941            None,
5942            "2026-01-01T00:00:00Z",
5943        )
5944        .unwrap();
5945        log.append(
5946            "envelope_breach",
5947            "high",
5948            None,
5949            None,
5950            "2026-01-01T00:01:00Z",
5951        )
5952        .unwrap();
5953
5954        assert_eq!(
5955            Value::Array(log.entries().to_vec()),
5956            vector["safety_log_entries"]
5957        );
5958        assert_eq!(
5959            log.head(),
5960            vector["expected_safety_log_head"].as_str().unwrap()
5961        );
5962        assert_eq!(log.summarize(), vector["expected_safety_summary"]);
5963        assert!(verify_safety_log(log.entries(), None).ok);
5964    }
5965
5966    #[test]
5967    fn safety_record_build_verify_and_tamper() {
5968        let seed = [22u8; 32];
5969        let kp = Ed25519KeyPair::from_seed(&seed);
5970        let mut log = SafetyEventLog::new(None);
5971        log.append("near_miss", "low", None, None, "2026-01-01T00:00:00Z")
5972            .unwrap();
5973        let summary = log.summarize();
5974
5975        let record = build_safety_record(
5976            &seed,
5977            &BuildSafetyRecord {
5978                issuer_did: "did:web:owner.example.com".into(),
5979                robot_did: "did:web:robot.example.com".into(),
5980                summary,
5981                period_start: Some("2026-01-01T00:00:00Z".into()),
5982                period_end: Some("2026-01-31T00:00:00Z".into()),
5983                valid_from: "2026-02-01T00:00:00Z".into(),
5984                valid_until: None,
5985            },
5986        )
5987        .unwrap();
5988
5989        let subject = verify_safety_record(&record, &kp.public_key())
5990            .unwrap()
5991            .expect("safety record verifies");
5992        assert_eq!(subject["totalEvents"], json!(1));
5993        assert_eq!(subject["period"]["start"], json!("2026-01-01T00:00:00Z"));
5994
5995        let mut tampered = record.clone();
5996        tampered["credentialSubject"]["totalEvents"] = json!(99);
5997        assert!(verify_safety_record(&tampered, &kp.public_key())
5998            .unwrap()
5999            .is_none());
6000
6001        // Tamper detection in the ledger itself.
6002        let mut entries = log.entries().to_vec();
6003        entries[0]["severity"] = json!("critical");
6004        assert!(!verify_safety_log(&entries, None).ok);
6005    }
6006
6007    // Cross-language interop: Rust reproduces the exact credentialStatus entry.
6008    #[test]
6009    fn status_entry_matches_interop_vector() {
6010        let vector = load_vector();
6011        let entry = build_status_list_entry(
6012            "https://fleet.example.com/status/1",
6013            42,
6014            STATUS_PURPOSE_REVOCATION,
6015            None,
6016        )
6017        .unwrap();
6018        assert_eq!(entry, vector["expected_credential_status_entry"]);
6019    }
6020
6021    #[test]
6022    fn attach_and_check_credential_status() {
6023        let seed = [23u8; 32];
6024        let kp = Ed25519KeyPair::from_seed(&seed);
6025        let did = "did:web:robot.example.com";
6026
6027        // Mint a passport, then attach a revocation status and re-sign.
6028        let pass = build_passport(
6029            &seed,
6030            &BuildPassport {
6031                issuer_did: did.into(),
6032                robot_did: did.into(),
6033                make: "Acme".into(),
6034                model: "AR-7".into(),
6035                owner: "did:web:owner.example.com".into(),
6036                authorized_actions: vec!["lift".into()],
6037                certification: None,
6038                status: None,
6039                valid_from: "2026-01-01T00:00:00Z".into(),
6040                valid_until: None,
6041            },
6042        )
6043        .unwrap();
6044
6045        let with_status = attach_credential_status(
6046            &pass,
6047            &seed,
6048            &AttachCredentialStatus {
6049                status_list_credential: "https://fleet.example.com/status/1".into(),
6050                status_list_index: 42,
6051                status_purpose: STATUS_PURPOSE_REVOCATION.into(),
6052                entry_id: None,
6053                created: "2026-01-01T00:00:00Z".into(),
6054            },
6055        )
6056        .unwrap();
6057
6058        // The re-signed credential still verifies and now carries the entry.
6059        assert!(data_integrity::verify_proof(&with_status, &kp.public_key()).unwrap());
6060        assert_eq!(
6061            with_status["credentialStatus"]["statusListIndex"],
6062            json!("42")
6063        );
6064
6065        // Build a status list with bit 42 set, then check the entry resolves.
6066        let mut bits = vec![0u8; crate::status_list::DEFAULT_BITSTRING_LENGTH / 8];
6067        crate::status_list::set_status(&mut bits, 42, true).unwrap();
6068        let encoded = crate::status_list::encode_bitstring(&bits).unwrap();
6069        let status_list = json!({
6070            "id": "https://fleet.example.com/status/1",
6071            "type": ["VerifiableCredential", "BitstringStatusListCredential"],
6072            "credentialSubject": {
6073                "type": "BitstringStatusList",
6074                "statusPurpose": "revocation",
6075                "encodedList": encoded,
6076            }
6077        });
6078        assert!(
6079            check_credential_status(&with_status, &status_list, STATUS_PURPOSE_REVOCATION).unwrap()
6080        );
6081
6082        // A credential with no status entry is not revoked.
6083        assert!(!check_credential_status(&pass, &status_list, STATUS_PURPOSE_REVOCATION).unwrap());
6084
6085        // A list with the bit clear reports not-revoked.
6086        let clear_bits = vec![0u8; crate::status_list::DEFAULT_BITSTRING_LENGTH / 8];
6087        let clear_encoded = crate::status_list::encode_bitstring(&clear_bits).unwrap();
6088        let mut clear_list = status_list.clone();
6089        clear_list["credentialSubject"]["encodedList"] = json!(clear_encoded);
6090        assert!(
6091            !check_credential_status(&with_status, &clear_list, STATUS_PURPOSE_REVOCATION).unwrap()
6092        );
6093    }
6094
6095    // Cross-language interop: Rust reproduces the exact frame hash Python pinned.
6096    #[test]
6097    fn frame_hash_matches_interop_vector() {
6098        let vector = load_vector();
6099        let sample_frame: Vec<u8> = (0u8..64).collect();
6100        let got = hash_frame(&sample_frame);
6101        assert_eq!(got, vector["expected_frame_hash"].as_str().unwrap());
6102        assert_eq!(got, "u_eq5rPNxA2K9JljNyaKej5x1f8-YEWA6jER80dkVEQg");
6103    }
6104
6105    // Cross-language interop: Rust reproduces the exact hash-linked perception log
6106    // Python pinned from the same fixed frames and timestamps.
6107    #[test]
6108    fn perception_log_matches_interop_vector() {
6109        let vector = load_vector();
6110        let sample_frame: Vec<u8> = (0u8..64).collect();
6111        let mut log = PerceptionLog::new(None);
6112        log.record(
6113            "cam-front",
6114            "camera",
6115            Some(&sample_frame),
6116            None,
6117            "2026-01-01T00:00:00Z",
6118        )
6119        .unwrap();
6120        log.record(
6121            "lidar-top",
6122            "lidar",
6123            None,
6124            Some(&hash_frame(b"scan-0")),
6125            "2026-01-01T00:00:01Z",
6126        )
6127        .unwrap();
6128
6129        assert_eq!(
6130            Value::Array(log.entries().to_vec()),
6131            vector["perception_log_entries"]
6132        );
6133        assert_eq!(
6134            log.head(),
6135            vector["expected_perception_log_head"].as_str().unwrap()
6136        );
6137        assert!(verify_perception_log(log.entries(), None).ok);
6138    }
6139
6140    #[test]
6141    fn perception_record_validation_and_tamper() {
6142        let mut log = PerceptionLog::new(None);
6143        // Unknown modality rejected.
6144        assert!(log
6145            .record("cam", "sonar", Some(b"x"), None, "2026-01-01T00:00:00Z")
6146            .is_err());
6147        // Both frame and frame_hash rejected.
6148        assert!(log
6149            .record(
6150                "cam",
6151                "camera",
6152                Some(b"x"),
6153                Some("uABC"),
6154                "2026-01-01T00:00:00Z"
6155            )
6156            .is_err());
6157        // Neither frame nor frame_hash rejected.
6158        assert!(log
6159            .record("cam", "camera", None, None, "2026-01-01T00:00:00Z")
6160            .is_err());
6161        // Empty sensor id rejected.
6162        assert!(log
6163            .record("", "camera", Some(b"x"), None, "2026-01-01T00:00:00Z")
6164            .is_err());
6165
6166        log.record(
6167            "cam",
6168            "camera",
6169            Some(b"frame-0"),
6170            None,
6171            "2026-01-01T00:00:00Z",
6172        )
6173        .unwrap();
6174        log.record(
6175            "cam",
6176            "camera",
6177            Some(b"frame-1"),
6178            None,
6179            "2026-01-01T00:00:01Z",
6180        )
6181        .unwrap();
6182        assert!(verify_perception_log(log.entries(), None).ok);
6183
6184        // Tamper detection in the chain.
6185        let mut entries = log.entries().to_vec();
6186        entries[0]["frameHash"] = json!("uTAMPERED");
6187        assert!(!verify_perception_log(&entries, None).ok);
6188    }
6189
6190    #[test]
6191    fn perception_attestation_build_verify_and_tamper() {
6192        let seed = [24u8; 32];
6193        let kp = Ed25519KeyPair::from_seed(&seed);
6194        let did = "did:web:robot.example.com";
6195        let frame = b"sensor-frame-bytes";
6196        let frame_hash = hash_frame(frame);
6197
6198        let cred = build_perception_attestation(
6199            &seed,
6200            &BuildPerception {
6201                robot_did: did.into(),
6202                sensor_id: "cam-front".into(),
6203                modality: "camera".into(),
6204                frame_hash: frame_hash.clone(),
6205                captured_at: Some("2026-01-01T00:00:00Z".into()),
6206                log_head: Some("uHEAD".into()),
6207                valid_from: "2026-01-01T00:00:00Z".into(),
6208                valid_until: None,
6209            },
6210        )
6211        .unwrap();
6212
6213        // Verify the proof and the embedded provenance, and recompute the frame.
6214        let subject = verify_perception_attestation(&cred, &kp.public_key(), Some(frame))
6215            .unwrap()
6216            .expect("perception attestation verifies");
6217        assert_eq!(subject["sensorId"], json!("cam-front"));
6218        assert_eq!(subject["frameHash"], json!(frame_hash));
6219        assert_eq!(subject["logHead"], json!("uHEAD"));
6220
6221        // Verify without the raw frame still passes (proof only).
6222        assert!(verify_perception_attestation(&cred, &kp.public_key(), None)
6223            .unwrap()
6224            .is_some());
6225
6226        // A different frame than the one attested is rejected.
6227        assert!(
6228            verify_perception_attestation(&cred, &kp.public_key(), Some(b"other-frame"))
6229                .unwrap()
6230                .is_none()
6231        );
6232
6233        // Tampered subject fails the proof.
6234        let mut tampered = cred.clone();
6235        tampered["credentialSubject"]["sensorId"] = json!("cam-rear");
6236        assert!(
6237            verify_perception_attestation(&tampered, &kp.public_key(), None)
6238                .unwrap()
6239                .is_none()
6240        );
6241
6242        // Wrong type rejected.
6243        let mut wrong = cred.clone();
6244        wrong["type"] = json!(["VerifiableCredential"]);
6245        assert!(
6246            verify_perception_attestation(&wrong, &kp.public_key(), None)
6247                .unwrap()
6248                .is_none()
6249        );
6250
6251        // Bad modality and missing frame_hash rejected at build time.
6252        assert!(build_perception_attestation(
6253            &seed,
6254            &BuildPerception {
6255                robot_did: did.into(),
6256                sensor_id: "s".into(),
6257                modality: "sonar".into(),
6258                frame_hash: frame_hash.clone(),
6259                captured_at: None,
6260                log_head: None,
6261                valid_from: "2026-01-01T00:00:00Z".into(),
6262                valid_until: None,
6263            },
6264        )
6265        .is_err());
6266        assert!(build_perception_attestation(
6267            &seed,
6268            &BuildPerception {
6269                robot_did: did.into(),
6270                sensor_id: "s".into(),
6271                modality: "camera".into(),
6272                frame_hash: String::new(),
6273                captured_at: None,
6274                log_head: None,
6275                valid_from: "2026-01-01T00:00:00Z".into(),
6276                valid_until: None,
6277            },
6278        )
6279        .is_err());
6280    }
6281
6282    fn jwk_pub(jwk: &Value) -> Vec<u8> {
6283        URL_SAFE_NO_PAD
6284            .decode(jwk["x"].as_str().unwrap())
6285            .expect("base64url JWK x")
6286    }
6287
6288    // Cross-language interop: Go and TypeScript verify this same Python-signed
6289    // delegation lease; the Rust core must too.
6290    #[test]
6291    fn verifies_python_lease_interop_vector() {
6292        let vector = load_vector();
6293        let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
6294        let lease = vector["delegation_lease_credential"].clone();
6295
6296        let subject = verify_delegation_lease(&lease, &robot_pub, None, None)
6297            .unwrap()
6298            .expect("the Python lease interop vector must verify in Rust");
6299        assert_eq!(subject["leaseId"], json!("lease-vector-1"));
6300    }
6301
6302    // Cross-language interop: Rust authorizes the Python-signed quorum with the
6303    // same two approver keys and a threshold of 2.
6304    #[test]
6305    fn verifies_python_quorum_interop_vector() {
6306        let vector = load_vector();
6307        let approvals = vector["quorum_approvals"].as_array().unwrap().clone();
6308        let action_id = vector["quorum_action_id"].as_str().unwrap();
6309        let keys: Vec<ApproverKey> = vector["quorum_approver_keys"]
6310            .as_object()
6311            .unwrap()
6312            .iter()
6313            .map(|(did, jwk)| ApproverKey {
6314                did: did.clone(),
6315                public_key: jwk_pub(jwk),
6316            })
6317            .collect();
6318
6319        let (ok, approvers) = verify_action_authorization(
6320            &approvals,
6321            action_id,
6322            "did:web:robot.example.com",
6323            &keys,
6324            2,
6325            None,
6326            None,
6327        )
6328        .unwrap();
6329        assert!(
6330            ok,
6331            "the Python quorum interop vector must authorize in Rust"
6332        );
6333        assert_eq!(approvers.len(), 2);
6334        assert_eq!(approvers[0], "did:web:approver-1.example.com");
6335        assert_eq!(approvers[1], "did:web:approver-2.example.com");
6336    }
6337
6338    #[test]
6339    fn lease_build_verify_permits_and_expiry() {
6340        let seed = [31u8; 32];
6341        let kp = Ed25519KeyPair::from_seed(&seed);
6342        let did = "did:web:robot.example.com";
6343        let scope = json!({
6344            "maxForceN": 80.0, "maxSpeedMps": 2.0, "maxSpeedNearHumansMps": 0.5,
6345            "allowedZones": ["warehouse-a", "dock-3"]
6346        });
6347        let lease = build_delegation_lease(
6348            &seed,
6349            &BuildDelegationLease {
6350                issuer_did: did.into(),
6351                robot_did: did.into(),
6352                lease_id: "lease-1".into(),
6353                scope: scope.clone(),
6354                parent_lease_id: None,
6355                valid_from: "2026-01-01T00:00:00Z".into(),
6356                valid_until: "2026-01-01T01:00:00Z".into(),
6357            },
6358        )
6359        .unwrap();
6360
6361        // Round-trip verify, in-window.
6362        let subject =
6363            verify_delegation_lease(&lease, &kp.public_key(), Some("2026-01-01T00:30:00Z"), None)
6364                .unwrap()
6365                .expect("lease verifies in window");
6366        assert_eq!(subject["leaseId"], json!("lease-1"));
6367
6368        // Permits a within-scope action, denies an out-of-scope one.
6369        assert!(lease_permits(
6370            &subject,
6371            &PhysicalAction {
6372                force_n: Some(50.0),
6373                zone: Some("warehouse-a".into()),
6374                ..Default::default()
6375            },
6376            Some(&lease),
6377            Some("2026-01-01T00:30:00Z"),
6378        ));
6379        assert!(!lease_permits(
6380            &subject,
6381            &PhysicalAction {
6382                force_n: Some(120.0),
6383                ..Default::default()
6384            },
6385            Some(&lease),
6386            Some("2026-01-01T00:30:00Z"),
6387        ));
6388
6389        // Expired window: verify fails and the lease no longer permits.
6390        assert!(verify_delegation_lease(
6391            &lease,
6392            &kp.public_key(),
6393            Some("2026-01-01T02:00:00Z"),
6394            None,
6395        )
6396        .unwrap()
6397        .is_none());
6398        assert!(!lease_permits(
6399            &subject,
6400            &PhysicalAction {
6401                force_n: Some(50.0),
6402                ..Default::default()
6403            },
6404            Some(&lease),
6405            Some("2026-01-01T02:00:00Z"),
6406        ));
6407
6408        // Tamper and wrong type rejected.
6409        let mut tampered = lease.clone();
6410        tampered["credentialSubject"]["leaseId"] = json!("lease-other");
6411        assert!(
6412            verify_delegation_lease(&tampered, &kp.public_key(), None, None)
6413                .unwrap()
6414                .is_none()
6415        );
6416    }
6417
6418    #[test]
6419    fn lease_sub_grant_attenuation() {
6420        let parent_seed = [32u8; 32];
6421        let child_seed = [33u8; 32];
6422        let parent_kp = Ed25519KeyPair::from_seed(&parent_seed);
6423        let child_kp = Ed25519KeyPair::from_seed(&child_seed);
6424        let parent_scope = json!({
6425            "maxForceN": 80.0, "maxSpeedMps": 2.0,
6426            "allowedZones": ["warehouse-a", "dock-3"]
6427        });
6428
6429        // A narrower sub-lease attenuates the parent: accepted.
6430        let narrower = build_delegation_lease(
6431            &child_seed,
6432            &BuildDelegationLease {
6433                issuer_did: "did:web:integrator.example.com".into(),
6434                robot_did: "did:web:robot.example.com".into(),
6435                lease_id: "lease-2".into(),
6436                scope: json!({
6437                    "maxForceN": 50.0, "maxSpeedMps": 1.0,
6438                    "allowedZones": ["warehouse-a"]
6439                }),
6440                parent_lease_id: Some("lease-1".into()),
6441                valid_from: "2026-01-01T00:00:00Z".into(),
6442                valid_until: "2026-01-01T01:00:00Z".into(),
6443            },
6444        )
6445        .unwrap();
6446        assert!(verify_delegation_lease(
6447            &narrower,
6448            &child_kp.public_key(),
6449            None,
6450            Some(&parent_scope),
6451        )
6452        .unwrap()
6453        .is_some());
6454
6455        // A widening sub-lease (force above the parent) is rejected against the
6456        // parent scope.
6457        let wider = build_delegation_lease(
6458            &parent_seed,
6459            &BuildDelegationLease {
6460                issuer_did: "did:web:integrator.example.com".into(),
6461                robot_did: "did:web:robot.example.com".into(),
6462                lease_id: "lease-3".into(),
6463                scope: json!({
6464                    "maxForceN": 200.0, "maxSpeedMps": 1.0,
6465                    "allowedZones": ["warehouse-a"]
6466                }),
6467                parent_lease_id: Some("lease-1".into()),
6468                valid_from: "2026-01-01T00:00:00Z".into(),
6469                valid_until: "2026-01-01T01:00:00Z".into(),
6470            },
6471        )
6472        .unwrap();
6473        assert!(verify_delegation_lease(
6474            &wider,
6475            &parent_kp.public_key(),
6476            None,
6477            Some(&parent_scope),
6478        )
6479        .unwrap()
6480        .is_none());
6481    }
6482
6483    #[test]
6484    fn quorum_threshold_and_distinct_counting() {
6485        let s1 = [41u8; 32];
6486        let s2 = [42u8; 32];
6487        let k1 = Ed25519KeyPair::from_seed(&s1);
6488        let k2 = Ed25519KeyPair::from_seed(&s2);
6489        let a1 = "did:web:approver-1.example.com";
6490        let a2 = "did:web:approver-2.example.com";
6491        let robot = "did:web:robot.example.com";
6492        let action = "action-x";
6493
6494        let build = |seed: &[u8], did: &str, decision: &str| {
6495            build_action_approval(
6496                seed,
6497                &BuildActionApproval {
6498                    approver_did: did.into(),
6499                    action_id: action.into(),
6500                    robot_did: robot.into(),
6501                    decision: decision.into(),
6502                    valid_from: "2026-01-01T00:00:00Z".into(),
6503                    valid_until: None,
6504                },
6505            )
6506            .unwrap()
6507        };
6508
6509        let ap1 = build(&s1, a1, APPROVE);
6510        let ap2 = build(&s2, a2, APPROVE);
6511        let keys = vec![
6512            ApproverKey {
6513                did: a1.into(),
6514                public_key: k1.public_key().to_vec(),
6515            },
6516            ApproverKey {
6517                did: a2.into(),
6518                public_key: k2.public_key().to_vec(),
6519            },
6520        ];
6521
6522        // Two distinct approvers meet a threshold of 2.
6523        let (ok, approvers) =
6524            verify_action_authorization(&[ap1.clone(), ap2], action, robot, &keys, 2, None, None)
6525                .unwrap();
6526        assert!(ok);
6527        assert_eq!(approvers, vec![a1.to_string(), a2.to_string()]);
6528
6529        // Duplicate approvals from one approver count once: threshold 2 not met.
6530        let dup = build(&s1, a1, APPROVE);
6531        let (ok2, approvers2) =
6532            verify_action_authorization(&[ap1.clone(), dup], action, robot, &keys, 2, None, None)
6533                .unwrap();
6534        assert!(!ok2);
6535        assert_eq!(approvers2, vec![a1.to_string()]);
6536
6537        // A single valid approver does not meet a threshold of 2.
6538        let (ok3, _) =
6539            verify_action_authorization(&[ap1], action, robot, &keys, 2, None, None).unwrap();
6540        assert!(!ok3);
6541
6542        // A rejection is never counted as an approval.
6543        let rej = build(&s1, a1, REJECT);
6544        let approve2 = build(&s2, a2, APPROVE);
6545        let (ok4, approvers4) =
6546            verify_action_authorization(&[rej, approve2], action, robot, &keys, 2, None, None)
6547                .unwrap();
6548        assert!(!ok4);
6549        assert_eq!(approvers4, vec![a2.to_string()]);
6550    }
6551
6552    // Cross-language interop: Rust verifies the Python-signed ownership transfer
6553    // under the owner's key from the vector.
6554    #[test]
6555    fn verifies_python_ownership_transfer_interop_vector() {
6556        let vector = load_vector();
6557        let owner_pub = jwk_pub(&vector["ownership_transfer_owner_key"]);
6558        let cred = vector["ownership_transfer_credential"].clone();
6559
6560        let subject = verify_ownership_transfer(&cred, &owner_pub)
6561            .unwrap()
6562            .expect("the Python ownership-transfer interop vector must verify in Rust");
6563        assert_eq!(subject["toOwner"], json!("did:web:owner-b.example.com"));
6564    }
6565
6566    // Cross-language interop: Rust verifies the Python-signed key rotation under
6567    // the robot key from robot_public_key_jwk.
6568    #[test]
6569    fn verifies_python_key_rotation_interop_vector() {
6570        let vector = load_vector();
6571        let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
6572        let cred = vector["key_rotation_credential"].clone();
6573
6574        let subject = verify_key_rotation(&cred, &robot_pub)
6575            .unwrap()
6576            .expect("the Python key-rotation interop vector must verify in Rust");
6577        assert_eq!(
6578            subject["newKey"],
6579            json!("z6MkmtWtY63GQVBrpMyRJWEzsnxfsGkemu6CtMDwGTv4RYj2")
6580        );
6581    }
6582
6583    // Cross-language interop: Rust verifies the Python-signed decommission under
6584    // the authority key from the vector.
6585    #[test]
6586    fn verifies_python_decommission_interop_vector() {
6587        let vector = load_vector();
6588        let authority_pub = jwk_pub(&vector["decommission_authority_key"]);
6589        let cred = vector["decommission_credential"].clone();
6590
6591        let subject = verify_decommission(&cred, &authority_pub, None)
6592            .unwrap()
6593            .expect("the Python decommission interop vector must verify in Rust");
6594        assert_eq!(subject["reason"], json!("end of service life"));
6595        assert_eq!(subject["finalDisposition"], json!("recycled"));
6596    }
6597
6598    #[test]
6599    fn ownership_transfer_roundtrip_and_issuer_rule() {
6600        let owner_a_seed = [51u8; 32];
6601        let owner_b_seed = [52u8; 32];
6602        let a = Ed25519KeyPair::from_seed(&owner_a_seed);
6603        let b = Ed25519KeyPair::from_seed(&owner_b_seed);
6604        let owner_a = "did:web:owner-a.example.com";
6605        let owner_b = "did:web:owner-b.example.com";
6606        let robot = "did:web:robot.example.com";
6607
6608        let transfer = build_ownership_transfer(
6609            &owner_a_seed,
6610            &BuildOwnershipTransfer {
6611                issuer_did: owner_a.into(),
6612                robot_did: robot.into(),
6613                to_owner: owner_b.into(),
6614                from_owner: None,
6615                prev_transfer_id: None,
6616                valid_from: "2026-01-01T00:00:00Z".into(),
6617            },
6618        )
6619        .unwrap();
6620
6621        let subject = verify_ownership_transfer(&transfer, &a.public_key())
6622            .unwrap()
6623            .expect("transfer verifies under the current owner key");
6624        assert_eq!(subject["fromOwner"], json!(owner_a));
6625        assert_eq!(subject["toOwner"], json!(owner_b));
6626
6627        // Wrong type rejected.
6628        let mut wrong = transfer.clone();
6629        wrong["type"] = json!(["VerifiableCredential"]);
6630        assert!(verify_ownership_transfer(&wrong, &a.public_key())
6631            .unwrap()
6632            .is_none());
6633
6634        // The issuer must equal fromOwner: forge a transfer whose issuer is not the
6635        // declared seller and re-sign it. It must be rejected even with a valid
6636        // proof under the signing key.
6637        let forged = build_ownership_transfer(
6638            &owner_b_seed,
6639            &BuildOwnershipTransfer {
6640                issuer_did: owner_b.into(),
6641                robot_did: robot.into(),
6642                to_owner: "did:web:owner-c.example.com".into(),
6643                // Claim the robot was sold by owner A while owner B signs.
6644                from_owner: Some(owner_a.into()),
6645                prev_transfer_id: None,
6646                valid_from: "2026-01-01T00:00:00Z".into(),
6647            },
6648        )
6649        .unwrap();
6650        assert!(verify_ownership_transfer(&forged, &b.public_key())
6651            .unwrap()
6652            .is_none());
6653    }
6654
6655    #[test]
6656    fn custody_chain_links_and_rejects() {
6657        let owner_a_seed = [51u8; 32];
6658        let owner_b_seed = [52u8; 32];
6659        let owner_c_seed = [53u8; 32];
6660        let a = Ed25519KeyPair::from_seed(&owner_a_seed);
6661        let b = Ed25519KeyPair::from_seed(&owner_b_seed);
6662        let c = Ed25519KeyPair::from_seed(&owner_c_seed);
6663        let owner_a = "did:web:owner-a.example.com";
6664        let owner_b = "did:web:owner-b.example.com";
6665        let owner_c = "did:web:owner-c.example.com";
6666        let robot = "did:web:robot.example.com";
6667
6668        let t1 = build_ownership_transfer(
6669            &owner_a_seed,
6670            &BuildOwnershipTransfer {
6671                issuer_did: owner_a.into(),
6672                robot_did: robot.into(),
6673                to_owner: owner_b.into(),
6674                from_owner: None,
6675                prev_transfer_id: None,
6676                valid_from: "2026-01-01T00:00:00Z".into(),
6677            },
6678        )
6679        .unwrap();
6680        let t2 = build_ownership_transfer(
6681            &owner_b_seed,
6682            &BuildOwnershipTransfer {
6683                issuer_did: owner_b.into(),
6684                robot_did: robot.into(),
6685                to_owner: owner_c.into(),
6686                from_owner: None,
6687                prev_transfer_id: Some("transfer-1".into()),
6688                valid_from: "2026-02-01T00:00:00Z".into(),
6689            },
6690        )
6691        .unwrap();
6692
6693        let keys = vec![
6694            OwnerKey {
6695                did: owner_a.into(),
6696                public_key: a.public_key().to_vec(),
6697            },
6698            OwnerKey {
6699                did: owner_b.into(),
6700                public_key: b.public_key().to_vec(),
6701            },
6702            OwnerKey {
6703                did: owner_c.into(),
6704                public_key: c.public_key().to_vec(),
6705            },
6706        ];
6707
6708        // A clean two-link chain rooted at owner A ends at owner C.
6709        let (ok, current) =
6710            verify_custody_chain(&[t1.clone(), t2.clone()], &keys, Some(owner_a)).unwrap();
6711        assert!(ok);
6712        assert_eq!(current.as_deref(), Some(owner_c));
6713
6714        // A wrong declared origin breaks the first link.
6715        let (bad_origin, _) =
6716            verify_custody_chain(&[t1.clone(), t2.clone()], &keys, Some(owner_c)).unwrap();
6717        assert!(!bad_origin);
6718
6719        // A gap (link two without link one) breaks the toOwner -> fromOwner join.
6720        let (gap, _) =
6721            verify_custody_chain(std::slice::from_ref(&t2), &keys, Some(owner_a)).unwrap();
6722        assert!(!gap);
6723
6724        // A missing key for an issuer fails the chain.
6725        let partial = vec![OwnerKey {
6726            did: owner_a.into(),
6727            public_key: a.public_key().to_vec(),
6728        }];
6729        let (no_key, _) = verify_custody_chain(&[t1, t2], &partial, Some(owner_a)).unwrap();
6730        assert!(!no_key);
6731    }
6732
6733    #[test]
6734    fn key_rotation_roundtrip_and_history() {
6735        let k1_seed = [61u8; 32];
6736        let k2_seed = [62u8; 32];
6737        let k3_seed = [63u8; 32];
6738        let k1 = Ed25519KeyPair::from_seed(&k1_seed);
6739        let k2 = Ed25519KeyPair::from_seed(&k2_seed);
6740        let k3 = Ed25519KeyPair::from_seed(&k3_seed);
6741        let robot = "did:web:robot.example.com";
6742
6743        // Rotate k1 -> k2, signed by k1.
6744        let r1 = build_key_rotation(
6745            &k1_seed,
6746            &BuildKeyRotation {
6747                robot_did: robot.into(),
6748                new_key_multibase: k2.public_multikey(),
6749                reason: Some("scheduled rotation".into()),
6750                valid_from: "2026-01-01T00:00:00Z".into(),
6751            },
6752        )
6753        .unwrap();
6754
6755        let subject = verify_key_rotation(&r1, &k1.public_key())
6756            .unwrap()
6757            .expect("rotation verifies under the old key");
6758        assert_eq!(subject["previousKey"], json!(k1.public_multikey()));
6759        assert_eq!(subject["newKey"], json!(k2.public_multikey()));
6760
6761        // The new key cannot verify a rotation that the old key signed.
6762        assert!(verify_key_rotation(&r1, &k2.public_key())
6763            .unwrap()
6764            .is_none());
6765
6766        // Wrong type rejected.
6767        let mut wrong = r1.clone();
6768        wrong["type"] = json!(["VerifiableCredential"]);
6769        assert!(verify_key_rotation(&wrong, &k1.public_key())
6770            .unwrap()
6771            .is_none());
6772
6773        // Rotate k2 -> k3, signed by k2, forming a history.
6774        let r2 = build_key_rotation(
6775            &k2_seed,
6776            &BuildKeyRotation {
6777                robot_did: robot.into(),
6778                new_key_multibase: k3.public_multikey(),
6779                reason: None,
6780                valid_from: "2026-02-01T00:00:00Z".into(),
6781            },
6782        )
6783        .unwrap();
6784
6785        let public_keys = vec![
6786            KeyEntry {
6787                multibase: k1.public_multikey(),
6788                public_key: k1.public_key().to_vec(),
6789            },
6790            KeyEntry {
6791                multibase: k2.public_multikey(),
6792                public_key: k2.public_key().to_vec(),
6793            },
6794            KeyEntry {
6795                multibase: k3.public_multikey(),
6796                public_key: k3.public_key().to_vec(),
6797            },
6798        ];
6799
6800        let (ok, current) = verify_key_history(
6801            &[r1.clone(), r2.clone()],
6802            &k1.public_multikey(),
6803            &public_keys,
6804        )
6805        .unwrap();
6806        assert!(ok);
6807        assert_eq!(current.as_deref(), Some(k3.public_multikey().as_str()));
6808
6809        // A wrong origin key breaks the first previousKey match.
6810        let (bad_origin, _) =
6811            verify_key_history(&[r1, r2], &k3.public_multikey(), &public_keys).unwrap();
6812        assert!(!bad_origin);
6813    }
6814
6815    #[test]
6816    fn decommission_roundtrip_and_trusted_authority() {
6817        let seed = [71u8; 32];
6818        let kp = Ed25519KeyPair::from_seed(&seed);
6819        let authority = "did:web:authority.example.com";
6820        let robot = "did:web:robot.example.com";
6821
6822        let cred = build_decommission(
6823            &seed,
6824            &BuildDecommission {
6825                issuer_did: authority.into(),
6826                robot_did: robot.into(),
6827                reason: "end of service life".into(),
6828                final_disposition: Some("recycled".into()),
6829                valid_from: "2026-01-01T00:00:00Z".into(),
6830                valid_until: None,
6831            },
6832        )
6833        .unwrap();
6834
6835        let mut trusted = HashSet::new();
6836        trusted.insert(authority.to_string());
6837        let subject = verify_decommission(&cred, &kp.public_key(), Some(&trusted))
6838            .unwrap()
6839            .expect("a trusted authority decommission verifies");
6840        assert_eq!(subject["decommissionedBy"], json!(authority));
6841
6842        // An untrusted issuer is rejected even with a valid proof.
6843        let mut other = HashSet::new();
6844        other.insert("did:web:someone-else.example.com".to_string());
6845        assert!(verify_decommission(&cred, &kp.public_key(), Some(&other))
6846            .unwrap()
6847            .is_none());
6848
6849        // No trusted-authority set: a valid proof verifies.
6850        assert!(verify_decommission(&cred, &kp.public_key(), None)
6851            .unwrap()
6852            .is_some());
6853
6854        // Wrong type rejected.
6855        let mut wrong = cred.clone();
6856        wrong["type"] = json!(["VerifiableCredential"]);
6857        assert!(verify_decommission(&wrong, &kp.public_key(), None)
6858            .unwrap()
6859            .is_none());
6860
6861        // reason is required at build time.
6862        assert!(build_decommission(
6863            &seed,
6864            &BuildDecommission {
6865                issuer_did: authority.into(),
6866                robot_did: robot.into(),
6867                reason: String::new(),
6868                final_disposition: None,
6869                valid_from: "2026-01-01T00:00:00Z".into(),
6870                valid_until: None,
6871            },
6872        )
6873        .is_err());
6874    }
6875
6876    // Cross-language interop: Rust reproduces the exact conformance report and
6877    // digest Python pinned, from the same credential set and profile.
6878    #[test]
6879    fn conformance_matches_interop_vector() {
6880        let vector = load_vector();
6881        let credentials: Vec<Value> = vector["conformance_credentials"]
6882            .as_array()
6883            .expect("conformance_credentials present")
6884            .clone();
6885        let profile_id = vector["conformance_profile_id"].as_str().unwrap();
6886
6887        let report = check_conformance(&credentials, profile_id).unwrap();
6888        assert_eq!(report, vector["expected_conformance_report"]);
6889
6890        let digest = report_digest(&report);
6891        assert_eq!(
6892            digest,
6893            vector["expected_conformance_report_digest"]
6894                .as_str()
6895                .unwrap()
6896        );
6897    }
6898
6899    // Presence alone is not evidence. A heartbeat that reports an envelope
6900    // breach must not satisfy the continuous-monitoring requirement just by
6901    // carrying a motionDigest.
6902    #[test]
6903    fn a_breaching_heartbeat_does_not_evidence_monitoring() {
6904        let breaching = json!({
6905            "type": ["VerifiableCredential", "RobotHeartbeatCredential"],
6906            "credentialSubject": {
6907                "motionDigest": {"withinEnvelope": false, "samples": 120}
6908            }
6909        });
6910        let report = check_conformance(&[breaching.clone()], "iso-ts-15066").unwrap();
6911        let monitoring = report["requirements"]
6912            .as_array()
6913            .unwrap()
6914            .iter()
6915            .find(|r| r["id"] == json!("iso15066-monitoring"))
6916            .expect("monitoring requirement present");
6917        assert_eq!(monitoring["satisfied"], json!(false));
6918
6919        // The same heartbeat reporting no breach does satisfy it.
6920        let mut clean = breaching;
6921        clean["credentialSubject"]["motionDigest"]["withinEnvelope"] = json!(true);
6922        let report = check_conformance(&[clean], "iso-ts-15066").unwrap();
6923        let monitoring = report["requirements"]
6924            .as_array()
6925            .unwrap()
6926            .iter()
6927            .find(|r| r["id"] == json!("iso15066-monitoring"))
6928            .unwrap();
6929        assert_eq!(monitoring["satisfied"], json!(true));
6930    }
6931
6932    // Every requirement declares where its clause number came from, and the
6933    // report totals them, so CONFORMS never reads as more authoritative about
6934    // the regulation than its sources are.
6935    #[test]
6936    fn conformance_report_carries_citation_provenance() {
6937        for profile_id in [
6938            "iso-10218",
6939            "iso-ts-15066",
6940            "eu-machinery-2023-1230",
6941            "eu-ai-act-high-risk",
6942            "ul-3300",
6943        ] {
6944            let report = check_conformance(&[], profile_id).unwrap();
6945            let citations = report["citations"].as_object().unwrap();
6946            assert_eq!(citations.len(), CITATION_STATUSES.len());
6947            let counted: i64 = citations.values().map(|v| v.as_i64().unwrap()).sum();
6948            assert_eq!(counted, report["totalCount"].as_i64().unwrap());
6949            for result in report["requirements"].as_array().unwrap() {
6950                let citation = result["citation"].as_str().unwrap();
6951                assert!(CITATION_STATUSES.contains(&citation));
6952            }
6953        }
6954
6955        // UL 3300 is paywalled with no clause numbering available, so none of
6956        // its "clauses" are citable.
6957        let ul = check_conformance(&[], "ul-3300").unwrap();
6958        assert_eq!(ul["citations"][CITATION_DESCRIPTIVE], ul["totalCount"]);
6959        assert_eq!(ul["citations"][CITATION_VERIFIED_PRIMARY], json!(0));
6960    }
6961
6962    #[test]
6963    fn conformance_unknown_profile_and_missing_field() {
6964        assert!(check_conformance(&[], "no-such-profile").is_err());
6965
6966        // An empty credential set satisfies nothing.
6967        let empty = check_conformance(&[], "eu-ai-act-high-risk").unwrap();
6968        assert_eq!(empty["conforms"], json!(false));
6969        assert_eq!(empty["satisfiedCount"], json!(0));
6970        assert_eq!(empty["totalCount"], json!(4));
6971
6972        // A safety record with no logHead does not satisfy the record-keeping
6973        // requirement (a missing field counts as unsatisfied).
6974        let creds = vec![json!({
6975            "type": ["VerifiableCredential", "RobotSafetyRecordCredential"],
6976            "credentialSubject": { "id": "did:web:robot.example.com", "totalEvents": 2 }
6977        })];
6978        let report = check_conformance(&creds, "eu-ai-act-high-risk").unwrap();
6979        let record_keeping = report["requirements"]
6980            .as_array()
6981            .unwrap()
6982            .iter()
6983            .find(|r| r["id"] == json!("eu-aia-record-keeping"))
6984            .unwrap();
6985        assert_eq!(record_keeping["satisfied"], json!(false));
6986
6987        // An empty allowedZones array is also unsatisfied.
6988        let zone_creds = vec![json!({
6989            "type": ["VerifiableCredential", "PhysicalCapabilityScope"],
6990            "credentialSubject": {
6991                "id": "did:web:robot.example.com",
6992                "physicalScope": { "maxSpeedMps": 1.5, "allowedZones": [] }
6993            }
6994        })];
6995        let ul = check_conformance(&zone_creds, "ul-3300").unwrap();
6996        let limits = ul["requirements"]
6997            .as_array()
6998            .unwrap()
6999            .iter()
7000            .find(|r| r["id"] == json!("ul3300-operating-limits"))
7001            .unwrap();
7002        assert_eq!(limits["satisfied"], json!(false));
7003    }
7004
7005    #[test]
7006    fn conformance_attestation_roundtrip_and_rejections() {
7007        let seed = [77u8; 32];
7008        let kp = Ed25519KeyPair::from_seed(&seed);
7009        let vector = load_vector();
7010        let credentials: Vec<Value> = vector["conformance_credentials"]
7011            .as_array()
7012            .unwrap()
7013            .clone();
7014        let report = check_conformance(&credentials, "eu-ai-act-high-risk").unwrap();
7015
7016        let att = build_conformance_attestation(
7017            &seed,
7018            &BuildConformanceAttestation {
7019                issuer_did: "did:web:authority.example.com".into(),
7020                robot_did: "did:web:robot.example.com".into(),
7021                report: report.clone(),
7022                valid_from: "2026-01-01T00:00:00Z".into(),
7023                valid_until: Some("2027-01-01T00:00:00Z".into()),
7024            },
7025        )
7026        .unwrap();
7027
7028        // Round-trip: a well-formed attestation verifies and surfaces the subject.
7029        let subject = verify_conformance_attestation(&att, &kp.public_key())
7030            .unwrap()
7031            .expect("a valid conformance attestation verifies");
7032        assert_eq!(subject["profileId"], json!("eu-ai-act-high-risk"));
7033        assert_eq!(subject["conforms"], json!(true));
7034        assert_eq!(
7035            subject["reportDigest"],
7036            vector["expected_conformance_report_digest"]
7037        );
7038
7039        // Wrong key is rejected.
7040        let wrong_kp = Ed25519KeyPair::from_seed(&[88u8; 32]);
7041        assert!(verify_conformance_attestation(&att, &wrong_kp.public_key())
7042            .unwrap()
7043            .is_none());
7044
7045        // A tampered embedded report no longer matches the bound digest.
7046        let mut tampered = att.clone();
7047        tampered["credentialSubject"]["report"]["conforms"] = json!(false);
7048        assert!(verify_conformance_attestation(&tampered, &kp.public_key())
7049            .unwrap()
7050            .is_none());
7051
7052        // Wrong type is rejected.
7053        let mut wrong_type = att.clone();
7054        wrong_type["type"] = json!(["VerifiableCredential"]);
7055        assert!(
7056            verify_conformance_attestation(&wrong_type, &kp.public_key())
7057                .unwrap()
7058                .is_none()
7059        );
7060
7061        // robot_did is required at build time.
7062        assert!(build_conformance_attestation(
7063            &seed,
7064            &BuildConformanceAttestation {
7065                issuer_did: "did:web:authority.example.com".into(),
7066                robot_did: String::new(),
7067                report,
7068                valid_from: "2026-01-01T00:00:00Z".into(),
7069                valid_until: None,
7070            },
7071        )
7072        .is_err());
7073    }
7074
7075    // -- post-quantum robot credentials ------------------------------------
7076
7077    fn classical_robot_credential(issuer: &str, seed: &[u8]) -> Value {
7078        let cred = json!({
7079            "@context": [VC_CONTEXT_V2, VOUCH_CONTEXT_V1],
7080            "type": ["VerifiableCredential", ROBOT_IDENTITY_TYPE],
7081            "issuer": issuer,
7082            "validFrom": "2026-01-01T00:00:00Z",
7083            "credentialSubject": {
7084                "id": issuer,
7085                "make": "Acme Robotics",
7086                "model": "AR-7",
7087                "serial": "SN-000123"
7088            }
7089        });
7090        let opts = BuildProofOptions::new(format!("{issuer}#key-1"), "2026-01-01T00:00:00Z");
7091        data_integrity::sign(&cred, seed, &opts).unwrap()
7092    }
7093
7094    // Cross-language interop: Rust verifies the Python-signed hybrid PQ robot
7095    // identity under the Ed25519 key and the ML-DSA-44 multikey from the vector.
7096    #[test]
7097    fn verifies_python_pq_robot_identity_interop_vector() {
7098        let vector = load_vector();
7099        let ed_pub = jwk_pub(&vector["robot_public_key_jwk"]);
7100        let ml_multikey = vector["robot_mldsa44_public_multikey"].as_str().unwrap();
7101        let cred = vector["pq_robot_identity_credential"].clone();
7102
7103        // (b) the credential is detected as post-quantum.
7104        assert!(is_pq(&cred));
7105
7106        // (a) dual verify auto-detected from the proof, with the ML-DSA multikey.
7107        let ok = verify_robot_credential(&cred, &ed_pub, Some(ml_multikey.as_bytes()))
7108            .expect("the Python hybrid PQ interop vector must verify in Rust");
7109        assert!(ok);
7110
7111        // verify_pq accepts the multikey string form directly.
7112        let resolved = mldsa44_public_from_multikey(ml_multikey).unwrap();
7113        assert!(verify_pq(&cred, &ed_pub, &resolved).unwrap());
7114    }
7115
7116    #[test]
7117    fn pq_sign_verify_roundtrip_and_rejects() {
7118        let issuer = "did:web:robot.example.com";
7119        let seed = [21u8; 32];
7120        let kp = Ed25519KeyPair::from_seed(&seed);
7121        let ml = MlDsa44KeyPair::generate().unwrap();
7122
7123        let classical = classical_robot_credential(issuer, &seed);
7124        assert!(!is_pq(&classical));
7125
7126        // Sign post-quantum; any prior proof is replaced by a proof set holding
7127        // one classical and one ML-DSA-44 proof.
7128        let signed = sign_pq(&classical, &seed, &ml, "2026-02-01T00:00:00Z").unwrap();
7129        assert!(is_pq(&signed));
7130        let proofs = signed["proof"].as_array().expect("proof set");
7131        assert_eq!(proofs.len(), 2);
7132        assert_eq!(
7133            proofs[0]["cryptosuite"],
7134            json!(hybrid::EDDSA_CRYPTOSUITE_ID)
7135        );
7136        assert_eq!(
7137            proofs[1]["cryptosuite"],
7138            json!(hybrid::MLDSA44_CRYPTOSUITE_ID)
7139        );
7140        // Each proof carries the Multibase encoding its cryptosuite specifies.
7141        assert!(proofs[0]["proofValue"].as_str().unwrap().starts_with('z'));
7142        assert!(proofs[1]["proofValue"].as_str().unwrap().starts_with('u'));
7143
7144        // Round-trip: both signatures validate under the correct keys.
7145        assert!(verify_pq(&signed, &kp.public_key(), &ml.public_key()).unwrap());
7146        assert!(
7147            verify_robot_credential(&signed, &kp.public_key(), Some(&ml.public_key())).unwrap()
7148        );
7149
7150        // The multikey string form is accepted too (as UTF-8 bytes).
7151        let ml_mk = multikey::encode_mldsa44_public(&ml.public_key()).unwrap();
7152        assert!(
7153            verify_robot_credential(&signed, &kp.public_key(), Some(ml_mk.as_bytes())).unwrap()
7154        );
7155
7156        // Tampering the body breaks verification.
7157        let mut tampered = signed.clone();
7158        tampered["credentialSubject"]["model"] = json!("AR-9");
7159        assert!(!verify_pq(&tampered, &kp.public_key(), &ml.public_key()).unwrap());
7160
7161        // Wrong Ed25519 key is rejected.
7162        let other_ed = Ed25519KeyPair::from_seed(&[99u8; 32]);
7163        assert!(!verify_pq(&signed, &other_ed.public_key(), &ml.public_key()).unwrap());
7164
7165        // Wrong ML-DSA-44 key is rejected.
7166        let other_ml = MlDsa44KeyPair::generate().unwrap();
7167        assert!(!verify_pq(&signed, &kp.public_key(), &other_ml.public_key()).unwrap());
7168
7169        // A hybrid credential without the ML-DSA key returns false, not true.
7170        assert!(!verify_robot_credential(&signed, &kp.public_key(), None).unwrap());
7171
7172        // Downgrade by extraction: an attacker strips the proof set to the lone
7173        // standalone classical proof. A verifier that supplies the ML-DSA key
7174        // (so requires post-quantum) must reject it, not accept it as classical.
7175        let proofs = signed["proof"].as_array().unwrap();
7176        let classical_proof = proofs
7177            .iter()
7178            .find(|p| p["cryptosuite"] == json!(hybrid::EDDSA_CRYPTOSUITE_ID))
7179            .unwrap()
7180            .clone();
7181        let mut stripped = signed.clone();
7182        stripped["proof"] = classical_proof;
7183        assert!(!is_pq(&stripped));
7184        assert!(
7185            !verify_robot_credential(&stripped, &kp.public_key(), Some(&ml.public_key())).unwrap(),
7186            "a stripped proof set must not verify when the caller requires post-quantum"
7187        );
7188        // The extracted classical proof is genuine, so a caller that only does
7189        // classical verification (no ML-DSA key) still accepts it.
7190        assert!(verify_robot_credential(&stripped, &kp.public_key(), None).unwrap());
7191    }
7192
7193    #[test]
7194    fn classical_credential_passes_dual_verify_without_pq_key() {
7195        let issuer = "did:web:robot.example.com";
7196        let seed = [22u8; 32];
7197        let kp = Ed25519KeyPair::from_seed(&seed);
7198        let classical = classical_robot_credential(issuer, &seed);
7199
7200        assert!(!is_pq(&classical));
7201        // A classical credential verifies through the dual path with no ML-DSA key.
7202        assert!(verify_robot_credential(&classical, &kp.public_key(), None).unwrap());
7203
7204        // A wrong key still fails.
7205        let other = Ed25519KeyPair::from_seed(&[7u8; 32]);
7206        assert!(!verify_robot_credential(&classical, &other.public_key(), None).unwrap());
7207    }
7208
7209    #[test]
7210    fn migrate_to_pq_resigns_classical_credential() {
7211        let issuer = "did:web:robot.example.com";
7212        let seed = [23u8; 32];
7213        let kp = Ed25519KeyPair::from_seed(&seed);
7214        let ml = MlDsa44KeyPair::generate().unwrap();
7215
7216        let classical = classical_robot_credential(issuer, &seed);
7217        assert!(verify_robot_credential(&classical, &kp.public_key(), None).unwrap());
7218
7219        let migrated = migrate_to_pq(&classical, &seed, &ml, "2026-03-01T00:00:00Z").unwrap();
7220        assert!(is_pq(&migrated));
7221        // The body is preserved across migration.
7222        assert_eq!(
7223            migrated["credentialSubject"],
7224            classical["credentialSubject"]
7225        );
7226        assert!(
7227            verify_robot_credential(&migrated, &kp.public_key(), Some(&ml.public_key())).unwrap()
7228        );
7229    }
7230
7231    // Cross-language interop: Rust verifies the Python-signed embodiment continuity
7232    // chain under the one agent key from the vector, ending on body-b, with no fork.
7233    #[test]
7234    fn verifies_python_embodiment_interop_vector() {
7235        let vector = load_vector();
7236        let agent_pub = jwk_pub(&vector["embodiment_agent_key"]);
7237        let chain: Vec<Value> = vector["embodiment_chain"]
7238            .as_array()
7239            .expect("embodiment_chain array")
7240            .clone();
7241
7242        let (ok, current) = verify_continuity_chain(&chain, &agent_pub, None).unwrap();
7243        assert!(ok, "the Python embodiment chain must verify in Rust");
7244        assert_eq!(
7245            current.as_deref(),
7246            Some("did:web:body-b.example.com"),
7247            "the chain ends on body-b"
7248        );
7249
7250        let (no_fork, conflict) = check_no_fork(&chain).unwrap();
7251        assert!(no_fork, "the Python embodiment chain has no fork");
7252        assert!(conflict.is_none());
7253    }
7254
7255    #[test]
7256    fn embodiment_roundtrip_and_issuer_rule() {
7257        let agent_seed = [61u8; 32];
7258        let other_seed = [62u8; 32];
7259        let agent = Ed25519KeyPair::from_seed(&agent_seed);
7260        let other = Ed25519KeyPair::from_seed(&other_seed);
7261        let agent_did = "did:web:agent.example.com";
7262        let body_a = "did:web:body-a.example.com";
7263
7264        let cred = build_embodiment(
7265            &agent_seed,
7266            &BuildEmbodiment {
7267                agent_did: agent_did.into(),
7268                body_did: body_a.into(),
7269                body_hardware_root: "uROOTA".into(),
7270                from_body: None,
7271                embodied_at: "2026-01-01T00:00:00Z".into(),
7272                valid_until: None,
7273            },
7274        )
7275        .unwrap();
7276
7277        let subject = verify_embodiment(&cred, &agent.public_key())
7278            .unwrap()
7279            .expect("embodiment verifies under the agent key");
7280        assert_eq!(subject["body"], json!(body_a));
7281        assert_eq!(subject["bodyHardwareRoot"], json!("uROOTA"));
7282
7283        // The issuer must equal the subject id: forge a credential issued by an
7284        // impostor over an unchanged subject (still the agent) and re-sign it. It
7285        // must be rejected even with a valid proof under the signing key, because a
7286        // mind only authorizes its own embodiment.
7287        let forged = {
7288            let mut bare = cred.clone();
7289            bare.as_object_mut().unwrap().remove("proof");
7290            bare["issuer"] = json!("did:web:impostor.example.com");
7291            let opts = BuildProofOptions::new(
7292                "did:web:impostor.example.com#key-1".to_string(),
7293                "2026-01-01T00:00:00Z",
7294            );
7295            data_integrity::sign(&bare, &other_seed, &opts).unwrap()
7296        };
7297        assert!(verify_embodiment(&forged, &other.public_key())
7298            .unwrap()
7299            .is_none());
7300    }
7301
7302    #[test]
7303    fn continuity_chain_links_and_rejects() {
7304        let agent_seed = [61u8; 32];
7305        let stranger_seed = [63u8; 32];
7306        let agent = Ed25519KeyPair::from_seed(&agent_seed);
7307        let stranger = Ed25519KeyPair::from_seed(&stranger_seed);
7308        let agent_did = "did:web:agent.example.com";
7309        let body_a = "did:web:body-a.example.com";
7310        let body_b = "did:web:body-b.example.com";
7311
7312        let e1 = build_embodiment(
7313            &agent_seed,
7314            &BuildEmbodiment {
7315                agent_did: agent_did.into(),
7316                body_did: body_a.into(),
7317                body_hardware_root: "uROOTA".into(),
7318                from_body: None,
7319                embodied_at: "2026-01-01T00:00:00Z".into(),
7320                valid_until: Some("2026-01-01T01:00:00Z".into()),
7321            },
7322        )
7323        .unwrap();
7324        let e2 = build_embodiment(
7325            &agent_seed,
7326            &BuildEmbodiment {
7327                agent_did: agent_did.into(),
7328                body_did: body_b.into(),
7329                body_hardware_root: "uROOTB".into(),
7330                from_body: Some(body_a.into()),
7331                embodied_at: "2026-01-01T01:00:00Z".into(),
7332                valid_until: None,
7333            },
7334        )
7335        .unwrap();
7336
7337        // A clean two-link chain ends at body-b: the first link opens on body-a
7338        // and the second link's fromBody re-binds to it.
7339        let (ok, current) =
7340            verify_continuity_chain(&[e1.clone(), e2.clone()], &agent.public_key(), None).unwrap();
7341        assert!(ok);
7342        assert_eq!(current.as_deref(), Some(body_b));
7343
7344        // Declaring the wrong origin body breaks the first link, since the first
7345        // link's fromBody must match the origin when given.
7346        let (bad_origin, _) =
7347            verify_continuity_chain(&[e1.clone(), e2.clone()], &agent.public_key(), Some(body_b))
7348                .unwrap();
7349        assert!(!bad_origin);
7350
7351        // A broken link (second link's fromBody does not match the first's body)
7352        // fails the chain.
7353        let broken = build_embodiment(
7354            &agent_seed,
7355            &BuildEmbodiment {
7356                agent_did: agent_did.into(),
7357                body_did: body_b.into(),
7358                body_hardware_root: "uROOTB".into(),
7359                from_body: Some("did:web:body-x.example.com".into()),
7360                embodied_at: "2026-01-01T01:00:00Z".into(),
7361                valid_until: None,
7362            },
7363        )
7364        .unwrap();
7365        let (bad_link, _) =
7366            verify_continuity_chain(&[e1.clone(), broken], &agent.public_key(), None).unwrap();
7367        assert!(!bad_link);
7368
7369        // Every link must verify under the SAME agent key: a link signed by a
7370        // different key breaks the chain (a mind is one persistent identity).
7371        let e2_stranger = build_embodiment(
7372            &stranger_seed,
7373            &BuildEmbodiment {
7374                agent_did: agent_did.into(),
7375                body_did: body_b.into(),
7376                body_hardware_root: "uROOTB".into(),
7377                from_body: Some(body_a.into()),
7378                embodied_at: "2026-01-01T01:00:00Z".into(),
7379                valid_until: None,
7380            },
7381        )
7382        .unwrap();
7383        assert!(verify_embodiment(&e2_stranger, &stranger.public_key())
7384            .unwrap()
7385            .is_some());
7386        let (mixed_keys, _) =
7387            verify_continuity_chain(&[e1, e2_stranger], &agent.public_key(), None).unwrap();
7388        assert!(!mixed_keys);
7389    }
7390
7391    #[test]
7392    fn fork_detection_flags_overlapping_bodies() {
7393        let agent_seed = [61u8; 32];
7394        let agent_did = "did:web:agent.example.com";
7395        let body_a = "did:web:body-a.example.com";
7396        let body_b = "did:web:body-b.example.com";
7397
7398        let build = |body: &str, root: &str, from: &str, until: &str| {
7399            build_embodiment(
7400                &agent_seed,
7401                &BuildEmbodiment {
7402                    agent_did: agent_did.into(),
7403                    body_did: body.into(),
7404                    body_hardware_root: root.into(),
7405                    from_body: None,
7406                    embodied_at: from.into(),
7407                    valid_until: Some(until.into()),
7408                },
7409            )
7410            .unwrap()
7411        };
7412
7413        // A clean handover: body-a's window ends exactly where body-b's begins.
7414        // Half-open intervals do not overlap, so this is not a fork.
7415        let clean_a = build(
7416            body_a,
7417            "uROOTA",
7418            "2026-01-01T00:00:00Z",
7419            "2026-01-01T01:00:00Z",
7420        );
7421        let clean_b = build(
7422            body_b,
7423            "uROOTB",
7424            "2026-01-01T01:00:00Z",
7425            "2026-01-01T02:00:00Z",
7426        );
7427        let (clean, conflict) = check_no_fork(&[clean_a, clean_b]).unwrap();
7428        assert!(clean);
7429        assert!(conflict.is_none());
7430
7431        // Overlapping windows on different bodies are a fork; the conflict names
7432        // both bodies.
7433        let fork_a = build(
7434            body_a,
7435            "uROOTA",
7436            "2026-01-01T00:00:00Z",
7437            "2026-01-01T02:00:00Z",
7438        );
7439        let fork_b = build(
7440            body_b,
7441            "uROOTB",
7442            "2026-01-01T01:00:00Z",
7443            "2026-01-01T03:00:00Z",
7444        );
7445        let (forked, conflict) = check_no_fork(&[fork_a, fork_b]).unwrap();
7446        assert!(!forked);
7447        let conflict = conflict.expect("a fork names the two conflicting bodies");
7448        assert_eq!(conflict.body_a, body_a);
7449        assert_eq!(conflict.body_b, body_b);
7450    }
7451
7452    // Custody handoff (Phase 5.16) -----------------------------------------
7453
7454    fn actor_keys_from_vector(map: &Value) -> Vec<ActorKey> {
7455        map.as_object()
7456            .expect("custody_actor_keys object")
7457            .iter()
7458            .map(|(did, jwk)| ActorKey {
7459                did: did.clone(),
7460                public_key: jwk_pub(jwk),
7461            })
7462            .collect()
7463    }
7464
7465    // Cross-language interop: Rust verifies the Python-signed custody chain under
7466    // the actor keys from the vector, ending on robot-b, and localizes the
7467    // condition change to the hop robot-a was responsible for.
7468    #[test]
7469    fn verifies_python_custody_interop_vector() {
7470        let vector = load_vector();
7471        let chain: Vec<Value> = vector["custody_chain"]
7472            .as_array()
7473            .expect("custody_chain array")
7474            .clone();
7475        let keys = actor_keys_from_vector(&vector["custody_actor_keys"]);
7476        let origin = vector["custody_origin_actor"].as_str().unwrap();
7477
7478        let (ok, current) = verify_handoff_chain(&chain, &keys, Some(origin)).unwrap();
7479        assert!(ok, "the Python custody chain must verify in Rust");
7480        assert_eq!(
7481            current.as_deref(),
7482            Some("did:web:robot-b.example.com"),
7483            "the chain ends holding at robot-b"
7484        );
7485
7486        let change = locate_condition_change(&chain).expect("the condition changed");
7487        assert_eq!(
7488            change.responsible_holder.as_deref(),
7489            Some("did:web:robot-a.example.com"),
7490            "robot-a held the task while its condition changed"
7491        );
7492        assert_eq!(change.from_condition, "intact");
7493        assert_eq!(change.to_condition, "damaged");
7494    }
7495
7496    #[test]
7497    fn handoff_roundtrip_and_receiver_rule() {
7498        let robot_seed = [71u8; 32];
7499        let other_seed = [72u8; 32];
7500        let robot = Ed25519KeyPair::from_seed(&robot_seed);
7501        let other = Ed25519KeyPair::from_seed(&other_seed);
7502        let worker = "did:web:worker-jane.example.com";
7503        let robot_a = "did:web:robot-a.example.com";
7504
7505        let cred = build_handoff(
7506            &robot_seed,
7507            &BuildHandoff {
7508                task_id: "tote-42".into(),
7509                from_actor: worker.into(),
7510                to_actor: robot_a.into(),
7511                condition: Some("intact".into()),
7512                handoff_at: "2026-01-01T00:00:00Z".into(),
7513                valid_until: None,
7514            },
7515        )
7516        .unwrap();
7517
7518        let subject = verify_handoff(&cred, &robot.public_key())
7519            .unwrap()
7520            .expect("handoff verifies under the receiver key");
7521        assert_eq!(subject["fromActor"], json!(worker));
7522        assert_eq!(subject["toActor"], json!(robot_a));
7523
7524        // The issuer must be the receiver: forge a handoff issued by a different
7525        // party over the same subject and re-sign it. It must be rejected even with
7526        // a valid proof under the signing key, because a party attests its own
7527        // acceptance of custody.
7528        let forged = {
7529            let mut bare = cred.clone();
7530            bare.as_object_mut().unwrap().remove("proof");
7531            bare["issuer"] = json!("did:web:impostor.example.com");
7532            let opts = BuildProofOptions::new(
7533                "did:web:impostor.example.com#key-1".to_string(),
7534                "2026-01-01T00:00:00Z",
7535            );
7536            data_integrity::sign(&bare, &other_seed, &opts).unwrap()
7537        };
7538        assert!(verify_handoff(&forged, &other.public_key())
7539            .unwrap()
7540            .is_none());
7541    }
7542
7543    #[test]
7544    fn handoff_chain_links_and_rejects() {
7545        let a_seed = [73u8; 32];
7546        let b_seed = [74u8; 32];
7547        let a = Ed25519KeyPair::from_seed(&a_seed);
7548        let b = Ed25519KeyPair::from_seed(&b_seed);
7549        let worker = "did:web:worker-jane.example.com";
7550        let robot_a = "did:web:robot-a.example.com";
7551        let robot_b = "did:web:robot-b.example.com";
7552
7553        let h1 = build_handoff(
7554            &a_seed,
7555            &BuildHandoff {
7556                task_id: "tote-42".into(),
7557                from_actor: worker.into(),
7558                to_actor: robot_a.into(),
7559                condition: Some("intact".into()),
7560                handoff_at: "2026-01-01T00:00:00Z".into(),
7561                valid_until: None,
7562            },
7563        )
7564        .unwrap();
7565        let h2 = build_handoff(
7566            &b_seed,
7567            &BuildHandoff {
7568                task_id: "tote-42".into(),
7569                from_actor: robot_a.into(),
7570                to_actor: robot_b.into(),
7571                condition: Some("damaged".into()),
7572                handoff_at: "2026-01-01T00:10:00Z".into(),
7573                valid_until: None,
7574            },
7575        )
7576        .unwrap();
7577
7578        let keys = vec![
7579            ActorKey {
7580                did: robot_a.into(),
7581                public_key: a.public_key().to_vec(),
7582            },
7583            ActorKey {
7584                did: robot_b.into(),
7585                public_key: b.public_key().to_vec(),
7586            },
7587        ];
7588
7589        // A clean two-link chain ends holding at robot-b: the first link's
7590        // fromActor is the origin worker and the second link re-binds to robot-a.
7591        let (ok, current) =
7592            verify_handoff_chain(&[h1.clone(), h2.clone()], &keys, Some(worker)).unwrap();
7593        assert!(ok);
7594        assert_eq!(current.as_deref(), Some(robot_b));
7595
7596        // Declaring the wrong origin actor breaks the first link.
7597        let (bad_origin, _) =
7598            verify_handoff_chain(&[h1.clone(), h2.clone()], &keys, Some(robot_b)).unwrap();
7599        assert!(!bad_origin);
7600
7601        // A broken link (second link's fromActor does not match the first's
7602        // toActor) fails the chain.
7603        let broken = build_handoff(
7604            &b_seed,
7605            &BuildHandoff {
7606                task_id: "tote-42".into(),
7607                from_actor: "did:web:robot-x.example.com".into(),
7608                to_actor: robot_b.into(),
7609                condition: Some("damaged".into()),
7610                handoff_at: "2026-01-01T00:10:00Z".into(),
7611                valid_until: None,
7612            },
7613        )
7614        .unwrap();
7615        let (bad_link, _) =
7616            verify_handoff_chain(&[h1.clone(), broken], &keys, Some(worker)).unwrap();
7617        assert!(!bad_link);
7618
7619        // A missing receiver key for a link fails the chain.
7620        let partial = vec![ActorKey {
7621            did: robot_a.into(),
7622            public_key: a.public_key().to_vec(),
7623        }];
7624        let (no_key, _) =
7625            verify_handoff_chain(&[h1.clone(), h2.clone()], &partial, Some(worker)).unwrap();
7626        assert!(!no_key);
7627
7628        // holder_at reports who held the task at a moment: robot-a right after the
7629        // first handoff, robot-b right after the second.
7630        assert_eq!(
7631            holder_at(&[h1.clone(), h2.clone()], "2026-01-01T00:05:00Z").as_deref(),
7632            Some(robot_a)
7633        );
7634        assert_eq!(
7635            holder_at(&[h1.clone(), h2.clone()], "2026-01-01T00:15:00Z").as_deref(),
7636            Some(robot_b)
7637        );
7638
7639        // A chain whose condition never changes localizes nothing.
7640        let steady = build_handoff(
7641            &b_seed,
7642            &BuildHandoff {
7643                task_id: "tote-42".into(),
7644                from_actor: robot_a.into(),
7645                to_actor: robot_b.into(),
7646                condition: Some("intact".into()),
7647                handoff_at: "2026-01-01T00:10:00Z".into(),
7648                valid_until: None,
7649            },
7650        )
7651        .unwrap();
7652        assert!(locate_condition_change(&[h1, steady]).is_none());
7653    }
7654
7655    // Robot-to-infrastructure bounded access (Phase 5.17) ------------------
7656
7657    // Cross-language interop: Rust authorizes the Python-signed grant and request
7658    // from the vector under the operator and robot keys, offline.
7659    #[test]
7660    fn authorizes_python_access_interop_vector() {
7661        let vector = load_vector();
7662        let grant = vector["access_grant_credential"].clone();
7663        let request = vector["access_request_credential"].clone();
7664        let operator_pub = jwk_pub(&vector["access_operator_key"]);
7665        let robot_pub = jwk_pub(&vector["access_robot_key"]);
7666
7667        let res = authorize_access(
7668            &grant,
7669            &request,
7670            &operator_pub,
7671            &robot_pub,
7672            Some("2026-01-01T00:05:00Z"),
7673        )
7674        .unwrap();
7675        assert!(
7676            res.ok,
7677            "the Python grant and request must authorize in Rust"
7678        );
7679        assert!(res.reasons.is_empty());
7680    }
7681
7682    // Fused-sensor provenance (Phase 5.18) ---------------------------------
7683
7684    // Cross-language interop: Rust reproduces the exact inputs digest and fused
7685    // output hash Python pinned, and verifies the Python-signed attestation.
7686    #[test]
7687    fn verifies_python_fused_interop_vector() {
7688        let vector = load_vector();
7689        let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
7690
7691        let inputs: Vec<String> = vector["fused_input_frame_hashes"]
7692            .as_array()
7693            .unwrap()
7694            .iter()
7695            .map(|v| v.as_str().unwrap().to_string())
7696            .collect();
7697        assert_eq!(
7698            fusion_inputs_digest(&inputs).unwrap(),
7699            vector["expected_fusion_inputs_digest"].as_str().unwrap()
7700        );
7701
7702        assert_eq!(
7703            hash_fused_output(b"world-model-0"),
7704            vector["expected_fused_output_hash"].as_str().unwrap()
7705        );
7706
7707        let cred = vector["fused_perception_attestation"].clone();
7708        let subject = verify_fused_attestation(&cred, &robot_pub, None)
7709            .unwrap()
7710            .expect("fused attestation verifies");
7711        assert_eq!(subject["fusionMethod"], "occupancy-grid-v1");
7712        assert_eq!(
7713            subject["inputsDigest"].as_str().unwrap(),
7714            vector["expected_fusion_inputs_digest"].as_str().unwrap()
7715        );
7716    }
7717
7718    // Wear and degradation attestation (Phase 5.19) ------------------------
7719
7720    // Cross-language interop: Rust verifies the Python-signed wear history and
7721    // reproduces the physical scope narrowed for the pinned wear level.
7722    #[test]
7723    fn verifies_python_wear_interop_vector() {
7724        let vector = load_vector();
7725        let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
7726
7727        let chain: Vec<Value> = vector["wear_chain"].as_array().unwrap().clone();
7728        let latest = verify_wear_chain(&chain, &robot_pub)
7729            .unwrap()
7730            .expect("wear chain verifies");
7731        assert_eq!(latest["wearLevel"].as_f64().unwrap(), 0.3);
7732
7733        let scope = vector["wear_input_scope"].clone();
7734        let level = vector["wear_attenuation_level"].as_f64().unwrap();
7735        let narrowed = attenuate_for_wear(&scope, level).unwrap();
7736        assert_eq!(narrowed, vector["expected_attenuated_scope"]);
7737        assert_eq!(narrowed["maxForceN"].as_f64().unwrap(), 60.0);
7738        assert_eq!(narrowed["maxSpeedMps"].as_f64().unwrap(), 1.125);
7739        assert_eq!(narrowed["maxSpeedNearHumansMps"].as_f64().unwrap(), 0.1875);
7740        assert!(attenuates(&scope, &narrowed));
7741    }
7742
7743    // Bystander-consent evidence (Phase 5.20) ------------------------------
7744
7745    // Cross-language interop: Rust reproduces the capture hash Python pinned,
7746    // verifies the bystander-signed token is bound to that capture, and verifies
7747    // the robot-signed evidence with the token and the bystander key.
7748    #[test]
7749    fn verifies_python_consent_interop_vector() {
7750        let vector = load_vector();
7751        let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
7752        let bystander_pub = jwk_pub(&vector["consent_bystander_key"]);
7753
7754        let capture = b"bystander-frame-0";
7755        let capture_hash = hash_capture(capture);
7756        assert_eq!(
7757            capture_hash,
7758            vector["expected_consent_capture_hash"].as_str().unwrap()
7759        );
7760
7761        let token = vector["consent_token_credential"].clone();
7762        let robot_did = token["credentialSubject"]["robotDid"].as_str().unwrap();
7763        let tok_subject = verify_consent_token(
7764            &token,
7765            &bystander_pub,
7766            &capture_hash,
7767            robot_did,
7768            Some("2026-01-01T00:05:00Z"),
7769        )
7770        .unwrap()
7771        .expect("consent token verifies bound to the capture");
7772        assert_eq!(tok_subject["captureHash"].as_str().unwrap(), capture_hash);
7773
7774        let evidence = vector["consent_evidence_credential"].clone();
7775        let bystander_did = token["issuer"].as_str().unwrap();
7776        let keys = [BystanderKey {
7777            did: bystander_did.to_string(),
7778            public_key: bystander_pub.clone(),
7779        }];
7780        let ev_subject = verify_consent_evidence(
7781            &evidence,
7782            &robot_pub,
7783            Some(capture),
7784            Some(&[token.clone()]),
7785            Some(&keys),
7786            Some("2026-01-01T00:05:00Z"),
7787        )
7788        .unwrap()
7789        .expect("consent evidence verifies with token and bystander key");
7790        assert_eq!(ev_subject["basis"].as_str().unwrap(), "explicit-consent");
7791    }
7792}
7793
7794#[cfg(test)]
7795mod robot_root_identity_tests {
7796    use super::*;
7797    use crate::keys::Ed25519KeyPair;
7798    use std::path::PathBuf;
7799
7800    const NOW: &str = "2026-07-01T00:00:00Z";
7801    const VALID_FROM: &str = "2026-01-01T00:00:00Z";
7802    const CREATED: &str = "2026-01-01T00:00:00Z";
7803    const VALID_SECONDS: i64 = 100 * 365 * 24 * 3600;
7804    // Matches the manufacturer seed recorded in the interop vector (0x04 x32).
7805    const MANUFACTURER_SEED: [u8; 32] = [0x04; 32];
7806    const FORGED_ID: &str = "urn:uuid:66666666-6666-6666-6666-666666666666";
7807
7808    fn load_vector() -> Value {
7809        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
7810            .join("../../test-vectors/root-of-trust/vector.json");
7811        let text = std::fs::read_to_string(&path)
7812            .unwrap_or_else(|e| panic!("read vector {}: {e}", path.display()));
7813        serde_json::from_str(&text).expect("vector is valid JSON")
7814    }
7815
7816    fn robot_pub(vector: &Value) -> Vec<u8> {
7817        let x = vector["robotPublicKey"]["x"].as_str().unwrap();
7818        URL_SAFE_NO_PAD.decode(x).unwrap()
7819    }
7820
7821    fn stray_multikey(seed: &[u8]) -> String {
7822        let kp = Ed25519KeyPair::from_seed_slice(seed).unwrap();
7823        multikey::encode_ed25519_public(&kp.public_key()).unwrap()
7824    }
7825
7826    fn stray_did(seed: &[u8]) -> String {
7827        Ed25519KeyPair::from_seed_slice(seed).unwrap().did_key()
7828    }
7829
7830    fn robot_attributes() -> Value {
7831        json!({ "make": "Acme Robotics", "model": "AR-7", "serial": "SN-000123" })
7832    }
7833
7834    // The committed Python-minted robot chain must verify in Rust: recognized
7835    // manufacturer provenance plus hardware-rooting.
7836    #[test]
7837    fn verifies_python_robot_identity_interop_vector() {
7838        let v = load_vector();
7839        let root = v["trustedRoot"].as_str().unwrap();
7840        let r = verify_robot_identity_chain(
7841            &v["robotAuthorityIdentity"],
7842            &v["robotRecognizedIssuer"],
7843            &v["robotHardwareCredential"],
7844            root,
7845            &robot_pub(&v),
7846            Some(&v["rootOfTrust"]),
7847            NOW,
7848            30,
7849        );
7850        assert!(r.ok, "robot chain must verify: {:?}", r.reason);
7851        assert!(r.hardware_rooted);
7852        assert_eq!(r.robot_did.as_deref(), v["expected"]["robotDid"].as_str());
7853        assert_eq!(
7854            r.issuer_did.as_deref(),
7855            v["expected"]["robotIssuerDid"].as_str()
7856        );
7857        assert_eq!(r.root_did.as_deref(), Some(root));
7858        assert_eq!(
7859            v["expected"]["verifyRobotIdentityChain"].as_bool(),
7860            Some(true)
7861        );
7862    }
7863
7864    // Adversarial: pinning a different root breaks the recognition anchor.
7865    #[test]
7866    fn wrong_pinned_root_rejected() {
7867        let v = load_vector();
7868        let other_root = stray_did(&[0x09; 32]);
7869        let r = verify_robot_identity_chain(
7870            &v["robotAuthorityIdentity"],
7871            &v["robotRecognizedIssuer"],
7872            &v["robotHardwareCredential"],
7873            &other_root,
7874            &robot_pub(&v),
7875            None,
7876            NOW,
7877            30,
7878        );
7879        assert!(!r.ok);
7880        assert_eq!(r.reason.as_deref(), Some("recognized_issuer_not_from_root"));
7881    }
7882
7883    // Adversarial: the manufacturer vouched a key that is not the robot's real
7884    // key. Provenance holds but the hardware key does not match.
7885    #[test]
7886    fn manufacturer_vouched_a_different_key() {
7887        let v = load_vector();
7888        let root = v["trustedRoot"].as_str().unwrap();
7889        let robot_did = v["expected"]["robotDid"].as_str().unwrap();
7890        let forged = build_robot_identity(
7891            &MANUFACTURER_SEED,
7892            robot_did,
7893            &stray_multikey(&[0x09; 32]),
7894            &robot_attributes(),
7895            VALID_SECONDS,
7896            VALID_FROM,
7897            CREATED,
7898            None,
7899            FORGED_ID,
7900        )
7901        .unwrap();
7902        let r = verify_robot_identity_chain(
7903            &forged,
7904            &v["robotRecognizedIssuer"],
7905            &v["robotHardwareCredential"],
7906            root,
7907            &robot_pub(&v),
7908            Some(&v["rootOfTrust"]),
7909            NOW,
7910            30,
7911        );
7912        assert!(!r.ok);
7913        assert_eq!(r.reason.as_deref(), Some("hardware_key_mismatch"));
7914    }
7915
7916    // Adversarial: an impostor key is presented for the hardware credential, so
7917    // the secure-element attestation no longer verifies.
7918    #[test]
7919    fn impostor_key_fails_hardware_root() {
7920        let v = load_vector();
7921        let root = v["trustedRoot"].as_str().unwrap();
7922        let impostor = Ed25519KeyPair::from_seed(&[0x09; 32]).public_key();
7923        let r = verify_robot_identity_chain(
7924            &v["robotAuthorityIdentity"],
7925            &v["robotRecognizedIssuer"],
7926            &v["robotHardwareCredential"],
7927            root,
7928            &impostor,
7929            Some(&v["rootOfTrust"]),
7930            NOW,
7931            30,
7932        );
7933        assert!(!r.ok);
7934        assert_eq!(r.reason.as_deref(), Some("hardware_root_invalid"));
7935    }
7936}