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::robotics_verify::{self as rv, Keys, VerifyOptions, Window};
26use crate::root_of_trust::{self, ACTION_ISSUE_ROBOT_IDENTITY};
27use crate::{hybrid, jcs, multikey};
28
29use aes_gcm::aead::{Aead, Payload};
30use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
31use base64::engine::general_purpose::URL_SAFE_NO_PAD;
32use base64::Engine;
33use sha2::{Digest, Sha256};
34use std::collections::HashSet;
35
36pub const VC_CONTEXT_V2: &str = "https://www.w3.org/ns/credentials/v2";
37pub const VOUCH_CONTEXT_V1: &str = "https://vouch-protocol.com/contexts/v1";
38pub const ROBOT_IDENTITY_TYPE: &str = "RobotIdentityCredential";
39
40/// Multibase ('u') base64url-no-pad encoding, matching the Python/TS/Go `mb64`.
41pub(crate) fn mb64(bytes: &[u8]) -> String {
42    format!("u{}", URL_SAFE_NO_PAD.encode(bytes))
43}
44
45/// Decode a multibase ('u') base64url-no-pad string.
46pub(crate) fn unmb64(s: &str) -> Result<Vec<u8>> {
47    let body = s
48        .strip_prefix('u')
49        .ok_or_else(|| CoreError::Json("expected multibase 'u' prefix".into()))?;
50    URL_SAFE_NO_PAD
51        .decode(body)
52        .map_err(|e| CoreError::Json(format!("bad base64url: {e}")))
53}
54
55/// The canonical bytes a hardware root signs to bind a robot's identity key to
56/// its hardware: JCS of `{"key": robot_key_multibase, "robotDid": robot_did}`.
57pub fn robot_identity_binding(robot_did: &str, robot_key_multibase: &str) -> Vec<u8> {
58    jcs::canonicalize(&json!({
59        "key": robot_key_multibase,
60        "robotDid": robot_did,
61    }))
62}
63
64/// Parameters for [`mint_robot_identity`]. Timestamps are ISO-8601 strings the
65/// caller supplies. `attestation` is the hardware root's signature over
66/// [`robot_identity_binding`]; `root_public_multibase` is that root's public key.
67#[derive(Debug, Clone)]
68pub struct MintRobotIdentity {
69    pub robot_did: String,
70    pub make: String,
71    pub model: String,
72    pub serial: String,
73    pub owner: Option<String>,
74    pub root_kind: String,
75    pub root_public_multibase: String,
76    pub attestation: Vec<u8>,
77    /// Optional explicit lifecycle array; defaults to a single "commissioned" entry.
78    pub lifecycle: Option<Value>,
79    pub valid_from: String,
80    pub valid_until: Option<String>,
81}
82
83/// Mint a hardware-attested `RobotIdentityCredential`, signed by the robot's own
84/// Ed25519 seed. The hardware-root attestation is embedded as
85/// `credentialSubject.hardwareRoot.attestation`.
86pub fn mint_robot_identity(robot_seed: &[u8], params: &MintRobotIdentity) -> Result<Value> {
87    let lifecycle = params
88        .lifecycle
89        .clone()
90        .unwrap_or_else(|| json!([{ "event": "commissioned", "timestamp": params.valid_from }]));
91
92    let mut subject = Map::new();
93    subject.insert("id".into(), json!(params.robot_did));
94    subject.insert("make".into(), json!(params.make));
95    subject.insert("model".into(), json!(params.model));
96    subject.insert("serial".into(), json!(params.serial));
97    subject.insert(
98        "hardwareRoot".into(),
99        json!({
100            "kind": params.root_kind,
101            "publicKeyMultibase": params.root_public_multibase,
102            "attestation": mb64(&params.attestation),
103        }),
104    );
105    subject.insert("lifecycle".into(), lifecycle);
106    if let Some(owner) = &params.owner {
107        subject.insert("owner".into(), json!(owner));
108    }
109
110    let mut cred = Map::new();
111    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
112    cred.insert(
113        "type".into(),
114        json!(["VerifiableCredential", ROBOT_IDENTITY_TYPE]),
115    );
116    cred.insert("issuer".into(), json!(params.robot_did));
117    cred.insert("validFrom".into(), json!(params.valid_from));
118    if let Some(vu) = &params.valid_until {
119        cred.insert("validUntil".into(), json!(vu));
120    }
121    cred.insert("credentialSubject".into(), Value::Object(subject));
122
123    let opts = BuildProofOptions::new(
124        format!("{}#key-1", params.robot_did),
125        params.valid_from.clone(),
126    );
127    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
128}
129
130/// Verify a credential through the shared issuer-binding helper
131/// ([`crate::robotics_verify`]) at `now_iso`. Errors only on a malformed
132/// `now_iso`; any problem with the credential itself is `Ok(None)`.
133pub(crate) fn bound(
134    credential: &Value,
135    keys: Keys<'_>,
136    expected_type: &str,
137    now_iso: &str,
138    window: Window,
139) -> Result<Option<rv::Verified>> {
140    let now = rv::require_now(now_iso)?;
141    Ok(rv::verify_robotics_credential(
142        credential,
143        keys,
144        Some(expected_type),
145        now,
146        VerifyOptions::window(window),
147    )
148    .ok())
149}
150
151/// True when a self-attestation names its issuer as `credentialSubject.id`.
152pub(crate) fn issuer_is_subject(v: &rv::Verified) -> bool {
153    v.subject.get("id").and_then(|x| x.as_str()) == Some(v.issuer.as_str())
154}
155
156/// Verify a `RobotIdentityCredential`: the credential proof bound to the robot
157/// as issuer (which must also be `credentialSubject.id`), the validity window
158/// at `now_iso` (validFrom required), AND the hardware-root attestation binding
159/// the robot key to the hardware. `robot_keys` is a `{robot_did: key}` source
160/// (or, for a did:key robot, the bare key). When `hardware_root_key` is given,
161/// the credential's hardware-root key must be exactly that key. Returns the
162/// credentialSubject on success, `None` if invalid.
163pub fn verify_robot_identity(
164    credential: &Value,
165    robot_keys: Keys<'_>,
166    hardware_root_key: Option<&[u8]>,
167    now_iso: &str,
168) -> Result<Option<Value>> {
169    let v = match bound(
170        credential,
171        robot_keys,
172        ROBOT_IDENTITY_TYPE,
173        now_iso,
174        Window::FromRequired,
175    )? {
176        Some(v) if issuer_is_subject(&v) => v,
177        _ => return Ok(None),
178    };
179    let robot_key =
180        match rv::resolve_issuer_key(&v.issuer, rv::pin_if_keyless(robot_keys, Some(&v.issuer))) {
181            Ok(k) => k,
182            Err(_) => return Ok(None),
183        };
184    let subject = match v.subject.as_object() {
185        Some(s) => s,
186        None => return Ok(None),
187    };
188    let hw = match subject.get("hardwareRoot").and_then(|h| h.as_object()) {
189        Some(h) => h,
190        None => return Ok(None),
191    };
192    let hw_mb = match hw.get("publicKeyMultibase").and_then(|v| v.as_str()) {
193        Some(s) => s,
194        None => return Ok(None),
195    };
196    let attestation_mb = match hw.get("attestation").and_then(|v| v.as_str()) {
197        Some(s) => s,
198        None => return Ok(None),
199    };
200
201    let decoded = match multikey::decode(hw_mb) {
202        Ok(d) if d.algorithm == "Ed25519" && d.raw_key.len() == 32 => d,
203        _ => return Ok(None),
204    };
205    if let Some(pin) = hardware_root_key {
206        if pin != decoded.raw_key.as_slice() {
207            return Ok(None);
208        }
209    }
210    let attestation = match unmb64(attestation_mb) {
211        Ok(a) => a,
212        Err(_) => return Ok(None),
213    };
214
215    let robot_key_mb = multikey::encode_ed25519_public(&robot_key)?;
216    let binding = robot_identity_binding(&v.issuer, &robot_key_mb);
217
218    if !matches!(
219        keys::verify(&decoded.raw_key, &binding, &attestation),
220        Ok(true)
221    ) {
222        return Ok(None);
223    }
224    Ok(Some(v.subject))
225}
226
227// ---------------------------------------------------------------------------
228// Root of Trust for robot identity (Phase 5.1, authority binding)
229// ---------------------------------------------------------------------------
230//
231// Byte-exact port of the Python reference `vouch/robotics/root_identity.py`.
232//
233// The Root of Trust for Machine Identity lets one pinned Vouch root recognize
234// issuers, and a recognized issuer bind a subject DID to attributes, verified
235// offline against that one pinned root. This extends it to robots. A recognized
236// manufacturer (an issuer the root granted the `issueRobotIdentity` action)
237// issues an identity that binds a robot's DID and its hardware-rooted key to
238// attributes such as make, model, serial, and owner. The robot separately holds
239// a hardware-attested `RobotIdentityCredential` proving its key is bound to a
240// secure element.
241//
242// [`verify_robot_identity_chain`] closes the loop: from one pinned root a
243// verifier confirms both that the robot is a legitimate robot from a recognized
244// manufacturer (the authority chain via [`root_of_trust::verify_identity_chain`])
245// and that the key the manufacturer vouched for is genuinely hardware-rooted (the
246// secure-element attestation via [`verify_robot_identity`]), and that the two
247// name the same robot and the same key. It follows the anchor-once model and the
248// reason-code style of the underlying root_of_trust.
249
250/// Outcome of [`verify_robot_identity_chain`].
251///
252/// `ok` is true only if the authority chain verified against the pinned root AND
253/// the robot's own credential names the same robot and the vouched key.
254/// `hardware_rooted` is true only when the manufacturer also bound the
255/// hardware-root key and the attestation was made by exactly that key. On failure `reason`
256/// carries a structured code matching the Python reference exactly.
257#[derive(Debug, Clone, PartialEq, Eq)]
258pub struct RobotIdentityChainResult {
259    pub ok: bool,
260    pub reason: Option<String>,
261    pub robot_did: Option<String>,
262    pub issuer_did: Option<String>,
263    pub root_did: Option<String>,
264    pub attributes: Option<Value>,
265    pub hardware_rooted: bool,
266}
267
268impl RobotIdentityChainResult {
269    /// A failure result carrying the reason code and the pinned root that was in
270    /// force when the check failed.
271    fn fail(reason: impl Into<String>, root_did: &str) -> Self {
272        Self {
273            ok: false,
274            reason: Some(reason.into()),
275            robot_did: None,
276            issuer_did: None,
277            root_did: Some(root_did.to_string()),
278            attributes: None,
279            hardware_rooted: false,
280        }
281    }
282}
283
284/// Issue an authority robot identity: a recognized manufacturer binds `robot_did`,
285/// its hardware-rooted key (`hardware_key_multibase`, the robot's Ed25519 key as a
286/// multikey), and identity `attributes` (make, model, serial, owner). The
287/// manufacturer (derived from `issuer_seed`) must be a recognized issuer for the
288/// `issueRobotIdentity` action.
289///
290/// The credential is an `AgentIdentityCredential` so the shared identity-chain
291/// verification applies, with a `kind` of "robot" and the hardware key carried in
292/// the bound identity attributes.
293///
294/// `hardware_root_key_multibase` is the public key of the robot's secure element
295/// as the manufacturer recorded it. Bound as `hardwareRootKey`, it lets a
296/// verifier tell the robot's hardware attestation comes from that exact
297/// hardware; without it the chain verifies but is never hardware-rooted.
298#[allow(clippy::too_many_arguments)]
299pub fn build_robot_identity(
300    issuer_seed: &[u8],
301    robot_did: &str,
302    hardware_key_multibase: &str,
303    attributes: &Value,
304    valid_seconds: i64,
305    valid_from: &str,
306    created: &str,
307    credential_status: Option<Value>,
308    credential_id: &str,
309    hardware_root_key_multibase: Option<&str>,
310) -> Result<Value> {
311    if robot_did.is_empty() {
312        return Err(CoreError::Json("robot_did is required".into()));
313    }
314    if hardware_key_multibase.is_empty() {
315        return Err(CoreError::Json("hardware_key_multibase is required".into()));
316    }
317    let bound = match attributes.as_object() {
318        Some(o) if !o.is_empty() => {
319            let mut m = o.clone();
320            m.insert("kind".into(), json!("robot"));
321            m.insert("hardwareKey".into(), json!(hardware_key_multibase));
322            if let Some(root) = hardware_root_key_multibase {
323                if root.is_empty() {
324                    return Err(CoreError::Json(
325                        "hardware_root_key_multibase must be a multikey string".into(),
326                    ));
327                }
328                m.insert("hardwareRootKey".into(), json!(root));
329            }
330            Value::Object(m)
331        }
332        _ => {
333            return Err(CoreError::Json(
334                "attributes must be a non-empty object".into(),
335            ))
336        }
337    };
338    root_of_trust::build_agent_identity(
339        issuer_seed,
340        robot_did,
341        &bound,
342        valid_seconds,
343        valid_from,
344        created,
345        credential_status,
346        credential_id,
347    )
348}
349
350/// Verify a robot's identity against a single pinned Vouch root, confirming both
351/// provenance and hardware-rooting.
352///
353/// From `trusted_root`, the pinned root DID:
354///
355///   1. The authority chain: the recognized manufacturer must be recognized by
356///      the pinned root for the `issueRobotIdentity` action, and the authority
357///      identity must be signed by that manufacturer (shared identity-chain verify).
358///   2. The vouched key: the authority identity must carry a hardware key.
359///   3. The robot credential: the robot's own `RobotIdentityCredential` must
360///      verify under the key the manufacturer vouched for, name the same robot,
361///      and carry a valid secure-element attestation.
362///   4. The hardware root: when the manufacturer bound a `hardwareRootKey`, the
363///      attestation's hardware key must be exactly that key (else
364///      `hardware_root_mismatch`), and only then is `hardware_rooted` true.
365///
366/// `robot_public_key` is the robot's raw 32-byte Ed25519 public key. `now_iso` is
367/// the current instant used for the temporal window; `clock_skew_seconds` is the
368/// allowed drift. Reason codes on failure match the Python reference exactly.
369#[allow(clippy::too_many_arguments)]
370pub fn verify_robot_identity_chain(
371    authority_identity: &Value,
372    recognized_issuer_credential: &Value,
373    robot_hardware_credential: &Value,
374    trusted_root: &str,
375    robot_public_key: &[u8],
376    root_credential: Option<&Value>,
377    now_iso: &str,
378    clock_skew_seconds: i64,
379) -> RobotIdentityChainResult {
380    let chain = root_of_trust::verify_identity_chain(
381        authority_identity,
382        recognized_issuer_credential,
383        trusted_root,
384        root_credential,
385        None,
386        ACTION_ISSUE_ROBOT_IDENTITY,
387        now_iso,
388        clock_skew_seconds,
389    );
390    if !chain.ok {
391        return RobotIdentityChainResult {
392            ok: false,
393            reason: chain.reason,
394            robot_did: None,
395            issuer_did: None,
396            root_did: Some(trusted_root.to_string()),
397            attributes: None,
398            hardware_rooted: false,
399        };
400    }
401
402    let attributes = match &chain.attributes {
403        Some(v @ Value::Object(_)) => v.clone(),
404        _ => json!({}),
405    };
406    let hardware_key = match attributes.get("hardwareKey").and_then(|v| v.as_str()) {
407        Some(s) if !s.is_empty() => s.to_string(),
408        _ => return RobotIdentityChainResult::fail("identity_no_hardware_key", trusted_root),
409    };
410
411    // The robot's own credential must verify under the supplied key, accepted
412    // for whatever DID the credential names; the next two checks pin that DID
413    // to the manufacturer's subject and the key to the vouched key.
414    let any_did = |_: &str| Some(robot_public_key.to_vec());
415    let hw_subject = match verify_robot_identity(
416        robot_hardware_credential,
417        Keys::Resolver(&any_did),
418        None,
419        now_iso,
420    ) {
421        Ok(Some(s)) => s,
422        _ => return RobotIdentityChainResult::fail("hardware_root_invalid", trusted_root),
423    };
424    if hw_subject.get("id").and_then(|v| v.as_str()) != chain.agent_did.as_deref() {
425        return RobotIdentityChainResult::fail("hardware_subject_mismatch", trusted_root);
426    }
427
428    let robot_key_mb = match multikey::encode_ed25519_public(robot_public_key) {
429        Ok(mb) => mb,
430        Err(_) => return RobotIdentityChainResult::fail("hardware_key_unresolvable", trusted_root),
431    };
432    if robot_key_mb != hardware_key {
433        return RobotIdentityChainResult::fail("hardware_key_mismatch", trusted_root);
434    }
435
436    // Hardware-rooted only when the manufacturer bound the hardware-root key and
437    // the robot's attestation was made by exactly that key.
438    let mut hardware_rooted = false;
439    if let Some(pinned) = attributes.get("hardwareRootKey") {
440        let claimed = hw_subject
441            .get("hardwareRoot")
442            .and_then(|h| h.get("publicKeyMultibase"))
443            .and_then(|v| v.as_str());
444        if pinned.as_str().is_none() || claimed != pinned.as_str() {
445            return RobotIdentityChainResult::fail("hardware_root_mismatch", trusted_root);
446        }
447        hardware_rooted = true;
448    }
449
450    RobotIdentityChainResult {
451        ok: true,
452        reason: None,
453        robot_did: chain.agent_did,
454        issuer_did: chain.issuer_did,
455        root_did: Some(trusted_root.to_string()),
456        attributes: Some(attributes),
457        hardware_rooted,
458    }
459}
460
461// ---------------------------------------------------------------------------
462// Model and config provenance (Phase 5.2)
463// ---------------------------------------------------------------------------
464
465pub const MODEL_PROVENANCE_TYPE: &str = "ModelProvenanceAttestation";
466
467/// Multibase SHA-256 of the JCS-canonical config object. Python, TypeScript, Go,
468/// and Rust all canonicalize identically, so the digest is the same byte string
469/// in every language.
470pub fn config_hash(config: &Value) -> String {
471    let digest = Sha256::digest(jcs::canonicalize(config));
472    mb64(&digest)
473}
474
475/// Parameters for [`build_provenance_attestation`]. The issuer is the signer (the
476/// robot itself or an authority); `robot_did` names the robot the attestation is
477/// about.
478#[derive(Debug, Clone)]
479pub struct BuildProvenance {
480    pub issuer_did: String,
481    pub robot_did: String,
482    pub model_name: String,
483    pub weights_hash: String,
484    pub safety_policy: String,
485    pub config: Option<Value>,
486    pub version: Option<String>,
487    pub supersedes: Option<String>,
488    pub valid_from: String,
489    pub valid_until: Option<String>,
490}
491
492/// Build a signed `ModelProvenanceAttestation` for the software on a robot.
493pub fn build_provenance_attestation(signer_seed: &[u8], params: &BuildProvenance) -> Result<Value> {
494    let mut vla = Map::new();
495    vla.insert("modelName".into(), json!(params.model_name));
496    vla.insert("weightsHash".into(), json!(params.weights_hash));
497    vla.insert("safetyPolicy".into(), json!(params.safety_policy));
498    if let Some(v) = &params.version {
499        vla.insert("version".into(), json!(v));
500    }
501    if let Some(cfg) = &params.config {
502        vla.insert("configHash".into(), json!(config_hash(cfg)));
503    }
504
505    let mut subject = Map::new();
506    subject.insert("id".into(), json!(params.robot_did));
507    subject.insert("vla".into(), Value::Object(vla));
508    if let Some(s) = &params.supersedes {
509        subject.insert("supersedes".into(), json!(s));
510    }
511
512    let mut cred = Map::new();
513    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
514    cred.insert(
515        "type".into(),
516        json!(["VerifiableCredential", MODEL_PROVENANCE_TYPE]),
517    );
518    cred.insert("issuer".into(), json!(params.issuer_did));
519    cred.insert("validFrom".into(), json!(params.valid_from));
520    if let Some(vu) = &params.valid_until {
521        cred.insert("validUntil".into(), json!(vu));
522    }
523    cred.insert("credentialSubject".into(), Value::Object(subject));
524
525    let opts = BuildProofOptions::new(
526        format!("{}#key-1", params.issuer_did),
527        params.valid_from.clone(),
528    );
529    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
530}
531
532/// Verify a `ModelProvenanceAttestation`. When `config` is supplied, also check
533/// the recorded configHash reproduces. Returns the subject on success, `None`
534/// otherwise.
535pub fn verify_provenance_attestation(
536    attestation: &Value,
537    keys: Keys<'_>,
538    config: Option<&Value>,
539    now_iso: &str,
540) -> Result<Option<Value>> {
541    let v = match bound(
542        attestation,
543        keys,
544        MODEL_PROVENANCE_TYPE,
545        now_iso,
546        Window::FromRequired,
547    )? {
548        Some(v) => v,
549        None => return Ok(None),
550    };
551    if let Some(cfg) = config {
552        let want = config_hash(cfg);
553        let got = v
554            .subject
555            .get("vla")
556            .and_then(|v| v.as_object())
557            .and_then(|v| v.get("configHash"))
558            .and_then(|v| v.as_str());
559        if got != Some(want.as_str()) {
560            return Ok(None);
561        }
562    }
563    Ok(Some(v.subject))
564}
565
566/// The reference a superseding attestation uses: multibase SHA-256 of the JCS
567/// form of the whole signed attestation (proof included).
568pub fn provenance_attestation_id(attestation: &Value) -> String {
569    mb64(&Sha256::digest(jcs::canonicalize(attestation)))
570}
571
572/// Verify an ordered OTA history of provenance attestations for `robot_did`:
573/// every attestation verifies and is about `robot_did`; each one after the
574/// first names the previous by [`provenance_attestation_id`] as `supersedes`
575/// and is dated no earlier. Each earlier attestation must still have been valid
576/// when the next was made, and the last at `now_iso`. Returns the latest
577/// subject on success.
578pub fn verify_provenance_chain(
579    attestations: &[Value],
580    keys: Keys<'_>,
581    robot_did: &str,
582    now_iso: &str,
583) -> Result<Option<Value>> {
584    rv::require_now(now_iso)?;
585    if attestations.is_empty() || robot_did.is_empty() {
586        return Ok(None);
587    }
588    let mut prev: Option<&Value> = None;
589    let mut latest = None;
590    for (i, att) in attestations.iter().enumerate() {
591        let at: String = match attestations.get(i + 1) {
592            Some(next) => match next.get("validFrom").and_then(|v| v.as_str()) {
593                Some(t) if rv::time_ns(next.get("validFrom")).is_some() => t.to_string(),
594                _ => return Ok(None),
595            },
596            None => now_iso.to_string(),
597        };
598        let subject = match verify_provenance_attestation(att, keys, None, &at)? {
599            Some(s) if s.get("id").and_then(|v| v.as_str()) == Some(robot_did) => s,
600            _ => return Ok(None),
601        };
602        if let Some(p) = prev {
603            if subject.get("supersedes").and_then(|v| v.as_str())
604                != Some(provenance_attestation_id(p).as_str())
605            {
606                return Ok(None);
607            }
608            if rv::time_ns(att.get("validFrom")) < rv::time_ns(p.get("validFrom")) {
609                return Ok(None);
610            }
611        }
612        prev = Some(att);
613        latest = Some(subject);
614    }
615    Ok(latest)
616}
617
618// ---------------------------------------------------------------------------
619// Physical capability scope (Phase 5.3)
620// ---------------------------------------------------------------------------
621
622pub const PHYSICAL_SCOPE_TYPE: &str = "PhysicalCapabilityScope";
623
624/// An allowed time-of-day window, "HH:MM" start and end.
625#[derive(Debug, Clone)]
626pub struct ShiftWindow {
627    pub start: String,
628    pub end: String,
629}
630
631/// A proposed actuation to check against a scope. `None` numerics mean "not
632/// specified" (a meaningful zero is still `Some(0.0)`).
633#[derive(Debug, Clone, Default)]
634pub struct PhysicalAction {
635    pub force_n: Option<f64>,
636    pub speed_mps: Option<f64>,
637    pub near_humans: bool,
638    pub zone: Option<String>,
639    pub time_hm: Option<String>,
640}
641
642/// The outcome of [`check_physical_action`].
643#[derive(Debug, Clone)]
644pub struct CheckResult {
645    pub ok: bool,
646    pub reasons: Vec<String>,
647}
648
649/// Parameters for [`build_physical_scope_credential`]. The issuer is the signer
650/// (a fleet authority); `subject_did` is the robot the scope is granted to.
651#[derive(Debug, Clone, Default)]
652pub struct BuildPhysicalScope {
653    pub issuer_did: String,
654    pub subject_did: String,
655    pub max_force_n: Option<f64>,
656    pub max_speed_mps: Option<f64>,
657    pub max_speed_near_humans_mps: Option<f64>,
658    pub allowed_zones: Option<Vec<String>>,
659    pub shift_windows: Option<Vec<ShiftWindow>>,
660    pub valid_from: String,
661    pub valid_until: Option<String>,
662}
663
664/// Build a signed `PhysicalCapabilityScope` credential.
665pub fn build_physical_scope_credential(
666    signer_seed: &[u8],
667    params: &BuildPhysicalScope,
668) -> Result<Value> {
669    let mut scope = Map::new();
670    if let Some(v) = params.max_force_n {
671        scope.insert("maxForceN".into(), json!(v));
672    }
673    if let Some(v) = params.max_speed_mps {
674        scope.insert("maxSpeedMps".into(), json!(v));
675    }
676    if let Some(v) = params.max_speed_near_humans_mps {
677        scope.insert("maxSpeedNearHumansMps".into(), json!(v));
678    }
679    if let Some(zones) = &params.allowed_zones {
680        scope.insert("allowedZones".into(), json!(zones));
681    }
682    if let Some(ws) = &params.shift_windows {
683        let arr: Vec<Value> = ws
684            .iter()
685            .map(|w| json!({"start": w.start, "end": w.end}))
686            .collect();
687        scope.insert("shiftWindows".into(), Value::Array(arr));
688    }
689
690    let mut subject = Map::new();
691    subject.insert("id".into(), json!(params.subject_did));
692    subject.insert("physicalScope".into(), Value::Object(scope));
693
694    let mut cred = Map::new();
695    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
696    cred.insert(
697        "type".into(),
698        json!(["VerifiableCredential", PHYSICAL_SCOPE_TYPE]),
699    );
700    cred.insert("issuer".into(), json!(params.issuer_did));
701    cred.insert("validFrom".into(), json!(params.valid_from));
702    if let Some(vu) = &params.valid_until {
703        cred.insert("validUntil".into(), json!(vu));
704    }
705    cred.insert("credentialSubject".into(), Value::Object(subject));
706
707    let opts = BuildProofOptions::new(
708        format!("{}#key-1", params.issuer_did),
709        params.valid_from.clone(),
710    );
711    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
712}
713
714/// The numeric caps a physical scope may set.
715pub const CAP_KEYS: [&str; 3] = ["maxForceN", "maxSpeedMps", "maxSpeedNearHumansMps"];
716/// Every dimension a physical scope may set.
717pub const SCOPE_KEYS: [&str; 5] = [
718    "maxForceN",
719    "maxSpeedMps",
720    "maxSpeedNearHumansMps",
721    "allowedZones",
722    "shiftWindows",
723];
724
725/// Minutes since midnight for a strict `HH:MM` string (00:00-23:59), else `None`.
726pub fn parse_hm(value: &str) -> Option<u32> {
727    let b = value.as_bytes();
728    if b.len() != 5
729        || b[2] != b':'
730        || !b
731            .iter()
732            .enumerate()
733            .all(|(i, c)| i == 2 || c.is_ascii_digit())
734    {
735        return None;
736    }
737    let h = u32::from(b[0] - b'0') * 10 + u32::from(b[1] - b'0');
738    let m = u32::from(b[3] - b'0') * 10 + u32::from(b[4] - b'0');
739    if h > 23 || m > 59 {
740        return None;
741    }
742    Some(h * 60 + m)
743}
744
745/// A usable physical cap: a finite, non-negative JSON number (never a boolean).
746pub fn valid_cap(v: &Value) -> bool {
747    v.is_number() && v.as_f64().is_some_and(|n| n.is_finite() && n >= 0.0)
748}
749
750/// `(start, end)` minutes of a `{"start", "end"}` window with start <= end.
751pub fn parse_window(w: &Value) -> Option<(u32, u32)> {
752    let o = w.as_object()?;
753    let start = parse_hm(o.get("start")?.as_str()?)?;
754    let end = parse_hm(o.get("end")?.as_str()?)?;
755    (start <= end).then_some((start, end))
756}
757
758/// Every window of a list, or `None` if the list or any window is malformed.
759pub fn parse_windows(v: &Value) -> Option<Vec<(u32, u32)>> {
760    v.as_array()?.iter().map(parse_window).collect()
761}
762
763/// The zone ids of a list of strings, or `None` if malformed.
764pub fn parse_zones(v: &Value) -> Option<Vec<&str>> {
765    v.as_array()?.iter().map(|z| z.as_str()).collect()
766}
767
768/// Reasons the scope itself cannot be read; empty when every set dimension is
769/// well-formed.
770pub fn scope_problems(scope: &Value) -> Vec<String> {
771    let o = match scope.as_object() {
772        Some(o) => o,
773        None => return vec!["scope_malformed: not an object".into()],
774    };
775    let mut problems = Vec::new();
776    for key in CAP_KEYS {
777        if o.get(key).is_some_and(|v| !valid_cap(v)) {
778            problems.push(format!(
779                "scope_malformed: {key} is not a finite non-negative number"
780            ));
781        }
782    }
783    if o.get("allowedZones")
784        .is_some_and(|v| parse_zones(v).is_none())
785    {
786        problems.push("scope_malformed: allowedZones is not a list of strings".into());
787    }
788    if o.get("shiftWindows")
789        .is_some_and(|v| parse_windows(v).is_none())
790    {
791        problems.push("scope_malformed: shiftWindows is not a list of HH:MM windows".into());
792    }
793    problems
794}
795
796/// Verify a `PhysicalCapabilityScope` credential and return its physicalScope:
797/// the proof bound to the issuer, the window at `now_iso` (validFrom
798/// required), a well-formed scope with no unknown dimension (a misspelt cap
799/// would otherwise limit nothing), and (when given) the subject `subject_did`.
800pub fn verify_physical_scope_credential(
801    credential: &Value,
802    keys: Keys<'_>,
803    subject_did: Option<&str>,
804    now_iso: &str,
805) -> Result<Option<Value>> {
806    let v = match bound(
807        credential,
808        keys,
809        PHYSICAL_SCOPE_TYPE,
810        now_iso,
811        Window::FromRequired,
812    )? {
813        Some(v) => v,
814        None => return Ok(None),
815    };
816    if subject_did.is_some_and(|d| v.subject.get("id").and_then(|x| x.as_str()) != Some(d)) {
817        return Ok(None);
818    }
819    let scope = match v.subject.get("physicalScope") {
820        Some(sc @ Value::Object(o)) if o.keys().all(|k| SCOPE_KEYS.contains(&k.as_str())) => sc,
821        _ => return Ok(None),
822    };
823    if !scope_problems(scope).is_empty() {
824        return Ok(None);
825    }
826    Ok(Some(scope.clone()))
827}
828
829/// Check a proposed physical action against a physical scope object, returning
830/// ok plus a reason for each violation. A scope dimension that is set but
831/// malformed, and an action value that is not a finite non-negative number or
832/// not a strict `HH:MM`, are violations. An empty zone or shift-window list
833/// allows nothing. Near humans, the speed cap is the lower of `maxSpeedMps`
834/// and `maxSpeedNearHumansMps`.
835pub fn check_physical_action(scope: &Value, action: &PhysicalAction) -> CheckResult {
836    let mut reasons = scope_problems(scope);
837    if !reasons.is_empty() {
838        return CheckResult { ok: false, reasons };
839    }
840    let o = scope
841        .as_object()
842        .expect("scope_problems checked it is an object");
843    for (name, value) in [("force_n", action.force_n), ("speed_mps", action.speed_mps)] {
844        if let Some(v) = value {
845            if !v.is_finite() || v < 0.0 {
846                reasons.push(format!(
847                    "action_malformed: {name} is not a finite non-negative number"
848                ));
849            }
850        }
851    }
852    if !reasons.is_empty() {
853        return CheckResult { ok: false, reasons };
854    }
855    let cap = |k: &str| o.get(k).and_then(|v| v.as_f64());
856
857    if let (Some(force), Some(c)) = (action.force_n, cap("maxForceN")) {
858        if force > c {
859            reasons.push(format!("force_exceeded: {force}N > {c}N"));
860        }
861    }
862    if let Some(speed) = action.speed_mps {
863        let mut c = cap("maxSpeedMps");
864        if action.near_humans {
865            if let Some(near) = cap("maxSpeedNearHumansMps") {
866                c = Some(c.map_or(near, |g| g.min(near)));
867            }
868        }
869        if let Some(c) = c {
870            if speed > c {
871                let label = if action.near_humans {
872                    "near_humans "
873                } else {
874                    ""
875                };
876                reasons.push(format!("{label}speed_exceeded: {speed} m/s > {c} m/s"));
877            }
878        }
879    }
880    if let (Some(zone), Some(zones)) = (&action.zone, o.get("allowedZones").and_then(parse_zones)) {
881        if !zones.contains(&zone.as_str()) {
882            reasons.push(format!("zone_not_allowed: {zone}"));
883        }
884    }
885    if let (Some(hm), Some(ws)) = (&action.time_hm, o.get("shiftWindows")) {
886        match parse_hm(hm) {
887            None => reasons.push(format!("action_malformed: time_hm {hm:?} is not HH:MM")),
888            Some(t) => {
889                let windows = parse_windows(ws).unwrap_or_default();
890                if !windows.iter().any(|(s, e)| *s <= t && t <= *e) {
891                    reasons.push(format!("outside_shift_window: {hm}"));
892                }
893            }
894        }
895    }
896    CheckResult {
897        ok: reasons.is_empty(),
898        reasons,
899    }
900}
901
902/// Report whether `child` is a valid attenuation of `parent`: never broader on
903/// any physical dimension. Both scopes must be well-formed; for every dimension
904/// the parent sets, the child must set it too and be no broader (a cap no
905/// higher, a NON-EMPTY subset of zones, a NON-EMPTY list of windows each inside
906/// some parent window). Leaving a dimension out, or an empty list, is never an
907/// attenuation of a parent that limits it.
908pub fn attenuates(parent: &Value, child: &Value) -> bool {
909    if !scope_problems(parent).is_empty() || !scope_problems(child).is_empty() {
910        return false;
911    }
912    let (p, c) = match (parent.as_object(), child.as_object()) {
913        (Some(p), Some(c)) => (p, c),
914        _ => return false,
915    };
916    for key in CAP_KEYS {
917        if let Some(pv) = p.get(key).and_then(|v| v.as_f64()) {
918            match c.get(key).and_then(|v| v.as_f64()) {
919                Some(cv) if cv <= pv => {}
920                _ => return false,
921            }
922        }
923    }
924    if let Some(pz) = p.get("allowedZones").and_then(parse_zones) {
925        match c.get("allowedZones").and_then(parse_zones) {
926            Some(cz) if !cz.is_empty() && cz.iter().all(|z| pz.contains(z)) => {}
927            _ => return false,
928        }
929    }
930    if let Some(pw) = p.get("shiftWindows").and_then(parse_windows) {
931        match c.get("shiftWindows").and_then(parse_windows) {
932            Some(cw) if !cw.is_empty() => {
933                for (cs, ce) in cw {
934                    if !pw.iter().any(|(ps, pe)| *ps <= cs && ce <= *pe) {
935                        return false;
936                    }
937                }
938            }
939            _ => return false,
940        }
941    }
942    true
943}
944
945// ---------------------------------------------------------------------------
946// Robot-to-robot trust handshake (Phase 5.4)
947// ---------------------------------------------------------------------------
948
949pub const HELLO: &str = "handshake_hello";
950pub const ACCEPT: &str = "handshake_accept";
951pub const CONFIRM: &str = "handshake_confirm";
952
953/// Decides whether a peer DID is trusted: its did:web or did:webvh name must
954/// be allowed, or `accept_unknown` is set. The name is the domain plus any
955/// path, colon-joined (`did:web:a.example:agents` is `a.example:agents`), so a
956/// bare-domain entry trusts the bare domain only and a path is trusted only
957/// when the policy names it.
958#[derive(Debug, Clone, Default)]
959pub struct TrustPolicy {
960    pub trusted_domains: HashSet<String>,
961    pub accept_unknown: bool,
962}
963
964impl TrustPolicy {
965    pub fn new(domains: impl IntoIterator<Item = String>, accept_unknown: bool) -> Self {
966        Self {
967            trusted_domains: domains.into_iter().collect(),
968            accept_unknown,
969        }
970    }
971
972    pub fn is_trusted(&self, did: &str) -> bool {
973        if self.accept_unknown {
974            return true;
975        }
976        match did_web_domain(did) {
977            Some(d) => self.trusted_domains.contains(&d),
978            None => false,
979        }
980    }
981}
982
983/// The agreed cooperation session after a successful handshake.
984#[derive(Debug, Clone)]
985pub struct BoundedSession {
986    pub session_id: String,
987    pub initiator: String,
988    pub responder: String,
989    pub scope: Vec<String>,
990    pub nonce: String,
991    pub valid_until: Option<String>,
992}
993
994/// The name a did:web or did:webvh DID is trusted under, or None: the domain,
995/// then each path segment after a colon. Each prefix keeps its trailing colon,
996/// so a did:webvh DID never reads as did:web. A did:webvh DID is parsed
997/// strictly ([`crate::did_webvh::parse`]) and gives its host (percent-decoded
998/// and lower-cased) and its percent-decoded path; one that does not parse has
999/// no name. A did:web with an empty segment has no name.
1000fn did_web_domain(did: &str) -> Option<String> {
1001    if crate::did_webvh::is_did_webvh(did) {
1002        return crate::did_webvh::parse(did).ok().map(|parsed| {
1003            std::iter::once(parsed.host)
1004                .chain(parsed.path)
1005                .collect::<Vec<_>>()
1006                .join(":")
1007        });
1008    }
1009    let rest = did.strip_prefix("did:web:")?;
1010    if rest.split(':').any(str::is_empty) {
1011        None
1012    } else {
1013        Some(rest.to_string())
1014    }
1015}
1016
1017/// Parameters for [`build_hello`]. `nonce` and `issued_at` are caller-supplied so
1018/// the core stays deterministic; the wrapper SDKs generate them.
1019#[derive(Debug, Clone, Default)]
1020pub struct BuildHello {
1021    pub from_did: String,
1022    pub proposed_scope: Vec<String>,
1023    pub nonce: String,
1024    pub peer_did: Option<String>,
1025    pub issued_at: String,
1026}
1027
1028/// Open the handshake (initiator A): a proposed scope and a fresh nonce, signed.
1029pub fn build_hello(signer_seed: &[u8], params: &BuildHello) -> Result<Value> {
1030    let mut hello = Map::new();
1031    hello.insert("type".into(), json!(HELLO));
1032    hello.insert("from".into(), json!(params.from_did));
1033    hello.insert(
1034        "to".into(),
1035        match &params.peer_did {
1036            Some(p) => json!(p),
1037            None => Value::Null,
1038        },
1039    );
1040    hello.insert("nonce".into(), json!(params.nonce));
1041    hello.insert("proposedScope".into(), json!(params.proposed_scope));
1042    hello.insert("issuedAt".into(), json!(params.issued_at));
1043    let opts = BuildProofOptions::new(format!("{}#key-1", params.from_did), &params.issued_at);
1044    data_integrity::sign(&Value::Object(hello), signer_seed, &opts)
1045}
1046
1047/// The default clock skew for handshake freshness checks (seconds).
1048pub const DEFAULT_HANDSHAKE_SKEW_SECONDS: i64 = 30;
1049/// The oldest HELLO a responder answers (seconds).
1050pub const DEFAULT_MAX_HELLO_AGE_SECONDS: i64 = 300;
1051/// The longest session an ACCEPT may grant (validUntil - issuedAt).
1052pub const DEFAULT_MAX_SESSION_SECONDS: i64 = 3600;
1053
1054/// The message is `expected_type` and its proof is bound to the DID in `from`
1055/// (assertionMethod, verification method of that DID, key resolved from it).
1056fn handshake_message_ok(obj: &Value, keys: Keys<'_>, expected_type: &str) -> bool {
1057    if obj.get("type").and_then(|v| v.as_str()) != Some(expected_type) {
1058        return false;
1059    }
1060    if rv::input_too_large(obj, rv::MAX_CREDENTIAL_BYTES).is_some() {
1061        return false;
1062    }
1063    let sender = match obj.get("from").and_then(|v| v.as_str()) {
1064        Some(s) if s.starts_with("did:") => s,
1065        _ => return false,
1066    };
1067    if rv::proof_unbound_reason(obj.get("proof").unwrap_or(&Value::Null), sender).is_some() {
1068        return false;
1069    }
1070    // The handshake binds each message to the DID in `from`; whether that
1071    // party is trusted is the policy's decision (or the caller's own HELLO or
1072    // ACCEPT pins it), so `from` is the pinned issuer here.
1073    let key = match rv::resolve_issuer_key(sender, rv::pin_if_keyless(keys, Some(sender))) {
1074        Ok(k) => k,
1075        Err(_) => return false,
1076    };
1077    matches!(data_integrity::verify_proof(obj, &key), Ok(true))
1078}
1079
1080fn scope_list(v: Option<&Value>) -> Option<Vec<String>> {
1081    v?.as_array()?
1082        .iter()
1083        .map(|x| x.as_str().map(String::from))
1084        .collect()
1085}
1086
1087fn issued_recently(v: Option<&Value>, now_ns: i128, skew: i64, max_age: i64) -> bool {
1088    let issued = match rv::time_ns(v) {
1089        Some(t) => t,
1090        None => return false,
1091    };
1092    let second: i128 = 1_000_000_000;
1093    now_ns - i128::from(max_age.saturating_add(skew)) * second <= issued
1094        && issued <= now_ns + i128::from(skew) * second
1095}
1096
1097impl BoundedSession {
1098    /// True while `now_iso` is at or before the session's validUntil (required).
1099    pub fn is_current(&self, now_iso: &str) -> bool {
1100        match (
1101            self.valid_until
1102                .as_deref()
1103                .and_then(|u| crate::time::parse_protocol_time_ns(u).ok()),
1104            crate::time::parse_protocol_time_ns(now_iso).ok(),
1105        ) {
1106            (Some(u), Some(n)) => n <= u,
1107            _ => false,
1108        }
1109    }
1110}
1111
1112/// Parameters for [`build_accept`]. `issued_at` is the responder's clock (it
1113/// also judges the HELLO's age); `valid_until` bounds the session.
1114#[derive(Debug, Clone, Default)]
1115pub struct BuildAccept {
1116    pub from_did: String,
1117    pub offered_scope: Vec<String>,
1118    pub session_id: String,
1119    pub valid_until: String,
1120    pub created: String,
1121}
1122
1123/// Verify A's HELLO, check A's domain, intersect the scope, and sign an
1124/// acceptance (responder B). The HELLO's proof must be bound to its `from` DID
1125/// (`hello_keys` is a `{did: key}` source, or the bare key of a did:key
1126/// initiator); it must be addressed to this responder (`to` unset or this
1127/// responder's DID) and its `issuedAt` within [`DEFAULT_MAX_HELLO_AGE_SECONDS`]
1128/// (plus [`DEFAULT_HANDSHAKE_SKEW_SECONDS`]) of `params.created`. The trust
1129/// policy is applied to the verified `from`. The ACCEPT carries `issuedAt`.
1130pub fn build_accept(
1131    signer_seed: &[u8],
1132    hello: &Value,
1133    hello_keys: Keys<'_>,
1134    policy: &TrustPolicy,
1135    params: &BuildAccept,
1136) -> Result<Value> {
1137    let now = rv::require_now(&params.created)?;
1138    if !handshake_message_ok(hello, hello_keys, HELLO) {
1139        return Err(CoreError::Json(
1140            "HELLO is not signed by the DID it is from".into(),
1141        ));
1142    }
1143    match hello.get("to") {
1144        None | Some(Value::Null) => {}
1145        Some(Value::String(t)) if *t == params.from_did => {}
1146        _ => return Err(CoreError::Json("HELLO is addressed to another node".into())),
1147    }
1148    if !issued_recently(
1149        hello.get("issuedAt"),
1150        now,
1151        DEFAULT_HANDSHAKE_SKEW_SECONDS,
1152        DEFAULT_MAX_HELLO_AGE_SECONDS,
1153    ) {
1154        return Err(CoreError::Json(
1155            "HELLO is stale, from the future, or has no valid issuedAt".into(),
1156        ));
1157    }
1158    let proposed = scope_list(hello.get("proposedScope"));
1159    let nonce = hello
1160        .get("nonce")
1161        .and_then(|v| v.as_str())
1162        .filter(|n| !n.is_empty());
1163    let (proposed, nonce) = match (proposed, nonce) {
1164        (Some(p), Some(n)) => (p, n),
1165        _ => return Err(CoreError::Json("HELLO is malformed".into())),
1166    };
1167    let initiator = hello.get("from").and_then(|v| v.as_str()).unwrap_or("");
1168    if !policy.is_trusted(initiator) {
1169        return Err(CoreError::Json(format!(
1170            "peer {initiator} is not in this trust domain's policy"
1171        )));
1172    }
1173    if rv::time_ns(Some(&json!(params.valid_until))).is_none_or(|u| u <= now) {
1174        return Err(CoreError::Json(
1175            "valid_until must be a protocol time after created".into(),
1176        ));
1177    }
1178
1179    let offered: HashSet<&str> = params.offered_scope.iter().map(|s| s.as_str()).collect();
1180    let mut bounded: Vec<String> = proposed
1181        .into_iter()
1182        .filter(|s| offered.contains(s.as_str()))
1183        .collect::<HashSet<_>>()
1184        .into_iter()
1185        .collect();
1186    bounded.sort();
1187
1188    let mut accept = Map::new();
1189    accept.insert("type".into(), json!(ACCEPT));
1190    accept.insert("from".into(), json!(params.from_did));
1191    accept.insert("to".into(), json!(initiator));
1192    accept.insert("sessionId".into(), json!(params.session_id));
1193    accept.insert("nonce".into(), json!(nonce));
1194    accept.insert("boundedScope".into(), json!(bounded));
1195    accept.insert("issuedAt".into(), json!(params.created));
1196    accept.insert("validUntil".into(), json!(params.valid_until));
1197    let opts = BuildProofOptions::new(format!("{}#key-1", params.from_did), &params.created);
1198    data_integrity::sign(&Value::Object(accept), signer_seed, &opts)
1199}
1200
1201/// Verify B's ACCEPT against the HELLO that A sent (initiator A). The ACCEPT's
1202/// proof must be bound to its `from` DID; it must be addressed to A (`to` ==
1203/// the HELLO's `from`), come from the node the HELLO was addressed to (a HELLO
1204/// addressed to nobody needs a `policy` that trusts the responder), echo the
1205/// HELLO's nonce (and `expected_nonce` when given), carry a bounded scope that
1206/// is a subset of what A proposed, and not have expired at `now_iso`.
1207pub fn verify_accept(
1208    accept: &Value,
1209    accept_keys: Keys<'_>,
1210    hello: &Value,
1211    expected_nonce: Option<&str>,
1212    policy: Option<&TrustPolicy>,
1213    now_iso: &str,
1214) -> Result<Option<BoundedSession>> {
1215    let now = rv::require_now(now_iso)?;
1216    if !hello.is_object() || !handshake_message_ok(accept, accept_keys, ACCEPT) {
1217        return Ok(None);
1218    }
1219    let responder = accept
1220        .get("from")
1221        .and_then(|v| v.as_str())
1222        .unwrap_or("")
1223        .to_string();
1224    if accept.get("to") != hello.get("from") {
1225        return Ok(None);
1226    }
1227    match hello.get("to") {
1228        Some(Value::String(t)) if *t != responder => return Ok(None),
1229        Some(Value::String(_)) => {}
1230        _ if policy.is_none() => return Ok(None),
1231        _ => {}
1232    }
1233    if let Some(p) = policy {
1234        if !p.is_trusted(&responder) {
1235            return Ok(None);
1236        }
1237    }
1238    let nonce = match accept.get("nonce").and_then(|v| v.as_str()) {
1239        Some(n) if Some(n) == hello.get("nonce").and_then(|v| v.as_str()) => n.to_string(),
1240        _ => return Ok(None),
1241    };
1242    if expected_nonce.is_some_and(|e| e != nonce) {
1243        return Ok(None);
1244    }
1245    let (bounded, proposed) = match (
1246        scope_list(accept.get("boundedScope")),
1247        scope_list(hello.get("proposedScope")),
1248    ) {
1249        (Some(b), Some(p)) if b.iter().all(|x| p.contains(x)) => (b, p),
1250        _ => return Ok(None),
1251    };
1252    let _ = proposed;
1253    let sid = match non_empty_str(accept, "sessionId") {
1254        Some(s) => s.to_string(),
1255        None => return Ok(None),
1256    };
1257    let session = BoundedSession {
1258        session_id: sid,
1259        initiator: accept
1260            .get("to")
1261            .and_then(|v| v.as_str())
1262            .unwrap_or("")
1263            .to_string(),
1264        responder,
1265        scope: bounded,
1266        nonce,
1267        valid_until: accept
1268            .get("validUntil")
1269            .and_then(|v| v.as_str())
1270            .map(String::from),
1271    };
1272    if !session.is_current(now_iso) {
1273        return Ok(None);
1274    }
1275    // issuedAt is required: no older than the HELLO age limit, not ahead of
1276    // the clock beyond the skew, and the session it grants is bounded.
1277    if !issued_recently(
1278        accept.get("issuedAt"),
1279        now,
1280        DEFAULT_HANDSHAKE_SKEW_SECONDS,
1281        DEFAULT_MAX_HELLO_AGE_SECONDS,
1282    ) {
1283        return Ok(None);
1284    }
1285    match (
1286        rv::time_ns(accept.get("issuedAt")),
1287        rv::time_ns(accept.get("validUntil")),
1288    ) {
1289        (Some(i), Some(u))
1290            if u > i && u - i <= i128::from(DEFAULT_MAX_SESSION_SECONDS) * 1_000_000_000 => {}
1291        _ => return Ok(None),
1292    }
1293    Ok(Some(session))
1294}
1295
1296/// Sign A's confirmation of the bounded session to B. Refuses an expired
1297/// session (checked at `created`).
1298pub fn build_confirm(
1299    signer_seed: &[u8],
1300    from_did: &str,
1301    session: &BoundedSession,
1302    created: &str,
1303) -> Result<Value> {
1304    rv::require_now(created)?;
1305    if !session.is_current(created) {
1306        return Err(CoreError::Json("the session has expired".into()));
1307    }
1308    let mut confirm = Map::new();
1309    confirm.insert("type".into(), json!(CONFIRM));
1310    confirm.insert("from".into(), json!(from_did));
1311    confirm.insert("to".into(), json!(session.responder));
1312    confirm.insert("sessionId".into(), json!(session.session_id));
1313    confirm.insert("nonce".into(), json!(session.nonce));
1314    confirm.insert("acceptedScope".into(), json!(session.scope));
1315    let opts = BuildProofOptions::new(format!("{from_did}#key-1"), created);
1316    data_integrity::sign(&Value::Object(confirm), signer_seed, &opts)
1317}
1318
1319/// Verify A's CONFIRM closes the session B accepted (responder B). `accept` is
1320/// the ACCEPT B sent. The CONFIRM's proof must be bound to its `from` DID,
1321/// which must be the initiator (the ACCEPT's `to`); it must be addressed to
1322/// B, name the same session and nonce, accept a scope within the bounded
1323/// scope, and arrive while the session is still valid at `now_iso`.
1324pub fn verify_confirm(
1325    confirm: &Value,
1326    confirm_keys: Keys<'_>,
1327    accept: &Value,
1328    now_iso: &str,
1329) -> Result<bool> {
1330    let now = rv::require_now(now_iso)?;
1331    if !accept.is_object() || !handshake_message_ok(confirm, confirm_keys, CONFIRM) {
1332        return Ok(false);
1333    }
1334    if confirm.get("from") != accept.get("to") || confirm.get("to") != accept.get("from") {
1335        return Ok(false);
1336    }
1337    if confirm.get("sessionId") != accept.get("sessionId")
1338        || confirm.get("nonce") != accept.get("nonce")
1339    {
1340        return Ok(false);
1341    }
1342    match (
1343        scope_list(confirm.get("acceptedScope")),
1344        scope_list(accept.get("boundedScope")),
1345    ) {
1346        (Some(a), Some(b)) if a.iter().all(|x| b.contains(x)) => {}
1347        _ => return Ok(false),
1348    }
1349    Ok(rv::time_ns(accept.get("validUntil")).is_some_and(|u| now <= u))
1350}
1351
1352// ---------------------------------------------------------------------------
1353// Black box and kill switch (Phase 5.5)
1354// ---------------------------------------------------------------------------
1355
1356/// Version 1.1 entries bind their header (every field but the ciphertext and
1357/// the hash) into AES-GCM as associated data; 1.0 entries do not.
1358pub const BLACKBOX_VERSION: &str = "1.1";
1359/// The pre-1.1 entry version, still opened (without associated data).
1360pub const BLACKBOX_LEGACY_VERSION: &str = "1.0";
1361/// A signed black-box head: entry count plus last hash.
1362pub const BLACKBOX_HEAD_TYPE: &str = "BlackBoxHeadCredential";
1363/// Size cap for a log handed to a verifier (before canonicalization).
1364pub const MAX_LOG_BYTES: usize = 64 * 1024 * 1024;
1365pub const KILLSWITCH_TYPE: &str = "KillSwitchCredential";
1366pub const EMERGENCY_STOP: &str = "emergency_stop";
1367
1368/// The prevHash of the first entry: multibase of 32 zero bytes.
1369pub fn genesis_prev_hash() -> String {
1370    mb64(&[0u8; 32])
1371}
1372
1373/// The entry header bound into AES-GCM: JCS of every field but the ciphertext
1374/// and the entry hash.
1375fn entry_aad(entry: &Map<String, Value>) -> Vec<u8> {
1376    let mut header = entry.clone();
1377    header.remove("ciphertext");
1378    header.remove("entryHash");
1379    jcs::canonicalize(&Value::Object(header))
1380}
1381
1382fn entry_hash(body: &Map<String, Value>) -> Result<String> {
1383    let mut clean = body.clone();
1384    clean.remove("entryHash");
1385    let canonical = jcs::canonicalize(&Value::Object(clean));
1386    Ok(mb64(&Sha256::digest(canonical)))
1387}
1388
1389/// Build one black-box entry statelessly: encrypt `payload` under `key`, link it
1390/// to `prev_hash` at `seq`, and return the entry with its `entryHash`. The
1391/// stateful [`BlackBoxLog`] and the FFI layer both build on this. The encrypted
1392/// blob is nonce(12) || ciphertext || tag(16).
1393pub fn blackbox_append_entry(
1394    key: &[u8],
1395    seq: u64,
1396    event: &str,
1397    payload: &Value,
1398    timestamp: &str,
1399    prev_hash: &str,
1400) -> Result<Value> {
1401    if key.len() != 32 {
1402        return Err(CoreError::Crypto(
1403            "black box key must be 32 bytes (AES-256)".into(),
1404        ));
1405    }
1406    let mut nonce = [0u8; 12];
1407    getrandom::getrandom(&mut nonce).map_err(|e| CoreError::Crypto(format!("rng: {e}")))?;
1408    let plaintext = jcs::canonicalize(payload);
1409    let mut body = Map::new();
1410    body.insert("version".into(), json!(BLACKBOX_VERSION));
1411    body.insert("seq".into(), json!(seq));
1412    body.insert("timestamp".into(), json!(timestamp));
1413    body.insert("event".into(), json!(event));
1414    body.insert("prevHash".into(), json!(prev_hash));
1415    let aad = entry_aad(&body);
1416    let cipher =
1417        Aes256Gcm::new_from_slice(key).map_err(|e| CoreError::Crypto(format!("aes key: {e}")))?;
1418    let ct = cipher
1419        .encrypt(
1420            Nonce::from_slice(&nonce),
1421            Payload {
1422                msg: plaintext.as_ref(),
1423                aad: &aad,
1424            },
1425        )
1426        .map_err(|e| CoreError::Crypto(format!("encrypt: {e}")))?;
1427    let mut blob = Vec::with_capacity(nonce.len() + ct.len());
1428    blob.extend_from_slice(&nonce);
1429    blob.extend_from_slice(&ct);
1430    body.insert("ciphertext".into(), json!(mb64(&blob)));
1431    let h = entry_hash(&body)?;
1432    body.insert("entryHash".into(), json!(h));
1433    Ok(Value::Object(body))
1434}
1435
1436/// An append-only, AES-256-GCM-encrypted, JCS hash-linked event log. The key is
1437/// 32 bytes. The encrypted blob is nonce(12) || ciphertext || tag(16), matching
1438/// Python, TypeScript, and Go.
1439pub struct BlackBoxLog {
1440    key: Vec<u8>,
1441    genesis: String,
1442    entries: Vec<Value>,
1443    head: String,
1444}
1445
1446impl BlackBoxLog {
1447    /// Build a log. A `None` genesis uses [`genesis_prev_hash`].
1448    pub fn new(key: &[u8], genesis_prev_hash_override: Option<&str>) -> Result<Self> {
1449        if key.len() != 32 {
1450            return Err(CoreError::Crypto(
1451                "black box key must be 32 bytes (AES-256)".into(),
1452            ));
1453        }
1454        let genesis = genesis_prev_hash_override
1455            .map(String::from)
1456            .unwrap_or_else(genesis_prev_hash);
1457        Ok(Self {
1458            key: key.to_vec(),
1459            head: genesis.clone(),
1460            genesis,
1461            entries: Vec::new(),
1462        })
1463    }
1464
1465    /// Encrypt `payload`, link it to the chain head, and return the new entry.
1466    pub fn append(&mut self, event: &str, payload: &Value, timestamp: &str) -> Result<Value> {
1467        let entry = blackbox_append_entry(
1468            &self.key,
1469            self.entries.len() as u64,
1470            event,
1471            payload,
1472            timestamp,
1473            &self.head,
1474        )?;
1475        self.head = entry
1476            .get("entryHash")
1477            .and_then(|v| v.as_str())
1478            .unwrap_or("")
1479            .to_string();
1480        self.entries.push(entry.clone());
1481        Ok(entry)
1482    }
1483
1484    pub fn head(&self) -> &str {
1485        &self.head
1486    }
1487
1488    pub fn genesis(&self) -> &str {
1489        &self.genesis
1490    }
1491
1492    pub fn entries(&self) -> &[Value] {
1493        &self.entries
1494    }
1495
1496    /// The number of entries, the count a signed head carries.
1497    pub fn count(&self) -> usize {
1498        self.entries.len()
1499    }
1500
1501    pub fn open(&self, entry: &Value) -> Result<Value> {
1502        open_entry(entry, &self.key)
1503    }
1504}
1505
1506/// Decrypt a black-box entry payload with the log key.
1507pub fn open_entry(entry: &Value, key: &[u8]) -> Result<Value> {
1508    let obj = entry
1509        .as_object()
1510        .ok_or_else(|| CoreError::Json("entry has no ciphertext".into()))?;
1511    let ct_mb = obj
1512        .get("ciphertext")
1513        .and_then(|v| v.as_str())
1514        .ok_or_else(|| CoreError::Json("entry has no ciphertext".into()))?;
1515    // 1.1 entries open with their header as associated data, so a changed
1516    // label, time, sequence number or link fails to decrypt. 1.0 entries were
1517    // written before the header was bound and open without it.
1518    let aad = match obj.get("version").and_then(|v| v.as_str()) {
1519        Some(BLACKBOX_VERSION) => entry_aad(obj),
1520        Some(BLACKBOX_LEGACY_VERSION) => Vec::new(),
1521        other => {
1522            return Err(CoreError::Json(format!(
1523                "unsupported black-box entry version {other:?}"
1524            )))
1525        }
1526    };
1527    let blob = unmb64(ct_mb)?;
1528    if blob.len() < 12 + 16 {
1529        return Err(CoreError::Crypto("ciphertext too short".into()));
1530    }
1531    let cipher =
1532        Aes256Gcm::new_from_slice(key).map_err(|e| CoreError::Crypto(format!("aes key: {e}")))?;
1533    let (nonce, rest) = blob.split_at(12);
1534    let pt = cipher
1535        .decrypt(
1536            Nonce::from_slice(nonce),
1537            Payload {
1538                msg: rest,
1539                aad: &aad,
1540            },
1541        )
1542        .map_err(|_| CoreError::Crypto("decryption failed".into()))?;
1543    serde_json::from_slice(&pt).map_err(|e| CoreError::Json(format!("payload decode: {e}")))
1544}
1545
1546/// The outcome of [`verify_blackbox_chain`].
1547#[derive(Debug, Clone)]
1548pub struct ChainResult {
1549    pub ok: bool,
1550    pub reason: Option<String>,
1551}
1552
1553/// Verify the hash chain over the (still-encrypted) entries. Tamper-evident
1554/// without the key. A `None` genesis uses [`genesis_prev_hash`].
1555pub fn verify_blackbox_chain(
1556    entries: &[Value],
1557    genesis_prev_hash_override: Option<&str>,
1558) -> ChainResult {
1559    let mut prev = genesis_prev_hash_override
1560        .map(String::from)
1561        .unwrap_or_else(genesis_prev_hash);
1562    let as_value = Value::Array(entries.to_vec());
1563    if let Some(big) = rv::input_too_large(&as_value, MAX_LOG_BYTES) {
1564        return ChainResult {
1565            ok: false,
1566            reason: Some(big),
1567        };
1568    }
1569    for (i, entry) in entries.iter().enumerate() {
1570        if !entry.is_object() {
1571            return ChainResult {
1572                ok: false,
1573                reason: Some(format!("entry {i} is not an object")),
1574            };
1575        }
1576        if entry.get("seq").and_then(|v| v.as_u64()) != Some(i as u64) {
1577            return ChainResult {
1578                ok: false,
1579                reason: Some(format!("entry {i} seq mismatch")),
1580            };
1581        }
1582        if entry.get("prevHash").and_then(|v| v.as_str()).unwrap_or("") != prev {
1583            return ChainResult {
1584                ok: false,
1585                reason: Some(format!("entry {i} prevHash does not link")),
1586            };
1587        }
1588        let obj = match entry.as_object() {
1589            Some(o) => o,
1590            None => {
1591                return ChainResult {
1592                    ok: false,
1593                    reason: Some(format!("entry {i} is not an object")),
1594                }
1595            }
1596        };
1597        let want = match entry_hash(obj) {
1598            Ok(w) => w,
1599            Err(_) => {
1600                return ChainResult {
1601                    ok: false,
1602                    reason: Some(format!("entry {i} hash error")),
1603                }
1604            }
1605        };
1606        let eh = entry
1607            .get("entryHash")
1608            .and_then(|v| v.as_str())
1609            .unwrap_or("");
1610        if eh != want {
1611            return ChainResult {
1612                ok: false,
1613                reason: Some(format!("entry {i} entryHash mismatch (tampered)")),
1614            };
1615        }
1616        prev = eh.to_string();
1617    }
1618    ChainResult {
1619        ok: true,
1620        reason: None,
1621    }
1622}
1623
1624/// Parameters for [`build_killswitch_credential`].
1625#[derive(Debug, Clone, Default)]
1626pub struct BuildKillswitch {
1627    pub issuer_did: String,
1628    pub target: String,
1629    pub reason: String,
1630    pub command: Option<String>,
1631    pub scope: Option<Vec<String>>,
1632    pub valid_from: String,
1633    pub valid_until: Option<String>,
1634}
1635
1636/// Build a signed `KillSwitchCredential` proving who issued an emergency stop.
1637pub fn build_killswitch_credential(
1638    authority_seed: &[u8],
1639    params: &BuildKillswitch,
1640) -> Result<Value> {
1641    let command = params
1642        .command
1643        .clone()
1644        .unwrap_or_else(|| EMERGENCY_STOP.to_string());
1645    let mut subject = Map::new();
1646    subject.insert("id".into(), json!(params.target));
1647    subject.insert("command".into(), json!(command));
1648    subject.insert("reason".into(), json!(params.reason));
1649    subject.insert("issuedBy".into(), json!(params.issuer_did));
1650    if let Some(scope) = &params.scope {
1651        subject.insert("scope".into(), json!(scope));
1652    }
1653
1654    let mut cred = Map::new();
1655    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
1656    cred.insert(
1657        "type".into(),
1658        json!(["VerifiableCredential", KILLSWITCH_TYPE]),
1659    );
1660    cred.insert("issuer".into(), json!(params.issuer_did));
1661    cred.insert("validFrom".into(), json!(params.valid_from));
1662    if let Some(vu) = &params.valid_until {
1663        cred.insert("validUntil".into(), json!(vu));
1664    }
1665    cred.insert("credentialSubject".into(), Value::Object(subject));
1666
1667    let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), &params.valid_from);
1668    data_integrity::sign(&Value::Object(cred), authority_seed, &opts)
1669}
1670
1671/// Verify a `KillSwitchCredential`. When `trusted_authorities` is supplied, the
1672/// issuer DID MUST be in it. Returns the subject on success.
1673pub fn verify_killswitch_credential(
1674    credential: &Value,
1675    keys: Keys<'_>,
1676    trusted_authorities: Option<&HashSet<String>>,
1677    now_iso: &str,
1678) -> Result<Option<Value>> {
1679    let now = rv::require_now(now_iso)?;
1680    let opts = VerifyOptions {
1681        trusted_issuers: trusted_authorities,
1682        ..VerifyOptions::window(Window::FromRequired)
1683    };
1684    let v = match rv::verify_robotics_credential(credential, keys, Some(KILLSWITCH_TYPE), now, opts)
1685    {
1686        Ok(v) => v,
1687        Err(_) => return Ok(None),
1688    };
1689    // issuedBy, when present, must be the bound issuer.
1690    if let Some(by) = v.subject.get("issuedBy") {
1691        if by.as_str() != Some(v.issuer.as_str()) {
1692            return Ok(None);
1693        }
1694    }
1695    Ok(Some(v.subject))
1696}
1697
1698/// Verify the hash links AND that the log ends at a known head: `head` and
1699/// `count` come from something signed (a head credential, a safety-record
1700/// summary, a perception attestation). A log cut short, extended or rebuilt
1701/// does not end at that head with that many entries.
1702pub fn verify_chain_against_head(
1703    entries: &[Value],
1704    head: Option<&Value>,
1705    count: Option<&Value>,
1706    genesis_prev_hash_override: Option<&str>,
1707) -> ChainResult {
1708    let res = verify_blackbox_chain(entries, genesis_prev_hash_override);
1709    if !res.ok {
1710        return res;
1711    }
1712    let fail = |r: String| ChainResult {
1713        ok: false,
1714        reason: Some(r),
1715    };
1716    let n = match count.and_then(|c| rv::strict_int(Some(c))) {
1717        Some(n) if n >= 0 => n,
1718        _ => return fail("anchored count is not a non-negative integer".into()),
1719    };
1720    if entries.len() as i64 != n {
1721        return fail(format!(
1722            "log has {} entries, the signed head says {n}",
1723            entries.len()
1724        ));
1725    }
1726    let genesis = genesis_prev_hash_override
1727        .map(String::from)
1728        .unwrap_or_else(genesis_prev_hash);
1729    let last = match entries.last() {
1730        Some(e) => e
1731            .get("entryHash")
1732            .and_then(|v| v.as_str())
1733            .unwrap_or("")
1734            .to_string(),
1735        None => genesis,
1736    };
1737    if head.and_then(|h| h.as_str()) != Some(last.as_str()) {
1738        return fail("log does not end at the signed head".into());
1739    }
1740    ChainResult {
1741        ok: true,
1742        reason: None,
1743    }
1744}
1745
1746/// Sign the head of a black-box log (entry count plus last hash). The robot is
1747/// the issuer and the subject.
1748pub fn build_blackbox_head(
1749    robot_seed: &[u8],
1750    robot_did: &str,
1751    head: &str,
1752    entry_count: u64,
1753    valid_from: &str,
1754    valid_until: Option<&str>,
1755) -> Result<Value> {
1756    let mut cred = Map::new();
1757    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
1758    cred.insert(
1759        "type".into(),
1760        json!(["VerifiableCredential", BLACKBOX_HEAD_TYPE]),
1761    );
1762    cred.insert("issuer".into(), json!(robot_did));
1763    cred.insert("validFrom".into(), json!(valid_from));
1764    if let Some(vu) = valid_until {
1765        cred.insert("validUntil".into(), json!(vu));
1766    }
1767    cred.insert(
1768        "credentialSubject".into(),
1769        json!({"id": robot_did, "logHead": head, "entryCount": entry_count}),
1770    );
1771    let opts = BuildProofOptions::new(format!("{robot_did}#key-1"), valid_from);
1772    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
1773}
1774
1775/// Verify a log against the robot's signed head: the head credential must
1776/// verify bound to the robot as issuer and subject, and the log must link and
1777/// end at the signed head with exactly the signed number of entries.
1778pub fn verify_blackbox_head(
1779    credential: &Value,
1780    robot_keys: Keys<'_>,
1781    entries: &[Value],
1782    genesis_prev_hash_override: Option<&str>,
1783    now_iso: &str,
1784) -> Result<ChainResult> {
1785    let now = rv::require_now(now_iso)?;
1786    let v = match rv::verify_robotics_credential(
1787        credential,
1788        robot_keys,
1789        Some(BLACKBOX_HEAD_TYPE),
1790        now,
1791        VerifyOptions::window(Window::FromRequired),
1792    ) {
1793        Ok(v) => v,
1794        Err(r) => {
1795            return Ok(ChainResult {
1796                ok: false,
1797                reason: Some(r),
1798            })
1799        }
1800    };
1801    if !issuer_is_subject(&v) {
1802        return Ok(ChainResult {
1803            ok: false,
1804            reason: Some("head is not issued by the robot it describes".into()),
1805        });
1806    }
1807    Ok(verify_chain_against_head(
1808        entries,
1809        v.subject.get("logHead"),
1810        v.subject.get("entryCount"),
1811        genesis_prev_hash_override,
1812    ))
1813}
1814
1815// ---------------------------------------------------------------------------
1816// Halos safety-evidence recorder (NVIDIA Halos integration)
1817// ---------------------------------------------------------------------------
1818//
1819// Byte-exact port of the Python reference `vouch/robotics/halos.py`.
1820//
1821// Halos certifies that a robot's stack is functionally safe and secure by design.
1822// It does not, on its own, produce a verifiable record of what a specific robot
1823// did or bind that record to the robot's identity. This is the evidence layer
1824// under a Halos-certified stack: the robot seals its black-box chain head and
1825// entry count into a signed `HalosSafetyEvidenceCredential` that binds them to its
1826// identity, to the Halos stack elements it ran on, and to a time window. A
1827// verifier that holds the credential and the entries confirms, without the
1828// black-box key, that the record is unaltered, was not truncated or extended since
1829// it was sealed, and is attributable to that robot. This composes the existing
1830// black-box and credential primitives and adds no new cryptography.
1831
1832pub const HALOS_SAFETY_EVIDENCE_TYPE: &str = "HalosSafetyEvidenceCredential";
1833
1834/// Format Unix epoch seconds as "YYYY-MM-DDTHH:MM:SSZ" for a whole-second UTC
1835/// instant. Howard Hinnant's civil-from-days algorithm, matching the rest of the
1836/// core so a `valid_seconds` lifetime renders identically across languages.
1837fn halos_epoch_to_iso(epoch: i64) -> String {
1838    let days = epoch.div_euclid(86400);
1839    let secs = epoch.rem_euclid(86400);
1840    let z = days + 719468;
1841    let era = (if z >= 0 { z } else { z - 146096 }) / 146097;
1842    let doe = z - era * 146097;
1843    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
1844    let y = yoe + era * 400;
1845    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1846    let mp = (5 * doy + 2) / 153;
1847    let d = doy - (153 * mp + 2) / 5 + 1;
1848    let m = if mp < 10 { mp + 3 } else { mp - 9 };
1849    let year = if m <= 2 { y + 1 } else { y };
1850    let hh = secs / 3600;
1851    let mm = (secs % 3600) / 60;
1852    let ss = secs % 60;
1853    format!("{year:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}Z")
1854}
1855
1856/// Parameters for [`build_safety_evidence`]. The robot DID is derived from
1857/// `signer_seed` (a did:key), mirroring the Python signer. `blackbox_head` and
1858/// `entry_count` seal the robot's black-box chain; `halos_stack` names the
1859/// certified configuration; `window` covers the recorded events. Timestamps are
1860/// caller-supplied ISO-8601 strings.
1861#[derive(Debug, Clone)]
1862pub struct BuildSafetyEvidence {
1863    pub halos_stack: Value,
1864    pub window_from: String,
1865    pub window_to: String,
1866    pub blackbox_head: String,
1867    pub entry_count: u64,
1868    pub robot_identity: Option<String>,
1869    pub valid_seconds: Option<i64>,
1870    pub valid_from: String,
1871    pub created: String,
1872}
1873
1874/// Seal a robot's Halos safety-event record into a signed
1875/// `HalosSafetyEvidenceCredential`. The robot signs a credential binding the
1876/// black-box chain head and entry count to its identity, to the Halos stack
1877/// elements it ran on, and to the time window.
1878pub fn build_safety_evidence(signer_seed: &[u8], params: &BuildSafetyEvidence) -> Result<Value> {
1879    match params.halos_stack.as_object() {
1880        Some(o) if !o.is_empty() => {}
1881        _ => return Err(CoreError::Json("halos_stack is required".into())),
1882    }
1883    if params.window_from.is_empty() || params.window_to.is_empty() {
1884        return Err(CoreError::Json(
1885            "window with 'from' and 'to' is required".into(),
1886        ));
1887    }
1888
1889    let kp = keys::Ed25519KeyPair::from_seed_slice(signer_seed)?;
1890    let robot_did = keys::ed25519_to_did_key(&kp.public_key())?;
1891
1892    let mut subject = Map::new();
1893    subject.insert("id".into(), json!(robot_did));
1894    subject.insert("blackboxHead".into(), json!(params.blackbox_head));
1895    subject.insert("entryCount".into(), json!(params.entry_count));
1896    subject.insert("halosStack".into(), params.halos_stack.clone());
1897    subject.insert(
1898        "window".into(),
1899        json!({ "from": params.window_from, "to": params.window_to }),
1900    );
1901    if let Some(robot_identity) = &params.robot_identity {
1902        subject.insert("robotIdentity".into(), json!(robot_identity));
1903    }
1904
1905    let mut cred = Map::new();
1906    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
1907    cred.insert(
1908        "type".into(),
1909        json!(["VerifiableCredential", HALOS_SAFETY_EVIDENCE_TYPE]),
1910    );
1911    cred.insert("issuer".into(), json!(robot_did));
1912    cred.insert("validFrom".into(), json!(params.valid_from));
1913    if let Some(valid_seconds) = params.valid_seconds {
1914        let from = crate::time::iso_to_epoch_seconds(&params.valid_from)?;
1915        cred.insert(
1916            "validUntil".into(),
1917            json!(halos_epoch_to_iso(from + valid_seconds)),
1918        );
1919    }
1920    cred.insert("credentialSubject".into(), Value::Object(subject));
1921
1922    let opts = BuildProofOptions::new(format!("{robot_did}#key-1"), &params.created);
1923    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
1924}
1925
1926/// Verify a `HalosSafetyEvidenceCredential`: the robot's proof and that the issuer
1927/// is the robot (`credentialSubject.id`). When `entries` is supplied, also checks
1928/// that the black-box chain is intact, that its length matches the sealed entry
1929/// count, and that its head matches the sealed head, so a truncated, extended,
1930/// reordered, or tampered record is rejected. Returns `(ok, credentialSubject)`.
1931pub fn verify_safety_evidence(
1932    credential: &Value,
1933    robot_keys: Keys<'_>,
1934    entries: Option<&[Value]>,
1935    now_iso: &str,
1936) -> Result<(bool, Option<Value>)> {
1937    let v = match bound(
1938        credential,
1939        robot_keys,
1940        HALOS_SAFETY_EVIDENCE_TYPE,
1941        now_iso,
1942        Window::FromRequired,
1943    )? {
1944        Some(v) if issuer_is_subject(&v) => v,
1945        _ => return Ok((false, None)),
1946    };
1947    let subject = v.subject;
1948    let count = match rv::strict_int(subject.get("entryCount")) {
1949        Some(n) if n >= 0 => n,
1950        _ => return Ok((false, None)),
1951    };
1952
1953    if let Some(entries) = entries {
1954        if !verify_blackbox_chain(entries, None).ok {
1955            return Ok((false, None));
1956        }
1957        if count != entries.len() as i64 {
1958            return Ok((false, None));
1959        }
1960        let head = match entries.last() {
1961            Some(last) => last
1962                .get("entryHash")
1963                .and_then(|v| v.as_str())
1964                .unwrap_or("")
1965                .to_string(),
1966            None => genesis_prev_hash(),
1967        };
1968        if Some(head.as_str()) != subject.get("blackboxHead").and_then(|v| v.as_str()) {
1969            return Ok((false, None));
1970        }
1971    }
1972
1973    Ok((true, Some(subject)))
1974}
1975
1976// ---------------------------------------------------------------------------
1977// Scannable robot passport (Phase 5.6)
1978// ---------------------------------------------------------------------------
1979
1980pub const ROBOT_PASSPORT_TYPE: &str = "RobotPassport";
1981pub const PASSPORT_URI_SCHEME: &str = "vouch-passport:";
1982pub const STATUS_ACTIVE: &str = "active";
1983pub const STATUS_SUSPENDED: &str = "suspended";
1984pub const STATUS_DECOMMISSIONED: &str = "decommissioned";
1985
1986/// Parameters for [`build_passport`]. The issuer is the signer (the robot or an
1987/// authority); `robot_did` is the robot the passport describes.
1988#[derive(Debug, Clone, Default)]
1989pub struct BuildPassport {
1990    pub issuer_did: String,
1991    pub robot_did: String,
1992    pub make: String,
1993    pub model: String,
1994    pub owner: String,
1995    pub authorized_actions: Vec<String>,
1996    pub certification: Option<String>,
1997    pub status: Option<String>,
1998    pub valid_from: String,
1999    pub valid_until: Option<String>,
2000}
2001
2002/// Build a signed `RobotPassport` credential.
2003pub fn build_passport(signer_seed: &[u8], params: &BuildPassport) -> Result<Value> {
2004    let status = params
2005        .status
2006        .clone()
2007        .unwrap_or_else(|| STATUS_ACTIVE.to_string());
2008    let mut subject = Map::new();
2009    subject.insert("id".into(), json!(params.robot_did));
2010    subject.insert("make".into(), json!(params.make));
2011    subject.insert("model".into(), json!(params.model));
2012    subject.insert("owner".into(), json!(params.owner));
2013    subject.insert("authorizedActions".into(), json!(params.authorized_actions));
2014    subject.insert("status".into(), json!(status));
2015    if let Some(c) = &params.certification {
2016        subject.insert("certification".into(), json!(c));
2017    }
2018
2019    let mut cred = Map::new();
2020    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
2021    cred.insert(
2022        "type".into(),
2023        json!(["VerifiableCredential", ROBOT_PASSPORT_TYPE]),
2024    );
2025    cred.insert("issuer".into(), json!(params.issuer_did));
2026    cred.insert("validFrom".into(), json!(params.valid_from));
2027    if let Some(vu) = &params.valid_until {
2028        cred.insert("validUntil".into(), json!(vu));
2029    }
2030    cred.insert("credentialSubject".into(), Value::Object(subject));
2031
2032    let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), &params.valid_from);
2033    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
2034}
2035
2036/// Encode a passport into a compact `vouch-passport:` URI for a QR or NFC tag.
2037pub fn encode_passport(passport: &Value) -> String {
2038    format!(
2039        "{}{}",
2040        PASSPORT_URI_SCHEME,
2041        mb64(&jcs::canonicalize(passport))
2042    )
2043}
2044
2045/// Decode a `vouch-passport:` URI back into the passport credential.
2046pub fn decode_passport(uri: &str) -> Result<Value> {
2047    let body = uri
2048        .strip_prefix(PASSPORT_URI_SCHEME)
2049        .ok_or_else(|| CoreError::Json(format!("not a {PASSPORT_URI_SCHEME} URI")))?;
2050    if body.len() > 2 * rv::MAX_CREDENTIAL_BYTES {
2051        return Err(CoreError::Json("passport URI too large".into()));
2052    }
2053    let raw = unmb64(body)?;
2054    let decoded: Value = serde_json::from_slice(&raw)
2055        .map_err(|e| CoreError::Json(format!("passport decode: {e}")))?;
2056    if !decoded.is_object() {
2057        return Err(CoreError::Json("passport payload is not an object".into()));
2058    }
2059    Ok(decoded)
2060}
2061
2062/// Verify a passport: the proof bound to the issuer (`keys` is a `{did: key}`
2063/// source, or the bare key of a did:key issuer), the validity window at
2064/// `now_iso` (validFrom required, strict times), `authorizedActions` a list of
2065/// strings, and (when given) the issuer in `trusted_issuers`. A suspended or
2066/// decommissioned status still verifies; the caller reads it from the subject.
2067pub fn verify_passport(
2068    passport: &Value,
2069    keys: Keys<'_>,
2070    trusted_issuers: Option<&HashSet<String>>,
2071    now_iso: &str,
2072) -> Result<Option<Value>> {
2073    let now = rv::require_now(now_iso)?;
2074    let opts = VerifyOptions {
2075        trusted_issuers,
2076        ..VerifyOptions::window(Window::FromRequired)
2077    };
2078    let v = match rv::verify_robotics_credential(
2079        passport,
2080        keys,
2081        Some(ROBOT_PASSPORT_TYPE),
2082        now,
2083        opts,
2084    ) {
2085        Ok(v) => v,
2086        Err(_) => return Ok(None),
2087    };
2088    match v.subject.get("authorizedActions") {
2089        None => {}
2090        Some(Value::Array(a)) if a.iter().all(|x| x.is_string()) => {}
2091        _ => return Ok(None),
2092    }
2093    Ok(Some(v.subject))
2094}
2095
2096pub fn verify_passport_uri(
2097    uri: &str,
2098    keys: Keys<'_>,
2099    trusted_issuers: Option<&HashSet<String>>,
2100    now_iso: &str,
2101) -> Result<Option<Value>> {
2102    rv::require_now(now_iso)?;
2103    match decode_passport(uri) {
2104        Ok(p) => verify_passport(&p, keys, trusted_issuers, now_iso),
2105        Err(_) => Ok(None),
2106    }
2107}
2108
2109/// Verify a passport (a credential object or a `vouch-passport:` URI) as
2110/// [`verify_passport`] does and return the human-facing summary the Python
2111/// reference returns: robot, make, model, owner, authorizedActions,
2112/// certification, status, and the verified `issuer`.
2113pub fn verify_passport_summary(
2114    passport: &Value,
2115    keys: Keys<'_>,
2116    trusted_issuers: Option<&HashSet<String>>,
2117    now_iso: &str,
2118) -> Result<Option<Value>> {
2119    let cred = match passport {
2120        Value::String(uri) => match decode_passport(uri) {
2121            Ok(p) => p,
2122            Err(_) => return Ok(None),
2123        },
2124        other => other.clone(),
2125    };
2126    let subject = match verify_passport(&cred, keys, trusted_issuers, now_iso)? {
2127        Some(s) => s,
2128        None => return Ok(None),
2129    };
2130    let issuer = rv::issuer_id(cred.get("issuer")).unwrap_or("").to_string();
2131    let g = |k: &str| subject.get(k).cloned().unwrap_or(Value::Null);
2132    Ok(Some(json!({
2133        "robot": g("id"),
2134        "make": g("make"),
2135        "model": g("model"),
2136        "owner": g("owner"),
2137        "authorizedActions": subject.get("authorizedActions").cloned().unwrap_or(json!([])),
2138        "certification": g("certification"),
2139        "status": g("status"),
2140        "issuer": issuer,
2141    })))
2142}
2143
2144// ---------------------------------------------------------------------------
2145// Liveness heartbeat with safety-envelope conformance (Phase 5.7)
2146// ---------------------------------------------------------------------------
2147
2148pub const ROBOT_HEARTBEAT_TYPE: &str = "RobotHeartbeatCredential";
2149
2150/// Default number of missed intervals tolerated before trust is considered stale.
2151pub const DEFAULT_GRACE_INTERVALS: i64 = 2;
2152
2153/// One observed motion sample. `None` numerics mean "not specified" (a meaningful
2154/// zero is still `Some(0.0)`), matching [`PhysicalAction`].
2155#[derive(Debug, Clone, Default)]
2156pub struct MotionSample {
2157    pub force_n: Option<f64>,
2158    pub speed_mps: Option<f64>,
2159    pub near_humans: bool,
2160    pub zone: Option<String>,
2161    pub time_hm: Option<String>,
2162}
2163
2164/// Collector for per-interval motion telemetry. It accumulates aggregates of what
2165/// the robot physically did over a heartbeat interval and, when given a physical
2166/// scope, counts how many samples fell outside the declared envelope. The
2167/// physical analogue of the agent behavioral digest.
2168///
2169/// With `scope` set to `None` the digest still reports observed maxima but cannot
2170/// judge conformance, so it reports `withinEnvelope` true with a zero breach
2171/// count, mirroring the Python `MotionCollector`.
2172#[derive(Debug, Clone, Default)]
2173pub struct MotionCollector {
2174    scope: Option<Value>,
2175    samples: u64,
2176    max_force: f64,
2177    max_speed: f64,
2178    max_speed_near: f64,
2179    zone_breaches: u64,
2180    breaches: u64,
2181}
2182
2183impl MotionCollector {
2184    /// A collector that judges samples against `scope` (the
2185    /// `credentialSubject.physicalScope` object). Pass `None` to only aggregate.
2186    pub fn new(scope: Option<Value>) -> Self {
2187        Self {
2188            scope,
2189            ..Default::default()
2190        }
2191    }
2192
2193    /// Record a single observed motion sample, updating the running aggregates and
2194    /// (when a scope is set) the breach counts.
2195    pub fn record(&mut self, sample: &MotionSample) -> Result<()> {
2196        if let Some(f) = sample.force_n {
2197            if !f.is_finite() || f < 0.0 {
2198                return Err(CoreError::Json(format!(
2199                    "force_n must be a finite non-negative number, got {f}"
2200                )));
2201            }
2202        }
2203        if let Some(s) = sample.speed_mps {
2204            if !s.is_finite() || s < 0.0 {
2205                return Err(CoreError::Json(format!(
2206                    "speed_mps must be a finite non-negative number, got {s}"
2207                )));
2208            }
2209        }
2210
2211        self.samples += 1;
2212        if let Some(f) = sample.force_n {
2213            self.max_force = self.max_force.max(f);
2214        }
2215        if let Some(s) = sample.speed_mps {
2216            self.max_speed = self.max_speed.max(s);
2217            if sample.near_humans {
2218                self.max_speed_near = self.max_speed_near.max(s);
2219            }
2220        }
2221
2222        if let Some(scope) = &self.scope {
2223            let action = PhysicalAction {
2224                force_n: sample.force_n,
2225                speed_mps: sample.speed_mps,
2226                near_humans: sample.near_humans,
2227                zone: sample.zone.clone(),
2228                time_hm: sample.time_hm.clone(),
2229            };
2230            let result = check_physical_action(scope, &action);
2231            if !result.ok {
2232                self.breaches += 1;
2233                if result
2234                    .reasons
2235                    .iter()
2236                    .any(|r| r.starts_with("zone_not_allowed"))
2237                {
2238                    self.zone_breaches += 1;
2239                }
2240            }
2241        }
2242        Ok(())
2243    }
2244
2245    /// Return the `motionDigest` object for embedding in a heartbeat credential.
2246    pub fn digest(&self) -> Value {
2247        json!({
2248            "samples": self.samples,
2249            "maxForceN": self.max_force,
2250            "maxSpeedMps": self.max_speed,
2251            "maxSpeedNearHumansMps": self.max_speed_near,
2252            "zoneBreaches": self.zone_breaches,
2253            "breachCount": self.breaches,
2254            "withinEnvelope": self.breaches == 0,
2255        })
2256    }
2257
2258    /// Clear all state. Call after submitting a heartbeat to start fresh.
2259    pub fn reset(&mut self) {
2260        self.samples = 0;
2261        self.max_force = 0.0;
2262        self.max_speed = 0.0;
2263        self.max_speed_near = 0.0;
2264        self.zone_breaches = 0;
2265        self.breaches = 0;
2266    }
2267}
2268
2269fn digest_non_negative_int(digest: &Map<String, Value>, name: &str) -> Result<()> {
2270    match digest.get(name) {
2271        Some(v) if v.is_u64() => Ok(()),
2272        Some(Value::Number(n)) if n.as_i64().map(|i| i >= 0).unwrap_or(false) => Ok(()),
2273        Some(_) => Err(CoreError::Json(format!(
2274            "motionDigest.{name} must be a non-negative integer"
2275        ))),
2276        None => Err(CoreError::Json(format!("motionDigest.{name} is required"))),
2277    }
2278}
2279
2280/// Structural validation of a `motionDigest` object. Does not judge whether the
2281/// values are acceptable; that is policy, expressed through [`is_live`].
2282pub fn validate_motion_digest(digest: &Value) -> Result<()> {
2283    let obj = digest
2284        .as_object()
2285        .ok_or_else(|| CoreError::Json("motionDigest must be an object".into()))?;
2286
2287    for name in ["samples", "zoneBreaches", "breachCount"] {
2288        digest_non_negative_int(obj, name)?;
2289    }
2290    for name in ["maxForceN", "maxSpeedMps", "maxSpeedNearHumansMps"] {
2291        match obj.get(name) {
2292            Some(Value::Bool(_)) | None => {
2293                return Err(CoreError::Json(format!("motionDigest.{name} is required")))
2294            }
2295            Some(v) => {
2296                let n = rv::finite_number(Some(v)).ok_or_else(|| {
2297                    CoreError::Json(format!("motionDigest.{name} must be a finite number"))
2298                })?;
2299                if n < 0.0 {
2300                    return Err(CoreError::Json(format!(
2301                        "motionDigest.{name} must be non-negative"
2302                    )));
2303                }
2304            }
2305        }
2306    }
2307    let within = match obj.get("withinEnvelope") {
2308        Some(Value::Bool(b)) => *b,
2309        Some(_) => {
2310            return Err(CoreError::Json(
2311                "motionDigest.withinEnvelope must be a boolean".into(),
2312            ))
2313        }
2314        None => {
2315            return Err(CoreError::Json(
2316                "motionDigest.withinEnvelope is required".into(),
2317            ))
2318        }
2319    };
2320    let n = |k: &str| obj.get(k).and_then(|v| v.as_u64()).unwrap_or(0);
2321    if within != (n("breachCount") == 0) {
2322        return Err(CoreError::Json(
2323            "motionDigest.withinEnvelope disagrees with breachCount".into(),
2324        ));
2325    }
2326    if n("zoneBreaches") > n("breachCount") {
2327        return Err(CoreError::Json(
2328            "motionDigest.zoneBreaches exceeds breachCount".into(),
2329        ));
2330    }
2331    Ok(())
2332}
2333
2334/// The longest heartbeat cadence a verifier accepts from the heartbeat itself.
2335pub const MAX_INTERVAL_SECONDS: i64 = 3600;
2336
2337/// Parameters for [`build_robot_heartbeat`]. The robot self-issues the credential
2338/// with its own Ed25519 seed; `motion_digest` is produced by a [`MotionCollector`]
2339/// over the interval and `interval_seconds` is the declared heartbeat cadence.
2340#[derive(Debug, Clone)]
2341pub struct BuildRobotHeartbeat {
2342    pub robot_did: String,
2343    pub session_id: String,
2344    pub interval_index: i64,
2345    pub interval_seconds: i64,
2346    pub motion_digest: Value,
2347    pub valid_from: String,
2348}
2349
2350/// Build a signed `RobotHeartbeatCredential`.
2351pub fn build_robot_heartbeat(robot_seed: &[u8], params: &BuildRobotHeartbeat) -> Result<Value> {
2352    if params.interval_index < 0 {
2353        return Err(CoreError::Json(
2354            "interval_index must be non-negative".into(),
2355        ));
2356    }
2357    if params.interval_seconds <= 0 {
2358        return Err(CoreError::Json("interval_seconds must be positive".into()));
2359    }
2360    validate_motion_digest(&params.motion_digest)?;
2361
2362    let mut subject = Map::new();
2363    subject.insert("id".into(), json!(params.robot_did));
2364    subject.insert("sessionId".into(), json!(params.session_id));
2365    subject.insert("intervalIndex".into(), json!(params.interval_index));
2366    subject.insert("intervalSeconds".into(), json!(params.interval_seconds));
2367    subject.insert("motionDigest".into(), params.motion_digest.clone());
2368
2369    let mut cred = Map::new();
2370    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
2371    cred.insert(
2372        "type".into(),
2373        json!(["VerifiableCredential", ROBOT_HEARTBEAT_TYPE]),
2374    );
2375    cred.insert("issuer".into(), json!(params.robot_did));
2376    cred.insert("validFrom".into(), json!(params.valid_from));
2377    cred.insert("credentialSubject".into(), Value::Object(subject));
2378
2379    let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), &params.valid_from);
2380    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
2381}
2382
2383/// Verify a `RobotHeartbeatCredential`: the credential proof bound to the robot
2384/// as issuer (which must also be `credentialSubject.id`), a validFrom no later
2385/// than `now_iso`, and the structural validity of the embedded motion digest. Returns the subject on
2386/// success. Whether the robot is currently trusted is a separate, time-dependent
2387/// question answered by [`is_live`].
2388pub fn verify_robot_heartbeat(
2389    credential: &Value,
2390    robot_keys: Keys<'_>,
2391    now_iso: &str,
2392) -> Result<Option<Value>> {
2393    let v = match bound(
2394        credential,
2395        robot_keys,
2396        ROBOT_HEARTBEAT_TYPE,
2397        now_iso,
2398        Window::FromRequired,
2399    )? {
2400        Some(v) if issuer_is_subject(&v) => v,
2401        _ => return Ok(None),
2402    };
2403    let digest = v
2404        .subject
2405        .get("motionDigest")
2406        .cloned()
2407        .unwrap_or(Value::Null);
2408    if validate_motion_digest(&digest).is_err() {
2409        return Ok(None);
2410    }
2411    Ok(Some(v.subject))
2412}
2413
2414/// Decide whether a robot is currently trusted, given its most recent heartbeat
2415/// (verify it with [`verify_robot_heartbeat`] first). Live only when: the
2416/// heartbeat was issued within `grace_intervals` cadence periods of `now_iso`
2417/// (the cadence is the verifier's `interval_seconds` when given, else the
2418/// heartbeat's declared interval capped at [`MAX_INTERVAL_SECONDS`]); the
2419/// motion digest covers at least one sample; and the digest is well-formed and
2420/// reports withinEnvelope true. Malformed input returns `false`.
2421pub fn is_live(
2422    credential: &Value,
2423    now_iso: &str,
2424    interval_seconds: Option<i64>,
2425    grace_intervals: i64,
2426) -> Result<bool> {
2427    if grace_intervals < 1 {
2428        return Err(CoreError::Json("grace_intervals must be at least 1".into()));
2429    }
2430    let subject = match credential
2431        .get("credentialSubject")
2432        .and_then(|s| s.as_object())
2433    {
2434        Some(s) => s,
2435        None => return Ok(false),
2436    };
2437    let digest = match subject.get("motionDigest") {
2438        Some(d) if validate_motion_digest(d).is_ok() => d,
2439        _ => return Ok(false),
2440    };
2441    if digest.get("samples").and_then(|v| v.as_u64()).unwrap_or(0) == 0
2442        || digest.get("withinEnvelope") != Some(&Value::Bool(true))
2443    {
2444        return Ok(false);
2445    }
2446    let cadence = match interval_seconds {
2447        Some(c) => c,
2448        None => match rv::strict_int(subject.get("intervalSeconds")) {
2449            Some(d) if d > 0 => d.min(MAX_INTERVAL_SECONDS),
2450            _ => return Ok(false),
2451        },
2452    };
2453    if cadence <= 0 {
2454        return Ok(false);
2455    }
2456    let issued = match rv::time_ns(credential.get("validFrom")) {
2457        Some(t) => t,
2458        None => return Ok(false),
2459    };
2460    let moment = match crate::time::parse_protocol_time_ns(now_iso) {
2461        Ok(t) => t,
2462        Err(_) => return Ok(false),
2463    };
2464    let cadence_ns = i128::from(cadence) * 1_000_000_000;
2465    // A heartbeat from the future (clock skew beyond one cadence) is not trusted.
2466    if moment + cadence_ns < issued {
2467        return Ok(false);
2468    }
2469    Ok(moment <= issued + cadence_ns * i128::from(grace_intervals))
2470}
2471
2472// ---------------------------------------------------------------------------
2473// Per-credential revocation (Phase 5.8)
2474// ---------------------------------------------------------------------------
2475
2476pub use crate::status_list::{BITSTRING_STATUS_LIST_ENTRY_TYPE, STATUS_PURPOSE_REVOCATION};
2477
2478/// Build a BitstringStatusList `credentialStatus` entry referencing a bit index in
2479/// a published status list credential. Mirrors the agent-side
2480/// `status_list.build_status_list_entry`. `entry_id`, when `None`, defaults to
2481/// `{status_list_credential}#{status_list_index}`.
2482pub fn build_status_list_entry(
2483    status_list_credential: &str,
2484    status_list_index: i64,
2485    status_purpose: &str,
2486    entry_id: Option<&str>,
2487) -> Result<Value> {
2488    if !matches!(status_purpose, "revocation" | "suspension" | "message") {
2489        return Err(CoreError::Json(format!(
2490            "status_purpose must be one of revocation, suspension, message, got {status_purpose:?}"
2491        )));
2492    }
2493    if status_list_index < 0 {
2494        return Err(CoreError::Json(
2495            "status_list_index must be non-negative".into(),
2496        ));
2497    }
2498    if status_list_credential.is_empty() {
2499        return Err(CoreError::Json(
2500            "status_list_credential URL is required".into(),
2501        ));
2502    }
2503    let id = entry_id
2504        .map(String::from)
2505        .unwrap_or_else(|| format!("{status_list_credential}#{status_list_index}"));
2506    Ok(json!({
2507        "id": id,
2508        "type": BITSTRING_STATUS_LIST_ENTRY_TYPE,
2509        "statusPurpose": status_purpose,
2510        "statusListIndex": status_list_index.to_string(),
2511        "statusListCredential": status_list_credential,
2512    }))
2513}
2514
2515/// Parameters for [`attach_credential_status`].
2516#[derive(Debug, Clone)]
2517pub struct AttachCredentialStatus {
2518    pub status_list_credential: String,
2519    pub status_list_index: i64,
2520    pub status_purpose: String,
2521    pub entry_id: Option<String>,
2522    /// `validFrom`-style timestamp used as the proof `created` when re-signing.
2523    pub created: String,
2524}
2525
2526/// Add a BitstringStatusList `credentialStatus` entry to a robot credential and
2527/// re-sign it under `signer_seed`, so the proof covers the status binding. If the
2528/// credential already carries a `credentialStatus`, the new entry is appended (the
2529/// field becomes a list), matching the Verifiable Credentials data model. Any
2530/// pre-existing proof is replaced.
2531pub fn attach_credential_status(
2532    credential: &Value,
2533    signer_seed: &[u8],
2534    params: &AttachCredentialStatus,
2535) -> Result<Value> {
2536    let entry = build_status_list_entry(
2537        &params.status_list_credential,
2538        params.status_list_index,
2539        &params.status_purpose,
2540        params.entry_id.as_deref(),
2541    )?;
2542
2543    let mut obj = credential
2544        .as_object()
2545        .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
2546        .clone();
2547
2548    match obj.get("credentialStatus").cloned() {
2549        None => {
2550            obj.insert("credentialStatus".into(), entry);
2551        }
2552        Some(Value::Array(mut existing)) => {
2553            existing.push(entry);
2554            obj.insert("credentialStatus".into(), Value::Array(existing));
2555        }
2556        Some(existing) => {
2557            obj.insert("credentialStatus".into(), json!([existing, entry]));
2558        }
2559    }
2560
2561    // Re-sign: the proof must cover the credentialStatus we just added.
2562    obj.remove("proof");
2563    let issuer = obj.get("issuer").and_then(|v| v.as_str()).unwrap_or("");
2564    let opts = BuildProofOptions::new(format!("{issuer}#key-1"), &params.created);
2565    data_integrity::sign(&Value::Object(obj), signer_seed, &opts)
2566}
2567
2568fn status_entries(credential: &Value) -> Result<Vec<Value>> {
2569    match credential.get("credentialStatus") {
2570        None => Ok(Vec::new()),
2571        Some(Value::Array(a)) => Ok(a.iter().filter(|e| e.is_object()).cloned().collect()),
2572        Some(v) if v.is_object() => Ok(vec![v.clone()]),
2573        Some(_) => Err(CoreError::Json(
2574            "credentialStatus must be an object or a list of objects".into(),
2575        )),
2576    }
2577}
2578
2579/// Return `true` if the robot credential's status bit for `status_purpose` is
2580/// set in the supplied status list. Returns `false` only when the credential
2581/// carries no status entry for that purpose, or every entry for that purpose
2582/// that references this list has its bit clear (every matching entry is
2583/// checked). Errors when the credential has an entry for this purpose but none
2584/// references the supplied list (the list cannot answer), or when the list's
2585/// issuer is not the credential's issuer. The caller verifies the list's proof
2586/// first.
2587pub fn check_credential_status(
2588    credential: &Value,
2589    status_list_credential: &Value,
2590    status_purpose: &str,
2591) -> Result<bool> {
2592    check_status_inner(credential, status_list_credential, status_purpose, None)
2593}
2594
2595/// [`check_credential_status`], and the status list's own signature must
2596/// verify: issued by the issuer it names, under that issuer's key from `keys`
2597/// (see [`crate::robotics_dtn::verify_status_list_signature`]), checked at
2598/// `now_iso` with 30 s of skew. A list whose signature fails is an error.
2599pub fn check_credential_status_signed(
2600    credential: &Value,
2601    status_list_credential: &Value,
2602    status_purpose: &str,
2603    keys: Keys<'_>,
2604    now_iso: &str,
2605) -> Result<bool> {
2606    check_status_inner(
2607        credential,
2608        status_list_credential,
2609        status_purpose,
2610        Some((keys, now_iso)),
2611    )
2612}
2613
2614fn check_status_inner(
2615    credential: &Value,
2616    status_list_credential: &Value,
2617    status_purpose: &str,
2618    signed_by: Option<(Keys<'_>, &str)>,
2619) -> Result<bool> {
2620    let entries: Vec<Value> = status_entries(credential)?
2621        .into_iter()
2622        .filter(|e| e.get("statusPurpose").and_then(|v| v.as_str()) == Some(status_purpose))
2623        .collect();
2624    if entries.is_empty() {
2625        return Ok(false);
2626    }
2627    let referenced_id = status_list_credential.get("id");
2628    let matching: Vec<&Value> = entries
2629        .iter()
2630        .filter(|e| e.get("statusListCredential") == referenced_id)
2631        .collect();
2632    if matching.is_empty() {
2633        return Err(CoreError::Json(
2634            "the credential has a status entry for this purpose, but none references this list"
2635                .into(),
2636        ));
2637    }
2638    if rv::issuer_id(status_list_credential.get("issuer"))
2639        != rv::issuer_id(credential.get("issuer"))
2640    {
2641        return Err(CoreError::Json(
2642            "the status list is not from the credential's issuer".into(),
2643        ));
2644    }
2645    if let Some((keys, now_iso)) = signed_by {
2646        if !crate::robotics_dtn::verify_status_list_signature(
2647            status_list_credential,
2648            keys,
2649            now_iso,
2650            30,
2651        )? {
2652            return Err(CoreError::Json(
2653                "the status list signature does not verify".into(),
2654            ));
2655        }
2656    }
2657    for entry in matching {
2658        if crate::status_list::verify_status(entry, status_list_credential)? {
2659            return Ok(true);
2660        }
2661    }
2662    Ok(false)
2663}
2664
2665// ---------------------------------------------------------------------------
2666// Accountable safety record (Phase 5.9)
2667// ---------------------------------------------------------------------------
2668
2669pub const SAFETY_RECORD_TYPE: &str = "RobotSafetyRecordCredential";
2670pub const SAFETY_LOG_VERSION: &str = "1.0";
2671
2672/// Standard safety event types: the interoperable set a verifier and an insurer
2673/// can rely on. Implementers MAY use additional types.
2674pub const EVENT_TYPES: [&str; 6] = [
2675    "incident",
2676    "near_miss",
2677    "manual_override",
2678    "kill_switch",
2679    "envelope_breach",
2680    "maintenance",
2681];
2682
2683/// Severity bands, ordered from least to most serious.
2684pub const SEVERITIES: [&str; 5] = ["info", "low", "medium", "high", "critical"];
2685
2686/// Append-only, plaintext, hash-linked safety event ledger. Reuses the black-box
2687/// chain semantics ([`entry_hash`], [`genesis_prev_hash`]) so the two logs verify
2688/// the same way, but entries are plaintext: a safety record is meant to be read
2689/// and trusted by third parties.
2690pub struct SafetyEventLog {
2691    genesis: String,
2692    entries: Vec<Value>,
2693    head: String,
2694}
2695
2696impl SafetyEventLog {
2697    /// Build a log. A `None` genesis uses [`genesis_prev_hash`].
2698    pub fn new(genesis_prev_hash_override: Option<&str>) -> Self {
2699        let genesis = genesis_prev_hash_override
2700            .map(String::from)
2701            .unwrap_or_else(genesis_prev_hash);
2702        Self {
2703            head: genesis.clone(),
2704            genesis,
2705            entries: Vec::new(),
2706        }
2707    }
2708
2709    /// Append one safety event, link it to the chain head, and return the entry.
2710    pub fn append(
2711        &mut self,
2712        event_type: &str,
2713        severity: &str,
2714        details: Option<&Value>,
2715        actor: Option<&str>,
2716        timestamp: &str,
2717    ) -> Result<Value> {
2718        if !EVENT_TYPES.contains(&event_type) {
2719            return Err(CoreError::Json(format!(
2720                "event_type must be one of {EVENT_TYPES:?}, got {event_type:?}"
2721            )));
2722        }
2723        if !SEVERITIES.contains(&severity) {
2724            return Err(CoreError::Json(format!(
2725                "severity must be one of {SEVERITIES:?}, got {severity:?}"
2726            )));
2727        }
2728
2729        let mut body = Map::new();
2730        body.insert("version".into(), json!(SAFETY_LOG_VERSION));
2731        body.insert("seq".into(), json!(self.entries.len() as u64));
2732        body.insert("timestamp".into(), json!(timestamp));
2733        body.insert("eventType".into(), json!(event_type));
2734        body.insert("severity".into(), json!(severity));
2735        body.insert("prevHash".into(), json!(self.head));
2736        if let Some(d) = details {
2737            body.insert("details".into(), d.clone());
2738        }
2739        if let Some(a) = actor {
2740            body.insert("actor".into(), json!(a));
2741        }
2742        let h = entry_hash(&body)?;
2743        body.insert("entryHash".into(), json!(h));
2744        self.head = h;
2745        let entry = Value::Object(body);
2746        self.entries.push(entry.clone());
2747        Ok(entry)
2748    }
2749
2750    pub fn head(&self) -> &str {
2751        &self.head
2752    }
2753
2754    pub fn genesis(&self) -> &str {
2755        &self.genesis
2756    }
2757
2758    pub fn entries(&self) -> &[Value] {
2759        &self.entries
2760    }
2761
2762    /// Produce a summary object for embedding in a safety-record credential.
2763    pub fn summarize(&self) -> Value {
2764        summarize_entries(&self.entries, Some(&self.head))
2765    }
2766}
2767
2768/// Verify the hash chain over the ledger entries. Tamper-evident. Shares the
2769/// black-box chain verifier so the two logs verify identically.
2770pub fn verify_safety_log(
2771    entries: &[Value],
2772    genesis_prev_hash_override: Option<&str>,
2773) -> ChainResult {
2774    verify_blackbox_chain(entries, genesis_prev_hash_override)
2775}
2776
2777/// Summarize ledger entries into counts by event type (sorted) and by severity
2778/// (info..critical), the total event count, and (when supplied) the ledger head
2779/// hash that anchors the summary to a specific chain state.
2780pub fn summarize_entries(entries: &[Value], head: Option<&str>) -> Value {
2781    let mut sorted_types: Vec<&str> = EVENT_TYPES.to_vec();
2782    sorted_types.sort_unstable();
2783
2784    let mut event_counts = Map::new();
2785    for t in &sorted_types {
2786        event_counts.insert((*t).to_string(), json!(0));
2787    }
2788    let mut severity_counts = Map::new();
2789    for s in SEVERITIES {
2790        severity_counts.insert(s.to_string(), json!(0));
2791    }
2792
2793    for e in entries {
2794        if let Some(et) = e.get("eventType").and_then(|v| v.as_str()) {
2795            if let Some(c) = event_counts.get_mut(et).and_then(|v| v.as_u64()) {
2796                event_counts.insert(et.to_string(), json!(c + 1));
2797            }
2798        }
2799        if let Some(sv) = e.get("severity").and_then(|v| v.as_str()) {
2800            if let Some(c) = severity_counts.get_mut(sv).and_then(|v| v.as_u64()) {
2801                severity_counts.insert(sv.to_string(), json!(c + 1));
2802            }
2803        }
2804    }
2805
2806    let mut summary = Map::new();
2807    summary.insert("eventCounts".into(), Value::Object(event_counts));
2808    summary.insert("severityCounts".into(), Value::Object(severity_counts));
2809    summary.insert("totalEvents".into(), json!(entries.len() as u64));
2810    if let Some(h) = head {
2811        summary.insert("logHead".into(), json!(h));
2812    }
2813    Value::Object(summary)
2814}
2815
2816/// Structural validation of a safety summary.
2817pub fn validate_safety_summary(summary: &Value) -> Result<()> {
2818    let obj = summary
2819        .as_object()
2820        .ok_or_else(|| CoreError::Json("summary must be an object".into()))?;
2821    for name in ["eventCounts", "severityCounts"] {
2822        let block = obj
2823            .get(name)
2824            .and_then(|v| v.as_object())
2825            .ok_or_else(|| CoreError::Json(format!("summary.{name} must be an object")))?;
2826        for (k, v) in block {
2827            let ok = v.is_u64() || v.as_i64().map(|i| i >= 0).unwrap_or(false);
2828            if v.is_boolean() || !ok {
2829                return Err(CoreError::Json(format!(
2830                    "summary.{name}[{k:?}] must be a non-negative integer"
2831                )));
2832            }
2833        }
2834    }
2835    let total_ok = obj
2836        .get("totalEvents")
2837        .map(|v| (v.is_u64() || v.as_i64().map(|i| i >= 0).unwrap_or(false)) && !v.is_boolean())
2838        .unwrap_or(false);
2839    if !total_ok {
2840        return Err(CoreError::Json(
2841            "summary.totalEvents must be a non-negative integer".into(),
2842        ));
2843    }
2844    Ok(())
2845}
2846
2847/// Parameters for [`build_safety_record`]. The issuer (an owner, an auditor, or
2848/// the robot itself) attests `summary`, produced by [`SafetyEventLog::summarize`]
2849/// or [`summarize_entries`].
2850#[derive(Debug, Clone)]
2851pub struct BuildSafetyRecord {
2852    pub issuer_did: String,
2853    pub robot_did: String,
2854    pub summary: Value,
2855    pub period_start: Option<String>,
2856    pub period_end: Option<String>,
2857    pub valid_from: String,
2858    pub valid_until: Option<String>,
2859}
2860
2861/// Build a signed `RobotSafetyRecordCredential` summarizing a robot's safety
2862/// ledger.
2863pub fn build_safety_record(signer_seed: &[u8], params: &BuildSafetyRecord) -> Result<Value> {
2864    validate_safety_summary(&params.summary)?;
2865
2866    let mut subject = Map::new();
2867    subject.insert("id".into(), json!(params.robot_did));
2868    if let Some(s) = params.summary.as_object() {
2869        for (k, v) in s {
2870            subject.insert(k.clone(), v.clone());
2871        }
2872    }
2873    if params.period_start.is_some() || params.period_end.is_some() {
2874        let mut period = Map::new();
2875        if let Some(start) = &params.period_start {
2876            period.insert("start".into(), json!(start));
2877        }
2878        if let Some(end) = &params.period_end {
2879            period.insert("end".into(), json!(end));
2880        }
2881        subject.insert("period".into(), Value::Object(period));
2882    }
2883
2884    let mut cred = Map::new();
2885    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
2886    cred.insert(
2887        "type".into(),
2888        json!(["VerifiableCredential", SAFETY_RECORD_TYPE]),
2889    );
2890    cred.insert("issuer".into(), json!(params.issuer_did));
2891    cred.insert("validFrom".into(), json!(params.valid_from));
2892    if let Some(vu) = &params.valid_until {
2893        cred.insert("validUntil".into(), json!(vu));
2894    }
2895    cred.insert("credentialSubject".into(), Value::Object(subject));
2896
2897    let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), &params.valid_from);
2898    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
2899}
2900
2901/// Options for [`verify_safety_record`].
2902#[derive(Default, Clone, Copy)]
2903pub struct SafetyRecordCheck<'a> {
2904    /// The ledger entries: they must link, end at the summary's `logHead` with
2905    /// exactly `totalEvents` entries, and reproduce the summary's counts.
2906    pub entries: Option<&'a [Value]>,
2907    /// The record must be about this robot.
2908    pub robot_did: Option<&'a str>,
2909    /// The issuer must be in this set.
2910    pub trusted_issuers: Option<&'a HashSet<String>>,
2911}
2912
2913/// Verify a `RobotSafetyRecordCredential`: the issuer's proof bound to the
2914/// issuer, the validity window at `now_iso` (validFrom required), and the
2915/// structure of the embedded summary, plus the [`SafetyRecordCheck`] options.
2916/// Returns the credentialSubject on success.
2917pub fn verify_safety_record(
2918    credential: &Value,
2919    keys: Keys<'_>,
2920    check: SafetyRecordCheck<'_>,
2921    now_iso: &str,
2922) -> Result<Option<Value>> {
2923    let now = rv::require_now(now_iso)?;
2924    let opts = VerifyOptions {
2925        trusted_issuers: check.trusted_issuers,
2926        ..VerifyOptions::window(Window::FromRequired)
2927    };
2928    let v =
2929        match rv::verify_robotics_credential(credential, keys, Some(SAFETY_RECORD_TYPE), now, opts)
2930        {
2931            Ok(v) => v,
2932            Err(_) => return Ok(None),
2933        };
2934    let subject = v.subject;
2935    if validate_safety_summary(&subject).is_err() {
2936        return Ok(None);
2937    }
2938    if let Some(robot) = check.robot_did {
2939        if subject.get("id").and_then(|x| x.as_str()) != Some(robot) {
2940            return Ok(None);
2941        }
2942    }
2943    if let Some(entries) = check.entries {
2944        if !verify_chain_against_head(
2945            entries,
2946            subject.get("logHead"),
2947            subject.get("totalEvents"),
2948            None,
2949        )
2950        .ok
2951        {
2952            return Ok(None);
2953        }
2954        let recount = summarize_entries(entries, None);
2955        if recount.get("eventCounts") != subject.get("eventCounts")
2956            || recount.get("severityCounts") != subject.get("severityCounts")
2957        {
2958            return Ok(None);
2959        }
2960    }
2961    Ok(Some(subject))
2962}
2963
2964// ---------------------------------------------------------------------------
2965// Perception provenance (Phase 5.10)
2966// ---------------------------------------------------------------------------
2967
2968pub const PERCEPTION_TYPE: &str = "PerceptionProvenanceCredential";
2969pub const PERCEPTION_LOG_VERSION: &str = "1.0";
2970
2971/// Standard sensor modalities: the interoperable set a verifier can rely on.
2972/// Implementers MAY use additional values.
2973pub const MODALITIES: [&str; 6] = ["camera", "lidar", "radar", "depth", "audio", "thermal"];
2974
2975/// Multibase (base64url) SHA-256 of a raw sensor frame. Only the hash travels in
2976/// the log and the attestation; the frame stays wherever the deployment keeps it.
2977pub fn hash_frame(frame: &[u8]) -> String {
2978    mb64(&Sha256::digest(frame))
2979}
2980
2981/// Append-only, plaintext, hash-linked log of sensor-frame provenance records.
2982/// Reuses the black-box chain semantics ([`entry_hash`], [`genesis_prev_hash`]),
2983/// so a perception log verifies the same way as the safety ledger. Each entry
2984/// binds a sequence number, a timestamp, the sensor id, the modality, the frame
2985/// hash, and the hash of the previous entry; the frames are not stored.
2986pub struct PerceptionLog {
2987    genesis: String,
2988    entries: Vec<Value>,
2989    head: String,
2990}
2991
2992impl PerceptionLog {
2993    /// Build a log. A `None` genesis uses [`genesis_prev_hash`].
2994    pub fn new(genesis_prev_hash_override: Option<&str>) -> Self {
2995        let genesis = genesis_prev_hash_override
2996            .map(String::from)
2997            .unwrap_or_else(genesis_prev_hash);
2998        Self {
2999            head: genesis.clone(),
3000            genesis,
3001            entries: Vec::new(),
3002        }
3003    }
3004
3005    /// Append one frame-provenance record, link it to the chain head, and return
3006    /// the entry. Provide either the raw `frame` (it is hashed) or a precomputed
3007    /// `frame_hash`, not both.
3008    pub fn record(
3009        &mut self,
3010        sensor_id: &str,
3011        modality: &str,
3012        frame: Option<&[u8]>,
3013        frame_hash: Option<&str>,
3014        timestamp: &str,
3015    ) -> Result<Value> {
3016        if !MODALITIES.contains(&modality) {
3017            return Err(CoreError::Json(format!(
3018                "modality must be one of {MODALITIES:?}, got {modality:?}"
3019            )));
3020        }
3021        if sensor_id.is_empty() {
3022            return Err(CoreError::Json("sensor_id is required".into()));
3023        }
3024        if frame.is_some() && frame_hash.is_some() {
3025            return Err(CoreError::Json(
3026                "provide either frame or frame_hash, not both".into(),
3027            ));
3028        }
3029        let resolved = match (frame, frame_hash) {
3030            (Some(f), None) => hash_frame(f),
3031            (None, Some(h)) if !h.is_empty() => h.to_string(),
3032            _ => return Err(CoreError::Json("frame or frame_hash is required".into())),
3033        };
3034
3035        let mut body = Map::new();
3036        body.insert("version".into(), json!(PERCEPTION_LOG_VERSION));
3037        body.insert("seq".into(), json!(self.entries.len() as u64));
3038        body.insert("timestamp".into(), json!(timestamp));
3039        body.insert("sensorId".into(), json!(sensor_id));
3040        body.insert("modality".into(), json!(modality));
3041        body.insert("frameHash".into(), json!(resolved));
3042        body.insert("prevHash".into(), json!(self.head));
3043        let h = entry_hash(&body)?;
3044        body.insert("entryHash".into(), json!(h));
3045        self.head = h;
3046        let entry = Value::Object(body);
3047        self.entries.push(entry.clone());
3048        Ok(entry)
3049    }
3050
3051    pub fn head(&self) -> &str {
3052        &self.head
3053    }
3054
3055    pub fn genesis(&self) -> &str {
3056        &self.genesis
3057    }
3058
3059    pub fn entries(&self) -> &[Value] {
3060        &self.entries
3061    }
3062
3063    /// The number of records, the count a perception attestation anchors.
3064    pub fn count(&self) -> usize {
3065        self.entries.len()
3066    }
3067}
3068
3069/// Verify the hash chain over the perception log entries. Tamper-evident. Shares
3070/// the black-box chain verifier so every hash-linked log verifies identically.
3071pub fn verify_perception_log(
3072    entries: &[Value],
3073    genesis_prev_hash_override: Option<&str>,
3074) -> ChainResult {
3075    verify_blackbox_chain(entries, genesis_prev_hash_override)
3076}
3077
3078/// Parameters for [`build_perception_attestation`]. The robot self-issues the
3079/// credential with its own Ed25519 seed. `captured_at`, when `None`, defaults to
3080/// `valid_from`. When `log_head` is supplied, the attestation also anchors the
3081/// segment of frames up to that chain head.
3082#[derive(Debug, Clone)]
3083pub struct BuildPerception {
3084    pub robot_did: String,
3085    pub sensor_id: String,
3086    pub modality: String,
3087    pub frame_hash: String,
3088    pub captured_at: Option<String>,
3089    pub log_head: Option<String>,
3090    /// The number of log entries up to `log_head`, so a verifier can tell a
3091    /// segment was not cut short.
3092    pub log_count: Option<u64>,
3093    pub valid_from: String,
3094    pub valid_until: Option<String>,
3095}
3096
3097/// Build a signed `PerceptionProvenanceCredential` attesting that a robot's sensor
3098/// captured a specific frame. Software frame-hash signing: the robot signs the
3099/// provenance of the captured frame with its own key.
3100pub fn build_perception_attestation(robot_seed: &[u8], params: &BuildPerception) -> Result<Value> {
3101    if !MODALITIES.contains(&params.modality.as_str()) {
3102        return Err(CoreError::Json(format!(
3103            "modality must be one of {MODALITIES:?}, got {:?}",
3104            params.modality
3105        )));
3106    }
3107    if params.frame_hash.is_empty() {
3108        return Err(CoreError::Json("frame_hash is required".into()));
3109    }
3110
3111    let captured = params
3112        .captured_at
3113        .clone()
3114        .unwrap_or_else(|| params.valid_from.clone());
3115
3116    let mut subject = Map::new();
3117    subject.insert("id".into(), json!(params.robot_did));
3118    subject.insert("sensorId".into(), json!(params.sensor_id));
3119    subject.insert("modality".into(), json!(params.modality));
3120    subject.insert("frameHash".into(), json!(params.frame_hash));
3121    subject.insert("capturedAt".into(), json!(captured));
3122    if let Some(head) = &params.log_head {
3123        subject.insert("logHead".into(), json!(head));
3124    }
3125    if let Some(n) = params.log_count {
3126        subject.insert("logCount".into(), json!(n));
3127    }
3128
3129    let mut cred = Map::new();
3130    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
3131    cred.insert(
3132        "type".into(),
3133        json!(["VerifiableCredential", PERCEPTION_TYPE]),
3134    );
3135    cred.insert("issuer".into(), json!(params.robot_did));
3136    cred.insert("validFrom".into(), json!(params.valid_from));
3137    if let Some(vu) = &params.valid_until {
3138        cred.insert("validUntil".into(), json!(vu));
3139    }
3140    cred.insert("credentialSubject".into(), Value::Object(subject));
3141
3142    let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), &params.valid_from);
3143    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
3144}
3145
3146/// Verify a `PerceptionProvenanceCredential`: the robot's proof and, when the raw
3147/// `frame` is supplied, that its hash reproduces the attested `frameHash`. Returns
3148/// the credentialSubject on success, `None` if invalid.
3149pub fn verify_perception_attestation(
3150    credential: &Value,
3151    keys: Keys<'_>,
3152    frame: Option<&[u8]>,
3153    now_iso: &str,
3154) -> Result<Option<Value>> {
3155    let v = match bound(
3156        credential,
3157        keys,
3158        PERCEPTION_TYPE,
3159        now_iso,
3160        Window::FromRequired,
3161    )? {
3162        Some(v) if issuer_is_subject(&v) => v,
3163        _ => return Ok(None),
3164    };
3165    let frame_hash = v.subject.get("frameHash").and_then(|v| v.as_str());
3166    let modality = v.subject.get("modality").and_then(|v| v.as_str());
3167    match (frame_hash, modality) {
3168        (Some(fh), Some(m)) if !fh.is_empty() && MODALITIES.contains(&m) => {}
3169        _ => return Ok(None),
3170    }
3171    if let Some(f) = frame {
3172        if hash_frame(f) != frame_hash.unwrap_or("") {
3173            return Ok(None);
3174        }
3175    }
3176    Ok(Some(v.subject))
3177}
3178
3179/// Verify a perception log against the robot's signed head: the attestation
3180/// must verify and carry `logHead` and `logCount`, and the log must link and
3181/// end at that head with exactly that many entries.
3182pub fn verify_perception_segment(
3183    entries: &[Value],
3184    attestation: &Value,
3185    keys: Keys<'_>,
3186    genesis_prev_hash_override: Option<&str>,
3187    now_iso: &str,
3188) -> Result<ChainResult> {
3189    let subject = match verify_perception_attestation(attestation, keys, None, now_iso)? {
3190        Some(s) => s,
3191        None => {
3192            return Ok(ChainResult {
3193                ok: false,
3194                reason: Some("attestation does not verify".into()),
3195            })
3196        }
3197    };
3198    if subject.get("logHead").is_none() || subject.get("logCount").is_none() {
3199        return Ok(ChainResult {
3200            ok: false,
3201            reason: Some("attestation does not anchor a log head and count".into()),
3202        });
3203    }
3204    Ok(verify_chain_against_head(
3205        entries,
3206        subject.get("logHead"),
3207        subject.get("logCount"),
3208        genesis_prev_hash_override,
3209    ))
3210}
3211
3212// ---------------------------------------------------------------------------
3213// Delegation lease (Phase 5.11)
3214// ---------------------------------------------------------------------------
3215
3216pub const DELEGATION_LEASE_TYPE: &str = "DelegationLeaseCredential";
3217
3218/// Parameters for [`build_delegation_lease`]. The issuer is the signer (an
3219/// authority or the holder of a parent lease); `robot_did` is the subject the
3220/// lease is granted to. `scope` is a physicalScope object (the same shape as a
3221/// `PhysicalCapabilityScope` credentialSubject.physicalScope). Leases are
3222/// short-lived by design, so the window is bounded by `valid_from`/`valid_until`.
3223/// Set `parent_lease_id` when sub-granting from another lease.
3224#[derive(Debug, Clone)]
3225pub struct BuildDelegationLease {
3226    pub issuer_did: String,
3227    pub robot_did: String,
3228    pub lease_id: String,
3229    pub scope: Value,
3230    pub parent_lease_id: Option<String>,
3231    pub valid_from: String,
3232    pub valid_until: String,
3233}
3234
3235/// Build a signed `DelegationLeaseCredential` granting `robot_did` a bounded
3236/// physical scope for a fixed window. The window is verifiable entirely offline.
3237pub fn build_delegation_lease(signer_seed: &[u8], params: &BuildDelegationLease) -> Result<Value> {
3238    if params.lease_id.is_empty() {
3239        return Err(CoreError::Json("lease_id is required".into()));
3240    }
3241    if !params.scope.is_object() {
3242        return Err(CoreError::Json(
3243            "scope must be a physicalScope object".into(),
3244        ));
3245    }
3246
3247    let mut subject = Map::new();
3248    subject.insert("id".into(), json!(params.robot_did));
3249    subject.insert("leaseId".into(), json!(params.lease_id));
3250    subject.insert("physicalScope".into(), params.scope.clone());
3251    if let Some(parent) = &params.parent_lease_id {
3252        subject.insert("parentLeaseId".into(), json!(parent));
3253    }
3254
3255    let mut cred = Map::new();
3256    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
3257    cred.insert(
3258        "type".into(),
3259        json!(["VerifiableCredential", DELEGATION_LEASE_TYPE]),
3260    );
3261    cred.insert("issuer".into(), json!(params.issuer_did));
3262    cred.insert("validFrom".into(), json!(params.valid_from));
3263    cred.insert("validUntil".into(), json!(params.valid_until));
3264    cred.insert("credentialSubject".into(), Value::Object(subject));
3265
3266    let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), &params.valid_from);
3267    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
3268}
3269
3270/// Verify a `DelegationLeaseCredential` offline: the issuer's proof bound to the
3271/// issuer (`keys` is a `{did: key}` source, or the bare key of a did:key
3272/// issuer), validFrom and validUntil both present with `now_iso` inside, the
3273/// lease is for `expected_robot` (required), it carries a `leaseId` and a
3274/// well-formed scope, the issuer is in `trusted_issuers` when given, and (when
3275/// `parent_scope` is supplied) the scope attenuates the parent. Returns the
3276/// credentialSubject on success, `None` if invalid.
3277pub fn verify_delegation_lease(
3278    credential: &Value,
3279    keys: Keys<'_>,
3280    expected_robot: &str,
3281    parent_scope: Option<&Value>,
3282    trusted_issuers: Option<&HashSet<String>>,
3283    now_iso: &str,
3284) -> Result<Option<Value>> {
3285    if expected_robot.is_empty() {
3286        return Err(CoreError::Json("expected_robot is required".into()));
3287    }
3288    let now = rv::require_now(now_iso)?;
3289    let opts = VerifyOptions {
3290        trusted_issuers,
3291        ..VerifyOptions::window(Window::Required)
3292    };
3293    let v = match rv::verify_robotics_credential(
3294        credential,
3295        keys,
3296        Some(DELEGATION_LEASE_TYPE),
3297        now,
3298        opts,
3299    ) {
3300        Ok(v) => v,
3301        Err(_) => return Ok(None),
3302    };
3303    if v.subject.get("id").and_then(|x| x.as_str()) != Some(expected_robot)
3304        || non_empty_str(&v.subject, "leaseId").is_none()
3305    {
3306        return Ok(None);
3307    }
3308    let scope = match v.subject.get("physicalScope") {
3309        Some(sc) if sc.is_object() && scope_problems(sc).is_empty() => sc,
3310        _ => return Ok(None),
3311    };
3312    if parent_scope.is_some_and(|p| !attenuates(p, scope)) {
3313        return Ok(None);
3314    }
3315    Ok(Some(v.subject))
3316}
3317
3318/// Verify a chain of leases from a trusted root down to `expected_robot`
3319/// (`leases` runs root to leaf). The root is issued by one of `root_issuers`
3320/// and has no `parentLeaseId`; each later lease names the previous `leaseId`
3321/// as its `parentLeaseId`, is issued by the party the previous lease was
3322/// granted to, has a window inside the previous window, and attenuates the
3323/// previous scope. Every lease is current at `now_iso`; the leaf is for
3324/// `expected_robot`. Returns the leaf subject on success.
3325pub fn verify_lease_chain(
3326    leases: &[Value],
3327    keys: Keys<'_>,
3328    expected_robot: &str,
3329    root_issuers: &HashSet<String>,
3330    now_iso: &str,
3331) -> Result<Option<Value>> {
3332    rv::require_now(now_iso)?;
3333    if leases.is_empty() || root_issuers.is_empty() {
3334        return Ok(None);
3335    }
3336    let mut prev: Option<(&Value, Value)> = None;
3337    for (i, lease) in leases.iter().enumerate() {
3338        let holder = lease
3339            .get("credentialSubject")
3340            .and_then(|s| s.get("id"))
3341            .and_then(|v| v.as_str())
3342            .unwrap_or("");
3343        let target = if i + 1 == leases.len() {
3344            expected_robot
3345        } else {
3346            holder
3347        };
3348        if target.is_empty() {
3349            return Ok(None);
3350        }
3351        let parent_scope = prev.as_ref().and_then(|(_, ps)| ps.get("physicalScope"));
3352        // The root must be one of `root_issuers`; each child must be issued by
3353        // the holder the verified parent names. Both are named sets, so did:key
3354        // parties verify under their own keys with no key source.
3355        let holder_set: HashSet<String> = prev
3356            .as_ref()
3357            .and_then(|(_, ps)| ps.get("id"))
3358            .and_then(|v| v.as_str())
3359            .filter(|h| !h.is_empty())
3360            .map(|h| [h.to_string()].into_iter().collect())
3361            .unwrap_or_default();
3362        let subject = match verify_delegation_lease(
3363            lease,
3364            keys,
3365            target,
3366            parent_scope,
3367            Some(if prev.is_none() {
3368                root_issuers
3369            } else {
3370                &holder_set
3371            }),
3372            now_iso,
3373        )? {
3374            Some(s) => s,
3375            None => return Ok(None),
3376        };
3377        match &prev {
3378            Some((p_lease, p_sub)) => {
3379                if subject.get("parentLeaseId") != p_sub.get("leaseId") {
3380                    return Ok(None);
3381                }
3382                if rv::issuer_id(lease.get("issuer")) != p_sub.get("id").and_then(|v| v.as_str()) {
3383                    return Ok(None);
3384                }
3385                let t = |c: &Value, k: &str| rv::time_ns(c.get(k));
3386                if t(lease, "validFrom") < t(p_lease, "validFrom")
3387                    || t(lease, "validUntil") > t(p_lease, "validUntil")
3388                {
3389                    return Ok(None);
3390                }
3391            }
3392            None => {
3393                if subject.get("parentLeaseId").is_some() {
3394                    return Ok(None);
3395                }
3396            }
3397        }
3398        prev = Some((lease, subject));
3399    }
3400    Ok(prev.map(|(_, s)| s))
3401}
3402
3403/// Decide whether a verified lease permits a proposed physical action. The full
3404/// lease `credential` is required and is verified again here (`keys` and
3405/// `trusted_issuers` as in [`verify_delegation_lease`], with `subject.id` as the
3406/// expected robot), so its window is read from signed data: a copy with a
3407/// re-dated `validUntil` no longer verifies. Its subject must equal `subject`,
3408/// its window must contain `now_iso`, and the action must fit the scope.
3409pub fn lease_permits(
3410    subject: &Value,
3411    action: &PhysicalAction,
3412    credential: Option<&Value>,
3413    keys: Keys<'_>,
3414    trusted_issuers: Option<&HashSet<String>>,
3415    now_iso: &str,
3416) -> Result<bool> {
3417    let now = rv::require_now(now_iso)?;
3418    let cred = match credential {
3419        Some(c) if c.is_object() && subject.is_object() => c,
3420        _ => return Ok(false),
3421    };
3422    let robot = match subject.get("id").and_then(|v| v.as_str()) {
3423        Some(r) if !r.is_empty() => r,
3424        _ => return Ok(false),
3425    };
3426    match verify_delegation_lease(cred, keys, robot, None, trusted_issuers, now_iso)? {
3427        Some(v) if &v == subject => {}
3428        _ => return Ok(false),
3429    }
3430    if rv::window_reason(cred, Window::Required, now, 0).is_some() {
3431        return Ok(false);
3432    }
3433    match subject.get("physicalScope") {
3434        Some(scope) if scope.is_object() => Ok(check_physical_action(scope, action).ok),
3435        _ => Ok(false),
3436    }
3437}
3438
3439// ---------------------------------------------------------------------------
3440// Physical quorum (Phase 5.12)
3441// ---------------------------------------------------------------------------
3442
3443pub const ACTION_APPROVAL_TYPE: &str = "PhysicalActionApprovalCredential";
3444pub const APPROVE: &str = "approve";
3445pub const REJECT: &str = "reject";
3446/// How long an approval lasts when its builder gives no end.
3447pub const DEFAULT_APPROVAL_SECONDS: i64 = 300;
3448/// The longest approval lifetime a verifier accepts.
3449pub const MAX_APPROVAL_SECONDS: i64 = 900;
3450
3451/// Parameters for [`build_action_approval`]. The approver is the signer; the
3452/// approval is over a specific physical action `action_id` that `robot_did`
3453/// would perform. `decision` is "approve" or "reject".
3454#[derive(Debug, Clone)]
3455pub struct BuildActionApproval {
3456    pub approver_did: String,
3457    pub action_id: String,
3458    pub robot_did: String,
3459    pub decision: String,
3460    pub valid_from: String,
3461    pub valid_until: Option<String>,
3462}
3463
3464/// Build a signed `PhysicalActionApprovalCredential` by one approver for a
3465/// specific physical action.
3466pub fn build_action_approval(approver_seed: &[u8], params: &BuildActionApproval) -> Result<Value> {
3467    if params.decision != APPROVE && params.decision != REJECT {
3468        return Err(CoreError::Json(format!(
3469            "decision must be {APPROVE:?} or {REJECT:?}, got {:?}",
3470            params.decision
3471        )));
3472    }
3473    if params.action_id.is_empty() {
3474        return Err(CoreError::Json("action_id is required".into()));
3475    }
3476
3477    let mut subject = Map::new();
3478    subject.insert("id".into(), json!(params.approver_did));
3479    subject.insert("actionId".into(), json!(params.action_id));
3480    subject.insert("robotDid".into(), json!(params.robot_did));
3481    subject.insert("decision".into(), json!(params.decision));
3482
3483    let mut cred = Map::new();
3484    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
3485    cred.insert(
3486        "type".into(),
3487        json!(["VerifiableCredential", ACTION_APPROVAL_TYPE]),
3488    );
3489    cred.insert("issuer".into(), json!(params.approver_did));
3490    cred.insert("validFrom".into(), json!(params.valid_from));
3491    // An approval is short-lived: without an explicit end it lasts
3492    // DEFAULT_APPROVAL_SECONDS, and a verifier refuses one without validUntil.
3493    let valid_until = match &params.valid_until {
3494        Some(vu) => vu.clone(),
3495        None => crate::time::epoch_seconds_to_iso(
3496            crate::time::iso_to_epoch_seconds(&params.valid_from)? + DEFAULT_APPROVAL_SECONDS,
3497        ),
3498    };
3499    cred.insert("validUntil".into(), json!(valid_until));
3500    cred.insert("credentialSubject".into(), Value::Object(subject));
3501
3502    let opts = BuildProofOptions::new(format!("{}#key-1", params.approver_did), &params.valid_from);
3503    data_integrity::sign(&Value::Object(cred), approver_seed, &opts)
3504}
3505
3506/// One approver's public key, looked up by issuer DID, for
3507/// [`verify_action_authorization`].
3508#[derive(Debug, Clone)]
3509pub struct ApproverKey {
3510    pub did: String,
3511    pub public_key: Vec<u8>,
3512}
3513
3514/// Verify that a high-consequence physical action is authorized by a quorum.
3515///
3516/// Each approval must carry a proof bound to its issuer and verified with the
3517/// issuer's key from `approver_keys`, name the issuer as its subject, match
3518/// `action_id` and `robot_did`, and carry both validFrom and validUntil with
3519/// `now_iso` inside and a lifetime of at most [`MAX_APPROVAL_SECONDS`]. When
3520/// `approver_set` is supplied, the approver must be in it. Each approver's
3521/// latest decision counts (at the same instant a rejection wins); any latest
3522/// rejection vetoes the action. Otherwise it is authorized when at least
3523/// `threshold` approvers with DISTINCT signing keys approve: two DIDs mapped to
3524/// the same key count once. Returns `(authorized, sorted approving DIDs)`.
3525pub fn verify_action_authorization(
3526    approvals: &[Value],
3527    action_id: &str,
3528    robot_did: &str,
3529    approver_keys: &[ApproverKey],
3530    threshold: i64,
3531    approver_set: Option<&HashSet<String>>,
3532    now_iso: &str,
3533) -> Result<(bool, Vec<String>)> {
3534    if threshold < 1 {
3535        return Err(CoreError::Json("threshold must be at least 1".into()));
3536    }
3537    let now = rv::require_now(now_iso)?;
3538    let map: std::collections::BTreeMap<String, Vec<u8>> =
3539        Keys::map_of(approver_keys.iter().map(|k| (k.did.clone(), &k.public_key)));
3540    let keys = Keys::Map(&map);
3541
3542    // The approver set is a named member set: with no key on file, its
3543    // did:key members verify under their own keys. A freshly minted did:key
3544    // is never an approver by itself.
3545    let opts = VerifyOptions {
3546        trusted_issuers: approver_set,
3547        ..VerifyOptions::window(Window::Required)
3548    };
3549    let mut latest: std::collections::BTreeMap<String, (i128, bool)> =
3550        std::collections::BTreeMap::new();
3551    for approval in approvals {
3552        let mut early = false;
3553        let v = match rv::verify_robotics_credential(
3554            approval,
3555            keys,
3556            Some(ACTION_APPROVAL_TYPE),
3557            now,
3558            opts,
3559        ) {
3560            Ok(v) if issuer_is_subject(&v) => v,
3561            Err(why) if why == "credential window: not_yet_valid" => {
3562                // A rejection dated slightly ahead of the verifier's clock
3563                // still vetoes: re-check everything else at its own start. An
3564                // early approval never counts.
3565                let at = match rv::time_ns(approval.get("validFrom")) {
3566                    Some(t) => t,
3567                    None => continue,
3568                };
3569                match rv::verify_robotics_credential(
3570                    approval,
3571                    keys,
3572                    Some(ACTION_APPROVAL_TYPE),
3573                    at,
3574                    opts,
3575                ) {
3576                    Ok(v) if issuer_is_subject(&v) => {
3577                        early = true;
3578                        v
3579                    }
3580                    _ => continue,
3581                }
3582            }
3583            _ => continue,
3584        };
3585        if v.subject.get("actionId").and_then(|x| x.as_str()) != Some(action_id)
3586            || v.subject.get("robotDid").and_then(|x| x.as_str()) != Some(robot_did)
3587        {
3588            continue;
3589        }
3590        let reject = match v.subject.get("decision").and_then(|x| x.as_str()) {
3591            Some(APPROVE) => false,
3592            Some(REJECT) => true,
3593            _ => continue,
3594        };
3595        if early && !reject {
3596            continue;
3597        }
3598        if let Some(set) = approver_set {
3599            if !set.contains(&v.issuer) {
3600                continue;
3601            }
3602        }
3603        let (start, end) = match (
3604            rv::time_ns(approval.get("validFrom")),
3605            rv::time_ns(approval.get("validUntil")),
3606        ) {
3607            (Some(a), Some(b)) => (a, b),
3608            _ => continue,
3609        };
3610        if end - start > i128::from(MAX_APPROVAL_SECONDS) * 1_000_000_000 {
3611            continue;
3612        }
3613        let newer = match latest.get(&v.issuer) {
3614            None => true,
3615            Some((t, _)) => start > *t || (start == *t && reject),
3616        };
3617        if newer {
3618            latest.insert(v.issuer, (start, reject));
3619        }
3620    }
3621
3622    if latest.values().any(|(_, reject)| *reject) {
3623        return Ok((false, Vec::new()));
3624    }
3625    let mut approvers: Vec<String> = Vec::new();
3626    let mut seen: HashSet<Vec<u8>> = HashSet::new();
3627    for issuer in latest.keys() {
3628        let raw = match map.get(issuer) {
3629            Some(k) => k.clone(),
3630            None => match crate::keys::did_key_to_ed25519(issuer) {
3631                Ok(k) if issuer.starts_with("did:key:") => k,
3632                _ => continue,
3633            },
3634        };
3635        if seen.insert(raw) {
3636            approvers.push(issuer.clone());
3637        }
3638    }
3639    approvers.sort();
3640    Ok((approvers.len() as i64 >= threshold, approvers))
3641}
3642
3643// ---------------------------------------------------------------------------
3644// Robot lifecycle: ownership transfer, key rotation, decommission (Phase 5.13)
3645// ---------------------------------------------------------------------------
3646
3647pub const OWNERSHIP_TRANSFER_TYPE: &str = "RobotOwnershipTransferCredential";
3648pub const KEY_ROTATION_TYPE: &str = "RobotKeyRotationCredential";
3649pub const DECOMMISSION_TYPE: &str = "RobotDecommissionCredential";
3650
3651/// Parameters for [`build_ownership_transfer`]. The signer is the current owner;
3652/// `from_owner` defaults to `issuer_did` (the current owner's DID). Setting
3653/// `prev_transfer_id` links this transfer to the previous one, forming a chain:
3654/// it must be the previous transfer's `id`. `credential_id` is this transfer's
3655/// own `id` (the caller supplies it; use a fresh `urn:uuid:`).
3656#[derive(Debug, Clone)]
3657pub struct BuildOwnershipTransfer {
3658    pub issuer_did: String,
3659    pub robot_did: String,
3660    pub to_owner: String,
3661    pub from_owner: Option<String>,
3662    pub prev_transfer_id: Option<String>,
3663    pub credential_id: String,
3664    pub valid_from: String,
3665}
3666
3667/// Build a signed transfer of `robot_did` from the current owner to `to_owner`.
3668/// The signer is the current owner; `from_owner` defaults to `issuer_did`.
3669pub fn build_ownership_transfer(
3670    current_owner_seed: &[u8],
3671    params: &BuildOwnershipTransfer,
3672) -> Result<Value> {
3673    if params.robot_did.is_empty() || params.to_owner.is_empty() {
3674        return Err(CoreError::Json(
3675            "robot_did and to_owner are required".into(),
3676        ));
3677    }
3678    if params.credential_id.is_empty() {
3679        return Err(CoreError::Json("credential_id is required".into()));
3680    }
3681    let seller = params
3682        .from_owner
3683        .clone()
3684        .unwrap_or_else(|| params.issuer_did.clone());
3685
3686    let mut subject = Map::new();
3687    subject.insert("id".into(), json!(params.robot_did));
3688    subject.insert("fromOwner".into(), json!(seller));
3689    subject.insert("toOwner".into(), json!(params.to_owner));
3690    if let Some(prev) = &params.prev_transfer_id {
3691        subject.insert("prevTransferId".into(), json!(prev));
3692    }
3693
3694    let mut cred = Map::new();
3695    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
3696    cred.insert("id".into(), json!(params.credential_id));
3697    cred.insert(
3698        "type".into(),
3699        json!(["VerifiableCredential", OWNERSHIP_TRANSFER_TYPE]),
3700    );
3701    cred.insert("issuer".into(), json!(params.issuer_did));
3702    cred.insert("validFrom".into(), json!(params.valid_from));
3703    cred.insert("credentialSubject".into(), Value::Object(subject));
3704
3705    let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), &params.valid_from);
3706    data_integrity::sign(&Value::Object(cred), current_owner_seed, &opts)
3707}
3708
3709fn non_empty_str<'v>(v: &'v Value, key: &str) -> Option<&'v str> {
3710    v.get(key)
3711        .and_then(|x| x.as_str())
3712        .filter(|s| !s.is_empty())
3713}
3714
3715/// Verify a transfer: the current owner's proof bound to the issuer, the
3716/// issuer is the `fromOwner` (only the current owner can transfer the robot),
3717/// `toOwner` and the robot `id` are non-empty strings, validFrom no later than
3718/// `now_iso`, and (when given) the transfer is for `robot_did`. `owner_keys` is
3719/// a `{owner_did: key}` source (or the bare key of a did:key owner).
3720pub fn verify_ownership_transfer(
3721    credential: &Value,
3722    owner_keys: Keys<'_>,
3723    robot_did: Option<&str>,
3724    now_iso: &str,
3725) -> Result<Option<Value>> {
3726    let v = match bound(
3727        credential,
3728        owner_keys,
3729        OWNERSHIP_TRANSFER_TYPE,
3730        now_iso,
3731        Window::FromRequired,
3732    )? {
3733        Some(v) => v,
3734        None => return Ok(None),
3735    };
3736    let ok = non_empty_str(&v.subject, "toOwner").is_some()
3737        && non_empty_str(&v.subject, "fromOwner") == Some(v.issuer.as_str())
3738        && non_empty_str(&v.subject, "id").is_some()
3739        && robot_did.is_none_or(|r| v.subject.get("id").and_then(|x| x.as_str()) == Some(r));
3740    Ok(if ok { Some(v.subject) } else { None })
3741}
3742
3743/// One owner's public key, looked up by owner DID, for [`verify_custody_chain`].
3744#[derive(Debug, Clone)]
3745pub struct OwnerKey {
3746    pub did: String,
3747    pub public_key: Vec<u8>,
3748}
3749
3750/// Verify an ordered list of transfer credentials forms a valid chain of custody
3751/// for `robot_did`: every link verifies under the owner who signed it (keys
3752/// from `public_keys`), names the previous link's `id` as its
3753/// `prevTransferId`, is dated no earlier than the previous link, each
3754/// `toOwner` is the next link's `fromOwner`, and the first `fromOwner` is
3755/// `origin_owner`. Returns `(ok, current_owner)`.
3756///
3757/// `origin_owner` is required: with no known first owner, anyone could sign a
3758/// first transfer of any robot from themselves. Without it the chain is
3759/// refused. Each link's signer is pinned (the origin, then each `toOwner`), so
3760/// a did:key owner verifies under its own key even with no entry in
3761/// `public_keys`.
3762pub fn verify_custody_chain(
3763    transfers: &[Value],
3764    public_keys: &[OwnerKey],
3765    robot_did: &str,
3766    origin_owner: Option<&str>,
3767    now_iso: &str,
3768) -> Result<(bool, Option<String>)> {
3769    rv::require_now(now_iso)?;
3770    if robot_did.is_empty() || origin_owner.is_none_or(str::is_empty) {
3771        return Ok((false, None));
3772    }
3773    let map = Keys::map_of(public_keys.iter().map(|k| (k.did.clone(), &k.public_key)));
3774    let mut expected_from: Option<String> = origin_owner.map(String::from);
3775    let mut current_owner: Option<String> = origin_owner.map(String::from);
3776    let mut prev_id: Option<String> = None;
3777    let mut prev_time: Option<i128> = None;
3778    for (i, transfer) in transfers.iter().enumerate() {
3779        let keys = rv::pin_if_keyless(Keys::Map(&map), expected_from.as_deref());
3780        let subject = match verify_ownership_transfer(transfer, keys, Some(robot_did), now_iso)? {
3781            Some(s) => s,
3782            None => return Ok((false, None)),
3783        };
3784        if let Some(expected) = &expected_from {
3785            if subject.get("fromOwner").and_then(|v| v.as_str()) != Some(expected.as_str()) {
3786                return Ok((false, None));
3787            }
3788        }
3789        let this_time = match rv::time_ns(transfer.get("validFrom")) {
3790            Some(t) if prev_time.is_none_or(|p| t >= p) => t,
3791            _ => return Ok((false, None)),
3792        };
3793        if i > 0 {
3794            match &prev_id {
3795                Some(p) if subject.get("prevTransferId").and_then(|v| v.as_str()) == Some(p) => {}
3796                _ => return Ok((false, None)),
3797            }
3798        }
3799        prev_id = non_empty_str(transfer, "id").map(String::from);
3800        prev_time = Some(this_time);
3801        current_owner = subject
3802            .get("toOwner")
3803            .and_then(|v| v.as_str())
3804            .map(String::from);
3805        expected_from = current_owner.clone();
3806    }
3807    Ok((true, current_owner))
3808}
3809
3810/// Parameters for [`build_key_rotation`]. The credential is signed by the old key
3811/// (the `signer_seed`) and issued under `robot_did`; the old key's public multibase
3812/// is recorded as `previousKey` and `new_key_multibase` as the authorized successor.
3813#[derive(Debug, Clone)]
3814pub struct BuildKeyRotation {
3815    pub robot_did: String,
3816    pub new_key_multibase: String,
3817    pub reason: Option<String>,
3818    pub valid_from: String,
3819}
3820
3821/// Build a key-rotation credential in which the robot's current (old) key
3822/// authorizes a new key. Signed by the old key, so anyone trusting the old key
3823/// can trust the new one. `old_key_seed` is the seed of the current key.
3824pub fn build_key_rotation(old_key_seed: &[u8], params: &BuildKeyRotation) -> Result<Value> {
3825    if params.new_key_multibase.is_empty() {
3826        return Err(CoreError::Json("new_key_multibase is required".into()));
3827    }
3828    let old_kp = keys::Ed25519KeyPair::from_seed_slice(old_key_seed)?;
3829
3830    let mut subject = Map::new();
3831    subject.insert("id".into(), json!(params.robot_did));
3832    subject.insert("previousKey".into(), json!(old_kp.public_multikey()));
3833    subject.insert("newKey".into(), json!(params.new_key_multibase));
3834    if let Some(reason) = &params.reason {
3835        subject.insert("reason".into(), json!(reason));
3836    }
3837
3838    let mut cred = Map::new();
3839    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
3840    cred.insert(
3841        "type".into(),
3842        json!(["VerifiableCredential", KEY_ROTATION_TYPE]),
3843    );
3844    cred.insert("issuer".into(), json!(params.robot_did));
3845    cred.insert("validFrom".into(), json!(params.valid_from));
3846    cred.insert("credentialSubject".into(), Value::Object(subject));
3847
3848    let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), &params.valid_from);
3849    data_integrity::sign(&Value::Object(cred), old_key_seed, &opts)
3850}
3851
3852/// The raw Ed25519 key of a `z...` multikey, or `None`.
3853fn multikey_raw(v: Option<&Value>) -> Option<Vec<u8>> {
3854    let s = v.and_then(|x| x.as_str()).filter(|s| s.starts_with('z'))?;
3855    match multikey::decode(s) {
3856        Ok(d) if d.algorithm == "Ed25519" && d.raw_key.len() == 32 => Some(d.raw_key),
3857        _ => None,
3858    }
3859}
3860
3861/// Verify a key rotation: the robot's OLD key signed it, binding the new key.
3862///
3863/// The rotation is a self-attestation: the issuer must be the robot
3864/// (`credentialSubject.id`), `previousKey` must decode to exactly the key the
3865/// caller trusts as the robot's current key (`old_keys`: a bare key, or a
3866/// `{robot_did: key}` source), the proof is checked under that key, and
3867/// `newKey` must decode and differ. When given, the rotation must be for
3868/// `robot_did`. Returns the credentialSubject (with `newKey` the successor).
3869pub fn verify_key_rotation(
3870    credential: &Value,
3871    old_keys: Keys<'_>,
3872    robot_did: Option<&str>,
3873    now_iso: &str,
3874) -> Result<Option<Value>> {
3875    let now = rv::require_now(now_iso)?;
3876    let issuer = match rv::issuer_id(credential.get("issuer")) {
3877        Some(i) => i.to_string(),
3878        None => return Ok(None),
3879    };
3880    let trusted: Option<Vec<u8>> = match old_keys {
3881        Keys::Embedded | Keys::Pinned(_) => None,
3882        Keys::Bare(k) => Some(k.to_vec()),
3883        Keys::One(did, k) => (did == issuer).then(|| k.to_vec()),
3884        Keys::Map(m) => m.get(&issuer).cloned(),
3885        Keys::Resolver(f) => f(&issuer),
3886    };
3887    let trusted = match trusted {
3888        Some(t) if t.len() == 32 => t,
3889        _ => return Ok(None),
3890    };
3891    let previous = credential
3892        .get("credentialSubject")
3893        .and_then(|s| s.get("previousKey"));
3894    if multikey_raw(previous) != Some(trusted.clone()) {
3895        return Ok(None);
3896    }
3897    let v = match rv::verify_robotics_credential(
3898        credential,
3899        Keys::One(&issuer, &trusted),
3900        Some(KEY_ROTATION_TYPE),
3901        now,
3902        VerifyOptions::window(Window::FromRequired),
3903    ) {
3904        Ok(v) if issuer_is_subject(&v) => v,
3905        _ => return Ok(None),
3906    };
3907    if robot_did.is_some_and(|r| r != v.issuer) {
3908        return Ok(None);
3909    }
3910    match multikey_raw(v.subject.get("newKey")) {
3911        Some(n) if n != trusted => Ok(Some(v.subject)),
3912        _ => Ok(None),
3913    }
3914}
3915
3916/// Verify an ordered list of key rotations forms one linear key history from
3917/// `origin_key_multibase`. Each rotation must be signed by the key it rotates
3918/// from, decoded from the multibase itself; every rotation is for the same
3919/// robot (`robot_did` when given, else the first rotation's robot) and dated no
3920/// earlier than the one before; a key that appears twice (a fork or a cycle)
3921/// is refused. Returns `(ok, current_key)`.
3922pub fn verify_key_history(
3923    rotations: &[Value],
3924    origin_key_multibase: &str,
3925    robot_did: Option<&str>,
3926    now_iso: &str,
3927) -> Result<(bool, Option<String>)> {
3928    rv::require_now(now_iso)?;
3929    let origin = match multikey_raw(Some(&json!(origin_key_multibase))) {
3930        Some(o) => o,
3931        None => return Ok((false, None)),
3932    };
3933    let mut current_key = origin_key_multibase.to_string();
3934    let mut current_raw = origin.clone();
3935    let mut seen: HashSet<Vec<u8>> = HashSet::from([origin]);
3936    let mut pinned: Option<String> = robot_did.map(String::from);
3937    let mut prev_time: Option<i128> = None;
3938    for rotation in rotations {
3939        let subject = match verify_key_rotation(
3940            rotation,
3941            Keys::Bare(&current_raw),
3942            pinned.as_deref(),
3943            now_iso,
3944        )? {
3945            Some(s) => s,
3946            None => return Ok((false, None)),
3947        };
3948        if pinned.is_none() {
3949            pinned = subject.get("id").and_then(|v| v.as_str()).map(String::from);
3950        }
3951        match rv::time_ns(rotation.get("validFrom")) {
3952            Some(t) if prev_time.is_none_or(|p| t >= p) => prev_time = Some(t),
3953            _ => return Ok((false, None)),
3954        }
3955        let new_raw = match multikey_raw(subject.get("newKey")) {
3956            Some(n) if !seen.contains(&n) => n,
3957            _ => return Ok((false, None)),
3958        };
3959        seen.insert(new_raw.clone());
3960        current_raw = new_raw;
3961        current_key = subject
3962            .get("newKey")
3963            .and_then(|v| v.as_str())
3964            .unwrap_or("")
3965            .to_string();
3966    }
3967    Ok((true, Some(current_key)))
3968}
3969
3970/// Parameters for [`build_decommission`]. The signer is the owner or an authority;
3971/// `final_disposition` records the outcome (for example recycled, destroyed, or
3972/// transferred to parts). When `valid_until` is set it bounds the credential.
3973#[derive(Debug, Clone)]
3974pub struct BuildDecommission {
3975    pub issuer_did: String,
3976    pub robot_did: String,
3977    pub reason: String,
3978    pub final_disposition: Option<String>,
3979    pub valid_from: String,
3980    pub valid_until: Option<String>,
3981}
3982
3983/// Build a signed decommission credential retiring `robot_did`. After
3984/// decommissioning, a verifier should refuse to trust the robot. `decommissionedBy`
3985/// is the issuer DID.
3986pub fn build_decommission(signer_seed: &[u8], params: &BuildDecommission) -> Result<Value> {
3987    if params.reason.is_empty() {
3988        return Err(CoreError::Json("reason is required".into()));
3989    }
3990    let mut subject = Map::new();
3991    subject.insert("id".into(), json!(params.robot_did));
3992    subject.insert("reason".into(), json!(params.reason));
3993    subject.insert("decommissionedBy".into(), json!(params.issuer_did));
3994    if let Some(disposition) = &params.final_disposition {
3995        subject.insert("finalDisposition".into(), json!(disposition));
3996    }
3997
3998    let mut cred = Map::new();
3999    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
4000    cred.insert(
4001        "type".into(),
4002        json!(["VerifiableCredential", DECOMMISSION_TYPE]),
4003    );
4004    cred.insert("issuer".into(), json!(params.issuer_did));
4005    cred.insert("validFrom".into(), json!(params.valid_from));
4006    if let Some(vu) = &params.valid_until {
4007        cred.insert("validUntil".into(), json!(vu));
4008    }
4009    cred.insert("credentialSubject".into(), Value::Object(subject));
4010
4011    let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), &params.valid_from);
4012    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
4013}
4014
4015/// Verify a decommission credential: the proof bound to the issuer, the
4016/// window at `now_iso` (validFrom required), `decommissionedBy` (when present)
4017/// equal to the issuer, the issuer in `trusted_authorities` when supplied, and
4018/// (when given) the credential is about `robot_did`.
4019pub fn verify_decommission(
4020    credential: &Value,
4021    keys: Keys<'_>,
4022    trusted_authorities: Option<&HashSet<String>>,
4023    robot_did: Option<&str>,
4024    now_iso: &str,
4025) -> Result<Option<Value>> {
4026    let now = rv::require_now(now_iso)?;
4027    let opts = VerifyOptions {
4028        trusted_issuers: trusted_authorities,
4029        ..VerifyOptions::window(Window::FromRequired)
4030    };
4031    let v = match rv::verify_robotics_credential(
4032        credential,
4033        keys,
4034        Some(DECOMMISSION_TYPE),
4035        now,
4036        opts,
4037    ) {
4038        Ok(v) => v,
4039        Err(_) => return Ok(None),
4040    };
4041    if let Some(by) = v.subject.get("decommissionedBy") {
4042        if by.as_str() != Some(v.issuer.as_str()) {
4043            return Ok(None);
4044        }
4045    }
4046    if robot_did.is_some_and(|r| v.subject.get("id").and_then(|x| x.as_str()) != Some(r)) {
4047        return Ok(None);
4048    }
4049    Ok(Some(v.subject))
4050}
4051
4052// ---------------------------------------------------------------------------
4053// Regulatory conformance profiles (Phase 5.14)
4054// ---------------------------------------------------------------------------
4055//
4056// A conformance profile is a machine-checkable mapping from Vouch robotics
4057// credentials to the clauses of a public safety or AI regulation. Given the
4058// credentials a robot presents, the checker reports which clauses are satisfied
4059// and cites each one, and an issuer can sign a point-in-time conformance
4060// attestation an auditor or notified body can consume. The profiles are plain
4061// data so every language reproduces them identically.
4062//
4063// This is the open layer: declarative profiles, a deterministic checker, and a
4064// signed point-in-time attestation over the full report. It is a reference
4065// crosswalk to make conformance verifiable in the open, not legal advice.
4066
4067pub const CONFORMANCE_ATTESTATION_TYPE: &str = "RobotConformanceAttestation";
4068
4069/// How well-sourced a requirement's clause citation is. A profile can be a
4070/// useful crosswalk while its citations are only as good as the sources that
4071/// were available, and a reader is entitled to know which. Every report and
4072/// every signed attestation carries these, so a conformance result never
4073/// implies more authority over the regulation than it has.
4074///
4075/// The clause text was read from the official published source.
4076pub const CITATION_VERIFIED_PRIMARY: &str = "verified-primary";
4077/// The mapping is believed sound, but the clause number comes from secondary
4078/// sources rather than the standard or official journal itself. The default,
4079/// because it is the honest default.
4080pub const CITATION_UNVERIFIED_SECONDARY: &str = "unverified-secondary";
4081/// Not a clause reference at all, only a description of the topic. An assessor
4082/// cannot look it up.
4083pub const CITATION_DESCRIPTIVE: &str = "descriptive";
4084
4085/// Every citation provenance value, in report order.
4086pub const CITATION_STATUSES: &[&str] = &[
4087    CITATION_VERIFIED_PRIMARY,
4088    CITATION_UNVERIFIED_SECONDARY,
4089    CITATION_DESCRIPTIVE,
4090];
4091
4092// Citation notes shared by several requirements. Macros rather than consts so
4093// they can be `concat!`-ed into the longer per-requirement notes, byte-for-byte
4094// identical with the Python, TypeScript and Go profiles.
4095macro_rules! iso_paywall_note {
4096    () => {
4097        "Clause number taken from secondary sources; the standard is paywalled \
4098         and the text has not been read."
4099    };
4100}
4101
4102macro_rules! iso_10218_note {
4103    () => {
4104        concat!(
4105            iso_paywall_note!(),
4106            " ISO 10218-1/-2:2011 were superseded by the 2025 editions (in \
4107             force 1 April 2025); this mapping still cites the 2011 clause \
4108             numbering and has not been migrated."
4109        )
4110    };
4111}
4112
4113macro_rules! oj_note {
4114    () => {
4115        "Article number taken from a third-party reproduction of the Official \
4116         Journal text, not from EUR-Lex itself."
4117    };
4118}
4119
4120macro_rules! ul_note {
4121    () => {
4122        "UL 3300 (now ANSI/CAN/UL 3300:2024) is paywalled and no clause \
4123         numbering was available; this names the topic only and cannot be \
4124         looked up."
4125    };
4126}
4127
4128/// One requirement in a profile: a clause of a regulation mapped to the
4129/// credential type and field paths that satisfy it.
4130struct ProfileRequirement {
4131    id: &'static str,
4132    clause: &'static str,
4133    title: &'static str,
4134    credential: &'static str,
4135    fields: &'static [&'static str],
4136    /// Subject paths that must hold boolean `true`, for requirements where mere
4137    /// presence is not evidence: a heartbeat reporting an envelope breach is not
4138    /// evidence of having stayed inside the envelope. This is the boolean subset
4139    /// of the `expect` map the Python, TypeScript and Go profiles carry; the
4140    /// built-in profiles use only boolean expectations.
4141    expect_true: &'static [&'static str],
4142    /// Provenance of the `clause` reference above, one of [`CITATION_STATUSES`].
4143    citation: &'static str,
4144    /// Anything a reader should know about the citation, such as a known
4145    /// conflict between sources.
4146    citation_note: Option<&'static str>,
4147}
4148
4149/// A built-in conformance profile: a regime, a version, and its requirements.
4150struct ConformanceProfile {
4151    regime: &'static str,
4152    version: &'static str,
4153    requirements: &'static [ProfileRequirement],
4154}
4155
4156const ISO_10218_REQUIREMENTS: &[ProfileRequirement] = &[
4157    ProfileRequirement {
4158        id: "iso10218-identification",
4159        clause: "ISO 10218-1:2011, 5.2",
4160        title: "Robot identification bound to its hardware",
4161        credential: "RobotIdentityCredential",
4162        fields: &["hardwareRoot.kind", "hardwareRoot.attestation"],
4163        expect_true: &[],
4164        citation: CITATION_UNVERIFIED_SECONDARY,
4165        citation_note: Some(iso_10218_note!()),
4166    },
4167    ProfileRequirement {
4168        id: "iso10218-software-integrity",
4169        clause: "ISO 10218-1:2011, 5.3",
4170        title: "Control software and configuration integrity",
4171        credential: "ModelProvenanceAttestation",
4172        fields: &["vla.weightsHash"],
4173        expect_true: &[],
4174        citation: CITATION_UNVERIFIED_SECONDARY,
4175        citation_note: Some(iso_10218_note!()),
4176    },
4177    ProfileRequirement {
4178        id: "iso10218-limits",
4179        clause: "ISO 10218-1:2011, 5.6",
4180        title: "Limiting of speed, force, and workspace",
4181        credential: "PhysicalCapabilityScope",
4182        fields: &[
4183            "physicalScope.maxForceN",
4184            "physicalScope.maxSpeedMps",
4185            "physicalScope.allowedZones",
4186        ],
4187        expect_true: &[],
4188        citation: CITATION_UNVERIFIED_SECONDARY,
4189        citation_note: Some(iso_10218_note!()),
4190    },
4191    ProfileRequirement {
4192        id: "iso10218-records",
4193        clause: "ISO 10218-2:2011, 5.2",
4194        title: "Records of safety-relevant events",
4195        credential: "RobotSafetyRecordCredential",
4196        fields: &["totalEvents", "logHead"],
4197        expect_true: &[],
4198        citation: CITATION_UNVERIFIED_SECONDARY,
4199        citation_note: Some(iso_10218_note!()),
4200    },
4201];
4202
4203const ISO_TS_15066_REQUIREMENTS: &[ProfileRequirement] = &[
4204    ProfileRequirement {
4205        id: "iso15066-power-force-limiting",
4206        clause: "ISO/TS 15066:2016, 5.5.4",
4207        title: "Power and force limiting near humans",
4208        credential: "PhysicalCapabilityScope",
4209        fields: &[
4210            "physicalScope.maxSpeedNearHumansMps",
4211            "physicalScope.maxForceN",
4212        ],
4213        expect_true: &[],
4214        citation: CITATION_UNVERIFIED_SECONDARY,
4215        citation_note: Some(concat!(
4216            iso_paywall_note!(),
4217            " Secondary sources disagree on whether power and force limiting \
4218             is 5.5.4 or 5.5.2; confirm against the published table of \
4219             contents before relying on the number."
4220        )),
4221    },
4222    ProfileRequirement {
4223        id: "iso15066-collaborative-workspace",
4224        clause: "ISO/TS 15066:2016, 5.5.2",
4225        title: "Defined collaborative workspace",
4226        credential: "PhysicalCapabilityScope",
4227        fields: &["physicalScope.allowedZones"],
4228        expect_true: &[],
4229        citation: CITATION_UNVERIFIED_SECONDARY,
4230        citation_note: Some(concat!(
4231            iso_paywall_note!(),
4232            " Shares the unresolved 5.5.2/5.5.4 numbering conflict with \
4233             iso15066-power-force-limiting."
4234        )),
4235    },
4236    ProfileRequirement {
4237        id: "iso15066-monitoring",
4238        clause: "ISO/TS 15066:2016, 5.2",
4239        title: "Continuous monitoring of the collaborative operation",
4240        credential: "RobotHeartbeatCredential",
4241        fields: &["motionDigest"],
4242        expect_true: &["motionDigest.withinEnvelope"],
4243        citation: CITATION_UNVERIFIED_SECONDARY,
4244        citation_note: Some(iso_paywall_note!()),
4245    },
4246];
4247
4248const EU_MACHINERY_REQUIREMENTS: &[ProfileRequirement] = &[
4249    ProfileRequirement {
4250        id: "eu-mr-identification",
4251        clause: "Reg (EU) 2023/1230, Annex III 1.7.4",
4252        title: "Machinery identification and traceability",
4253        credential: "RobotIdentityCredential",
4254        fields: &["make", "model", "serial"],
4255        expect_true: &[],
4256        citation: CITATION_UNVERIFIED_SECONDARY,
4257        citation_note: Some(oj_note!()),
4258    },
4259    ProfileRequirement {
4260        id: "eu-mr-software-integrity",
4261        clause: "Reg (EU) 2023/1230, Annex III 1.1.9",
4262        title: "Protection against corruption of safety software",
4263        credential: "ModelProvenanceAttestation",
4264        fields: &["vla.weightsHash", "vla.safetyPolicy"],
4265        expect_true: &[],
4266        citation: CITATION_UNVERIFIED_SECONDARY,
4267        citation_note: Some(concat!(
4268            oj_note!(),
4269            " The Annex III subclause for protection against corruption has \
4270             not been confirmed and may need to be re-pointed."
4271        )),
4272    },
4273    ProfileRequirement {
4274        id: "eu-mr-safe-limits",
4275        clause: "Reg (EU) 2023/1230, Annex III 1.2.1",
4276        title: "Safety and reliability of control systems and limits",
4277        credential: "PhysicalCapabilityScope",
4278        fields: &["physicalScope.maxForceN"],
4279        expect_true: &[],
4280        citation: CITATION_UNVERIFIED_SECONDARY,
4281        citation_note: Some(oj_note!()),
4282    },
4283    ProfileRequirement {
4284        id: "eu-mr-records",
4285        clause: "Reg (EU) 2023/1230, Annex III 1.2.1",
4286        title: "Recording of safety-relevant data",
4287        credential: "RobotSafetyRecordCredential",
4288        fields: &["totalEvents", "logHead"],
4289        expect_true: &[],
4290        citation: CITATION_UNVERIFIED_SECONDARY,
4291        citation_note: Some(oj_note!()),
4292    },
4293];
4294
4295const EU_AI_ACT_REQUIREMENTS: &[ProfileRequirement] = &[
4296    ProfileRequirement {
4297        id: "eu-aia-record-keeping",
4298        clause: "Reg (EU) 2024/1689, Art. 12",
4299        title: "Automatic recording of events (logging)",
4300        credential: "RobotSafetyRecordCredential",
4301        fields: &["logHead"],
4302        expect_true: &[],
4303        citation: CITATION_UNVERIFIED_SECONDARY,
4304        citation_note: Some(oj_note!()),
4305    },
4306    ProfileRequirement {
4307        id: "eu-aia-transparency",
4308        clause: "Reg (EU) 2024/1689, Art. 13",
4309        title: "Model and configuration transparency",
4310        credential: "ModelProvenanceAttestation",
4311        fields: &["vla.modelName", "vla.configHash"],
4312        expect_true: &[],
4313        citation: CITATION_UNVERIFIED_SECONDARY,
4314        citation_note: Some(oj_note!()),
4315    },
4316    ProfileRequirement {
4317        id: "eu-aia-human-oversight",
4318        clause: "Reg (EU) 2024/1689, Art. 14",
4319        title: "Human oversight through enforced operating limits",
4320        credential: "PhysicalCapabilityScope",
4321        fields: &["physicalScope.maxSpeedNearHumansMps"],
4322        expect_true: &[],
4323        citation: CITATION_UNVERIFIED_SECONDARY,
4324        citation_note: Some(concat!(
4325            oj_note!(),
4326            " Art. 14 also requires a means for the overseer to intervene or \
4327             stop the system, which an operating-limit scope alone does not \
4328             evidence."
4329        )),
4330    },
4331    ProfileRequirement {
4332        id: "eu-aia-accuracy-robustness",
4333        clause: "Reg (EU) 2024/1689, Art. 15",
4334        title: "Accuracy and robustness traceable to a known build",
4335        credential: "ModelProvenanceAttestation",
4336        fields: &["vla.weightsHash"],
4337        expect_true: &[],
4338        citation: CITATION_UNVERIFIED_SECONDARY,
4339        citation_note: Some(oj_note!()),
4340    },
4341];
4342
4343const UL_3300_REQUIREMENTS: &[ProfileRequirement] = &[
4344    ProfileRequirement {
4345        id: "ul3300-identity",
4346        clause: "UL 3300, identification",
4347        title: "Robot identity bound to its hardware",
4348        credential: "RobotIdentityCredential",
4349        fields: &["hardwareRoot.kind", "hardwareRoot.attestation"],
4350        expect_true: &[],
4351        citation: CITATION_DESCRIPTIVE,
4352        citation_note: Some(ul_note!()),
4353    },
4354    ProfileRequirement {
4355        id: "ul3300-operating-limits",
4356        clause: "UL 3300, operating limits",
4357        title: "Enforced speed and zone limits",
4358        credential: "PhysicalCapabilityScope",
4359        fields: &["physicalScope.maxSpeedMps", "physicalScope.allowedZones"],
4360        expect_true: &[],
4361        citation: CITATION_DESCRIPTIVE,
4362        citation_note: Some(ul_note!()),
4363    },
4364    ProfileRequirement {
4365        id: "ul3300-perception-integrity",
4366        clause: "UL 3300, sensing integrity",
4367        title: "Integrity of perception used for safe operation",
4368        credential: "PerceptionProvenanceCredential",
4369        fields: &["frameHash"],
4370        expect_true: &[],
4371        citation: CITATION_DESCRIPTIVE,
4372        citation_note: Some(ul_note!()),
4373    },
4374    ProfileRequirement {
4375        id: "ul3300-records",
4376        clause: "UL 3300, incident records",
4377        title: "Records of safety-relevant incidents",
4378        credential: "RobotSafetyRecordCredential",
4379        fields: &["totalEvents", "logHead"],
4380        expect_true: &[],
4381        citation: CITATION_DESCRIPTIVE,
4382        citation_note: Some(ul_note!()),
4383    },
4384];
4385
4386/// Return a built-in profile by id, or `None` if it is unknown. The five profiles
4387/// cover ISO 10218-1/-2 (industrial), ISO/TS 15066 (collaborative), the EU
4388/// Machinery Regulation 2023/1230, the EU AI Act high-risk requirements, and
4389/// UL 3300 (service and mobile robots).
4390fn conformance_profile(profile_id: &str) -> Option<ConformanceProfile> {
4391    match profile_id {
4392        "iso-10218" => Some(ConformanceProfile {
4393            regime: "ISO 10218-1/-2 industrial robots",
4394            version: "2011 (superseded by the 2025 editions; mapping not yet migrated)",
4395            requirements: ISO_10218_REQUIREMENTS,
4396        }),
4397        "iso-ts-15066" => Some(ConformanceProfile {
4398            regime: "ISO/TS 15066 collaborative robots",
4399            version: "2016",
4400            requirements: ISO_TS_15066_REQUIREMENTS,
4401        }),
4402        "eu-machinery-2023-1230" => Some(ConformanceProfile {
4403            regime: "EU Machinery Regulation 2023/1230",
4404            version: "2023",
4405            requirements: EU_MACHINERY_REQUIREMENTS,
4406        }),
4407        "eu-ai-act-high-risk" => Some(ConformanceProfile {
4408            regime: "EU AI Act high-risk systems",
4409            version: "2024",
4410            requirements: EU_AI_ACT_REQUIREMENTS,
4411        }),
4412        "ul-3300" => Some(ConformanceProfile {
4413            regime: "UL 3300 service, communication, and mobile robots",
4414            version: "2022 (see ANSI/CAN/UL 3300:2024)",
4415            requirements: UL_3300_REQUIREMENTS,
4416        }),
4417        _ => None,
4418    }
4419}
4420
4421/// The type array of a credential, accepting a JSON string or an array of strings.
4422fn credential_types(credential: &Value) -> Vec<&str> {
4423    match credential.get("type") {
4424        Some(Value::String(s)) => vec![s.as_str()],
4425        Some(Value::Array(items)) => items.iter().filter_map(|v| v.as_str()).collect(),
4426        _ => Vec::new(),
4427    }
4428}
4429
4430/// Follow a dot-separated path from the credentialSubject, returning the value at
4431/// the leaf or `None` if any segment is missing or not an object.
4432fn path_value<'a>(subject: &'a Value, path: &str) -> Option<&'a Value> {
4433    let mut node = subject;
4434    for part in path.split('.') {
4435        match node {
4436            Value::Object(map) => match map.get(part) {
4437                Some(v) => node = v,
4438                None => return None,
4439            },
4440            _ => return None,
4441        }
4442    }
4443    Some(node)
4444}
4445
4446/// True when a value is present and non-empty: not null, and not an empty array
4447/// or empty object. Any other value (including `false`, `0`, or `""`) counts.
4448fn value_present(value: &Value) -> bool {
4449    match value {
4450        Value::Null => false,
4451        Value::Array(a) => !a.is_empty(),
4452        Value::Object(o) => !o.is_empty(),
4453        _ => true,
4454    }
4455}
4456
4457/// True when `credential` satisfies `requirement`: its type array includes the
4458/// requirement's credential type, its credentialSubject has a non-null,
4459/// non-empty value at every field path, and every `expect_true` path holds
4460/// boolean `true`. Presence alone is not evidence: a heartbeat that reports an
4461/// envelope breach does not evidence having stayed inside the envelope.
4462fn credential_satisfies(credential: &Value, requirement: &ProfileRequirement) -> bool {
4463    if !credential_types(credential).contains(&requirement.credential) {
4464        return false;
4465    }
4466    let empty = Value::Object(Map::new());
4467    let subject = credential.get("credentialSubject").unwrap_or(&empty);
4468    for path in requirement.fields {
4469        match path_value(subject, path) {
4470            Some(v) if value_present(v) => {}
4471            _ => return false,
4472        }
4473    }
4474    for path in requirement.expect_true {
4475        if path_value(subject, path) != Some(&Value::Bool(true)) {
4476            return false;
4477        }
4478    }
4479    true
4480}
4481
4482/// Check the presented `credentials` against the named profile and return a
4483/// deterministic report. Each requirement is satisfied when some presented
4484/// credential matches its type and has every required field. The caller is
4485/// expected to have verified the credentials' signatures first; this checks
4486/// structure and coverage, not proofs.
4487///
4488/// Every requirement carries the provenance of its clause citation, and the
4489/// report totals them, so a result never reads as more authoritative about the
4490/// regulation than its sources are.
4491///
4492/// The report has exactly `{profileId, regime, version, conforms,
4493/// satisfiedCount, totalCount, citations:{...},
4494/// requirements:[{id, clause, title, satisfied, citation, citationNote?}]}`.
4495pub fn check_conformance(credentials: &[Value], profile_id: &str) -> Result<Value> {
4496    check_conformance_for(credentials, profile_id, None)
4497}
4498
4499/// [`check_conformance`] bound to one robot: with `robot_did`, only credentials
4500/// whose `credentialSubject.id` is that robot count (so another robot's
4501/// credential mixed into the set cannot fill a gap), and the report carries
4502/// `robotDid`.
4503pub fn check_conformance_for(
4504    credentials: &[Value],
4505    profile_id: &str,
4506    robot_did: Option<&str>,
4507) -> Result<Value> {
4508    let prof = conformance_profile(profile_id)
4509        .ok_or_else(|| CoreError::Json(format!("unknown conformance profile: {profile_id}")))?;
4510    if robot_did.is_some_and(str::is_empty) {
4511        return Err(CoreError::Json("robot_did must be a non-empty DID".into()));
4512    }
4513    let presented: Vec<&Value> = credentials
4514        .iter()
4515        .filter(|c| c.is_object())
4516        .filter(|c| {
4517            robot_did.is_none_or(|r| {
4518                c.get("credentialSubject")
4519                    .and_then(|s| s.get("id"))
4520                    .and_then(|x| x.as_str())
4521                    == Some(r)
4522            })
4523        })
4524        .collect();
4525
4526    let mut results: Vec<Value> = Vec::with_capacity(prof.requirements.len());
4527    let mut satisfied = 0i64;
4528    let mut citations = Map::new();
4529    for status in CITATION_STATUSES {
4530        citations.insert((*status).into(), json!(0i64));
4531    }
4532    for requirement in prof.requirements {
4533        let ok = presented
4534            .iter()
4535            .any(|c| credential_satisfies(c, requirement));
4536        if ok {
4537            satisfied += 1;
4538        }
4539        let seen = citations
4540            .get(requirement.citation)
4541            .and_then(|v| v.as_i64())
4542            .unwrap_or(0);
4543        citations.insert(requirement.citation.into(), json!(seen + 1));
4544        let mut result = Map::new();
4545        result.insert("id".into(), json!(requirement.id));
4546        result.insert("clause".into(), json!(requirement.clause));
4547        result.insert("title".into(), json!(requirement.title));
4548        result.insert("satisfied".into(), json!(ok));
4549        result.insert("citation".into(), json!(requirement.citation));
4550        if let Some(note) = requirement.citation_note {
4551            result.insert("citationNote".into(), json!(note));
4552        }
4553        results.push(Value::Object(result));
4554    }
4555    let total = prof.requirements.len() as i64;
4556
4557    let mut report = Map::new();
4558    report.insert("profileId".into(), json!(profile_id));
4559    report.insert("regime".into(), json!(prof.regime));
4560    report.insert("version".into(), json!(prof.version));
4561    report.insert("conforms".into(), json!(satisfied == total));
4562    report.insert("satisfiedCount".into(), json!(satisfied));
4563    report.insert("totalCount".into(), json!(total));
4564    report.insert("citations".into(), Value::Object(citations));
4565    report.insert("requirements".into(), Value::Array(results));
4566    if let Some(r) = robot_did {
4567        report.insert("robotDid".into(), json!(r));
4568    }
4569    Ok(Value::Object(report))
4570}
4571
4572/// Multibase SHA-256 of the JCS-canonical report, for binding into an
4573/// attestation. Every language canonicalizes identically, so the digest is the
4574/// same byte string everywhere.
4575pub fn report_digest(report: &Value) -> String {
4576    mb64(&Sha256::digest(jcs::canonicalize(report)))
4577}
4578
4579/// Parameters for [`build_conformance_attestation`]. The signer is the robot, its
4580/// owner, or an assessing authority; `robot_did` names the robot the attestation
4581/// is about. `report` is produced by [`check_conformance`] and is embedded and
4582/// bound by digest. When `valid_seconds` is set it bounds the attestation.
4583#[derive(Debug, Clone)]
4584pub struct BuildConformanceAttestation {
4585    pub issuer_did: String,
4586    pub robot_did: String,
4587    pub report: Value,
4588    pub valid_from: String,
4589    pub valid_until: Option<String>,
4590}
4591
4592/// Build a signed point-in-time `RobotConformanceAttestation` for `robot_did`
4593/// over a `report` produced by [`check_conformance`]. The report is embedded and
4594/// bound by digest.
4595pub fn build_conformance_attestation(
4596    signer_seed: &[u8],
4597    params: &BuildConformanceAttestation,
4598) -> Result<Value> {
4599    if params.robot_did.is_empty() {
4600        return Err(CoreError::Json("robot_did is required".into()));
4601    }
4602    let report = params
4603        .report
4604        .as_object()
4605        .ok_or_else(|| CoreError::Json("report must come from check_conformance".into()))?;
4606    if !report.contains_key("profileId") || !report.contains_key("conforms") {
4607        return Err(CoreError::Json(
4608            "report must come from check_conformance".into(),
4609        ));
4610    }
4611
4612    let mut subject = Map::new();
4613    subject.insert("id".into(), json!(params.robot_did));
4614    subject.insert(
4615        "profileId".into(),
4616        report.get("profileId").cloned().unwrap_or(Value::Null),
4617    );
4618    subject.insert(
4619        "regime".into(),
4620        report.get("regime").cloned().unwrap_or(Value::Null),
4621    );
4622    subject.insert(
4623        "conforms".into(),
4624        report.get("conforms").cloned().unwrap_or(Value::Null),
4625    );
4626    subject.insert(
4627        "satisfiedCount".into(),
4628        report.get("satisfiedCount").cloned().unwrap_or(Value::Null),
4629    );
4630    subject.insert(
4631        "totalCount".into(),
4632        report.get("totalCount").cloned().unwrap_or(Value::Null),
4633    );
4634    subject.insert(
4635        "citations".into(),
4636        report
4637            .get("citations")
4638            .cloned()
4639            .unwrap_or_else(|| Value::Object(Map::new())),
4640    );
4641    subject.insert("reportDigest".into(), json!(report_digest(&params.report)));
4642    subject.insert("report".into(), params.report.clone());
4643
4644    let mut cred = Map::new();
4645    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
4646    cred.insert(
4647        "type".into(),
4648        json!(["VerifiableCredential", CONFORMANCE_ATTESTATION_TYPE]),
4649    );
4650    cred.insert("issuer".into(), json!(params.issuer_did));
4651    cred.insert("validFrom".into(), json!(params.valid_from));
4652    if let Some(vu) = &params.valid_until {
4653        cred.insert("validUntil".into(), json!(vu));
4654    }
4655    cred.insert("credentialSubject".into(), Value::Object(subject));
4656
4657    let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), &params.valid_from);
4658    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
4659}
4660
4661/// Verify a conformance attestation: the issuer's proof bound to the issuer,
4662/// the window at `now_iso` (validFrom required), that the embedded report
4663/// matches its bound digest, that every summary field (profileId, regime,
4664/// conforms, satisfiedCount, totalCount) matches the report, and that
4665/// `conforms` is a boolean. When given, the attestation must be about
4666/// `robot_did` and its issuer must be in `trusted_issuers`. Returns the
4667/// credentialSubject on success, `None` if invalid.
4668pub fn verify_conformance_attestation(
4669    credential: &Value,
4670    keys: Keys<'_>,
4671    robot_did: Option<&str>,
4672    trusted_issuers: Option<&HashSet<String>>,
4673    now_iso: &str,
4674) -> Result<Option<Value>> {
4675    let now = rv::require_now(now_iso)?;
4676    let opts = VerifyOptions {
4677        trusted_issuers,
4678        ..VerifyOptions::window(Window::FromRequired)
4679    };
4680    let v = match rv::verify_robotics_credential(
4681        credential,
4682        keys,
4683        Some(CONFORMANCE_ATTESTATION_TYPE),
4684        now,
4685        opts,
4686    ) {
4687        Ok(v) => v,
4688        Err(_) => return Ok(None),
4689    };
4690    let subject = v.subject;
4691    let embedded = match subject.get("report") {
4692        Some(r) if r.is_object() => r,
4693        _ => return Ok(None),
4694    };
4695    if subject.get("reportDigest").and_then(|v| v.as_str())
4696        != Some(report_digest(embedded).as_str())
4697    {
4698        return Ok(None);
4699    }
4700    for name in [
4701        "profileId",
4702        "regime",
4703        "conforms",
4704        "satisfiedCount",
4705        "totalCount",
4706    ] {
4707        if subject.get(name) != embedded.get(name) {
4708            return Ok(None);
4709        }
4710    }
4711    if !subject.get("conforms").is_some_and(|c| c.is_boolean()) {
4712        return Ok(None);
4713    }
4714    // A report bound to one robot cannot be attested as being about another.
4715    if embedded.get("robotDid").is_some() && embedded.get("robotDid") != subject.get("id") {
4716        return Ok(None);
4717    }
4718    if robot_did.is_some_and(|r| subject.get("id").and_then(|x| x.as_str()) != Some(r)) {
4719        return Ok(None);
4720    }
4721    Ok(Some(subject))
4722}
4723
4724// ---------------------------------------------------------------------------
4725// Post-quantum robot credentials (Phase 5.13)
4726// ---------------------------------------------------------------------------
4727//
4728// A robot fielded today lives for ten to twenty years, longer than classical
4729// Ed25519 is expected to stay safe, so a robot identity signed now could be
4730// forged once a quantum computer arrives. This section makes the hybrid
4731// post-quantum cryptosuite (`hybrid-eddsa-mldsa44-jcs-2026`, a classical
4732// Ed25519 signature alongside an ML-DSA-44 signature) available for robot
4733// credentials so they stay unforgeable across the robot's whole service life.
4734//
4735//   - sign_pq: attach a hybrid proof to a robot credential.
4736//   - verify_robot_credential: verify a robot credential whether it carries a
4737//     classical or a hybrid proof, auto-detected from the proof, so a fleet can
4738//     move to PQ gradually without breaking the classical credentials already in
4739//     the field.
4740//   - migrate_to_pq: re-sign a fielded robot's classical credential under PQ.
4741//
4742// This is the open layer: hybrid signing, backward-compatible verification, and
4743// a software re-signing migration path. It reuses the existing hybrid composite
4744// path ([`crate::hybrid`]) and the ML-DSA-44 and multikey helpers rather than
4745// re-deriving any cryptography.
4746
4747/// The classical (Ed25519-only) robot credential cryptosuite.
4748pub const CLASSICAL_CRYPTOSUITE: &str = data_integrity::CRYPTOSUITE_ID;
4749/// The hybrid post-quantum robot credential cryptosuite.
4750pub const HYBRID_CRYPTOSUITE: &str = hybrid::HYBRID_COMPOSITE_CRYPTOSUITE_ID;
4751
4752/// Coerce an ML-DSA-44 public key supplied either as raw 1312-byte bytes or as a
4753/// Multikey string into raw bytes. Errors on the wrong length or a non-ML-DSA
4754/// multikey.
4755pub fn coerce_mldsa44_public(mldsa44_public: &[u8]) -> Result<Vec<u8>> {
4756    if mldsa44_public.len() != MLDSA44_PUBLIC_LEN {
4757        return Err(CoreError::InvalidKeyLength {
4758            expected: MLDSA44_PUBLIC_LEN,
4759            got: mldsa44_public.len(),
4760        });
4761    }
4762    Ok(mldsa44_public.to_vec())
4763}
4764
4765/// Coerce an ML-DSA-44 Multikey string into raw public-key bytes. Errors if the
4766/// multikey does not carry an ML-DSA-44 key.
4767pub fn mldsa44_public_from_multikey(multikey_str: &str) -> Result<Vec<u8>> {
4768    let decoded = multikey::decode(multikey_str)?;
4769    if decoded.algorithm != "ML-DSA-44" {
4770        return Err(CoreError::InvalidMultikey(format!(
4771            "expected an ML-DSA-44 multikey, got {}",
4772            decoded.algorithm
4773        )));
4774    }
4775    coerce_mldsa44_public(&decoded.raw_key)
4776}
4777
4778fn pq_verification_method(credential: &Value) -> String {
4779    let issuer = credential
4780        .as_object()
4781        .and_then(|o| o.get("issuer"))
4782        .and_then(|v| v.as_str())
4783        .unwrap_or("");
4784    format!("{issuer}#key-1")
4785}
4786
4787/// The ML-DSA-44 verification method slot, matching the `#key-2` convention the
4788/// language SDKs derive for the post-quantum member of a proof set.
4789fn pq_mldsa_verification_method(credential: &Value) -> String {
4790    let issuer = credential
4791        .as_object()
4792        .and_then(|o| o.get("issuer"))
4793        .and_then(|v| v.as_str())
4794        .unwrap_or("");
4795    format!("{issuer}#key-2")
4796}
4797
4798/// Attach a hybrid (classical Ed25519 plus post-quantum ML-DSA-44) Data Integrity
4799/// proof to a pre-built robot `credential`. Any existing proof is replaced. The
4800/// robot signs with its Ed25519 seed and its ML-DSA-44 key pair; `created` is the
4801/// caller-supplied ISO-8601 instant, keeping the core deterministic.
4802pub fn sign_pq(
4803    credential: &Value,
4804    ed25519_seed: &[u8],
4805    mldsa: &MlDsa44KeyPair,
4806    created: &str,
4807) -> Result<Value> {
4808    let ed_vm = pq_verification_method(credential);
4809    let ml_vm = pq_mldsa_verification_method(credential);
4810    hybrid::sign_dual(credential, ed25519_seed, mldsa, &ed_vm, &ml_vm, created)
4811}
4812
4813/// Return true if `credential` carries a post-quantum proof, in either the
4814/// proof-set shape (a `proof` array holding an ML-DSA-44 proof) or the
4815/// pre-alignment composite shape.
4816pub fn is_pq(credential: &Value) -> bool {
4817    let proof = match credential.as_object().and_then(|o| o.get("proof")) {
4818        Some(p) => p,
4819        None => return false,
4820    };
4821    match proof {
4822        Value::Array(proofs) => proofs.iter().any(|p| {
4823            matches!(
4824                p.get("cryptosuite").and_then(|v| v.as_str()),
4825                Some(hybrid::MLDSA44_CRYPTOSUITE_ID) | Some(hybrid::MLDSA44_LEGACY_CRYPTOSUITE_ID)
4826            )
4827        }),
4828        Value::Object(o) => {
4829            o.get("cryptosuite").and_then(|v| v.as_str()) == Some(HYBRID_CRYPTOSUITE)
4830        }
4831        _ => false,
4832    }
4833}
4834
4835/// Verify a post-quantum robot credential in whichever shape it carries. Both
4836/// the Ed25519 and the ML-DSA-44 signatures MUST validate in either shape.
4837fn verify_pq_either_shape(
4838    credential: &Value,
4839    ed25519_public_key: &[u8],
4840    mldsa44_public_key: &[u8],
4841) -> Result<bool> {
4842    match credential.as_object().and_then(|o| o.get("proof")) {
4843        Some(Value::Array(_)) => {
4844            hybrid::verify_dual(credential, ed25519_public_key, mldsa44_public_key)
4845        }
4846        _ => hybrid::verify_composite(credential, ed25519_public_key, mldsa44_public_key),
4847    }
4848}
4849
4850/// Verify a hybrid robot credential. Both the Ed25519 and the ML-DSA-44 signature
4851/// MUST validate. `mldsa44_public_key` is raw 1312-byte bytes or an ML-DSA-44
4852/// Multikey string (pass `mldsa44_multikey` for the string form).
4853pub fn verify_pq(
4854    credential: &Value,
4855    ed25519_public_key: &[u8],
4856    mldsa44_public_key: &[u8],
4857) -> Result<bool> {
4858    let resolved_ml = coerce_mldsa44_public(mldsa44_public_key)?;
4859    verify_pq_either_shape(credential, ed25519_public_key, &resolved_ml)
4860}
4861
4862/// [`verify_robot_credential`] with the ML-DSA-44 key taken from a key source
4863/// like the Ed25519 key: a bare key, or a `{did: key}` map / resolver from which
4864/// the entry for the credential's issuer is used (no entry fails a
4865/// post-quantum credential). Map values are raw 1312-byte keys or ML-DSA-44
4866/// Multikey strings as UTF-8 bytes.
4867pub fn verify_robot_credential_keyed(
4868    credential: &Value,
4869    ed_keys: Keys<'_>,
4870    mldsa44_keys: Option<Keys<'_>>,
4871    expected_type: Option<&str>,
4872    now_iso: &str,
4873) -> Result<bool> {
4874    let ml = match mldsa44_keys {
4875        None => return verify_robot_credential(credential, ed_keys, None, expected_type, now_iso),
4876        Some(k) => k,
4877    };
4878    let issuer = rv::issuer_id(credential.get("issuer"))
4879        .unwrap_or("")
4880        .to_string();
4881    let picked: Option<Vec<u8>> = match ml {
4882        Keys::Embedded | Keys::Pinned(_) => None,
4883        Keys::Bare(k) => Some(k.to_vec()),
4884        Keys::One(d, k) => (d == issuer).then(|| k.to_vec()),
4885        Keys::Map(m) => m.get(&issuer).cloned(),
4886        Keys::Resolver(f) => f(&issuer),
4887    };
4888    match picked {
4889        Some(k) => verify_robot_credential(credential, ed_keys, Some(&k), expected_type, now_iso),
4890        // A post-quantum credential needs its issuer's ML-DSA key; a classical
4891        // one given an ML-DSA source is refused by the same rule as a bare key.
4892        None => Ok(false),
4893    }
4894}
4895
4896/// The backward-compatible robot credential verify a fleet uses while
4897/// migrating to post-quantum: auto-detects a hybrid proof set.
4898///
4899/// Every proof must be bound to the issuer (`proofPurpose` assertionMethod and
4900/// a verification method of the issuer DID), and the Ed25519 key must belong to
4901/// the issuer (the key inside a did:key, or `ed_keys` as a `{did: key}`
4902/// source for any other DID). Present validity bounds must be strict protocol
4903/// times with `now_iso` inside. When `expected_type` is given the credential
4904/// must carry it. A post-quantum credential requires `mldsa44_public_key`;
4905/// supplying one for a classical credential refuses it (so a stripped ML-DSA
4906/// proof cannot pass as classical). Malformed input returns `false`.
4907pub fn verify_robot_credential(
4908    credential: &Value,
4909    ed_keys: Keys<'_>,
4910    mldsa44_public_key: Option<&[u8]>,
4911    expected_type: Option<&str>,
4912    now_iso: &str,
4913) -> Result<bool> {
4914    let now = rv::require_now(now_iso)?;
4915    if !credential.is_object() {
4916        return Ok(false);
4917    }
4918    if is_pq(credential) {
4919        let ml = match mldsa44_public_key {
4920            Some(k) => k,
4921            None => return Ok(false),
4922        };
4923        let issuer = match rv::issuer_id(credential.get("issuer")) {
4924            Some(i) => i,
4925            None => return Ok(false),
4926        };
4927        if rv::input_too_large(credential, rv::MAX_CREDENTIAL_BYTES).is_some() {
4928            return Ok(false);
4929        }
4930        let types: Vec<&str> = match credential.get("type") {
4931            Some(Value::String(t)) => vec![t.as_str()],
4932            Some(Value::Array(a)) if a.iter().all(|t| t.is_string()) => {
4933                a.iter().filter_map(|t| t.as_str()).collect()
4934            }
4935            _ => return Ok(false),
4936        };
4937        if expected_type.is_some_and(|e| !types.contains(&e)) {
4938            return Ok(false);
4939        }
4940        let members: Vec<&Value> = match credential.get("proof") {
4941            Some(Value::Array(a)) => a.iter().collect(),
4942            Some(p) => vec![p],
4943            None => return Ok(false),
4944        };
4945        if members.is_empty()
4946            || members
4947                .iter()
4948                .any(|m| rv::proof_unbound_reason(m, issuer).is_some())
4949        {
4950            return Ok(false);
4951        }
4952        if rv::window_reason(credential, Window::IfPresent, now, 0).is_some() {
4953            return Ok(false);
4954        }
4955        let ed = match rv::resolve_issuer_key(issuer, ed_keys) {
4956            Ok(k) => k,
4957            Err(_) => return Ok(false),
4958        };
4959        let resolved_ml = match resolve_mldsa44_public(ml) {
4960            Ok(m) => m,
4961            Err(_) => return Ok(false),
4962        };
4963        return Ok(verify_pq_either_shape(credential, &ed, &resolved_ml).unwrap_or(false));
4964    }
4965    if mldsa44_public_key.is_some() {
4966        return Ok(false);
4967    }
4968    Ok(rv::verify_robotics_credential(
4969        credential,
4970        ed_keys,
4971        expected_type,
4972        now,
4973        VerifyOptions::window(Window::IfPresent),
4974    )
4975    .is_ok())
4976}
4977
4978/// Resolve an ML-DSA-44 public key given either raw bytes or a Multikey string.
4979/// A 1312-byte input is the raw key; otherwise it is parsed as a UTF-8 Multikey.
4980pub fn resolve_mldsa44_public(mldsa44_public_key: &[u8]) -> Result<Vec<u8>> {
4981    if mldsa44_public_key.len() == MLDSA44_PUBLIC_LEN {
4982        return Ok(mldsa44_public_key.to_vec());
4983    }
4984    let s = std::str::from_utf8(mldsa44_public_key).map_err(|_| {
4985        CoreError::InvalidMultikey("ML-DSA-44 key must be raw bytes or a Multikey string".into())
4986    })?;
4987    mldsa44_public_from_multikey(s)
4988}
4989
4990/// Re-sign a fielded robot's classical `credential` under the hybrid PQ
4991/// cryptosuite, preserving its body. The robot holds its current Ed25519 seed and
4992/// an ML-DSA-44 key pair; `created` is the caller-supplied re-signing instant.
4993pub fn migrate_to_pq(
4994    credential: &Value,
4995    ed25519_seed: &[u8],
4996    mldsa: &MlDsa44KeyPair,
4997    created: &str,
4998) -> Result<Value> {
4999    sign_pq(credential, ed25519_seed, mldsa, created)
5000}
5001
5002// ---------------------------------------------------------------------------
5003// Cross-embodiment identity continuity (Phase 5.15)
5004// ---------------------------------------------------------------------------
5005//
5006// An AI agent (a policy with its own Vouch identity) can run on one robot body
5007// today and a different body tomorrow. An embodiment credential binds the agent
5008// identity to a specific body (a hardware-rooted robot identity) and that body's
5009// hardware root for a period, signed by the agent's own persistent key. Linking
5010// each embodiment to the previous forms a continuity chain a verifier walks to
5011// confirm the same accountable agent persisted across bodies, re-binding to each
5012// body's hardware root as it moved. A fork check confirms the agent was never
5013// actively embodied in two bodies at once.
5014//
5015// This is the inverse of the ownership custody chain: there one body passes
5016// between owners; here one mind passes between bodies, and the constant that
5017// signs every link is the agent identity itself.
5018//
5019// This is the open layer: plain signed embodiment credentials, continuity-chain
5020// verification, and software fork detection. It reuses the core proof path
5021// ([`data_integrity`]) rather than re-deriving any cryptography.
5022
5023pub const EMBODIMENT_TYPE: &str = "AgentEmbodimentCredential";
5024
5025/// Parameters for [`build_embodiment`]. The signer is the agent's own persistent
5026/// key; `agent_did` is both issuer and subject id, so the whole continuity chain
5027/// is signed by one accountable identity. `from_body`, when set, links this
5028/// embodiment to the body the agent left, forming the chain. `valid_until`, when
5029/// set, bounds the active window (used by [`check_no_fork`]).
5030#[derive(Debug, Clone)]
5031pub struct BuildEmbodiment {
5032    pub agent_did: String,
5033    pub body_did: String,
5034    pub body_hardware_root: String,
5035    pub from_body: Option<String>,
5036    pub embodied_at: String,
5037    pub valid_until: Option<String>,
5038}
5039
5040/// Build a signed embodiment credential: the agent `agent_did` authorizes running
5041/// on `body_did`, re-binding to that body's hardware root `body_hardware_root`.
5042/// Signed by the agent's own persistent key. `from_body` links this embodiment to
5043/// the body the agent left.
5044pub fn build_embodiment(agent_seed: &[u8], params: &BuildEmbodiment) -> Result<Value> {
5045    if params.agent_did.is_empty()
5046        || params.body_did.is_empty()
5047        || params.body_hardware_root.is_empty()
5048    {
5049        return Err(CoreError::Json(
5050            "agent_did, body_did, and body_hardware_root are required".into(),
5051        ));
5052    }
5053
5054    let mut subject = Map::new();
5055    subject.insert("id".into(), json!(params.agent_did));
5056    subject.insert("body".into(), json!(params.body_did));
5057    subject.insert("bodyHardwareRoot".into(), json!(params.body_hardware_root));
5058    if let Some(from_body) = &params.from_body {
5059        subject.insert("fromBody".into(), json!(from_body));
5060    }
5061
5062    let mut cred = Map::new();
5063    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
5064    cred.insert(
5065        "type".into(),
5066        json!(["VerifiableCredential", EMBODIMENT_TYPE]),
5067    );
5068    cred.insert("issuer".into(), json!(params.agent_did));
5069    cred.insert("validFrom".into(), json!(params.embodied_at));
5070    if let Some(vu) = &params.valid_until {
5071        cred.insert("validUntil".into(), json!(vu));
5072    }
5073    cred.insert("credentialSubject".into(), Value::Object(subject));
5074
5075    let opts = BuildProofOptions::new(format!("{}#key-1", params.agent_did), &params.embodied_at);
5076    data_integrity::sign(&Value::Object(cred), agent_seed, &opts)
5077}
5078
5079/// Verify an embodiment credential: the agent's proof bound to the agent as
5080/// issuer (a mind authorizes its own embodiment, so the issuer must be
5081/// `credentialSubject.id`), the window at `now_iso` (validFrom required), and
5082/// that the subject carries a `body` and a `bodyHardwareRoot`. When
5083/// `body_hardware_roots` (body DID -> trusted hardware-root key) is given, the
5084/// credential's `bodyHardwareRoot` must match the entry for its body. Returns
5085/// the credentialSubject on success, `None` if invalid.
5086pub fn verify_embodiment(
5087    credential: &Value,
5088    agent_keys: Keys<'_>,
5089    body_hardware_roots: Option<&std::collections::BTreeMap<String, String>>,
5090    now_iso: &str,
5091) -> Result<Option<Value>> {
5092    let v = match bound(
5093        credential,
5094        agent_keys,
5095        EMBODIMENT_TYPE,
5096        now_iso,
5097        Window::FromRequired,
5098    )? {
5099        Some(v) if issuer_is_subject(&v) => v,
5100        _ => return Ok(None),
5101    };
5102    let body = non_empty_str(&v.subject, "body");
5103    let root = non_empty_str(&v.subject, "bodyHardwareRoot");
5104    let (body, root) = match (body, root) {
5105        (Some(b), Some(r)) => (b, r),
5106        _ => return Ok(None),
5107    };
5108    if let Some(roots) = body_hardware_roots {
5109        if roots.get(body).map(String::as_str) != Some(root) {
5110            return Ok(None);
5111        }
5112    }
5113    Ok(Some(v.subject))
5114}
5115
5116/// Verify an ordered list of embodiment credentials forms a valid continuity
5117/// chain: every link verifies under the same agent (the persistent mind), each
5118/// link's `fromBody` matches the previous link's `body`, and (when given) the
5119/// first `fromBody` is `origin_body`. Links start in order; each earlier link
5120/// must still have been valid when the next one started, and the last link
5121/// must be valid at `now_iso`. The verified links are then checked for forks.
5122/// Returns `(ok, current_body)`.
5123pub fn verify_continuity_chain(
5124    embodiments: &[Value],
5125    agent_keys: Keys<'_>,
5126    origin_body: Option<&str>,
5127    body_hardware_roots: Option<&std::collections::BTreeMap<String, String>>,
5128    now_iso: &str,
5129) -> Result<(bool, Option<String>)> {
5130    rv::require_now(now_iso)?;
5131    let mut expected_from: Option<String> = origin_body.map(String::from);
5132    let mut current_body: Option<String> = origin_body.map(String::from);
5133    let mut agent: Option<String> = None;
5134    let mut prev_start: Option<i128> = None;
5135    for (i, embodiment) in embodiments.iter().enumerate() {
5136        let at: String = match embodiments.get(i + 1) {
5137            Some(next) => match next.get("validFrom").and_then(|v| v.as_str()) {
5138                Some(t) if rv::time_ns(next.get("validFrom")).is_some() => t.to_string(),
5139                _ => return Ok((false, None)),
5140            },
5141            None => now_iso.to_string(),
5142        };
5143        let subject = match verify_embodiment(embodiment, agent_keys, body_hardware_roots, &at)? {
5144            Some(s) => s,
5145            None => return Ok((false, None)),
5146        };
5147        let id = subject.get("id").and_then(|v| v.as_str()).map(String::from);
5148        match &agent {
5149            None => agent = id,
5150            Some(a) if id.as_deref() == Some(a.as_str()) => {}
5151            _ => return Ok((false, None)),
5152        }
5153        match rv::time_ns(embodiment.get("validFrom")) {
5154            Some(t) if prev_start.is_none_or(|p| t >= p) => prev_start = Some(t),
5155            _ => return Ok((false, None)),
5156        }
5157        if let Some(expected) = &expected_from {
5158            if subject.get("fromBody").and_then(|v| v.as_str()) != Some(expected.as_str()) {
5159                return Ok((false, None));
5160            }
5161        }
5162        current_body = subject
5163            .get("body")
5164            .and_then(|v| v.as_str())
5165            .map(String::from);
5166        expected_from = current_body.clone();
5167    }
5168    if !check_no_fork(embodiments)?.0 {
5169        return Ok((false, None));
5170    }
5171    Ok((true, current_body))
5172}
5173
5174/// Two conflicting bodies surfaced by [`check_no_fork`].
5175#[derive(Debug, Clone, PartialEq, Eq)]
5176pub struct ForkConflict {
5177    pub body_a: String,
5178    pub body_b: String,
5179}
5180
5181/// Half-open intervals [start, end); a missing end is open-ended (+infinity). A
5182/// clean handover sets one window's end to the next window's start, which does not
5183/// overlap.
5184fn windows_overlap(start_a: i128, end_a: Option<i128>, start_b: i128, end_b: Option<i128>) -> bool {
5185    let a_before_b = end_a.map(|e| e <= start_b).unwrap_or(false);
5186    let b_before_a = end_b.map(|e| e <= start_a).unwrap_or(false);
5187    !(a_before_b || b_before_a)
5188}
5189
5190/// Confirm no two embodiments place the agent in different bodies with overlapping
5191/// active windows. Each embodiment is active from `validFrom` to `validUntil` (a
5192/// missing `validUntil` is treated as open-ended). Two embodiments on different
5193/// bodies whose windows overlap are a fork. Returns `(ok, conflict)` where
5194/// conflict, when present, names the two conflicting bodies.
5195pub fn check_no_fork(embodiments: &[Value]) -> Result<(bool, Option<ForkConflict>)> {
5196    let mut windows: Vec<(String, i128, Option<i128>)> = Vec::with_capacity(embodiments.len());
5197    for embodiment in embodiments {
5198        let subject = embodiment
5199            .get("credentialSubject")
5200            .and_then(|s| s.as_object());
5201        let body = subject
5202            .and_then(|s| s.get("body"))
5203            .and_then(|v| v.as_str())
5204            .filter(|s| !s.is_empty());
5205        let start = rv::time_ns(embodiment.get("validFrom"));
5206        let (body, start) = match (body, start) {
5207            (Some(b), Some(s)) => (b.to_string(), s),
5208            _ => return Ok((false, None)),
5209        };
5210        // A present end must be a strict time; only an absent end is open-ended.
5211        let end = match embodiment.get("validUntil") {
5212            None => None,
5213            Some(v) => match rv::time_ns(Some(v)) {
5214                Some(t) => Some(t),
5215                None => return Ok((false, None)),
5216            },
5217        };
5218        windows.push((body, start, end));
5219    }
5220
5221    for i in 0..windows.len() {
5222        let (body_i, start_i, end_i) = &windows[i];
5223        for window_j in windows.iter().skip(i + 1) {
5224            let (body_j, start_j, end_j) = window_j;
5225            if body_i == body_j {
5226                continue;
5227            }
5228            if windows_overlap(*start_i, *end_i, *start_j, *end_j) {
5229                return Ok((
5230                    false,
5231                    Some(ForkConflict {
5232                        body_a: body_i.clone(),
5233                        body_b: body_j.clone(),
5234                    }),
5235                ));
5236            }
5237        }
5238    }
5239    Ok((true, None))
5240}
5241
5242// ---------------------------------------------------------------------------
5243// Physical custody handoff (Phase 5.16)
5244// ---------------------------------------------------------------------------
5245//
5246// A physical task or object passes across a chain of actors, human and robot: a
5247// person picks an item, hands it to a robot, that robot hands it to another
5248// robot, which places it. Each handoff is a signed custody transition, so a
5249// physical-world event traces to the exact hop and the actor responsible.
5250//
5251// A custody handoff credential records that a receiving actor accepted custody
5252// of a task or object from a releasing actor, signed by the receiver. Linking
5253// each handoff to the previous forms a chain a verifier walks to establish who
5254// held the task at any time. A condition attested at each handoff lets a state
5255// change be localized to the specific hop whose holder was responsible.
5256//
5257// This is the open layer: signed handoff credentials, chain verification, a
5258// holder-at-time helper, and software condition localization. It reuses the core
5259// proof path ([`data_integrity`]) rather than re-deriving any cryptography.
5260
5261pub const CUSTODY_HANDOFF_TYPE: &str = "CustodyHandoffCredential";
5262
5263/// A signed custody release: the actor handing a task over states that it
5264/// releases custody to the receiver. The receiver embeds it in its handoff.
5265pub const CUSTODY_RELEASE_TYPE: &str = "CustodyReleaseCredential";
5266
5267/// Build a signed custody release by `releaser_did` (the signer) for
5268/// `task_id` to `to_actor`, dated `released_at`.
5269pub fn build_release(
5270    releaser_seed: &[u8],
5271    releaser_did: &str,
5272    task_id: &str,
5273    to_actor: &str,
5274    released_at: &str,
5275) -> Result<Value> {
5276    if task_id.is_empty() || to_actor.is_empty() {
5277        return Err(CoreError::Json("task_id and to_actor are required".into()));
5278    }
5279    let cred = json!({
5280        "@context": [VC_CONTEXT_V2, VOUCH_CONTEXT_V1],
5281        "type": ["VerifiableCredential", CUSTODY_RELEASE_TYPE],
5282        "issuer": releaser_did,
5283        "validFrom": released_at,
5284        "credentialSubject": {"id": task_id, "fromActor": releaser_did, "toActor": to_actor},
5285    });
5286    let opts = BuildProofOptions::new(format!("{releaser_did}#key-1"), released_at);
5287    data_integrity::sign(&cred, releaser_seed, &opts)
5288}
5289
5290/// Parameters for [`build_handoff`]. The signer is the receiver (`to_actor`), the
5291/// party taking responsibility. `condition`, when set, attests the state of the
5292/// task or object as received, which lets a later state change be localized to
5293/// a hop. `release` is the releasing actor's signed [`build_release`]
5294/// credential (a chain verifier requires it). `prev_handoff_id` is the previous
5295/// handoff's `id`; `credential_id` is this handoff's own `id`. `valid_until`,
5296/// when set, bounds the handoff's active window.
5297#[derive(Debug, Clone)]
5298pub struct BuildHandoff {
5299    pub task_id: String,
5300    pub from_actor: String,
5301    pub to_actor: String,
5302    pub condition: Option<String>,
5303    pub handoff_at: String,
5304    pub valid_until: Option<String>,
5305    pub release: Option<Value>,
5306    pub prev_handoff_id: Option<String>,
5307    pub credential_id: String,
5308}
5309
5310/// Build a signed custody handoff: the receiving actor `to_actor` accepts custody
5311/// of `task_id` from `from_actor`, signed by the receiver. The issuer is the
5312/// receiver, so a party attests its own acceptance of custody.
5313pub fn build_handoff(receiver_seed: &[u8], params: &BuildHandoff) -> Result<Value> {
5314    if params.task_id.is_empty() || params.from_actor.is_empty() || params.to_actor.is_empty() {
5315        return Err(CoreError::Json(
5316            "task_id, from_actor, and to_actor are required".into(),
5317        ));
5318    }
5319    if params.credential_id.is_empty() {
5320        return Err(CoreError::Json("credential_id is required".into()));
5321    }
5322
5323    let mut subject = Map::new();
5324    subject.insert("id".into(), json!(params.task_id));
5325    subject.insert("fromActor".into(), json!(params.from_actor));
5326    subject.insert("toActor".into(), json!(params.to_actor));
5327    if let Some(condition) = &params.condition {
5328        subject.insert("condition".into(), json!(condition));
5329    }
5330    if let Some(release) = &params.release {
5331        subject.insert("release".into(), release.clone());
5332    }
5333    if let Some(prev) = &params.prev_handoff_id {
5334        subject.insert("prevHandoffId".into(), json!(prev));
5335    }
5336
5337    let mut cred = Map::new();
5338    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
5339    cred.insert("id".into(), json!(params.credential_id));
5340    cred.insert(
5341        "type".into(),
5342        json!(["VerifiableCredential", CUSTODY_HANDOFF_TYPE]),
5343    );
5344    cred.insert("issuer".into(), json!(params.to_actor));
5345    cred.insert("validFrom".into(), json!(params.handoff_at));
5346    if let Some(vu) = &params.valid_until {
5347        cred.insert("validUntil".into(), json!(vu));
5348    }
5349    cred.insert("credentialSubject".into(), Value::Object(subject));
5350
5351    let opts = BuildProofOptions::new(format!("{}#key-1", params.to_actor), &params.handoff_at);
5352    data_integrity::sign(&Value::Object(cred), receiver_seed, &opts)
5353}
5354
5355/// True when the handoff `subject` embeds a release signed by its `fromActor`
5356/// that names the same task and receiver.
5357fn release_ok(subject: &Value, releaser_keys: Keys<'_>, now_ns: i128) -> bool {
5358    let release = match subject.get("release") {
5359        Some(r) => r,
5360        None => return false,
5361    };
5362    let v = match rv::verify_robotics_credential(
5363        release,
5364        releaser_keys,
5365        Some(CUSTODY_RELEASE_TYPE),
5366        now_ns,
5367        VerifyOptions::window(Window::FromRequired),
5368    ) {
5369        Ok(v) => v,
5370        Err(_) => return false,
5371    };
5372    let s = |x: &Value, k: &str| x.get(k).and_then(|y| y.as_str()).map(String::from);
5373    Some(v.issuer.clone()) == s(subject, "fromActor")
5374        && s(&v.subject, "fromActor").as_deref() == Some(v.issuer.as_str())
5375        && s(&v.subject, "id") == s(subject, "id")
5376        && s(&v.subject, "toActor") == s(subject, "toActor")
5377}
5378
5379/// Options for [`verify_handoff`].
5380#[derive(Clone, Copy, Default)]
5381pub struct HandoffCheck<'a> {
5382    /// The handoff must be for this task.
5383    pub task_id: Option<&'a str>,
5384    /// Key source for the releasing actor; giving one requires the release.
5385    pub releaser_keys: Option<Keys<'a>>,
5386    /// Require the releasing actor's signed release (keys from the receiver
5387    /// source when no `releaser_keys` is given).
5388    pub require_release: bool,
5389    /// The releasing actor the caller expects. The release must be signed by
5390    /// it and name it as `fromActor`; with no releaser key a did:key releaser
5391    /// verifies under its own key only when this names it, and the receiver
5392    /// is then pinned to the toActor that verified release names.
5393    pub from_actor: Option<&'a str>,
5394}
5395
5396/// Verify a custody handoff: the receiver's proof bound to the issuer, the
5397/// issuer is the receiving actor (`toActor`), `id` / `fromActor` / `toActor`
5398/// are non-empty strings, and the window at `now_iso` (validFrom required).
5399/// With [`HandoffCheck`] options, the task is pinned and the embedded release
5400/// must be signed by the `fromActor` and name the same task and receiver.
5401pub fn verify_handoff(
5402    credential: &Value,
5403    receiver_keys: Keys<'_>,
5404    check: HandoffCheck<'_>,
5405    now_iso: &str,
5406) -> Result<Option<Value>> {
5407    let now = rv::require_now(now_iso)?;
5408    let releaser_keys = rv::pin_if_keyless(
5409        check.releaser_keys.unwrap_or(receiver_keys),
5410        check.from_actor,
5411    );
5412    // With no receiver key, the receiver is pinned to the toActor named by the
5413    // release the pinned releaser signed.
5414    let mut receiver_pin: Option<String> = None;
5415    if check.from_actor.is_some() && rv::no_key_source(&receiver_keys) {
5416        if let Some(rel) = credential
5417            .get("credentialSubject")
5418            .and_then(|s| s.get("release"))
5419        {
5420            if let Ok(r) = rv::verify_robotics_credential(
5421                rel,
5422                releaser_keys,
5423                Some(CUSTODY_RELEASE_TYPE),
5424                now,
5425                VerifyOptions::window(Window::FromRequired),
5426            ) {
5427                if r.subject.get("fromActor").and_then(|x| x.as_str()) == Some(r.issuer.as_str()) {
5428                    receiver_pin = non_empty_str(&r.subject, "toActor").map(String::from);
5429                }
5430            }
5431        }
5432    }
5433    let v = match rv::verify_robotics_credential(
5434        credential,
5435        rv::pin_if_keyless(receiver_keys, receiver_pin.as_deref()),
5436        Some(CUSTODY_HANDOFF_TYPE),
5437        now,
5438        VerifyOptions::window(Window::FromRequired),
5439    ) {
5440        Ok(v) => v,
5441        Err(_) => return Ok(None),
5442    };
5443    for f in ["id", "fromActor", "toActor"] {
5444        if non_empty_str(&v.subject, f).is_none() {
5445            return Ok(None);
5446        }
5447    }
5448    if v.subject.get("toActor").and_then(|x| x.as_str()) != Some(v.issuer.as_str()) {
5449        return Ok(None);
5450    }
5451    if check
5452        .task_id
5453        .is_some_and(|t| v.subject.get("id").and_then(|x| x.as_str()) != Some(t))
5454    {
5455        return Ok(None);
5456    }
5457    if check
5458        .from_actor
5459        .is_some_and(|f| v.subject.get("fromActor").and_then(|x| x.as_str()) != Some(f))
5460    {
5461        return Ok(None);
5462    }
5463    if (check.require_release || check.releaser_keys.is_some() || check.from_actor.is_some())
5464        && !release_ok(&v.subject, releaser_keys, now)
5465    {
5466        return Ok(None);
5467    }
5468    Ok(Some(v.subject))
5469}
5470
5471/// One actor's public key, looked up by actor DID, for [`verify_handoff_chain`].
5472#[derive(Debug, Clone)]
5473pub struct ActorKey {
5474    pub did: String,
5475    pub public_key: Vec<u8>,
5476}
5477
5478/// Verify an ordered list of handoff credentials forms a valid custody chain for
5479/// `task_id`: every handoff verifies under its receiver's key and (with
5480/// `require_release`) carries a release signed by its releasing actor (keys for
5481/// both from `public_keys`); each `toActor` matches the next link's
5482/// `fromActor`; each link after the first names the previous link's `id` as
5483/// `prevHandoffId`; links are in time order; and the first `fromActor` is
5484/// `origin_actor`. Each earlier link must still have been valid when the next
5485/// began, and the last at `now_iso`. Returns `(ok, current_holder)`.
5486///
5487/// `origin_actor` is required: with no known first holder, anyone could sign a
5488/// first link handing the task from themselves. Each link's releaser is pinned
5489/// (the origin, then each `toActor`), so did:key actors verify under their own
5490/// keys even with no entry in `public_keys`.
5491pub fn verify_handoff_chain(
5492    handoffs: &[Value],
5493    public_keys: &[ActorKey],
5494    task_id: &str,
5495    origin_actor: Option<&str>,
5496    require_release: bool,
5497    now_iso: &str,
5498) -> Result<(bool, Option<String>)> {
5499    rv::require_now(now_iso)?;
5500    if task_id.is_empty() || origin_actor.is_none_or(str::is_empty) {
5501        return Ok((false, None));
5502    }
5503    let map = Keys::map_of(public_keys.iter().map(|k| (k.did.clone(), &k.public_key)));
5504    let keys = Keys::Map(&map);
5505    let mut expected_from: Option<String> = origin_actor.map(String::from);
5506    let mut current_holder: Option<String> = origin_actor.map(String::from);
5507    let mut prev_id: Option<String> = None;
5508    let mut prev_time: Option<i128> = None;
5509    for (i, handoff) in handoffs.iter().enumerate() {
5510        let at: String = match handoffs.get(i + 1) {
5511            Some(next) => match next.get("validFrom").and_then(|v| v.as_str()) {
5512                Some(t) if rv::time_ns(next.get("validFrom")).is_some() => t.to_string(),
5513                _ => return Ok((false, None)),
5514            },
5515            None => now_iso.to_string(),
5516        };
5517        let check = HandoffCheck {
5518            task_id: Some(task_id),
5519            releaser_keys: if require_release { Some(keys) } else { None },
5520            require_release,
5521            from_actor: if require_release {
5522                expected_from.as_deref()
5523            } else {
5524                None
5525            },
5526        };
5527        let subject = match verify_handoff(handoff, keys, check, &at)? {
5528            Some(s) => s,
5529            None => return Ok((false, None)),
5530        };
5531        if let Some(expected) = &expected_from {
5532            if subject.get("fromActor").and_then(|v| v.as_str()) != Some(expected.as_str()) {
5533                return Ok((false, None));
5534            }
5535        }
5536        match rv::time_ns(handoff.get("validFrom")) {
5537            Some(t) if prev_time.is_none_or(|p| t >= p) => prev_time = Some(t),
5538            _ => return Ok((false, None)),
5539        }
5540        if i > 0 {
5541            match &prev_id {
5542                Some(p) if subject.get("prevHandoffId").and_then(|v| v.as_str()) == Some(p) => {}
5543                _ => return Ok((false, None)),
5544            }
5545        }
5546        prev_id = non_empty_str(handoff, "id").map(String::from);
5547        current_holder = subject
5548            .get("toActor")
5549            .and_then(|v| v.as_str())
5550            .map(String::from);
5551        expected_from = current_holder.clone();
5552    }
5553    Ok((true, current_holder))
5554}
5555
5556/// Return the actor holding the task at protocol time `at`: the receiver
5557/// (`toActor`) of the most recent handoff whose `validFrom` is at or before
5558/// `at`. Returns `None` if no handoff had occurred yet or `at` is not a strict
5559/// protocol time. `handoffs` is assumed in chain order.
5560pub fn holder_at(handoffs: &[Value], at: &str) -> Option<String> {
5561    let when = crate::time::parse_protocol_time_ns(at).ok()?;
5562    let mut holder: Option<String> = None;
5563    for handoff in handoffs {
5564        if let Some(start) = rv::time_ns(handoff.get("validFrom")) {
5565            if start <= when {
5566                holder = handoff
5567                    .get("credentialSubject")
5568                    .and_then(|s| s.get("toActor"))
5569                    .and_then(|v| v.as_str())
5570                    .map(String::from);
5571            }
5572        }
5573    }
5574    holder
5575}
5576
5577/// A condition change localized to the hop responsible for it, surfaced by
5578/// [`locate_condition_change`].
5579#[derive(Debug, Clone, PartialEq, Eq)]
5580pub struct ConditionChange {
5581    pub responsible_holder: Option<String>,
5582    pub from_condition: String,
5583    pub to_condition: String,
5584}
5585
5586/// Find the first hop where the attested condition differs from the previous
5587/// handoff. The holder responsible for the change is the actor who held the task
5588/// during it (the previous handoff's receiver). Returns the change, or `None` if
5589/// the condition never changed. Handoffs without a condition are skipped for the
5590/// comparison.
5591pub fn locate_condition_change(handoffs: &[Value]) -> Option<ConditionChange> {
5592    let mut prev_condition: Option<String> = None;
5593    let mut prev_holder: Option<String> = None;
5594    for handoff in handoffs {
5595        let subject = handoff.get("credentialSubject");
5596        let condition = subject
5597            .and_then(|s| s.get("condition"))
5598            .and_then(|v| v.as_str());
5599        let condition = match condition {
5600            Some(c) => c,
5601            None => continue,
5602        };
5603        if let Some(prev) = &prev_condition {
5604            if condition != prev {
5605                return Some(ConditionChange {
5606                    responsible_holder: prev_holder,
5607                    from_condition: prev.clone(),
5608                    to_condition: condition.to_string(),
5609                });
5610            }
5611        }
5612        prev_condition = Some(condition.to_string());
5613        prev_holder = subject
5614            .and_then(|s| s.get("toActor"))
5615            .and_then(|v| v.as_str())
5616            .map(String::from);
5617    }
5618    None
5619}
5620
5621// ---------------------------------------------------------------------------
5622// Robot-to-infrastructure bounded access (Phase 5.17)
5623// ---------------------------------------------------------------------------
5624//
5625// A robot in a warehouse, hospital, or building needs to open doors, call
5626// elevators, dock at chargers, and operate machines. This gives it a bounded,
5627// revocable, auditable way to do so. The infrastructure operator issues an access
5628// grant naming a resource, the permitted operations, an optional zone, and a time
5629// window, signed by the operator. The robot presents a signed access request for a
5630// specific operation on a specific resource, and the resource authorizes it
5631// offline: the grant must be valid and operator-signed, the request valid and
5632// robot-signed, the operation permitted, and the moment inside the window. The
5633// grant plus the request is a tamper-evident, attributable record of the access.
5634//
5635// This is the open layer: signed grants and requests, an offline authorize
5636// decision, shrink-only attenuation, and the audit record. Hardware-enforced
5637// actuation in the resource and managed fleet access-policy orchestration are out
5638// of scope for the open layer.
5639
5640pub const ACCESS_GRANT_TYPE: &str = "InfrastructureAccessGrant";
5641pub const ACCESS_REQUEST_TYPE: &str = "InfrastructureAccessRequest";
5642
5643/// Parameters for [`build_access_grant`]. The signer is the operator; the grant
5644/// names the robot, the resource, the permitted operations, an optional zone, and
5645/// a validity window. `valid_until`, when set, bounds the window (the wrapper
5646/// derives it from a `valid_seconds` lifetime added to `granted_at`, keeping the
5647/// core's clock caller-supplied).
5648#[derive(Debug, Clone)]
5649pub struct BuildAccessGrant {
5650    pub operator_did: String,
5651    pub robot_did: String,
5652    pub resource: String,
5653    pub operations: Vec<String>,
5654    pub zone: Option<String>,
5655    pub granted_at: String,
5656    pub valid_until: Option<String>,
5657}
5658
5659/// Build a signed access grant: the operator grants `robot_did` permission to
5660/// perform `operations` on `resource` (optionally within `zone`) for the window.
5661/// Signed by the operator.
5662pub fn build_access_grant(operator_seed: &[u8], params: &BuildAccessGrant) -> Result<Value> {
5663    if params.robot_did.is_empty() || params.resource.is_empty() {
5664        return Err(CoreError::Json(
5665            "robot_did and resource are required".into(),
5666        ));
5667    }
5668    if params.operations.is_empty() {
5669        return Err(CoreError::Json(
5670            "operations must be a non-empty list".into(),
5671        ));
5672    }
5673
5674    let mut subject = Map::new();
5675    subject.insert("id".into(), json!(params.robot_did));
5676    subject.insert("resource".into(), json!(params.resource));
5677    subject.insert("operations".into(), json!(params.operations));
5678    if let Some(zone) = &params.zone {
5679        subject.insert("zone".into(), json!(zone));
5680    }
5681
5682    let mut cred = Map::new();
5683    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
5684    cred.insert(
5685        "type".into(),
5686        json!(["VerifiableCredential", ACCESS_GRANT_TYPE]),
5687    );
5688    cred.insert("issuer".into(), json!(params.operator_did));
5689    cred.insert("validFrom".into(), json!(params.granted_at));
5690    if let Some(vu) = &params.valid_until {
5691        cred.insert("validUntil".into(), json!(vu));
5692    }
5693    cred.insert("credentialSubject".into(), Value::Object(subject));
5694
5695    let opts = BuildProofOptions::new(format!("{}#key-1", params.operator_did), &params.granted_at);
5696    data_integrity::sign(&Value::Object(cred), operator_seed, &opts)
5697}
5698
5699/// Verify an access grant: the operator's proof bound to the issuer
5700/// (`operator_keys` is a `{did: key}` source, or the bare key of a did:key
5701/// operator), validFrom and validUntil present strict protocol times with
5702/// `now_iso` inside, a non-empty string `resource`, a non-empty list of string
5703/// `operations`, and (when given) the operator in `trusted_operators`. Returns
5704/// the credentialSubject on success, `None` if invalid.
5705pub fn verify_access_grant(
5706    credential: &Value,
5707    operator_keys: Keys<'_>,
5708    trusted_operators: Option<&HashSet<String>>,
5709    now_iso: &str,
5710) -> Result<Option<Value>> {
5711    let now = rv::require_now(now_iso)?;
5712    let opts = VerifyOptions {
5713        trusted_issuers: trusted_operators,
5714        ..VerifyOptions::window(Window::Required)
5715    };
5716    let v = match rv::verify_robotics_credential(
5717        credential,
5718        operator_keys,
5719        Some(ACCESS_GRANT_TYPE),
5720        now,
5721        opts,
5722    ) {
5723        Ok(v) => v,
5724        Err(_) => return Ok(None),
5725    };
5726    if non_empty_str(&v.subject, "resource").is_none() {
5727        return Ok(None);
5728    }
5729    match v.subject.get("operations") {
5730        Some(Value::Array(ops)) if !ops.is_empty() && ops.iter().all(|o| o.is_string()) => {}
5731        _ => return Ok(None),
5732    }
5733    Ok(Some(v.subject))
5734}
5735
5736/// Parameters for [`build_access_request`]. The signer is the robot; the request
5737/// names the resource and the single operation the robot wants to perform.
5738#[derive(Debug, Clone)]
5739pub struct BuildAccessRequest {
5740    pub robot_did: String,
5741    pub resource: String,
5742    pub operation: String,
5743    pub requested_at: String,
5744    /// A one-time value the resource remembers to refuse a replay.
5745    pub nonce: String,
5746}
5747
5748/// Build a signed access request: the robot requests to perform `operation` on
5749/// `resource`. Signed by the robot.
5750pub fn build_access_request(robot_seed: &[u8], params: &BuildAccessRequest) -> Result<Value> {
5751    if params.robot_did.is_empty() || params.resource.is_empty() || params.operation.is_empty() {
5752        return Err(CoreError::Json(
5753            "robot_did, resource, and operation are required".into(),
5754        ));
5755    }
5756    if params.nonce.is_empty() {
5757        return Err(CoreError::Json("nonce is required".into()));
5758    }
5759
5760    let mut subject = Map::new();
5761    subject.insert("id".into(), json!(params.robot_did));
5762    subject.insert("resource".into(), json!(params.resource));
5763    subject.insert("operation".into(), json!(params.operation));
5764    subject.insert("nonce".into(), json!(params.nonce));
5765
5766    let mut cred = Map::new();
5767    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
5768    cred.insert(
5769        "type".into(),
5770        json!(["VerifiableCredential", ACCESS_REQUEST_TYPE]),
5771    );
5772    cred.insert("issuer".into(), json!(params.robot_did));
5773    cred.insert("validFrom".into(), json!(params.requested_at));
5774    cred.insert("credentialSubject".into(), Value::Object(subject));
5775
5776    let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), &params.requested_at);
5777    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
5778}
5779
5780/// The outcome of an offline access authorization: `ok` plus any reasons it
5781/// failed. Surfaced by [`authorize_access`].
5782#[derive(Debug, Clone)]
5783pub struct AuthorizeResult {
5784    pub ok: bool,
5785    pub reasons: Vec<String>,
5786}
5787
5788/// Decide, offline, whether to allow the requested access. The grant must verify
5789/// under the operator's key and be in window, the request must verify bound to
5790/// the robot as issuer (and name it as subject) with validFrom no later than
5791/// `now_iso` (keys are `{did: key}` sources, or bare keys of did:key parties), the grant and request must
5792/// name the same robot and resource, and the requested operation must be permitted
5793/// by the grant. Returns an [`AuthorizeResult`] with the reasons for any refusal.
5794/// How old an access request may be by default (seconds).
5795pub const DEFAULT_MAX_REQUEST_AGE_SECONDS: i64 = 60;
5796
5797/// Replay limits for [`authorize_access`]: the request may be no older than
5798/// `max_age_seconds` and not from the future (both with `clock_skew_seconds`),
5799/// and its nonce must not be in `seen_nonces` (it is added when access is
5800/// allowed).
5801pub struct RequestReplay<'a> {
5802    pub seen_nonces: &'a mut HashSet<String>,
5803    pub max_age_seconds: i64,
5804    pub clock_skew_seconds: i64,
5805    /// With no operator key, the grant verifies only when its did:key
5806    /// operator is in this non-empty set.
5807    pub trusted_operators: Option<&'a HashSet<String>>,
5808}
5809
5810impl<'a> RequestReplay<'a> {
5811    /// The default limits (60 s age, 30 s skew) over `seen_nonces`.
5812    pub fn new(seen_nonces: &'a mut HashSet<String>) -> Self {
5813        Self {
5814            seen_nonces,
5815            max_age_seconds: DEFAULT_MAX_REQUEST_AGE_SECONDS,
5816            clock_skew_seconds: 30,
5817            trusted_operators: None,
5818        }
5819    }
5820}
5821
5822pub fn authorize_access(
5823    grant: &Value,
5824    request: &Value,
5825    operator_keys: Keys<'_>,
5826    robot_keys: Keys<'_>,
5827    replay: RequestReplay<'_>,
5828    now_iso: &str,
5829) -> Result<AuthorizeResult> {
5830    let current = rv::require_now(now_iso)?;
5831    let mut reasons: Vec<String> = Vec::new();
5832
5833    let grant_subject =
5834        match verify_access_grant(grant, operator_keys, replay.trusted_operators, now_iso)? {
5835            Some(s) => s,
5836            None => {
5837                reasons.push("grant invalid or out of window".into());
5838                return Ok(AuthorizeResult { ok: false, reasons });
5839            }
5840        };
5841
5842    // With no robot key, only the robot the verified grant names may sign.
5843    let granted_robot = grant_subject
5844        .get("id")
5845        .and_then(|v| v.as_str())
5846        .map(String::from);
5847    let req_subject = match bound(
5848        request,
5849        rv::pin_if_keyless(robot_keys, granted_robot.as_deref()),
5850        ACCESS_REQUEST_TYPE,
5851        now_iso,
5852        Window::FromRequired,
5853    )? {
5854        Some(v) if issuer_is_subject(&v) => v.subject,
5855        _ => {
5856            reasons.push("request invalid".into());
5857            return Ok(AuthorizeResult { ok: false, reasons });
5858        }
5859    };
5860    let second: i128 = 1_000_000_000;
5861    let skew = i128::from(replay.clock_skew_seconds) * second;
5862    match rv::time_ns(request.get("validFrom")) {
5863        Some(issued) if issued > current + skew => {
5864            reasons.push("request is dated in the future".into())
5865        }
5866        Some(issued) if current - issued > i128::from(replay.max_age_seconds) * second + skew => {
5867            reasons.push("request is too old".into())
5868        }
5869        Some(_) => {}
5870        None => reasons.push("request is dated in the future".into()),
5871    }
5872    let nonce = non_empty_str(&req_subject, "nonce").map(String::from);
5873    match &nonce {
5874        None => reasons.push("request carries no nonce".into()),
5875        Some(n) if replay.seen_nonces.contains(n) => {
5876            reasons.push("request was already used (replay)".into())
5877        }
5878        Some(_) => {}
5879    }
5880    if !reasons.is_empty() {
5881        return Ok(AuthorizeResult { ok: false, reasons });
5882    }
5883    let req_id = req_subject.get("id").and_then(|v| v.as_str());
5884
5885    if grant_subject.get("id").and_then(|v| v.as_str()) != req_id {
5886        reasons.push("grant and request name different robots".into());
5887    }
5888    if grant_subject.get("resource").and_then(|v| v.as_str())
5889        != req_subject.get("resource").and_then(|v| v.as_str())
5890    {
5891        reasons.push("grant and request name different resources".into());
5892    }
5893    let operation = req_subject.get("operation").and_then(|v| v.as_str());
5894    let permitted = grant_subject
5895        .get("operations")
5896        .and_then(|v| v.as_array())
5897        .map(|ops| operation.is_some() && ops.iter().any(|o| o.as_str() == operation))
5898        .unwrap_or(false);
5899    if !permitted {
5900        reasons.push("operation not permitted by the grant".into());
5901    }
5902    if reasons.is_empty() {
5903        if let Some(n) = nonce {
5904            replay.seen_nonces.insert(n);
5905        }
5906    }
5907
5908    Ok(AuthorizeResult {
5909        ok: reasons.is_empty(),
5910        reasons,
5911    })
5912}
5913
5914/// Return true if `child` is a valid attenuation of `parent`: the same resource, a
5915/// subset of the operations, and the same zone (or the parent had no zone). A
5916/// sub-grant may only narrow, never widen, the access it inherits.
5917pub fn attenuates_grant(parent: &Value, child: &Value) -> bool {
5918    let p = parent.get("credentialSubject");
5919    let c = child.get("credentialSubject");
5920    let p_resource = p.and_then(|s| s.get("resource")).and_then(|v| v.as_str());
5921    let c_resource = c.and_then(|s| s.get("resource")).and_then(|v| v.as_str());
5922    if p_resource != c_resource {
5923        return false;
5924    }
5925    let p_ops: HashSet<&str> = p
5926        .and_then(|s| s.get("operations"))
5927        .and_then(|v| v.as_array())
5928        .map(|a| a.iter().filter_map(|o| o.as_str()).collect())
5929        .unwrap_or_default();
5930    let c_ops: HashSet<&str> = c
5931        .and_then(|s| s.get("operations"))
5932        .and_then(|v| v.as_array())
5933        .map(|a| a.iter().filter_map(|o| o.as_str()).collect())
5934        .unwrap_or_default();
5935    if !c_ops.is_subset(&p_ops) {
5936        return false;
5937    }
5938    let p_zone = p.and_then(|s| s.get("zone")).and_then(|v| v.as_str());
5939    let c_zone = c.and_then(|s| s.get("zone")).and_then(|v| v.as_str());
5940    if p_zone.is_some() && c_zone != p_zone {
5941        return false;
5942    }
5943    true
5944}
5945
5946// ---------------------------------------------------------------------------
5947// Fused-sensor provenance (Phase 5.18)
5948// ---------------------------------------------------------------------------
5949//
5950// Perception provenance signs individual sensor frames. A robot rarely acts on
5951// one frame, though: it fuses many frames, from cameras, lidar, radar, and other
5952// sensors, into a single world model, an object set, an occupancy grid, or a
5953// pose estimate, and acts on that. This binds a fused output to the exact set of
5954// input frames that produced it and the fusion method that produced it, signed by
5955// the robot, so a manipulated fusion result or a silently dropped or substituted
5956// input is detectable at the provenance layer.
5957//
5958// A fused-perception attestation carries the hash of the fused output, an ordered
5959// list of the input frame hashes, a digest over those inputs, and a fusion method
5960// identifier, signed by the robot. A verifier reproduces the input digest from the
5961// listed inputs and, when it holds the raw fused output, reproduces its hash, so
5962// the attestation commits to exactly those inputs and that output. Checking each
5963// listed input against the robot's signed perception log confirms every fused
5964// input traces to a frame the robot actually recorded.
5965//
5966// This is the open layer: the robot signs the binding of a fused output to its
5967// inputs in software, reusing the perception frame hashes. Hardware sensor
5968// attestation and managed sensor-fusion orchestration are out of scope for the
5969// open layer.
5970
5971pub const FUSED_PERCEPTION_TYPE: &str = "FusedPerceptionAttestation";
5972
5973/// Multibase (base64url) SHA-256 of a raw fused output. Only the hash travels in
5974/// the attestation; the fused output stays wherever the deployment keeps it.
5975pub fn hash_fused_output(output: &[u8]) -> String {
5976    mb64(&Sha256::digest(output))
5977}
5978
5979/// Input-digest version 1: SHA-256 of the hashes joined by "\n" (the
5980/// original; assumed when an attestation names no version).
5981pub const INPUTS_DIGEST_V1: &str = "1";
5982/// Input-digest version 2: SHA-256 of the JCS JSON array of the hashes (the
5983/// default for new attestations).
5984pub const INPUTS_DIGEST_V2: &str = "2";
5985
5986/// Deterministic multibase digest over an ordered list of input frame hashes
5987/// (version 2, the default). It commits to the exact inputs and their order.
5988pub fn fusion_inputs_digest(input_frame_hashes: &[String]) -> Result<String> {
5989    fusion_inputs_digest_version(input_frame_hashes, INPUTS_DIGEST_V2)
5990}
5991
5992/// [`fusion_inputs_digest`] under a named version. Version 1 refuses a hash
5993/// that contains "\n" (otherwise two different lists could share a digest).
5994pub fn fusion_inputs_digest_version(
5995    input_frame_hashes: &[String],
5996    version: &str,
5997) -> Result<String> {
5998    if input_frame_hashes.is_empty() {
5999        return Err(CoreError::Json(
6000            "input_frame_hashes must be a non-empty list".into(),
6001        ));
6002    }
6003    for h in input_frame_hashes {
6004        if h.is_empty() {
6005            return Err(CoreError::Json(
6006                "each input frame hash must be a non-empty string".into(),
6007            ));
6008        }
6009    }
6010    match version {
6011        INPUTS_DIGEST_V2 => Ok(mb64(&Sha256::digest(jcs::canonicalize(&json!(
6012            input_frame_hashes
6013        ))))),
6014        INPUTS_DIGEST_V1 => {
6015            if input_frame_hashes.iter().any(|h| h.contains('\n')) {
6016                return Err(CoreError::Json(
6017                    "a version 1 input digest cannot carry a hash containing a newline".into(),
6018                ));
6019            }
6020            Ok(mb64(&Sha256::digest(
6021                input_frame_hashes.join("\n").as_bytes(),
6022            )))
6023        }
6024        other => Err(CoreError::Json(format!(
6025            "unknown inputs digest version {other:?}"
6026        ))),
6027    }
6028}
6029
6030/// Parameters for [`build_fused_attestation`]. The robot self-issues the
6031/// credential with its own Ed25519 seed. Provide either the raw `fused_output` (it
6032/// is hashed) or a precomputed `fused_output_hash`, not both. `captured_at`, when
6033/// `None`, defaults to `valid_from`.
6034#[derive(Debug, Clone)]
6035pub struct BuildFusedAttestation {
6036    pub robot_did: String,
6037    pub fusion_method: String,
6038    pub input_frame_hashes: Vec<String>,
6039    pub fused_output: Option<Vec<u8>>,
6040    pub fused_output_hash: Option<String>,
6041    pub captured_at: Option<String>,
6042    pub valid_from: String,
6043    pub valid_until: Option<String>,
6044}
6045
6046/// Build a signed `FusedPerceptionAttestation`: the robot attests that a fused
6047/// output was produced by `fusion_method` from the frames named in
6048/// `input_frame_hashes`. The attestation carries a digest over the ordered inputs,
6049/// so the set of inputs is tamper-evident. Signed by the robot.
6050pub fn build_fused_attestation(robot_seed: &[u8], params: &BuildFusedAttestation) -> Result<Value> {
6051    if params.robot_did.is_empty() {
6052        return Err(CoreError::Json("robot_did is required".into()));
6053    }
6054    if params.fusion_method.is_empty() {
6055        return Err(CoreError::Json("fusion_method is required".into()));
6056    }
6057    if params.input_frame_hashes.is_empty() {
6058        return Err(CoreError::Json(
6059            "input_frame_hashes must be a non-empty list".into(),
6060        ));
6061    }
6062    if params.fused_output.is_some() && params.fused_output_hash.is_some() {
6063        return Err(CoreError::Json(
6064            "provide either fused_output or fused_output_hash, not both".into(),
6065        ));
6066    }
6067    let fused_output_hash = match (&params.fused_output, &params.fused_output_hash) {
6068        (Some(o), None) => hash_fused_output(o),
6069        (None, Some(h)) if !h.is_empty() => h.clone(),
6070        _ => {
6071            return Err(CoreError::Json(
6072                "fused_output or fused_output_hash is required".into(),
6073            ))
6074        }
6075    };
6076
6077    let captured = params
6078        .captured_at
6079        .clone()
6080        .unwrap_or_else(|| params.valid_from.clone());
6081
6082    let mut subject = Map::new();
6083    subject.insert("id".into(), json!(params.robot_did));
6084    subject.insert("fusionMethod".into(), json!(params.fusion_method));
6085    subject.insert("fusedOutputHash".into(), json!(fused_output_hash));
6086    subject.insert("inputFrameHashes".into(), json!(params.input_frame_hashes));
6087    subject.insert(
6088        "inputsDigest".into(),
6089        json!(fusion_inputs_digest(&params.input_frame_hashes)?),
6090    );
6091    subject.insert("inputsDigestVersion".into(), json!(INPUTS_DIGEST_V2));
6092    subject.insert("capturedAt".into(), json!(captured));
6093
6094    let mut cred = Map::new();
6095    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
6096    cred.insert(
6097        "type".into(),
6098        json!(["VerifiableCredential", FUSED_PERCEPTION_TYPE]),
6099    );
6100    cred.insert("issuer".into(), json!(params.robot_did));
6101    cred.insert("validFrom".into(), json!(params.valid_from));
6102    if let Some(vu) = &params.valid_until {
6103        cred.insert("validUntil".into(), json!(vu));
6104    }
6105    cred.insert("credentialSubject".into(), Value::Object(subject));
6106
6107    let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), &params.valid_from);
6108    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
6109}
6110
6111/// Verify a `FusedPerceptionAttestation`: the robot's proof bound to the robot
6112/// as issuer (which must also be `credentialSubject.id`), the window at
6113/// `now_iso` (validFrom required), that the digest over
6114/// the listed inputs reproduces the attested `inputsDigest` (so the inputs are
6115/// internally consistent and tamper-evident), and, when the raw `fused_output` is
6116/// supplied, that its hash reproduces the attested `fusedOutputHash`. Returns the
6117/// credentialSubject on success, `None` if invalid.
6118pub fn verify_fused_attestation(
6119    credential: &Value,
6120    keys: Keys<'_>,
6121    fused_output: Option<&[u8]>,
6122    now_iso: &str,
6123) -> Result<Option<Value>> {
6124    let v = match bound(
6125        credential,
6126        keys,
6127        FUSED_PERCEPTION_TYPE,
6128        now_iso,
6129        Window::FromRequired,
6130    )? {
6131        Some(v) if issuer_is_subject(&v) => v,
6132        _ => return Ok(None),
6133    };
6134    let subject = v.subject;
6135    let fused_output_hash = non_empty_str(&subject, "fusedOutputHash");
6136    let inputs: Vec<String> = match subject.get("inputFrameHashes") {
6137        Some(Value::Array(a)) if !a.is_empty() && a.iter().all(|e| e.is_string()) => a
6138            .iter()
6139            .filter_map(|e| e.as_str().map(String::from))
6140            .collect(),
6141        _ => return Ok(None),
6142    };
6143    if fused_output_hash.is_none() {
6144        return Ok(None);
6145    }
6146    let version = match subject.get("inputsDigestVersion") {
6147        None => INPUTS_DIGEST_V1,
6148        Some(Value::String(v)) if v == INPUTS_DIGEST_V1 || v == INPUTS_DIGEST_V2 => v.as_str(),
6149        _ => return Ok(None),
6150    };
6151    match fusion_inputs_digest_version(&inputs, version) {
6152        Ok(d) => {
6153            if Some(d.as_str()) != subject.get("inputsDigest").and_then(|v| v.as_str()) {
6154                return Ok(None);
6155            }
6156        }
6157        Err(_) => return Ok(None),
6158    }
6159    if let Some(o) = fused_output {
6160        if Some(hash_fused_output(o).as_str()) != fused_output_hash {
6161            return Ok(None);
6162        }
6163    }
6164    Ok(Some(subject))
6165}
6166
6167/// The outcome of confirming an attestation's inputs against a perception log:
6168/// `ok` plus the input frame hashes not found. Surfaced by [`verify_fusion_inputs`].
6169#[derive(Debug, Clone)]
6170pub struct FusionInputsResult {
6171    pub ok: bool,
6172    pub missing: Vec<String>,
6173}
6174
6175/// Confirm every input frame the attestation names was actually recorded in the
6176/// robot's perception log. Returns `ok` plus `missing`, the input frame hashes that
6177/// do not appear as a recorded frame, so a dropped or substituted fused input is
6178/// named rather than hidden.
6179pub fn verify_fusion_inputs(credential: &Value, log_entries: &[Value]) -> FusionInputsResult {
6180    let recorded: HashSet<&str> = log_entries
6181        .iter()
6182        .filter_map(|e| e.get("frameHash").and_then(|v| v.as_str()))
6183        .filter(|h| !h.is_empty())
6184        .collect();
6185    // A missing or empty input list is malformed: fail closed.
6186    let inputs = match credential
6187        .get("credentialSubject")
6188        .and_then(|s| s.get("inputFrameHashes"))
6189        .and_then(|v| v.as_array())
6190    {
6191        Some(a) if !a.is_empty() => a,
6192        _ => {
6193            return FusionInputsResult {
6194                ok: false,
6195                missing: Vec::new(),
6196            }
6197        }
6198    };
6199    let missing: Vec<String> = inputs
6200        .iter()
6201        .filter(|h| !h.as_str().is_some_and(|s| recorded.contains(s)))
6202        .map(|h| match h.as_str() {
6203            Some(s) => s.to_string(),
6204            None => h.to_string(),
6205        })
6206        .collect();
6207    FusionInputsResult {
6208        ok: missing.is_empty(),
6209        missing,
6210    }
6211}
6212
6213// ---------------------------------------------------------------------------
6214// Wear and degradation attestation (Phase 5.19)
6215// ---------------------------------------------------------------------------
6216//
6217// A robot does not stay as capable as it left the factory. Actuators wear, joints
6218// develop backlash, sensors drift out of calibration, and error rates creep up.
6219// This lets a robot sign its own degradation state, bound to its identity and
6220// hash-linked over time so the history is tamper-evident, and derives a narrowed
6221// physical capability scope from that state, so a worn robot operates inside a
6222// tighter, verifiable envelope instead of trusting the static limit it shipped
6223// with.
6224//
6225// A wear attestation carries a normalized wear level (0 for as-new, 1 for fully
6226// worn) and optional detailed metrics, signed by the robot. Linking each
6227// attestation to the previous one by its proof value forms a chain a verifier
6228// walks to see how the robot degraded over its life. `attenuate_for_wear` derives
6229// a physical scope whose numeric caps are scaled down by the wear level, and the
6230// result is a valid attenuation of the original scope, so the same attenuation
6231// rule the rest of Vouch uses carries the derating.
6232//
6233// This is the open layer: the robot signs its wear state and derives the narrowed
6234// scope credential in software. Firmware-level enforcement of the narrowed
6235// envelope and managed predictive-maintenance modeling are out of scope for the
6236// open layer.
6237
6238pub const WEAR_ATTESTATION_TYPE: &str = "RobotWearAttestation";
6239
6240/// Numeric caps that scale down with wear. Zones and shift windows are preserved
6241/// unchanged, so the derived scope stays a valid attenuation of the original.
6242const WEAR_DERATED_CAPS: [&str; 3] = ["maxForceN", "maxSpeedMps", "maxSpeedNearHumansMps"];
6243
6244/// Parameters for [`build_wear_attestation`]. The robot self-issues the credential
6245/// with its own Ed25519 seed. `metrics`, when present, is carried through into the
6246/// subject unchanged. `prev_proof`, when present, links this attestation to the
6247/// previous one, forming a wear history. `attested_at`, when `None`, defaults to
6248/// `valid_from`.
6249#[derive(Debug, Clone)]
6250pub struct BuildWearAttestation {
6251    pub robot_did: String,
6252    pub wear_level: f64,
6253    pub metrics: Option<Value>,
6254    pub prev_proof: Option<String>,
6255    pub attested_at: Option<String>,
6256    pub valid_from: String,
6257    pub valid_until: Option<String>,
6258}
6259
6260/// Build a signed `RobotWearAttestation`: the robot attests its own degradation as
6261/// a normalized `wear_level` in `[0, 1]`, optionally with detailed `metrics`. When
6262/// `prev_proof` is the proof value of the previous attestation, the new one links
6263/// to it, forming a tamper-evident wear history. Signed by the robot.
6264pub fn build_wear_attestation(robot_seed: &[u8], params: &BuildWearAttestation) -> Result<Value> {
6265    if params.robot_did.is_empty() {
6266        return Err(CoreError::Json("robot_did is required".into()));
6267    }
6268    if params.wear_level < 0.0 || params.wear_level > 1.0 {
6269        return Err(CoreError::Json(
6270            "wear_level must be between 0.0 and 1.0".into(),
6271        ));
6272    }
6273
6274    let attested = params
6275        .attested_at
6276        .clone()
6277        .unwrap_or_else(|| params.valid_from.clone());
6278
6279    let mut subject = Map::new();
6280    subject.insert("id".into(), json!(params.robot_did));
6281    subject.insert("wearLevel".into(), json!(params.wear_level));
6282    subject.insert("attestedAt".into(), json!(attested));
6283    if let Some(m) = &params.metrics {
6284        subject.insert("metrics".into(), m.clone());
6285    }
6286    if let Some(prev) = &params.prev_proof {
6287        subject.insert("prevProof".into(), json!(prev));
6288    }
6289
6290    let mut cred = Map::new();
6291    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
6292    cred.insert(
6293        "type".into(),
6294        json!(["VerifiableCredential", WEAR_ATTESTATION_TYPE]),
6295    );
6296    cred.insert("issuer".into(), json!(params.robot_did));
6297    cred.insert("validFrom".into(), json!(params.valid_from));
6298    if let Some(vu) = &params.valid_until {
6299        cred.insert("validUntil".into(), json!(vu));
6300    }
6301    cred.insert("credentialSubject".into(), Value::Object(subject));
6302
6303    let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), &params.valid_from);
6304    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
6305}
6306
6307/// Verify a `RobotWearAttestation`: the robot's proof bound to the robot as
6308/// issuer (which must also be `credentialSubject.id`), the window at `now_iso`
6309/// (validFrom required), and that the wear level is a finite number in [0, 1]. Returns the credentialSubject on
6310/// success, `None` if invalid.
6311pub fn verify_wear_attestation(
6312    credential: &Value,
6313    keys: Keys<'_>,
6314    now_iso: &str,
6315) -> Result<Option<Value>> {
6316    let v = match bound(
6317        credential,
6318        keys,
6319        WEAR_ATTESTATION_TYPE,
6320        now_iso,
6321        Window::FromRequired,
6322    )? {
6323        Some(v) if issuer_is_subject(&v) => v,
6324        _ => return Ok(None),
6325    };
6326    match rv::finite_number(v.subject.get("wearLevel")) {
6327        Some(level) if (0.0..=1.0).contains(&level) => Ok(Some(v.subject)),
6328        _ => Ok(None),
6329    }
6330}
6331
6332/// Verify an ordered wear history: each attestation verifies under the same
6333/// robot, each one after the first links to the previous by its proof value,
6334/// and they are in time order. Each earlier attestation must still have been
6335/// valid when the next was made, and the last at `now_iso`. Returns the latest
6336/// credentialSubject on success, `None` if the chain is empty or invalid.
6337pub fn verify_wear_chain(
6338    attestations: &[Value],
6339    keys: Keys<'_>,
6340    now_iso: &str,
6341) -> Result<Option<Value>> {
6342    rv::require_now(now_iso)?;
6343    if attestations.is_empty() {
6344        return Ok(None);
6345    }
6346    let mut prev_proof: Option<String> = None;
6347    let mut prev_time: Option<i128> = None;
6348    let mut robot: Option<String> = None;
6349    let mut latest: Option<Value> = None;
6350    for (i, att) in attestations.iter().enumerate() {
6351        let at: String = match attestations.get(i + 1) {
6352            Some(next) => match next.get("validFrom").and_then(|v| v.as_str()) {
6353                Some(t) if rv::time_ns(next.get("validFrom")).is_some() => t.to_string(),
6354                _ => return Ok(None),
6355            },
6356            None => now_iso.to_string(),
6357        };
6358        let subject = match verify_wear_attestation(att, keys, &at)? {
6359            Some(s) => s,
6360            None => return Ok(None),
6361        };
6362        let id = subject.get("id").and_then(|v| v.as_str()).map(String::from);
6363        match &robot {
6364            None => robot = id,
6365            Some(r) if id.as_deref() == Some(r.as_str()) => {}
6366            _ => return Ok(None),
6367        }
6368        if let Some(prev) = &prev_proof {
6369            if subject.get("prevProof").and_then(|v| v.as_str()) != Some(prev.as_str()) {
6370                return Ok(None);
6371            }
6372        }
6373        match rv::time_ns(att.get("validFrom")) {
6374            Some(t) if prev_time.is_none_or(|p| t >= p) => prev_time = Some(t),
6375            _ => return Ok(None),
6376        }
6377        prev_proof = att
6378            .get("proof")
6379            .and_then(|p| p.get("proofValue"))
6380            .and_then(|v| v.as_str())
6381            .map(String::from);
6382        latest = Some(subject);
6383    }
6384    Ok(latest)
6385}
6386
6387/// Derive a physical scope narrowed for the given wear level: each numeric cap is
6388/// scaled by `(1 - wear_level)`, and the allowed zones and shift windows are
6389/// carried through unchanged. The result is a valid attenuation of `scope` (never
6390/// broader on any dimension), so the same attenuation check the rest of Vouch uses
6391/// accepts it. A wear level of 0 returns the caps unchanged.
6392pub fn attenuate_for_wear(scope: &Value, wear_level: f64) -> Result<Value> {
6393    // `contains` is false for NaN, so a NaN wear level is refused here rather
6394    // than turning every cap into NaN (which a NaN-unaware check would ignore).
6395    if !(0.0..=1.0).contains(&wear_level) {
6396        return Err(CoreError::Json(
6397            "wear_level must be between 0.0 and 1.0".into(),
6398        ));
6399    }
6400    let problems = scope_problems(scope);
6401    if !problems.is_empty() {
6402        return Err(CoreError::Json(problems.join("; ")));
6403    }
6404    let factor = 1.0 - wear_level;
6405    let empty = Map::new();
6406    let src = scope.as_object().unwrap_or(&empty);
6407    let mut narrowed = Map::new();
6408    for (key, value) in src {
6409        if WEAR_DERATED_CAPS.contains(&key.as_str()) {
6410            if let Some(n) = value.as_f64() {
6411                narrowed.insert(key.clone(), json!(n * factor));
6412                continue;
6413            }
6414        }
6415        narrowed.insert(key.clone(), value.clone());
6416    }
6417    Ok(Value::Object(narrowed))
6418}
6419
6420// ---------------------------------------------------------------------------
6421// Bystander-consent evidence (Phase 5.20)
6422// ---------------------------------------------------------------------------
6423//
6424// A robot working in a shared or public space captures people incidentally
6425// through its cameras and microphones. This lets the robot record, at capture
6426// time, the basis on which a capture was permitted, bound to the specific capture
6427// and to the robot's identity, and lets a bystander (or their device) sign a
6428// consent token bound to that one capture. Only hashes and a consent basis are
6429// stored, never an image or a bystander's identifying data, so the evidence is
6430// verifiable without retaining anyone's biometrics.
6431//
6432// A bystander consent token is signed by the bystander over the hash of the
6433// capture and the robot's DID, so it verifies only against the capture it was
6434// given for and cannot be replayed to a different recording. A bystander-consent
6435// evidence credential is signed by the robot, binding the capture hash to a
6436// consent basis (an explicit token, posted notice, a legitimate interest, or a
6437// redaction that was applied) and, when the basis is explicit consent, to the
6438// tokens that cover it.
6439//
6440// This is the open layer: the cryptographic binding of a consent basis to a
6441// capture, and its verification, holding only hashes. On-device biometric
6442// detection and redaction, and managed consent-registry orchestration, are out of
6443// scope for the open layer.
6444
6445pub const CONSENT_EVIDENCE_TYPE: &str = "BystanderConsentEvidence";
6446pub const CONSENT_TOKEN_TYPE: &str = "BystanderConsentToken";
6447
6448/// Accepted consent bases: the interoperable set a verifier can rely on.
6449/// Implementers MAY use additional values.
6450pub const CONSENT_BASES: [&str; 4] = [
6451    "explicit-consent",
6452    "posted-notice",
6453    "legitimate-interest",
6454    "redacted",
6455];
6456
6457/// Multibase (base64url) SHA-256 of a raw capture. Only the hash travels in the
6458/// token and the evidence; the capture stays wherever the deployment keeps it.
6459pub fn hash_capture(capture: &[u8]) -> String {
6460    mb64(&Sha256::digest(capture))
6461}
6462
6463/// Parameters for [`build_consent_token`]. The signer is the bystander; the token
6464/// binds their consent to one capture (named by `capture_hash`) by one robot
6465/// (`robot_did`). `valid_until`, when set, bounds the window (the wrapper derives
6466/// it from a `valid_seconds` lifetime added to `granted_at`, keeping the core's
6467/// clock caller-supplied). `scope`, when set, records what the consent covers.
6468#[derive(Debug, Clone)]
6469pub struct BuildConsentToken {
6470    pub bystander_did: String,
6471    pub capture_hash: String,
6472    pub robot_did: String,
6473    pub scope: Option<String>,
6474    pub granted_at: String,
6475    pub valid_until: Option<String>,
6476}
6477
6478/// Build a signed `BystanderConsentToken`: a bystander grants consent for a
6479/// specific capture (named by `capture_hash`) by a specific robot (`robot_did`),
6480/// signed by the bystander. Binding the token to the capture hash means it cannot
6481/// be replayed to a different recording. Signed by the bystander.
6482pub fn build_consent_token(bystander_seed: &[u8], params: &BuildConsentToken) -> Result<Value> {
6483    if params.bystander_did.is_empty()
6484        || params.capture_hash.is_empty()
6485        || params.robot_did.is_empty()
6486    {
6487        return Err(CoreError::Json(
6488            "bystander_did, capture_hash, and robot_did are required".into(),
6489        ));
6490    }
6491
6492    let mut subject = Map::new();
6493    subject.insert("id".into(), json!(params.bystander_did));
6494    subject.insert("captureHash".into(), json!(params.capture_hash));
6495    subject.insert("robotDid".into(), json!(params.robot_did));
6496    if let Some(scope) = &params.scope {
6497        subject.insert("scope".into(), json!(scope));
6498    }
6499
6500    let mut cred = Map::new();
6501    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
6502    cred.insert(
6503        "type".into(),
6504        json!(["VerifiableCredential", CONSENT_TOKEN_TYPE]),
6505    );
6506    cred.insert("issuer".into(), json!(params.bystander_did));
6507    cred.insert("validFrom".into(), json!(params.granted_at));
6508    if let Some(vu) = &params.valid_until {
6509        cred.insert("validUntil".into(), json!(vu));
6510    }
6511    cred.insert("credentialSubject".into(), Value::Object(subject));
6512
6513    let opts = BuildProofOptions::new(
6514        format!("{}#key-1", params.bystander_did),
6515        &params.granted_at,
6516    );
6517    data_integrity::sign(&Value::Object(cred), bystander_seed, &opts)
6518}
6519
6520/// Verify a `BystanderConsentToken`: the bystander's proof bound to the issuer
6521/// (`bystander_keys` is a `{did: key}` source, or the bare key of a did:key
6522/// bystander), that the issuer is the bystander (`credentialSubject.id`), that
6523/// the token is bound to this capture and this robot, and that it is within its
6524/// window at `now_iso` (validFrom required, strict times). Returns the
6525/// credentialSubject on success, `None` if invalid.
6526pub fn verify_consent_token(
6527    token: &Value,
6528    bystander_keys: Keys<'_>,
6529    capture_hash: &str,
6530    robot_did: &str,
6531    now_iso: &str,
6532) -> Result<Option<Value>> {
6533    let v = match bound(
6534        token,
6535        bystander_keys,
6536        CONSENT_TOKEN_TYPE,
6537        now_iso,
6538        Window::FromRequired,
6539    )? {
6540        Some(v) if issuer_is_subject(&v) => v,
6541        _ => return Ok(None),
6542    };
6543    if v.subject.get("captureHash").and_then(|v| v.as_str()) != Some(capture_hash)
6544        || v.subject.get("robotDid").and_then(|v| v.as_str()) != Some(robot_did)
6545    {
6546        return Ok(None);
6547    }
6548    Ok(Some(v.subject))
6549}
6550
6551/// Parameters for [`build_consent_evidence`]. The signer is the robot; the
6552/// evidence records that a capture (named by `capture_hash`) was permitted on
6553/// `basis`, one of [`CONSENT_BASES`]. `consent_tokens`, when the basis is explicit
6554/// consent, are the bystander tokens that cover it, committed by their proof value.
6555/// `redaction_hash`, when set, records that a redacted output was produced.
6556/// `valid_until`, when set, bounds the window.
6557#[derive(Debug, Clone)]
6558pub struct BuildConsentEvidence {
6559    pub robot_did: String,
6560    pub capture_hash: String,
6561    pub basis: String,
6562    pub consent_tokens: Vec<Value>,
6563    pub redaction_hash: Option<String>,
6564    pub valid_from: String,
6565    pub valid_until: Option<String>,
6566}
6567
6568/// A privacy-preserving reference to a token: its proof value. Never embeds a
6569/// bystander's identifying data.
6570fn consent_token_ref(token: &Value) -> Result<String> {
6571    token
6572        .get("proof")
6573        .and_then(|p| p.get("proofValue"))
6574        .and_then(|v| v.as_str())
6575        .map(String::from)
6576        .ok_or_else(|| CoreError::Json("consent token is missing a proof value".into()))
6577}
6578
6579/// Build a signed `BystanderConsentEvidence` credential: the robot records that a
6580/// capture (named by `capture_hash`) was permitted on `basis`, one of
6581/// [`CONSENT_BASES`]. When the basis is explicit consent, the `consent_tokens` are
6582/// the bystander tokens that cover it, and the evidence commits to them by their
6583/// proof value (never embedding a bystander's identifying data). Signed by the
6584/// robot.
6585pub fn build_consent_evidence(robot_seed: &[u8], params: &BuildConsentEvidence) -> Result<Value> {
6586    if params.robot_did.is_empty() || params.capture_hash.is_empty() {
6587        return Err(CoreError::Json(
6588            "robot_did and capture_hash are required".into(),
6589        ));
6590    }
6591    if !CONSENT_BASES.contains(&params.basis.as_str()) {
6592        return Err(CoreError::Json(format!(
6593            "basis must be one of {:?}, got {:?}",
6594            CONSENT_BASES, params.basis
6595        )));
6596    }
6597    if params.basis == "explicit-consent" && params.consent_tokens.is_empty() {
6598        return Err(CoreError::Json(
6599            "explicit-consent basis requires at least one consent token".into(),
6600        ));
6601    }
6602
6603    let mut subject = Map::new();
6604    subject.insert("id".into(), json!(params.robot_did));
6605    subject.insert("captureHash".into(), json!(params.capture_hash));
6606    subject.insert("basis".into(), json!(params.basis));
6607    if !params.consent_tokens.is_empty() {
6608        let mut refs = Vec::with_capacity(params.consent_tokens.len());
6609        for t in &params.consent_tokens {
6610            refs.push(consent_token_ref(t)?);
6611        }
6612        subject.insert("consentTokenRefs".into(), json!(refs));
6613    }
6614    if let Some(rh) = &params.redaction_hash {
6615        subject.insert("redactionHash".into(), json!(rh));
6616    }
6617
6618    let mut cred = Map::new();
6619    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
6620    cred.insert(
6621        "type".into(),
6622        json!(["VerifiableCredential", CONSENT_EVIDENCE_TYPE]),
6623    );
6624    cred.insert("issuer".into(), json!(params.robot_did));
6625    cred.insert("validFrom".into(), json!(params.valid_from));
6626    if let Some(vu) = &params.valid_until {
6627        cred.insert("validUntil".into(), json!(vu));
6628    }
6629    cred.insert("credentialSubject".into(), Value::Object(subject));
6630
6631    let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), &params.valid_from);
6632    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
6633}
6634
6635/// One bystander's public key, looked up by bystander DID, for
6636/// [`verify_consent_evidence`].
6637#[derive(Debug, Clone)]
6638pub struct BystanderKey {
6639    pub did: String,
6640    pub public_key: Vec<u8>,
6641}
6642
6643/// Verify a `BystanderConsentEvidence` credential: the robot's proof bound to
6644/// the robot as issuer (which must also be `credentialSubject.id`), the window
6645/// at `now_iso` (validFrom required), and an accepted basis. When `capture` is
6646/// supplied, its hash must reproduce the attested capture hash.
6647///
6648/// An explicit-consent evidence is only as good as its tokens, so for that
6649/// basis `consent_tokens` and `bystander_keys` are required: every committed
6650/// reference must be matched by a token that verifies, is bound to this
6651/// capture and this robot, and is in its window. For other bases, tokens that
6652/// are supplied are checked the same way. Returns the credentialSubject on
6653/// success, `None` if invalid.
6654pub fn verify_consent_evidence(
6655    evidence: &Value,
6656    robot_keys: Keys<'_>,
6657    capture: Option<&[u8]>,
6658    consent_tokens: Option<&[Value]>,
6659    bystander_keys: Option<&[BystanderKey]>,
6660    now_iso: &str,
6661) -> Result<Option<Value>> {
6662    let v = match bound(
6663        evidence,
6664        robot_keys,
6665        CONSENT_EVIDENCE_TYPE,
6666        now_iso,
6667        Window::FromRequired,
6668    )? {
6669        Some(v) if issuer_is_subject(&v) => v,
6670        _ => return Ok(None),
6671    };
6672    let subject = v.subject;
6673    let basis = subject.get("basis").and_then(|v| v.as_str());
6674    match basis {
6675        Some(b) if CONSENT_BASES.contains(&b) => {}
6676        _ => return Ok(None),
6677    }
6678    let capture_hash = match non_empty_str(&subject, "captureHash") {
6679        Some(h) => h.to_string(),
6680        None => return Ok(None),
6681    };
6682    if let Some(c) = capture {
6683        if hash_capture(c) != capture_hash {
6684            return Ok(None);
6685        }
6686    }
6687
6688    let refs: Vec<&str> = match subject.get("consentTokenRefs") {
6689        None => Vec::new(),
6690        Some(Value::Array(a)) if a.iter().all(|r| r.is_string()) => {
6691            a.iter().filter_map(|r| r.as_str()).collect()
6692        }
6693        _ => return Ok(None),
6694    };
6695    let explicit = basis == Some("explicit-consent");
6696    if explicit && refs.is_empty() {
6697        return Ok(None);
6698    }
6699    if explicit && (consent_tokens.is_none() || bystander_keys.is_none()) {
6700        return Ok(None);
6701    }
6702
6703    if let (Some(tokens), Some(keys)) = (consent_tokens, bystander_keys) {
6704        let map = Keys::map_of(keys.iter().map(|k| (k.did.clone(), &k.public_key)));
6705        let mut matched: HashSet<String> = HashSet::new();
6706        for token in tokens {
6707            let tok_ok = !map.is_empty()
6708                && verify_consent_token(token, Keys::Map(&map), &capture_hash, &v.issuer, now_iso)?
6709                    .is_some();
6710            if !tok_ok {
6711                return Ok(None);
6712            }
6713            let r = match consent_token_ref(token) {
6714                Ok(r) if refs.contains(&r.as_str()) => r,
6715                _ => return Ok(None),
6716            };
6717            matched.insert(r);
6718        }
6719        if explicit {
6720            let all: HashSet<String> = refs.iter().map(|r| r.to_string()).collect();
6721            if matched != all {
6722                return Ok(None);
6723            }
6724        }
6725    }
6726
6727    Ok(Some(subject))
6728}
6729
6730#[cfg(test)]
6731mod tests {
6732    use super::*;
6733    use crate::keys::Ed25519KeyPair;
6734    #[allow(unused_imports)]
6735    use crate::robotics_verify::test_keys::{any_did, kd, TNOW};
6736    #[allow(unused_imports)]
6737    use crate::robotics_verify::Keys;
6738    use std::fs;
6739
6740    fn load_vector() -> Value {
6741        let raw = fs::read_to_string("../../test-vectors/robotics/vector.json")
6742            .expect("interop vector present");
6743        serde_json::from_str(&raw).unwrap()
6744    }
6745
6746    fn software_root_attest(root_seed: &[u8], robot_did: &str, robot_key_mb: &str) -> Vec<u8> {
6747        let kp = Ed25519KeyPair::from_seed_slice(root_seed).unwrap();
6748        let binding = robot_identity_binding(robot_did, robot_key_mb);
6749        kp.sign(&binding).to_vec()
6750    }
6751
6752    // Cross-language interop: Go and TypeScript verify this same Python-minted
6753    // credential; the Rust core must too.
6754    #[test]
6755    fn verifies_python_interop_vector() {
6756        let raw = fs::read_to_string("../../test-vectors/robotics/vector.json")
6757            .expect("interop vector present");
6758        let vector: Value = serde_json::from_str(&raw).unwrap();
6759        let jwk_x = vector["robot_public_key_jwk"]["x"].as_str().unwrap();
6760        let robot_pub = URL_SAFE_NO_PAD.decode(jwk_x).unwrap();
6761        let cred = vector["robot_identity_credential"].clone();
6762
6763        let subject = verify_robot_identity(&cred, kd(&cred, &robot_pub), None, TNOW).unwrap();
6764        let subject = subject.expect("the Python interop vector must verify in Rust");
6765        assert_eq!(subject["make"], json!("Acme Robotics"));
6766    }
6767
6768    #[test]
6769    fn mint_verify_roundtrip() {
6770        let robot_seed = [3u8; 32];
6771        let root_seed = [7u8; 32];
6772        let robot_did = "did:web:robot.example.com";
6773        let robot_kp = Ed25519KeyPair::from_seed(&robot_seed);
6774        let root_kp = Ed25519KeyPair::from_seed(&root_seed);
6775
6776        let attestation = software_root_attest(&root_seed, robot_did, &robot_kp.public_multikey());
6777        let params = MintRobotIdentity {
6778            robot_did: robot_did.into(),
6779            make: "Acme".into(),
6780            model: "AR-7".into(),
6781            serial: "SN-1".into(),
6782            owner: Some("did:web:owner.example.com".into()),
6783            root_kind: "TPM".into(),
6784            root_public_multibase: root_kp.public_multikey(),
6785            attestation,
6786            lifecycle: None,
6787            valid_from: "2026-01-01T00:00:00Z".into(),
6788            valid_until: None,
6789        };
6790        let cred = mint_robot_identity(&robot_seed, &params).unwrap();
6791        let subject =
6792            verify_robot_identity(&cred, kd(&cred, &robot_kp.public_key()), None, TNOW).unwrap();
6793        assert!(subject.is_some(), "round-trip identity must verify");
6794    }
6795
6796    // Cross-language interop: this HalosSafetyEvidenceCredential, its black-box
6797    // entries, and the robot public key were produced by the Python reference
6798    // (vouch/robotics/halos.py) from a fixed Ed25519 seed (0x05 x32), a fixed
6799    // black-box key, and a fixed `created` timestamp. The Rust verify must accept
6800    // it, and must reject a tampered entry or a wrong entry count.
6801    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"}}"#;
6802
6803    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"}]"#;
6804
6805    // Robot public key (raw 32-byte Ed25519) as base64url-no-pad.
6806    const PY_HALOS_ROBOT_PUB: &str = "bnoc3Smwt4_ROvTFWY_v9O8qlxZuPKby5Pv8zYBQW_E";
6807
6808    #[test]
6809    fn build_verify_safety_evidence_roundtrip() {
6810        let robot_seed = [5u8; 32];
6811        let robot_kp = Ed25519KeyPair::from_seed(&robot_seed);
6812
6813        // A black-box chain the robot recorded.
6814        let mut log = BlackBoxLog::new(&[9u8; 32], None).unwrap();
6815        log.append(
6816            "hazard_detected",
6817            &json!({"zone": "cell-3"}),
6818            "2026-01-01T00:00:01Z",
6819        )
6820        .unwrap();
6821        log.append(
6822            "slow_stop",
6823            &json!({"reason": "human"}),
6824            "2026-01-01T00:00:02Z",
6825        )
6826        .unwrap();
6827        let entries: Vec<Value> = log.entries().to_vec();
6828
6829        let params = BuildSafetyEvidence {
6830            halos_stack: json!({"igxSom": "IGX-Orin-64", "halosCore": "1.4.0"}),
6831            window_from: "2026-01-01T00:00:00Z".into(),
6832            window_to: "2026-01-01T00:00:10Z".into(),
6833            blackbox_head: log.head().to_string(),
6834            entry_count: entries.len() as u64,
6835            robot_identity: Some("urn:uuid:robot-identity-1".into()),
6836            valid_seconds: Some(3600),
6837            valid_from: "2026-01-01T00:00:00Z".into(),
6838            created: "2026-01-01T00:00:00Z".into(),
6839        };
6840        let cred = build_safety_evidence(&robot_seed, &params).unwrap();
6841
6842        // The issuer is the did:key derived from the seed and the validUntil is
6843        // rendered from the valid_seconds lifetime.
6844        assert_eq!(
6845            cred["issuer"],
6846            json!("did:key:z6MkmtWtY63GQVBrpMyRJWEzsnxfsGkemu6CtMDwGTv4RYj2")
6847        );
6848        assert_eq!(cred["validUntil"], json!("2026-01-01T01:00:00Z"));
6849
6850        let (ok, subject) = verify_safety_evidence(
6851            &cred,
6852            kd(&cred, &robot_kp.public_key()),
6853            Some(&entries),
6854            TNOW,
6855        )
6856        .unwrap();
6857        assert!(ok, "a Rust-built evidence credential must verify in Rust");
6858        assert_eq!(subject.unwrap()["entryCount"], json!(2));
6859
6860        // A credential whose issuer is not the subject id is rejected.
6861        let mut forged = cred.clone();
6862        forged["issuer"] = json!("did:key:z6Mkother");
6863        let (ok_forged, _) =
6864            verify_safety_evidence(&forged, kd(&forged, &robot_kp.public_key()), None, TNOW)
6865                .unwrap();
6866        assert!(!ok_forged, "issuer must equal credentialSubject.id");
6867    }
6868
6869    #[test]
6870    fn verifies_python_halos_evidence() {
6871        let credential: Value = serde_json::from_str(PY_HALOS_CREDENTIAL).unwrap();
6872        let entries: Vec<Value> = serde_json::from_str(PY_HALOS_ENTRIES).unwrap();
6873        let robot_pub = URL_SAFE_NO_PAD.decode(PY_HALOS_ROBOT_PUB).unwrap();
6874
6875        // The Python-produced credential and its entries verify in Rust.
6876        let (ok, subject) = verify_safety_evidence(
6877            &credential,
6878            kd(&credential, &robot_pub),
6879            Some(&entries),
6880            TNOW,
6881        )
6882        .unwrap();
6883        assert!(ok, "the Python Halos evidence must verify in Rust");
6884        let subject = subject.expect("subject present on success");
6885        assert_eq!(subject["entryCount"], json!(3));
6886        assert_eq!(
6887            subject["blackboxHead"],
6888            json!("utfv4sSWc6TH-n0HrNqB35Hacy3lYVksU0QYz6gbHol8")
6889        );
6890
6891        // The proof and issuer binding hold even without the entries.
6892        let (ok_no_entries, _) =
6893            verify_safety_evidence(&credential, kd(&credential, &robot_pub), None, TNOW).unwrap();
6894        assert!(
6895            ok_no_entries,
6896            "proof and issuer binding verify without entries"
6897        );
6898
6899        // Tampering one entry breaks the chain, so verification fails.
6900        let mut tampered = entries.clone();
6901        tampered[1]["ciphertext"] = json!("utampered_ciphertext_value_that_does_not_match_hash");
6902        let (ok_tampered, subj_tampered) = verify_safety_evidence(
6903            &credential,
6904            kd(&credential, &robot_pub),
6905            Some(&tampered),
6906            TNOW,
6907        )
6908        .unwrap();
6909        assert!(!ok_tampered, "a tampered entry must be rejected");
6910        assert!(subj_tampered.is_none());
6911
6912        // A wrong entry count (here a truncated log) is rejected against the seal.
6913        let truncated = entries[..2].to_vec();
6914        let (ok_truncated, _) = verify_safety_evidence(
6915            &credential,
6916            kd(&credential, &robot_pub),
6917            Some(&truncated),
6918            TNOW,
6919        )
6920        .unwrap();
6921        assert!(!ok_truncated, "a wrong entry count must be rejected");
6922    }
6923
6924    #[test]
6925    fn forged_hardware_root_fails() {
6926        let robot_seed = [3u8; 32];
6927        let root_seed = [7u8; 32];
6928        let attacker_seed = [9u8; 32];
6929        let robot_did = "did:web:robot.example.com";
6930        let robot_kp = Ed25519KeyPair::from_seed(&robot_seed);
6931        let root_kp = Ed25519KeyPair::from_seed(&root_seed);
6932        let attacker_kp = Ed25519KeyPair::from_seed(&attacker_seed);
6933
6934        let attestation = software_root_attest(&root_seed, robot_did, &robot_kp.public_multikey());
6935        let params = MintRobotIdentity {
6936            robot_did: robot_did.into(),
6937            make: "Acme".into(),
6938            model: "AR-7".into(),
6939            serial: "SN-1".into(),
6940            owner: None,
6941            root_kind: "TPM".into(),
6942            root_public_multibase: root_kp.public_multikey(),
6943            attestation,
6944            lifecycle: None,
6945            valid_from: "2026-01-01T00:00:00Z".into(),
6946            valid_until: None,
6947        };
6948        let mut cred = mint_robot_identity(&robot_seed, &params).unwrap();
6949
6950        // Point the hardware-root key at an attacker's and re-sign the credential
6951        // proof; the attestation over the binding no longer matches.
6952        cred["credentialSubject"]["hardwareRoot"]["publicKeyMultibase"] =
6953            json!(attacker_kp.public_multikey());
6954        let resigned = {
6955            let mut bare = cred.clone();
6956            bare.as_object_mut().unwrap().remove("proof");
6957            let opts = BuildProofOptions::new(format!("{robot_did}#key-1"), "2026-01-01T00:00:00Z");
6958            data_integrity::sign(&bare, &robot_seed, &opts).unwrap()
6959        };
6960        assert!(verify_robot_identity(
6961            &resigned,
6962            kd(&resigned, &robot_kp.public_key()),
6963            None,
6964            TNOW
6965        )
6966        .unwrap()
6967        .is_none());
6968    }
6969
6970    // Cross-language interop: Rust reproduces the exact configHash Python pinned.
6971    #[test]
6972    fn config_hash_matches_interop_vector() {
6973        let vector = load_vector();
6974        let got = config_hash(&vector["config"]);
6975        assert_eq!(got, vector["expected_config_hash"].as_str().unwrap());
6976        assert_eq!(got, "uMh9_H2Lk51-m9SpBhiEa1oqIwwwA7yT27e2QFS0YKUs");
6977    }
6978
6979    #[test]
6980    fn provenance_roundtrip_and_config_tamper() {
6981        let seed = [4u8; 32];
6982        let kp = Ed25519KeyPair::from_seed(&seed);
6983        let config = load_vector()["config"].clone();
6984        let params = BuildProvenance {
6985            issuer_did: "did:web:robot.example.com".into(),
6986            robot_did: "did:web:robot.example.com".into(),
6987            model_name: "openvla-7b".into(),
6988            weights_hash: "uABCDEF".into(),
6989            safety_policy: "did:web:authority.example.com#policy-v3".into(),
6990            config: Some(config.clone()),
6991            version: Some("2026.06".into()),
6992            supersedes: None,
6993            valid_from: "2026-01-01T00:00:00Z".into(),
6994            valid_until: None,
6995        };
6996        let att = build_provenance_attestation(&seed, &params).unwrap();
6997        assert!(verify_provenance_attestation(
6998            &att,
6999            kd(&att, &kp.public_key()),
7000            Some(&config),
7001            TNOW
7002        )
7003        .unwrap()
7004        .is_some());
7005        // A different config than the one signed must be rejected.
7006        let tampered = json!({"temperature": 1.0, "max_torque": 99.0});
7007        assert!(verify_provenance_attestation(
7008            &att,
7009            kd(&att, &kp.public_key()),
7010            Some(&tampered),
7011            TNOW
7012        )
7013        .unwrap()
7014        .is_none());
7015    }
7016
7017    #[test]
7018    fn capability_build_check_attenuate() {
7019        let seed = [6u8; 32];
7020        let kp = Ed25519KeyPair::from_seed(&seed);
7021        let params = BuildPhysicalScope {
7022            issuer_did: "did:web:fleet.example.com".into(),
7023            subject_did: "did:web:robot.example.com".into(),
7024            max_force_n: Some(80.0),
7025            max_speed_mps: Some(2.0),
7026            max_speed_near_humans_mps: Some(0.5),
7027            allowed_zones: Some(vec!["warehouse-a".into(), "dock-3".into()]),
7028            shift_windows: Some(vec![ShiftWindow {
7029                start: "08:00".into(),
7030                end: "18:00".into(),
7031            }]),
7032            valid_from: "2026-01-01T00:00:00Z".into(),
7033            valid_until: None,
7034        };
7035        let cred = build_physical_scope_credential(&seed, &params).unwrap();
7036        assert!(cred["type"]
7037            .as_array()
7038            .unwrap()
7039            .contains(&json!(PHYSICAL_SCOPE_TYPE)));
7040        assert!(data_integrity::verify_proof(&cred, &kp.public_key()).unwrap());
7041
7042        let scope = cred["credentialSubject"]["physicalScope"].clone();
7043        let within = check_physical_action(
7044            &scope,
7045            &PhysicalAction {
7046                force_n: Some(50.0),
7047                speed_mps: Some(1.5),
7048                zone: Some("warehouse-a".into()),
7049                time_hm: Some("09:30".into()),
7050                ..Default::default()
7051            },
7052        );
7053        assert!(within.ok, "within-scope action: {:?}", within.reasons);
7054        assert!(
7055            !check_physical_action(
7056                &scope,
7057                &PhysicalAction {
7058                    force_n: Some(120.0),
7059                    ..Default::default()
7060                }
7061            )
7062            .ok
7063        );
7064        // Near humans the 0.5 m/s cap applies; 1.5 is fine away from them.
7065        assert!(
7066            !check_physical_action(
7067                &scope,
7068                &PhysicalAction {
7069                    speed_mps: Some(1.5),
7070                    near_humans: true,
7071                    ..Default::default()
7072                }
7073            )
7074            .ok
7075        );
7076        assert!(
7077            check_physical_action(
7078                &scope,
7079                &PhysicalAction {
7080                    speed_mps: Some(1.5),
7081                    near_humans: false,
7082                    ..Default::default()
7083                }
7084            )
7085            .ok
7086        );
7087        assert!(
7088            !check_physical_action(
7089                &scope,
7090                &PhysicalAction {
7091                    zone: Some("loading-bay-9".into()),
7092                    ..Default::default()
7093                }
7094            )
7095            .ok
7096        );
7097        assert!(
7098            !check_physical_action(
7099                &scope,
7100                &PhysicalAction {
7101                    time_hm: Some("23:00".into()),
7102                    ..Default::default()
7103                }
7104            )
7105            .ok
7106        );
7107    }
7108
7109    #[test]
7110    fn attenuation_rules() {
7111        let parent = json!({
7112            "maxForceN": 80.0, "maxSpeedMps": 2.0, "maxSpeedNearHumansMps": 0.5,
7113            "allowedZones": ["warehouse-a", "dock-3"],
7114            "shiftWindows": [{"start": "08:00", "end": "18:00"}]
7115        });
7116        let narrower = json!({
7117            "maxForceN": 50.0, "maxSpeedMps": 1.0, "maxSpeedNearHumansMps": 0.3,
7118            "allowedZones": ["warehouse-a"],
7119            "shiftWindows": [{"start": "09:00", "end": "17:00"}]
7120        });
7121        assert!(attenuates(&parent, &narrower));
7122        assert!(!attenuates(
7123            &parent,
7124            &json!({"maxForceN": 100.0, "maxSpeedMps": 1.0, "maxSpeedNearHumansMps": 0.3, "allowedZones": ["warehouse-a"]})
7125        ));
7126        assert!(!attenuates(
7127            &parent,
7128            &json!({"maxForceN": 50.0, "allowedZones": ["warehouse-a"]})
7129        ));
7130        assert!(!attenuates(
7131            &parent,
7132            &json!({"maxForceN": 50.0, "maxSpeedMps": 1.0, "maxSpeedNearHumansMps": 0.3, "allowedZones": ["loading-bay-9"]})
7133        ));
7134        assert!(!attenuates(
7135            &parent,
7136            &json!({"maxForceN": 50.0, "maxSpeedMps": 1.0, "maxSpeedNearHumansMps": 0.3, "allowedZones": ["warehouse-a"], "shiftWindows": [{"start": "06:00", "end": "20:00"}]})
7137        ));
7138    }
7139
7140    #[test]
7141    fn handshake_full_flow() {
7142        let a_seed = [11u8; 32];
7143        let b_seed = [12u8; 32];
7144        let a = Ed25519KeyPair::from_seed(&a_seed);
7145        let b = Ed25519KeyPair::from_seed(&b_seed);
7146        let a_did = "did:web:robot-a.example.com";
7147        let b_did = "did:web:robot-b.example.com";
7148        let policy_b = TrustPolicy::new(["robot-a.example.com".to_string()], false);
7149
7150        let hello = build_hello(
7151            &a_seed,
7152            &BuildHello {
7153                from_did: a_did.into(),
7154                proposed_scope: vec!["lift".into(), "carry".into(), "scan".into()],
7155                nonce: "abc123".into(),
7156                peer_did: Some(b_did.into()),
7157                issued_at: "2026-01-01T00:00:00Z".into(),
7158            },
7159        )
7160        .unwrap();
7161
7162        let accept = build_accept(
7163            &b_seed,
7164            &hello,
7165            Keys::One(a_did, &a.public_key()),
7166            &policy_b,
7167            &BuildAccept {
7168                from_did: b_did.into(),
7169                offered_scope: vec!["carry".into(), "scan".into(), "weld".into()],
7170                session_id: "urn:uuid:sess-1".into(),
7171                valid_until: "2026-01-01T00:05:00Z".into(),
7172                created: "2026-01-01T00:00:01Z".into(),
7173            },
7174        )
7175        .unwrap();
7176
7177        let session = verify_accept(
7178            &accept,
7179            Keys::One(b_did, &b.public_key()),
7180            &hello,
7181            Some("abc123"),
7182            None,
7183            "2026-01-01T00:00:01Z",
7184        )
7185        .unwrap()
7186        .expect("accept verifies");
7187        // A bare key cannot vouch for a did:web peer, and a stale or expired
7188        // exchange is refused.
7189        assert!(verify_accept(
7190            &accept,
7191            Keys::Bare(&b.public_key()),
7192            &hello,
7193            None,
7194            None,
7195            "2026-01-01T00:00:01Z"
7196        )
7197        .unwrap()
7198        .is_none());
7199        assert!(verify_accept(
7200            &accept,
7201            Keys::One(b_did, &b.public_key()),
7202            &hello,
7203            None,
7204            None,
7205            "2026-01-01T00:06:00Z"
7206        )
7207        .unwrap()
7208        .is_none());
7209        // An ACCEPT replayed against another HELLO is refused.
7210        let other_hello = build_hello(
7211            &a_seed,
7212            &BuildHello {
7213                from_did: a_did.into(),
7214                proposed_scope: vec!["carry".into()],
7215                nonce: "zzz".into(),
7216                peer_did: Some(b_did.into()),
7217                issued_at: "2026-01-01T00:00:00Z".into(),
7218            },
7219        )
7220        .unwrap();
7221        assert!(verify_accept(
7222            &accept,
7223            Keys::One(b_did, &b.public_key()),
7224            &other_hello,
7225            None,
7226            None,
7227            "2026-01-01T00:00:01Z"
7228        )
7229        .unwrap()
7230        .is_none());
7231        assert_eq!(session.scope, vec!["carry".to_string(), "scan".to_string()]);
7232        assert_eq!(session.initiator, a_did);
7233        assert_eq!(session.responder, b_did);
7234
7235        let confirm = build_confirm(&a_seed, a_did, &session, "2026-01-01T00:00:02Z").unwrap();
7236        assert!(verify_confirm(
7237            &confirm,
7238            Keys::One(a_did, &a.public_key()),
7239            &accept,
7240            "2026-01-01T00:00:02Z"
7241        )
7242        .unwrap());
7243        assert!(!verify_confirm(
7244            &confirm,
7245            Keys::One(a_did, &a.public_key()),
7246            &accept,
7247            "2026-01-01T00:06:00Z"
7248        )
7249        .unwrap());
7250        // A stale HELLO is refused by the responder.
7251        assert!(build_accept(
7252            &b_seed,
7253            &hello,
7254            Keys::One(a_did, &a.public_key()),
7255            &policy_b,
7256            &BuildAccept {
7257                from_did: b_did.into(),
7258                offered_scope: vec!["carry".into()],
7259                session_id: "s2".into(),
7260                valid_until: "2026-01-01T01:00:00Z".into(),
7261                created: "2026-01-01T00:10:00Z".into(),
7262            }
7263        )
7264        .is_err());
7265    }
7266
7267    #[test]
7268    fn handshake_untrusted_tamper_and_nonce() {
7269        let a_seed = [11u8; 32];
7270        let b_seed = [12u8; 32];
7271        let a = Ed25519KeyPair::from_seed(&a_seed);
7272        let b = Ed25519KeyPair::from_seed(&b_seed);
7273        let a_did = "did:web:robot-a.example.com";
7274        let b_did = "did:web:robot-b.example.com";
7275
7276        let hello = build_hello(
7277            &a_seed,
7278            &BuildHello {
7279                from_did: a_did.into(),
7280                proposed_scope: vec!["lift".into()],
7281                nonce: "n1".into(),
7282                peer_did: None,
7283                issued_at: "2026-01-01T00:00:00Z".into(),
7284            },
7285        )
7286        .unwrap();
7287
7288        // Untrusted initiator.
7289        let strict = TrustPolicy::new(["someone-else.example.com".to_string()], false);
7290        assert!(build_accept(
7291            &b_seed,
7292            &hello,
7293            Keys::One(a_did, &a.public_key()),
7294            &strict,
7295            &BuildAccept {
7296                from_did: b_did.into(),
7297                offered_scope: vec!["lift".into()],
7298                session_id: "s".into(),
7299                valid_until: "2026-01-01T00:05:00Z".into(),
7300                created: "2026-01-01T00:00:01Z".into(),
7301            },
7302        )
7303        .is_err());
7304
7305        // Tampered HELLO (scope broadened after signing) fails signature check.
7306        let open = TrustPolicy::new(Vec::<String>::new(), true);
7307        let mut tampered = hello.clone();
7308        tampered["proposedScope"] = json!(["lift", "weld"]);
7309        assert!(build_accept(
7310            &b_seed,
7311            &tampered,
7312            Keys::One(a_did, &a.public_key()),
7313            &open,
7314            &BuildAccept {
7315                from_did: b_did.into(),
7316                offered_scope: vec!["lift".into(), "weld".into()],
7317                session_id: "s".into(),
7318                valid_until: "2026-01-01T00:05:00Z".into(),
7319                created: "2026-01-01T00:00:01Z".into(),
7320            },
7321        )
7322        .is_err());
7323
7324        // Nonce mismatch on a valid ACCEPT.
7325        let accept = build_accept(
7326            &b_seed,
7327            &hello,
7328            Keys::One(a_did, &a.public_key()),
7329            &open,
7330            &BuildAccept {
7331                from_did: b_did.into(),
7332                offered_scope: vec!["lift".into()],
7333                session_id: "s".into(),
7334                valid_until: "2026-01-01T00:05:00Z".into(),
7335                created: "2026-01-01T00:00:01Z".into(),
7336            },
7337        )
7338        .unwrap();
7339        assert!(verify_accept(
7340            &accept,
7341            Keys::One(b_did, &b.public_key()),
7342            &hello,
7343            Some("wrong-nonce"),
7344            Some(&open),
7345            "2026-01-01T00:00:01Z"
7346        )
7347        .unwrap()
7348        .is_none());
7349    }
7350
7351    #[test]
7352    fn did_web_domain_parsing() {
7353        let domain = |did: &str| did_web_domain(did);
7354        assert_eq!(
7355            domain("did:web:example.com").as_deref(),
7356            Some("example.com")
7357        );
7358        // A path is part of the name, so a bare-domain entry never covers it.
7359        assert_eq!(
7360            domain("did:web:robot.example.com:agent").as_deref(),
7361            Some("robot.example.com:agent")
7362        );
7363        assert_eq!(domain("did:web:robot.example.com:"), None);
7364        assert_eq!(domain("did:key:z6Mk"), None);
7365        // A did:webvh DID gives its parsed host, never read as did:web.
7366        let scid = "QmUy89VrfryQ254CeHZzQfmcKqByPoKNGqYykP3SeXuegQ";
7367        assert_eq!(
7368            domain(&format!("did:webvh:{scid}:Robot.Example.com%3A8443:agents")).as_deref(),
7369            Some("robot.example.com:agents")
7370        );
7371        // One that does not parse has no domain.
7372        assert_eq!(domain("did:webvh:{SCID}:robot.example.com"), None);
7373        assert_eq!(domain(&format!("did:webvh:{scid}:127.0.0.1")), None);
7374        assert_eq!(domain("did:webvhx:robot.example.com"), None);
7375        let policy = TrustPolicy::new(["robot.example.com".to_string()], false);
7376        assert!(policy.is_trusted(&format!("did:webvh:{scid}:robot.example.com")));
7377        assert!(!policy.is_trusted(&format!("did:webvh:{scid}:other.example.com")));
7378        assert!(!policy.is_trusted("did:webvh:{SCID}:robot.example.com"));
7379    }
7380
7381    #[test]
7382    fn blackbox_append_open_and_chain() {
7383        let key = [0x11u8; 32];
7384        let mut log = BlackBoxLog::new(&key, None).unwrap();
7385        let e0 = log
7386            .append(
7387                "motion",
7388                &json!({"speed": 1.5, "joint": "elbow"}),
7389                "2026-01-01T00:00:00Z",
7390            )
7391            .unwrap();
7392        log.append("stop", &json!({"reason": "human"}), "2026-01-01T00:00:01Z")
7393            .unwrap();
7394
7395        // Round-trip decrypt.
7396        let opened = log.open(&e0).unwrap();
7397        assert_eq!(opened["joint"], json!("elbow"));
7398
7399        // Chain verifies, in memory and after a JSON round trip.
7400        assert!(verify_blackbox_chain(log.entries(), None).ok);
7401        let wire: Vec<Value> =
7402            serde_json::from_str(&serde_json::to_string(log.entries()).unwrap()).unwrap();
7403        assert!(verify_blackbox_chain(&wire, None).ok);
7404        assert_eq!(open_entry(&wire[0], &key).unwrap()["joint"], json!("elbow"));
7405
7406        // Tamper detection.
7407        let mut tampered = wire.clone();
7408        tampered[1]["event"] = json!("tampered");
7409        assert!(!verify_blackbox_chain(&tampered, None).ok);
7410
7411        // Wrong key fails decryption; bad key length rejected.
7412        assert!(open_entry(&e0, &[0x22u8; 32]).is_err());
7413        assert!(BlackBoxLog::new(&[0u8; 16], None).is_err());
7414
7415        // Genesis constant matches the multibase of 32 zero bytes.
7416        assert_eq!(genesis_prev_hash(), format!("u{}", "A".repeat(43)));
7417    }
7418
7419    #[test]
7420    fn killswitch_build_verify_and_trust() {
7421        let seed = [13u8; 32];
7422        let kp = Ed25519KeyPair::from_seed(&seed);
7423        let cred = build_killswitch_credential(
7424            &seed,
7425            &BuildKillswitch {
7426                issuer_did: "did:web:safety.example.com".into(),
7427                target: "did:web:robot.example.com".into(),
7428                reason: "human in path".into(),
7429                command: None,
7430                scope: Some(vec!["arm".into(), "drive".into()]),
7431                valid_from: "2026-01-01T00:00:00Z".into(),
7432                valid_until: None,
7433            },
7434        )
7435        .unwrap();
7436
7437        let mut trusted = HashSet::new();
7438        trusted.insert("did:web:safety.example.com".to_string());
7439        let subject =
7440            verify_killswitch_credential(&cred, kd(&cred, &kp.public_key()), Some(&trusted), TNOW)
7441                .unwrap()
7442                .expect("trusted authority verifies");
7443        assert_eq!(subject["command"], json!(EMERGENCY_STOP));
7444
7445        // Untrusted issuer rejected though the signature is valid.
7446        let mut other = HashSet::new();
7447        other.insert("did:web:someone-else.example.com".to_string());
7448        assert!(verify_killswitch_credential(
7449            &cred,
7450            kd(&cred, &kp.public_key()),
7451            Some(&other),
7452            TNOW
7453        )
7454        .unwrap()
7455        .is_none());
7456
7457        // Wrong type rejected.
7458        let mut wrong = cred.clone();
7459        wrong["type"] = json!(["VerifiableCredential"]);
7460        assert!(
7461            verify_killswitch_credential(&wrong, kd(&wrong, &kp.public_key()), None, TNOW)
7462                .unwrap()
7463                .is_none()
7464        );
7465    }
7466
7467    #[test]
7468    fn passport_build_encode_verify() {
7469        let seed = [14u8; 32];
7470        let kp = Ed25519KeyPair::from_seed(&seed);
7471        let did = "did:web:robot.example.com";
7472        let pass = build_passport(
7473            &seed,
7474            &BuildPassport {
7475                issuer_did: did.into(),
7476                robot_did: did.into(),
7477                make: "Acme Robotics".into(),
7478                model: "AR-7".into(),
7479                owner: "did:web:owner.example.com".into(),
7480                authorized_actions: vec!["lift".into(), "carry".into()],
7481                certification: Some("ISO-10218".into()),
7482                status: None,
7483                valid_from: "2026-01-01T00:00:00Z".into(),
7484                valid_until: None,
7485            },
7486        )
7487        .unwrap();
7488
7489        // Direct verify.
7490        let subject = verify_passport(
7491            &pass,
7492            kd(&pass, &kp.public_key()),
7493            None,
7494            "2026-06-01T00:00:00Z",
7495        )
7496        .unwrap()
7497        .expect("passport verifies");
7498        assert_eq!(subject["owner"], json!("did:web:owner.example.com"));
7499        assert_eq!(subject["status"], json!(STATUS_ACTIVE));
7500
7501        // Encode to a URI, decode, and verify the offline-scan path.
7502        let uri = encode_passport(&pass);
7503        assert!(uri.starts_with("vouch-passport:u"));
7504        let decoded = decode_passport(&uri).unwrap();
7505        assert!(verify_passport(
7506            &decoded,
7507            kd(&decoded, &kp.public_key()),
7508            None,
7509            "2026-06-01T00:00:00Z"
7510        )
7511        .unwrap()
7512        .is_some());
7513        assert!(verify_passport_uri(
7514            &uri,
7515            Keys::Resolver(&any_did(&kp.public_key())),
7516            None,
7517            "2026-06-01T00:00:00Z"
7518        )
7519        .unwrap()
7520        .is_some());
7521
7522        // Tamper and wrong type rejected.
7523        let mut tampered = pass.clone();
7524        tampered["credentialSubject"]["owner"] = json!("did:web:attacker.example.com");
7525        assert!(verify_passport(
7526            &tampered,
7527            kd(&tampered, &kp.public_key()),
7528            None,
7529            "2026-06-01T00:00:00Z"
7530        )
7531        .unwrap()
7532        .is_none());
7533
7534        // Malformed URI.
7535        assert!(decode_passport("https://example.com/x").is_err());
7536    }
7537
7538    #[test]
7539    fn passport_expiry_and_suspended() {
7540        let seed = [15u8; 32];
7541        let kp = Ed25519KeyPair::from_seed(&seed);
7542        let did = "did:web:robot.example.com";
7543
7544        // Expiry: valid inside the window, expired past validUntil.
7545        let timed = build_passport(
7546            &seed,
7547            &BuildPassport {
7548                issuer_did: did.into(),
7549                robot_did: did.into(),
7550                make: "Acme".into(),
7551                model: "AR-7".into(),
7552                owner: "did:web:owner.example.com".into(),
7553                authorized_actions: vec!["lift".into()],
7554                certification: None,
7555                status: None,
7556                valid_from: "2026-01-01T00:00:00Z".into(),
7557                valid_until: Some("2026-01-01T00:01:00Z".into()),
7558            },
7559        )
7560        .unwrap();
7561        assert!(verify_passport(
7562            &timed,
7563            kd(&timed, &kp.public_key()),
7564            None,
7565            "2026-01-01T00:00:30Z"
7566        )
7567        .unwrap()
7568        .is_some());
7569        assert!(verify_passport(
7570            &timed,
7571            kd(&timed, &kp.public_key()),
7572            None,
7573            "2026-01-01T00:02:00Z"
7574        )
7575        .unwrap()
7576        .is_none());
7577
7578        // Suspended still verifies but the status is surfaced.
7579        let suspended = build_passport(
7580            &seed,
7581            &BuildPassport {
7582                issuer_did: did.into(),
7583                robot_did: did.into(),
7584                make: "Acme".into(),
7585                model: "AR-7".into(),
7586                owner: "did:web:owner.example.com".into(),
7587                authorized_actions: vec!["lift".into()],
7588                certification: None,
7589                status: Some(STATUS_SUSPENDED.into()),
7590                valid_from: "2026-01-01T00:00:00Z".into(),
7591                valid_until: None,
7592            },
7593        )
7594        .unwrap();
7595        let subject = verify_passport(
7596            &suspended,
7597            kd(&suspended, &kp.public_key()),
7598            None,
7599            "2026-06-01T00:00:00Z",
7600        )
7601        .unwrap()
7602        .expect("a suspended passport still verifies");
7603        assert_eq!(subject["status"], json!(STATUS_SUSPENDED));
7604    }
7605
7606    // Cross-language interop: Rust reproduces the exact motion digest Python
7607    // pinned from the same fixed samples against the same physical scope.
7608    #[test]
7609    fn motion_digest_matches_interop_vector() {
7610        let vector = load_vector();
7611        let scope = vector["physical_scope"].clone();
7612        let mut collector = MotionCollector::new(Some(scope));
7613        collector
7614            .record(&MotionSample {
7615                force_n: Some(12.0),
7616                speed_mps: Some(0.4),
7617                near_humans: false,
7618                zone: Some("cell-3".into()),
7619                time_hm: None,
7620            })
7621            .unwrap();
7622        collector
7623            .record(&MotionSample {
7624                force_n: Some(20.0),
7625                speed_mps: Some(0.2),
7626                near_humans: true,
7627                zone: Some("cell-3".into()),
7628                time_hm: None,
7629            })
7630            .unwrap();
7631        assert_eq!(collector.digest(), vector["expected_motion_digest"]);
7632    }
7633
7634    #[test]
7635    fn heartbeat_build_verify_and_liveness() {
7636        let seed = [21u8; 32];
7637        let kp = Ed25519KeyPair::from_seed(&seed);
7638        let did = "did:web:robot.example.com";
7639        let digest = json!({
7640            "samples": 2, "maxForceN": 20.0, "maxSpeedMps": 0.4,
7641            "maxSpeedNearHumansMps": 0.2, "zoneBreaches": 0, "breachCount": 0,
7642            "withinEnvelope": true
7643        });
7644        let hb = build_robot_heartbeat(
7645            &seed,
7646            &BuildRobotHeartbeat {
7647                robot_did: did.into(),
7648                session_id: "urn:uuid:sess-1".into(),
7649                interval_index: 0,
7650                interval_seconds: 60,
7651                motion_digest: digest,
7652                valid_from: "2026-01-01T00:00:00Z".into(),
7653            },
7654        )
7655        .unwrap();
7656
7657        let subject = verify_robot_heartbeat(&hb, kd(&hb, &kp.public_key()), TNOW)
7658            .unwrap()
7659            .expect("heartbeat verifies");
7660        assert_eq!(subject["sessionId"], json!("urn:uuid:sess-1"));
7661
7662        // Fresh and in-envelope: live. Stale: not live.
7663        assert!(is_live(&hb, "2026-01-01T00:01:00Z", None, DEFAULT_GRACE_INTERVALS).unwrap());
7664        assert!(!is_live(&hb, "2026-01-01T01:00:00Z", None, DEFAULT_GRACE_INTERVALS).unwrap());
7665
7666        // Out-of-envelope heartbeat is never live, even when fresh.
7667        let breached = json!({
7668            "samples": 1, "maxForceN": 99.0, "maxSpeedMps": 0.4,
7669            "maxSpeedNearHumansMps": 0.2, "zoneBreaches": 0, "breachCount": 1,
7670            "withinEnvelope": false
7671        });
7672        let hb2 = build_robot_heartbeat(
7673            &seed,
7674            &BuildRobotHeartbeat {
7675                robot_did: did.into(),
7676                session_id: "s".into(),
7677                interval_index: 1,
7678                interval_seconds: 60,
7679                motion_digest: breached,
7680                valid_from: "2026-01-01T00:00:00Z".into(),
7681            },
7682        )
7683        .unwrap();
7684        assert!(!is_live(&hb2, "2026-01-01T00:00:30Z", None, DEFAULT_GRACE_INTERVALS).unwrap());
7685
7686        // Tamper and wrong type rejected.
7687        let mut tampered = hb.clone();
7688        tampered["credentialSubject"]["sessionId"] = json!("urn:uuid:other");
7689        assert!(
7690            verify_robot_heartbeat(&tampered, kd(&tampered, &kp.public_key()), TNOW)
7691                .unwrap()
7692                .is_none()
7693        );
7694    }
7695
7696    // Cross-language interop: Rust reproduces the exact hash-linked ledger and
7697    // the summary Python pinned from the same fixed events and timestamps.
7698    #[test]
7699    fn safety_log_matches_interop_vector() {
7700        let vector = load_vector();
7701        let mut log = SafetyEventLog::new(None);
7702        log.append(
7703            "near_miss",
7704            "low",
7705            Some(&json!({"zone": "cell-3"})),
7706            None,
7707            "2026-01-01T00:00:00Z",
7708        )
7709        .unwrap();
7710        log.append(
7711            "envelope_breach",
7712            "high",
7713            None,
7714            None,
7715            "2026-01-01T00:01:00Z",
7716        )
7717        .unwrap();
7718
7719        assert_eq!(
7720            Value::Array(log.entries().to_vec()),
7721            vector["safety_log_entries"]
7722        );
7723        assert_eq!(
7724            log.head(),
7725            vector["expected_safety_log_head"].as_str().unwrap()
7726        );
7727        assert_eq!(log.summarize(), vector["expected_safety_summary"]);
7728        assert!(verify_safety_log(log.entries(), None).ok);
7729    }
7730
7731    #[test]
7732    fn safety_record_build_verify_and_tamper() {
7733        let seed = [22u8; 32];
7734        let kp = Ed25519KeyPair::from_seed(&seed);
7735        let mut log = SafetyEventLog::new(None);
7736        log.append("near_miss", "low", None, None, "2026-01-01T00:00:00Z")
7737            .unwrap();
7738        let summary = log.summarize();
7739
7740        let record = build_safety_record(
7741            &seed,
7742            &BuildSafetyRecord {
7743                issuer_did: "did:web:owner.example.com".into(),
7744                robot_did: "did:web:robot.example.com".into(),
7745                summary,
7746                period_start: Some("2026-01-01T00:00:00Z".into()),
7747                period_end: Some("2026-01-31T00:00:00Z".into()),
7748                valid_from: "2026-02-01T00:00:00Z".into(),
7749                valid_until: None,
7750            },
7751        )
7752        .unwrap();
7753
7754        let subject = verify_safety_record(
7755            &record,
7756            kd(&record, &kp.public_key()),
7757            SafetyRecordCheck::default(),
7758            "2026-03-01T00:00:00Z",
7759        )
7760        .unwrap()
7761        .expect("safety record verifies");
7762        assert_eq!(subject["totalEvents"], json!(1));
7763        assert_eq!(subject["period"]["start"], json!("2026-01-01T00:00:00Z"));
7764
7765        let mut tampered = record.clone();
7766        tampered["credentialSubject"]["totalEvents"] = json!(99);
7767        assert!(verify_safety_record(
7768            &tampered,
7769            kd(&tampered, &kp.public_key()),
7770            SafetyRecordCheck::default(),
7771            "2026-03-01T00:00:00Z"
7772        )
7773        .unwrap()
7774        .is_none());
7775
7776        // Tamper detection in the ledger itself.
7777        let mut entries = log.entries().to_vec();
7778        entries[0]["severity"] = json!("critical");
7779        assert!(!verify_safety_log(&entries, None).ok);
7780    }
7781
7782    // Cross-language interop: Rust reproduces the exact credentialStatus entry.
7783    #[test]
7784    fn status_entry_matches_interop_vector() {
7785        let vector = load_vector();
7786        let entry = build_status_list_entry(
7787            "https://fleet.example.com/status/1",
7788            42,
7789            STATUS_PURPOSE_REVOCATION,
7790            None,
7791        )
7792        .unwrap();
7793        assert_eq!(entry, vector["expected_credential_status_entry"]);
7794    }
7795
7796    #[test]
7797    fn attach_and_check_credential_status() {
7798        let seed = [23u8; 32];
7799        let kp = Ed25519KeyPair::from_seed(&seed);
7800        let did = "did:web:robot.example.com";
7801
7802        // Mint a passport, then attach a revocation status and re-sign.
7803        let pass = build_passport(
7804            &seed,
7805            &BuildPassport {
7806                issuer_did: did.into(),
7807                robot_did: did.into(),
7808                make: "Acme".into(),
7809                model: "AR-7".into(),
7810                owner: "did:web:owner.example.com".into(),
7811                authorized_actions: vec!["lift".into()],
7812                certification: None,
7813                status: None,
7814                valid_from: "2026-01-01T00:00:00Z".into(),
7815                valid_until: None,
7816            },
7817        )
7818        .unwrap();
7819
7820        let with_status = attach_credential_status(
7821            &pass,
7822            &seed,
7823            &AttachCredentialStatus {
7824                status_list_credential: "https://fleet.example.com/status/1".into(),
7825                status_list_index: 42,
7826                status_purpose: STATUS_PURPOSE_REVOCATION.into(),
7827                entry_id: None,
7828                created: "2026-01-01T00:00:00Z".into(),
7829            },
7830        )
7831        .unwrap();
7832
7833        // The re-signed credential still verifies and now carries the entry.
7834        assert!(data_integrity::verify_proof(&with_status, &kp.public_key()).unwrap());
7835        assert_eq!(
7836            with_status["credentialStatus"]["statusListIndex"],
7837            json!("42")
7838        );
7839
7840        // Build a status list with bit 42 set, then check the entry resolves.
7841        let mut bits = vec![0u8; crate::status_list::DEFAULT_BITSTRING_LENGTH / 8];
7842        crate::status_list::set_status(&mut bits, 42, true).unwrap();
7843        let encoded = crate::status_list::encode_bitstring(&bits).unwrap();
7844        let status_list = json!({
7845            "id": "https://fleet.example.com/status/1",
7846            "issuer": did,
7847            "type": ["VerifiableCredential", "BitstringStatusListCredential"],
7848            "credentialSubject": {
7849                "type": "BitstringStatusList",
7850                "statusPurpose": "revocation",
7851                "encodedList": encoded,
7852            }
7853        });
7854        assert!(
7855            check_credential_status(&with_status, &status_list, STATUS_PURPOSE_REVOCATION).unwrap()
7856        );
7857
7858        // A credential with no status entry is not revoked.
7859        assert!(!check_credential_status(&pass, &status_list, STATUS_PURPOSE_REVOCATION).unwrap());
7860
7861        // A list with the bit clear reports not-revoked.
7862        let clear_bits = vec![0u8; crate::status_list::DEFAULT_BITSTRING_LENGTH / 8];
7863        let clear_encoded = crate::status_list::encode_bitstring(&clear_bits).unwrap();
7864        let mut clear_list = status_list.clone();
7865        clear_list["credentialSubject"]["encodedList"] = json!(clear_encoded);
7866        assert!(
7867            !check_credential_status(&with_status, &clear_list, STATUS_PURPOSE_REVOCATION).unwrap()
7868        );
7869
7870        // A list from another issuer, or a list the entry does not name, cannot
7871        // answer: an error, never "not revoked".
7872        let mut foreign = status_list.clone();
7873        foreign["issuer"] = json!("did:web:someone-else.example.com");
7874        assert!(
7875            check_credential_status(&with_status, &foreign, STATUS_PURPOSE_REVOCATION).is_err()
7876        );
7877        let mut other = status_list.clone();
7878        other["id"] = json!("https://fleet.example.com/status/2");
7879        assert!(check_credential_status(&with_status, &other, STATUS_PURPOSE_REVOCATION).is_err());
7880    }
7881
7882    // Cross-language interop: Rust reproduces the exact frame hash Python pinned.
7883    #[test]
7884    fn frame_hash_matches_interop_vector() {
7885        let vector = load_vector();
7886        let sample_frame: Vec<u8> = (0u8..64).collect();
7887        let got = hash_frame(&sample_frame);
7888        assert_eq!(got, vector["expected_frame_hash"].as_str().unwrap());
7889        assert_eq!(got, "u_eq5rPNxA2K9JljNyaKej5x1f8-YEWA6jER80dkVEQg");
7890    }
7891
7892    // Cross-language interop: Rust reproduces the exact hash-linked perception log
7893    // Python pinned from the same fixed frames and timestamps.
7894    #[test]
7895    fn perception_log_matches_interop_vector() {
7896        let vector = load_vector();
7897        let sample_frame: Vec<u8> = (0u8..64).collect();
7898        let mut log = PerceptionLog::new(None);
7899        log.record(
7900            "cam-front",
7901            "camera",
7902            Some(&sample_frame),
7903            None,
7904            "2026-01-01T00:00:00Z",
7905        )
7906        .unwrap();
7907        log.record(
7908            "lidar-top",
7909            "lidar",
7910            None,
7911            Some(&hash_frame(b"scan-0")),
7912            "2026-01-01T00:00:01Z",
7913        )
7914        .unwrap();
7915
7916        assert_eq!(
7917            Value::Array(log.entries().to_vec()),
7918            vector["perception_log_entries"]
7919        );
7920        assert_eq!(
7921            log.head(),
7922            vector["expected_perception_log_head"].as_str().unwrap()
7923        );
7924        assert!(verify_perception_log(log.entries(), None).ok);
7925    }
7926
7927    #[test]
7928    fn perception_record_validation_and_tamper() {
7929        let mut log = PerceptionLog::new(None);
7930        // Unknown modality rejected.
7931        assert!(log
7932            .record("cam", "sonar", Some(b"x"), None, "2026-01-01T00:00:00Z")
7933            .is_err());
7934        // Both frame and frame_hash rejected.
7935        assert!(log
7936            .record(
7937                "cam",
7938                "camera",
7939                Some(b"x"),
7940                Some("uABC"),
7941                "2026-01-01T00:00:00Z"
7942            )
7943            .is_err());
7944        // Neither frame nor frame_hash rejected.
7945        assert!(log
7946            .record("cam", "camera", None, None, "2026-01-01T00:00:00Z")
7947            .is_err());
7948        // Empty sensor id rejected.
7949        assert!(log
7950            .record("", "camera", Some(b"x"), None, "2026-01-01T00:00:00Z")
7951            .is_err());
7952
7953        log.record(
7954            "cam",
7955            "camera",
7956            Some(b"frame-0"),
7957            None,
7958            "2026-01-01T00:00:00Z",
7959        )
7960        .unwrap();
7961        log.record(
7962            "cam",
7963            "camera",
7964            Some(b"frame-1"),
7965            None,
7966            "2026-01-01T00:00:01Z",
7967        )
7968        .unwrap();
7969        assert!(verify_perception_log(log.entries(), None).ok);
7970
7971        // Tamper detection in the chain.
7972        let mut entries = log.entries().to_vec();
7973        entries[0]["frameHash"] = json!("uTAMPERED");
7974        assert!(!verify_perception_log(&entries, None).ok);
7975    }
7976
7977    #[test]
7978    fn perception_attestation_build_verify_and_tamper() {
7979        let seed = [24u8; 32];
7980        let kp = Ed25519KeyPair::from_seed(&seed);
7981        let did = "did:web:robot.example.com";
7982        let frame = b"sensor-frame-bytes";
7983        let frame_hash = hash_frame(frame);
7984
7985        let cred = build_perception_attestation(
7986            &seed,
7987            &BuildPerception {
7988                robot_did: did.into(),
7989                sensor_id: "cam-front".into(),
7990                modality: "camera".into(),
7991                frame_hash: frame_hash.clone(),
7992                captured_at: Some("2026-01-01T00:00:00Z".into()),
7993                log_head: Some("uHEAD".into()),
7994                log_count: None,
7995                valid_from: "2026-01-01T00:00:00Z".into(),
7996                valid_until: None,
7997            },
7998        )
7999        .unwrap();
8000
8001        // Verify the proof and the embedded provenance, and recompute the frame.
8002        let subject =
8003            verify_perception_attestation(&cred, kd(&cred, &kp.public_key()), Some(frame), TNOW)
8004                .unwrap()
8005                .expect("perception attestation verifies");
8006        assert_eq!(subject["sensorId"], json!("cam-front"));
8007        assert_eq!(subject["frameHash"], json!(frame_hash));
8008        assert_eq!(subject["logHead"], json!("uHEAD"));
8009
8010        // Verify without the raw frame still passes (proof only).
8011        assert!(
8012            verify_perception_attestation(&cred, kd(&cred, &kp.public_key()), None, TNOW)
8013                .unwrap()
8014                .is_some()
8015        );
8016
8017        // A different frame than the one attested is rejected.
8018        assert!(verify_perception_attestation(
8019            &cred,
8020            kd(&cred, &kp.public_key()),
8021            Some(b"other-frame"),
8022            TNOW
8023        )
8024        .unwrap()
8025        .is_none());
8026
8027        // Tampered subject fails the proof.
8028        let mut tampered = cred.clone();
8029        tampered["credentialSubject"]["sensorId"] = json!("cam-rear");
8030        assert!(verify_perception_attestation(
8031            &tampered,
8032            kd(&tampered, &kp.public_key()),
8033            None,
8034            TNOW
8035        )
8036        .unwrap()
8037        .is_none());
8038
8039        // Wrong type rejected.
8040        let mut wrong = cred.clone();
8041        wrong["type"] = json!(["VerifiableCredential"]);
8042        assert!(
8043            verify_perception_attestation(&wrong, kd(&wrong, &kp.public_key()), None, TNOW)
8044                .unwrap()
8045                .is_none()
8046        );
8047
8048        // Bad modality and missing frame_hash rejected at build time.
8049        assert!(build_perception_attestation(
8050            &seed,
8051            &BuildPerception {
8052                robot_did: did.into(),
8053                sensor_id: "s".into(),
8054                modality: "sonar".into(),
8055                frame_hash: frame_hash.clone(),
8056                captured_at: None,
8057                log_head: None,
8058                log_count: None,
8059                valid_from: "2026-01-01T00:00:00Z".into(),
8060                valid_until: None,
8061            },
8062        )
8063        .is_err());
8064        assert!(build_perception_attestation(
8065            &seed,
8066            &BuildPerception {
8067                robot_did: did.into(),
8068                sensor_id: "s".into(),
8069                modality: "camera".into(),
8070                frame_hash: String::new(),
8071                captured_at: None,
8072                log_head: None,
8073                log_count: None,
8074                valid_from: "2026-01-01T00:00:00Z".into(),
8075                valid_until: None,
8076            },
8077        )
8078        .is_err());
8079    }
8080
8081    fn jwk_pub(jwk: &Value) -> Vec<u8> {
8082        URL_SAFE_NO_PAD
8083            .decode(jwk["x"].as_str().unwrap())
8084            .expect("base64url JWK x")
8085    }
8086
8087    // Cross-language interop: Go and TypeScript verify this same Python-signed
8088    // delegation lease; the Rust core must too.
8089    #[test]
8090    fn verifies_python_lease_interop_vector() {
8091        let vector = load_vector();
8092        let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
8093        let lease = vector["delegation_lease_credential"].clone();
8094
8095        let subject = verify_delegation_lease(
8096            &lease,
8097            kd(&lease, &robot_pub),
8098            "did:web:robot.example.com",
8099            None,
8100            None,
8101            "2026-06-01T00:00:00Z",
8102        )
8103        .unwrap()
8104        .expect("the Python lease interop vector must verify in Rust");
8105        assert_eq!(subject["leaseId"], json!("lease-vector-1"));
8106    }
8107
8108    // Cross-language interop: Rust authorizes the Python-signed quorum with the
8109    // same two approver keys and a threshold of 2.
8110    #[test]
8111    fn verifies_python_quorum_interop_vector() {
8112        let vector = load_vector();
8113        let approvals = vector["quorum_approvals"].as_array().unwrap().clone();
8114        let action_id = vector["quorum_action_id"].as_str().unwrap();
8115        let keys: Vec<ApproverKey> = vector["quorum_approver_keys"]
8116            .as_object()
8117            .unwrap()
8118            .iter()
8119            .map(|(did, jwk)| ApproverKey {
8120                did: did.clone(),
8121                public_key: jwk_pub(jwk),
8122            })
8123            .collect();
8124
8125        let (ok, approvers) = verify_action_authorization(
8126            &approvals,
8127            action_id,
8128            "did:web:robot.example.com",
8129            &keys,
8130            2,
8131            None,
8132            vector["quorum_now"].as_str().unwrap(),
8133        )
8134        .unwrap();
8135        assert!(
8136            ok,
8137            "the Python quorum interop vector must authorize in Rust"
8138        );
8139        assert_eq!(approvers.len(), 2);
8140        assert_eq!(approvers[0], "did:web:approver-1.example.com");
8141        assert_eq!(approvers[1], "did:web:approver-2.example.com");
8142    }
8143
8144    #[test]
8145    fn lease_build_verify_permits_and_expiry() {
8146        let seed = [31u8; 32];
8147        let kp = Ed25519KeyPair::from_seed(&seed);
8148        let did = "did:web:robot.example.com";
8149        let scope = json!({
8150            "maxForceN": 80.0, "maxSpeedMps": 2.0, "maxSpeedNearHumansMps": 0.5,
8151            "allowedZones": ["warehouse-a", "dock-3"]
8152        });
8153        let lease = build_delegation_lease(
8154            &seed,
8155            &BuildDelegationLease {
8156                issuer_did: did.into(),
8157                robot_did: did.into(),
8158                lease_id: "lease-1".into(),
8159                scope: scope.clone(),
8160                parent_lease_id: None,
8161                valid_from: "2026-01-01T00:00:00Z".into(),
8162                valid_until: "2026-01-01T01:00:00Z".into(),
8163            },
8164        )
8165        .unwrap();
8166
8167        // Round-trip verify, in-window.
8168        let subject = verify_delegation_lease(
8169            &lease,
8170            kd(&lease, &kp.public_key()),
8171            "did:web:robot.example.com",
8172            None,
8173            None,
8174            "2026-01-01T00:30:00Z",
8175        )
8176        .unwrap()
8177        .expect("lease verifies in window");
8178        assert_eq!(subject["leaseId"], json!("lease-1"));
8179
8180        // Permits a within-scope action, denies an out-of-scope one.
8181        assert!(lease_permits(
8182            &subject,
8183            &PhysicalAction {
8184                force_n: Some(50.0),
8185                zone: Some("warehouse-a".into()),
8186                ..Default::default()
8187            },
8188            Some(&lease),
8189            kd(&lease, &kp.public_key()),
8190            None,
8191            "2026-01-01T00:30:00Z",
8192        )
8193        .unwrap());
8194        assert!(!lease_permits(
8195            &subject,
8196            &PhysicalAction {
8197                force_n: Some(120.0),
8198                ..Default::default()
8199            },
8200            Some(&lease),
8201            kd(&lease, &kp.public_key()),
8202            None,
8203            "2026-01-01T00:30:00Z",
8204        )
8205        .unwrap());
8206
8207        // Expired window: verify fails and the lease no longer permits.
8208        assert!(verify_delegation_lease(
8209            &lease,
8210            kd(&lease, &kp.public_key()),
8211            "did:web:robot.example.com",
8212            None,
8213            None,
8214            "2026-01-01T02:00:00Z"
8215        )
8216        .unwrap()
8217        .is_none());
8218        assert!(!lease_permits(
8219            &subject,
8220            &PhysicalAction {
8221                force_n: Some(50.0),
8222                ..Default::default()
8223            },
8224            Some(&lease),
8225            kd(&lease, &kp.public_key()),
8226            None,
8227            "2026-01-01T02:00:00Z",
8228        )
8229        .unwrap());
8230
8231        // Tamper and wrong type rejected.
8232        let mut tampered = lease.clone();
8233        tampered["credentialSubject"]["leaseId"] = json!("lease-other");
8234        assert!(verify_delegation_lease(
8235            &tampered,
8236            kd(&tampered, &kp.public_key()),
8237            "did:web:robot.example.com",
8238            None,
8239            None,
8240            "2026-01-01T00:30:00Z"
8241        )
8242        .unwrap()
8243        .is_none());
8244    }
8245
8246    #[test]
8247    fn lease_sub_grant_attenuation() {
8248        let parent_seed = [32u8; 32];
8249        let child_seed = [33u8; 32];
8250        let parent_kp = Ed25519KeyPair::from_seed(&parent_seed);
8251        let child_kp = Ed25519KeyPair::from_seed(&child_seed);
8252        let parent_scope = json!({
8253            "maxForceN": 80.0, "maxSpeedMps": 2.0,
8254            "allowedZones": ["warehouse-a", "dock-3"]
8255        });
8256
8257        // A narrower sub-lease attenuates the parent: accepted.
8258        let narrower = build_delegation_lease(
8259            &child_seed,
8260            &BuildDelegationLease {
8261                issuer_did: "did:web:integrator.example.com".into(),
8262                robot_did: "did:web:robot.example.com".into(),
8263                lease_id: "lease-2".into(),
8264                scope: json!({
8265                    "maxForceN": 50.0, "maxSpeedMps": 1.0,
8266                    "allowedZones": ["warehouse-a"]
8267                }),
8268                parent_lease_id: Some("lease-1".into()),
8269                valid_from: "2026-01-01T00:00:00Z".into(),
8270                valid_until: "2026-01-01T01:00:00Z".into(),
8271            },
8272        )
8273        .unwrap();
8274        assert!(verify_delegation_lease(
8275            &narrower,
8276            kd(&narrower, &child_kp.public_key()),
8277            "did:web:robot.example.com",
8278            Some(&parent_scope),
8279            None,
8280            "2026-01-01T00:30:00Z"
8281        )
8282        .unwrap()
8283        .is_some());
8284
8285        // A widening sub-lease (force above the parent) is rejected against the
8286        // parent scope.
8287        let wider = build_delegation_lease(
8288            &parent_seed,
8289            &BuildDelegationLease {
8290                issuer_did: "did:web:integrator.example.com".into(),
8291                robot_did: "did:web:robot.example.com".into(),
8292                lease_id: "lease-3".into(),
8293                scope: json!({
8294                    "maxForceN": 200.0, "maxSpeedMps": 1.0,
8295                    "allowedZones": ["warehouse-a"]
8296                }),
8297                parent_lease_id: Some("lease-1".into()),
8298                valid_from: "2026-01-01T00:00:00Z".into(),
8299                valid_until: "2026-01-01T01:00:00Z".into(),
8300            },
8301        )
8302        .unwrap();
8303        assert!(verify_delegation_lease(
8304            &wider,
8305            kd(&wider, &parent_kp.public_key()),
8306            "did:web:robot.example.com",
8307            Some(&parent_scope),
8308            None,
8309            "2026-01-01T00:30:00Z"
8310        )
8311        .unwrap()
8312        .is_none());
8313    }
8314
8315    #[test]
8316    fn quorum_threshold_and_distinct_counting() {
8317        let s1 = [41u8; 32];
8318        let s2 = [42u8; 32];
8319        let k1 = Ed25519KeyPair::from_seed(&s1);
8320        let k2 = Ed25519KeyPair::from_seed(&s2);
8321        let a1 = "did:web:approver-1.example.com";
8322        let a2 = "did:web:approver-2.example.com";
8323        let robot = "did:web:robot.example.com";
8324        let action = "action-x";
8325
8326        let build = |seed: &[u8], did: &str, decision: &str| {
8327            build_action_approval(
8328                seed,
8329                &BuildActionApproval {
8330                    approver_did: did.into(),
8331                    action_id: action.into(),
8332                    robot_did: robot.into(),
8333                    decision: decision.into(),
8334                    valid_from: "2026-01-01T00:00:00Z".into(),
8335                    valid_until: None,
8336                },
8337            )
8338            .unwrap()
8339        };
8340
8341        let ap1 = build(&s1, a1, APPROVE);
8342        let ap2 = build(&s2, a2, APPROVE);
8343        let keys = vec![
8344            ApproverKey {
8345                did: a1.into(),
8346                public_key: k1.public_key().to_vec(),
8347            },
8348            ApproverKey {
8349                did: a2.into(),
8350                public_key: k2.public_key().to_vec(),
8351            },
8352        ];
8353
8354        // Two distinct approvers meet a threshold of 2.
8355        let (ok, approvers) = verify_action_authorization(
8356            &[ap1.clone(), ap2],
8357            action,
8358            robot,
8359            &keys,
8360            2,
8361            None,
8362            "2026-01-01T00:01:00Z",
8363        )
8364        .unwrap();
8365        assert!(ok);
8366        assert_eq!(approvers, vec![a1.to_string(), a2.to_string()]);
8367
8368        // Duplicate approvals from one approver count once: threshold 2 not met.
8369        let dup = build(&s1, a1, APPROVE);
8370        let (ok2, approvers2) = verify_action_authorization(
8371            &[ap1.clone(), dup],
8372            action,
8373            robot,
8374            &keys,
8375            2,
8376            None,
8377            "2026-01-01T00:01:00Z",
8378        )
8379        .unwrap();
8380        assert!(!ok2);
8381        assert_eq!(approvers2, vec![a1.to_string()]);
8382
8383        // A single valid approver does not meet a threshold of 2.
8384        let (ok3, _) = verify_action_authorization(
8385            &[ap1],
8386            action,
8387            robot,
8388            &keys,
8389            2,
8390            None,
8391            "2026-01-01T00:01:00Z",
8392        )
8393        .unwrap();
8394        assert!(!ok3);
8395
8396        // A rejection vetoes the action (each approver's latest decision counts).
8397        let rej = build(&s1, a1, REJECT);
8398        let approve2 = build(&s2, a2, APPROVE);
8399        let (ok4, approvers4) = verify_action_authorization(
8400            &[rej, approve2],
8401            action,
8402            robot,
8403            &keys,
8404            2,
8405            None,
8406            "2026-01-01T00:01:00Z",
8407        )
8408        .unwrap();
8409        assert!(!ok4);
8410        assert!(approvers4.is_empty());
8411    }
8412
8413    // Cross-language interop: Rust verifies the Python-signed ownership transfer
8414    // under the owner's key from the vector.
8415    #[test]
8416    fn verifies_python_ownership_transfer_interop_vector() {
8417        let vector = load_vector();
8418        let owner_pub = jwk_pub(&vector["ownership_transfer_owner_key"]);
8419        let cred = vector["ownership_transfer_credential"].clone();
8420
8421        let subject = verify_ownership_transfer(&cred, kd(&cred, &owner_pub), None, TNOW)
8422            .unwrap()
8423            .expect("the Python ownership-transfer interop vector must verify in Rust");
8424        assert_eq!(subject["toOwner"], json!("did:web:owner-b.example.com"));
8425    }
8426
8427    // Cross-language interop: Rust verifies the Python-signed key rotation under
8428    // the robot key from robot_public_key_jwk.
8429    #[test]
8430    fn verifies_python_key_rotation_interop_vector() {
8431        let vector = load_vector();
8432        let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
8433        let cred = vector["key_rotation_credential"].clone();
8434
8435        let subject = verify_key_rotation(&cred, Keys::Bare(&robot_pub), None, TNOW)
8436            .unwrap()
8437            .expect("the Python key-rotation interop vector must verify in Rust");
8438        assert_eq!(
8439            subject["newKey"],
8440            json!("z6MkmtWtY63GQVBrpMyRJWEzsnxfsGkemu6CtMDwGTv4RYj2")
8441        );
8442    }
8443
8444    // Cross-language interop: Rust verifies the Python-signed decommission under
8445    // the authority key from the vector.
8446    #[test]
8447    fn verifies_python_decommission_interop_vector() {
8448        let vector = load_vector();
8449        let authority_pub = jwk_pub(&vector["decommission_authority_key"]);
8450        let cred = vector["decommission_credential"].clone();
8451
8452        let subject = verify_decommission(&cred, kd(&cred, &authority_pub), None, None, TNOW)
8453            .unwrap()
8454            .expect("the Python decommission interop vector must verify in Rust");
8455        assert_eq!(subject["reason"], json!("end of service life"));
8456        assert_eq!(subject["finalDisposition"], json!("recycled"));
8457    }
8458
8459    #[test]
8460    fn ownership_transfer_roundtrip_and_issuer_rule() {
8461        let owner_a_seed = [51u8; 32];
8462        let owner_b_seed = [52u8; 32];
8463        let a = Ed25519KeyPair::from_seed(&owner_a_seed);
8464        let b = Ed25519KeyPair::from_seed(&owner_b_seed);
8465        let owner_a = "did:web:owner-a.example.com";
8466        let owner_b = "did:web:owner-b.example.com";
8467        let robot = "did:web:robot.example.com";
8468
8469        let transfer = build_ownership_transfer(
8470            &owner_a_seed,
8471            &BuildOwnershipTransfer {
8472                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000101".into(),
8473                issuer_did: owner_a.into(),
8474                robot_did: robot.into(),
8475                to_owner: owner_b.into(),
8476                from_owner: None,
8477                prev_transfer_id: None,
8478                valid_from: "2026-01-01T00:00:00Z".into(),
8479            },
8480        )
8481        .unwrap();
8482
8483        let subject =
8484            verify_ownership_transfer(&transfer, kd(&transfer, &a.public_key()), None, TNOW)
8485                .unwrap()
8486                .expect("transfer verifies under the current owner key");
8487        assert_eq!(subject["fromOwner"], json!(owner_a));
8488        assert_eq!(subject["toOwner"], json!(owner_b));
8489
8490        // Wrong type rejected.
8491        let mut wrong = transfer.clone();
8492        wrong["type"] = json!(["VerifiableCredential"]);
8493        assert!(
8494            verify_ownership_transfer(&wrong, kd(&wrong, &a.public_key()), None, TNOW)
8495                .unwrap()
8496                .is_none()
8497        );
8498
8499        // The issuer must equal fromOwner: forge a transfer whose issuer is not the
8500        // declared seller and re-sign it. It must be rejected even with a valid
8501        // proof under the signing key.
8502        let forged = build_ownership_transfer(
8503            &owner_b_seed,
8504            &BuildOwnershipTransfer {
8505                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000102".into(),
8506                issuer_did: owner_b.into(),
8507                robot_did: robot.into(),
8508                to_owner: "did:web:owner-c.example.com".into(),
8509                // Claim the robot was sold by owner A while owner B signs.
8510                from_owner: Some(owner_a.into()),
8511                prev_transfer_id: None,
8512                valid_from: "2026-01-01T00:00:00Z".into(),
8513            },
8514        )
8515        .unwrap();
8516        assert!(
8517            verify_ownership_transfer(&forged, kd(&forged, &b.public_key()), None, TNOW)
8518                .unwrap()
8519                .is_none()
8520        );
8521    }
8522
8523    #[test]
8524    fn custody_chain_links_and_rejects() {
8525        let owner_a_seed = [51u8; 32];
8526        let owner_b_seed = [52u8; 32];
8527        let owner_c_seed = [53u8; 32];
8528        let a = Ed25519KeyPair::from_seed(&owner_a_seed);
8529        let b = Ed25519KeyPair::from_seed(&owner_b_seed);
8530        let c = Ed25519KeyPair::from_seed(&owner_c_seed);
8531        let owner_a = "did:web:owner-a.example.com";
8532        let owner_b = "did:web:owner-b.example.com";
8533        let owner_c = "did:web:owner-c.example.com";
8534        let robot = "did:web:robot.example.com";
8535
8536        let t1 = build_ownership_transfer(
8537            &owner_a_seed,
8538            &BuildOwnershipTransfer {
8539                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000103".into(),
8540                issuer_did: owner_a.into(),
8541                robot_did: robot.into(),
8542                to_owner: owner_b.into(),
8543                from_owner: None,
8544                prev_transfer_id: None,
8545                valid_from: "2026-01-01T00:00:00Z".into(),
8546            },
8547        )
8548        .unwrap();
8549        let t2 = build_ownership_transfer(
8550            &owner_b_seed,
8551            &BuildOwnershipTransfer {
8552                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000104".into(),
8553                issuer_did: owner_b.into(),
8554                robot_did: robot.into(),
8555                to_owner: owner_c.into(),
8556                from_owner: None,
8557                prev_transfer_id: Some("urn:uuid:00000000-0000-4000-8000-000000000103".into()),
8558                valid_from: "2026-02-01T00:00:00Z".into(),
8559            },
8560        )
8561        .unwrap();
8562
8563        let keys = vec![
8564            OwnerKey {
8565                did: owner_a.into(),
8566                public_key: a.public_key().to_vec(),
8567            },
8568            OwnerKey {
8569                did: owner_b.into(),
8570                public_key: b.public_key().to_vec(),
8571            },
8572            OwnerKey {
8573                did: owner_c.into(),
8574                public_key: c.public_key().to_vec(),
8575            },
8576        ];
8577
8578        // A clean two-link chain rooted at owner A ends at owner C.
8579        let (ok, current) = verify_custody_chain(
8580            &[t1.clone(), t2.clone()],
8581            &keys,
8582            "did:web:robot.example.com",
8583            Some(owner_a),
8584            "2026-03-01T00:00:00Z",
8585        )
8586        .unwrap();
8587        assert!(ok);
8588        assert_eq!(current.as_deref(), Some(owner_c));
8589
8590        // A wrong declared origin breaks the first link.
8591        let (bad_origin, _) = verify_custody_chain(
8592            &[t1.clone(), t2.clone()],
8593            &keys,
8594            "did:web:robot.example.com",
8595            Some(owner_c),
8596            "2026-03-01T00:00:00Z",
8597        )
8598        .unwrap();
8599        assert!(!bad_origin);
8600
8601        // A gap (link two without link one) breaks the toOwner -> fromOwner join.
8602        let (gap, _) = verify_custody_chain(
8603            std::slice::from_ref(&t2),
8604            &keys,
8605            "did:web:robot.example.com",
8606            Some(owner_a),
8607            "2026-03-01T00:00:00Z",
8608        )
8609        .unwrap();
8610        assert!(!gap);
8611
8612        // A missing key for an issuer fails the chain.
8613        let partial = vec![OwnerKey {
8614            did: owner_a.into(),
8615            public_key: a.public_key().to_vec(),
8616        }];
8617        let (no_key, _) = verify_custody_chain(
8618            &[t1, t2],
8619            &partial,
8620            "did:web:robot.example.com",
8621            Some(owner_a),
8622            "2026-03-01T00:00:00Z",
8623        )
8624        .unwrap();
8625        assert!(!no_key);
8626    }
8627
8628    #[test]
8629    fn key_rotation_roundtrip_and_history() {
8630        let k1_seed = [61u8; 32];
8631        let k2_seed = [62u8; 32];
8632        let k3_seed = [63u8; 32];
8633        let k1 = Ed25519KeyPair::from_seed(&k1_seed);
8634        let k2 = Ed25519KeyPair::from_seed(&k2_seed);
8635        let k3 = Ed25519KeyPair::from_seed(&k3_seed);
8636        let robot = "did:web:robot.example.com";
8637
8638        // Rotate k1 -> k2, signed by k1.
8639        let r1 = build_key_rotation(
8640            &k1_seed,
8641            &BuildKeyRotation {
8642                robot_did: robot.into(),
8643                new_key_multibase: k2.public_multikey(),
8644                reason: Some("scheduled rotation".into()),
8645                valid_from: "2026-01-01T00:00:00Z".into(),
8646            },
8647        )
8648        .unwrap();
8649
8650        let subject = verify_key_rotation(&r1, Keys::Bare(&k1.public_key()), None, TNOW)
8651            .unwrap()
8652            .expect("rotation verifies under the old key");
8653        assert_eq!(subject["previousKey"], json!(k1.public_multikey()));
8654        assert_eq!(subject["newKey"], json!(k2.public_multikey()));
8655
8656        // The new key cannot verify a rotation that the old key signed.
8657        assert!(
8658            verify_key_rotation(&r1, Keys::Bare(&k2.public_key()), None, TNOW)
8659                .unwrap()
8660                .is_none()
8661        );
8662
8663        // Wrong type rejected.
8664        let mut wrong = r1.clone();
8665        wrong["type"] = json!(["VerifiableCredential"]);
8666        assert!(
8667            verify_key_rotation(&wrong, Keys::Bare(&k1.public_key()), None, TNOW)
8668                .unwrap()
8669                .is_none()
8670        );
8671
8672        // Rotate k2 -> k3, signed by k2, forming a history.
8673        let r2 = build_key_rotation(
8674            &k2_seed,
8675            &BuildKeyRotation {
8676                robot_did: robot.into(),
8677                new_key_multibase: k3.public_multikey(),
8678                reason: None,
8679                valid_from: "2026-02-01T00:00:00Z".into(),
8680            },
8681        )
8682        .unwrap();
8683
8684        let (ok, current) = verify_key_history(
8685            &[r1.clone(), r2.clone()],
8686            &k1.public_multikey(),
8687            None,
8688            "2026-03-01T00:00:00Z",
8689        )
8690        .unwrap();
8691        assert!(ok);
8692        assert_eq!(current.as_deref(), Some(k3.public_multikey().as_str()));
8693
8694        // A wrong origin key breaks the first previousKey match.
8695        let (bad_origin, _) = verify_key_history(
8696            &[r1, r2],
8697            &k3.public_multikey(),
8698            None,
8699            "2026-03-01T00:00:00Z",
8700        )
8701        .unwrap();
8702        assert!(!bad_origin);
8703    }
8704
8705    #[test]
8706    fn decommission_roundtrip_and_trusted_authority() {
8707        let seed = [71u8; 32];
8708        let kp = Ed25519KeyPair::from_seed(&seed);
8709        let authority = "did:web:authority.example.com";
8710        let robot = "did:web:robot.example.com";
8711
8712        let cred = build_decommission(
8713            &seed,
8714            &BuildDecommission {
8715                issuer_did: authority.into(),
8716                robot_did: robot.into(),
8717                reason: "end of service life".into(),
8718                final_disposition: Some("recycled".into()),
8719                valid_from: "2026-01-01T00:00:00Z".into(),
8720                valid_until: None,
8721            },
8722        )
8723        .unwrap();
8724
8725        let mut trusted = HashSet::new();
8726        trusted.insert(authority.to_string());
8727        let subject = verify_decommission(
8728            &cred,
8729            kd(&cred, &kp.public_key()),
8730            Some(&trusted),
8731            None,
8732            TNOW,
8733        )
8734        .unwrap()
8735        .expect("a trusted authority decommission verifies");
8736        assert_eq!(subject["decommissionedBy"], json!(authority));
8737
8738        // An untrusted issuer is rejected even with a valid proof.
8739        let mut other = HashSet::new();
8740        other.insert("did:web:someone-else.example.com".to_string());
8741        assert!(
8742            verify_decommission(&cred, kd(&cred, &kp.public_key()), Some(&other), None, TNOW)
8743                .unwrap()
8744                .is_none()
8745        );
8746
8747        // No trusted-authority set: a valid proof verifies.
8748        assert!(
8749            verify_decommission(&cred, kd(&cred, &kp.public_key()), None, None, TNOW)
8750                .unwrap()
8751                .is_some()
8752        );
8753
8754        // Wrong type rejected.
8755        let mut wrong = cred.clone();
8756        wrong["type"] = json!(["VerifiableCredential"]);
8757        assert!(
8758            verify_decommission(&wrong, kd(&wrong, &kp.public_key()), None, None, TNOW)
8759                .unwrap()
8760                .is_none()
8761        );
8762
8763        // reason is required at build time.
8764        assert!(build_decommission(
8765            &seed,
8766            &BuildDecommission {
8767                issuer_did: authority.into(),
8768                robot_did: robot.into(),
8769                reason: String::new(),
8770                final_disposition: None,
8771                valid_from: "2026-01-01T00:00:00Z".into(),
8772                valid_until: None,
8773            },
8774        )
8775        .is_err());
8776    }
8777
8778    // Cross-language interop: Rust reproduces the exact conformance report and
8779    // digest Python pinned, from the same credential set and profile.
8780    #[test]
8781    fn conformance_matches_interop_vector() {
8782        let vector = load_vector();
8783        let credentials: Vec<Value> = vector["conformance_credentials"]
8784            .as_array()
8785            .expect("conformance_credentials present")
8786            .clone();
8787        let profile_id = vector["conformance_profile_id"].as_str().unwrap();
8788
8789        let report = check_conformance(&credentials, profile_id).unwrap();
8790        assert_eq!(report, vector["expected_conformance_report"]);
8791
8792        let digest = report_digest(&report);
8793        assert_eq!(
8794            digest,
8795            vector["expected_conformance_report_digest"]
8796                .as_str()
8797                .unwrap()
8798        );
8799    }
8800
8801    // Presence alone is not evidence. A heartbeat that reports an envelope
8802    // breach must not satisfy the continuous-monitoring requirement just by
8803    // carrying a motionDigest.
8804    #[test]
8805    fn a_breaching_heartbeat_does_not_evidence_monitoring() {
8806        let breaching = json!({
8807            "type": ["VerifiableCredential", "RobotHeartbeatCredential"],
8808            "credentialSubject": {
8809                "motionDigest": {"withinEnvelope": false, "samples": 120}
8810            }
8811        });
8812        let report = check_conformance(std::slice::from_ref(&breaching), "iso-ts-15066").unwrap();
8813        let monitoring = report["requirements"]
8814            .as_array()
8815            .unwrap()
8816            .iter()
8817            .find(|r| r["id"] == json!("iso15066-monitoring"))
8818            .expect("monitoring requirement present");
8819        assert_eq!(monitoring["satisfied"], json!(false));
8820
8821        // The same heartbeat reporting no breach does satisfy it.
8822        let mut clean = breaching;
8823        clean["credentialSubject"]["motionDigest"]["withinEnvelope"] = json!(true);
8824        let report = check_conformance(&[clean], "iso-ts-15066").unwrap();
8825        let monitoring = report["requirements"]
8826            .as_array()
8827            .unwrap()
8828            .iter()
8829            .find(|r| r["id"] == json!("iso15066-monitoring"))
8830            .unwrap();
8831        assert_eq!(monitoring["satisfied"], json!(true));
8832    }
8833
8834    // Every requirement declares where its clause number came from, and the
8835    // report totals them, so CONFORMS never reads as more authoritative about
8836    // the regulation than its sources are.
8837    #[test]
8838    fn conformance_report_carries_citation_provenance() {
8839        for profile_id in [
8840            "iso-10218",
8841            "iso-ts-15066",
8842            "eu-machinery-2023-1230",
8843            "eu-ai-act-high-risk",
8844            "ul-3300",
8845        ] {
8846            let report = check_conformance(&[], profile_id).unwrap();
8847            let citations = report["citations"].as_object().unwrap();
8848            assert_eq!(citations.len(), CITATION_STATUSES.len());
8849            let counted: i64 = citations.values().map(|v| v.as_i64().unwrap()).sum();
8850            assert_eq!(counted, report["totalCount"].as_i64().unwrap());
8851            for result in report["requirements"].as_array().unwrap() {
8852                let citation = result["citation"].as_str().unwrap();
8853                assert!(CITATION_STATUSES.contains(&citation));
8854            }
8855        }
8856
8857        // UL 3300 is paywalled with no clause numbering available, so none of
8858        // its "clauses" are citable.
8859        let ul = check_conformance(&[], "ul-3300").unwrap();
8860        assert_eq!(ul["citations"][CITATION_DESCRIPTIVE], ul["totalCount"]);
8861        assert_eq!(ul["citations"][CITATION_VERIFIED_PRIMARY], json!(0));
8862    }
8863
8864    #[test]
8865    fn conformance_unknown_profile_and_missing_field() {
8866        assert!(check_conformance(&[], "no-such-profile").is_err());
8867
8868        // An empty credential set satisfies nothing.
8869        let empty = check_conformance(&[], "eu-ai-act-high-risk").unwrap();
8870        assert_eq!(empty["conforms"], json!(false));
8871        assert_eq!(empty["satisfiedCount"], json!(0));
8872        assert_eq!(empty["totalCount"], json!(4));
8873
8874        // A safety record with no logHead does not satisfy the record-keeping
8875        // requirement (a missing field counts as unsatisfied).
8876        let creds = vec![json!({
8877            "type": ["VerifiableCredential", "RobotSafetyRecordCredential"],
8878            "credentialSubject": { "id": "did:web:robot.example.com", "totalEvents": 2 }
8879        })];
8880        let report = check_conformance(&creds, "eu-ai-act-high-risk").unwrap();
8881        let record_keeping = report["requirements"]
8882            .as_array()
8883            .unwrap()
8884            .iter()
8885            .find(|r| r["id"] == json!("eu-aia-record-keeping"))
8886            .unwrap();
8887        assert_eq!(record_keeping["satisfied"], json!(false));
8888
8889        // An empty allowedZones array is also unsatisfied.
8890        let zone_creds = vec![json!({
8891            "type": ["VerifiableCredential", "PhysicalCapabilityScope"],
8892            "credentialSubject": {
8893                "id": "did:web:robot.example.com",
8894                "physicalScope": { "maxSpeedMps": 1.5, "allowedZones": [] }
8895            }
8896        })];
8897        let ul = check_conformance(&zone_creds, "ul-3300").unwrap();
8898        let limits = ul["requirements"]
8899            .as_array()
8900            .unwrap()
8901            .iter()
8902            .find(|r| r["id"] == json!("ul3300-operating-limits"))
8903            .unwrap();
8904        assert_eq!(limits["satisfied"], json!(false));
8905    }
8906
8907    #[test]
8908    fn conformance_attestation_roundtrip_and_rejections() {
8909        let seed = [77u8; 32];
8910        let kp = Ed25519KeyPair::from_seed(&seed);
8911        let vector = load_vector();
8912        let credentials: Vec<Value> = vector["conformance_credentials"]
8913            .as_array()
8914            .unwrap()
8915            .clone();
8916        let report = check_conformance(&credentials, "eu-ai-act-high-risk").unwrap();
8917
8918        let att = build_conformance_attestation(
8919            &seed,
8920            &BuildConformanceAttestation {
8921                issuer_did: "did:web:authority.example.com".into(),
8922                robot_did: "did:web:robot.example.com".into(),
8923                report: report.clone(),
8924                valid_from: "2026-01-01T00:00:00Z".into(),
8925                valid_until: Some("2027-01-01T00:00:00Z".into()),
8926            },
8927        )
8928        .unwrap();
8929
8930        // Round-trip: a well-formed attestation verifies and surfaces the subject.
8931        let subject =
8932            verify_conformance_attestation(&att, kd(&att, &kp.public_key()), None, None, TNOW)
8933                .unwrap()
8934                .expect("a valid conformance attestation verifies");
8935        assert_eq!(subject["profileId"], json!("eu-ai-act-high-risk"));
8936        assert_eq!(subject["conforms"], json!(true));
8937        assert_eq!(
8938            subject["reportDigest"],
8939            vector["expected_conformance_report_digest"]
8940        );
8941
8942        // Wrong key is rejected.
8943        let wrong_kp = Ed25519KeyPair::from_seed(&[88u8; 32]);
8944        assert!(verify_conformance_attestation(
8945            &att,
8946            kd(&att, &wrong_kp.public_key()),
8947            None,
8948            None,
8949            TNOW
8950        )
8951        .unwrap()
8952        .is_none());
8953
8954        // A tampered embedded report no longer matches the bound digest.
8955        let mut tampered = att.clone();
8956        tampered["credentialSubject"]["report"]["conforms"] = json!(false);
8957        assert!(verify_conformance_attestation(
8958            &tampered,
8959            kd(&tampered, &kp.public_key()),
8960            None,
8961            None,
8962            TNOW
8963        )
8964        .unwrap()
8965        .is_none());
8966
8967        // Wrong type is rejected.
8968        let mut wrong_type = att.clone();
8969        wrong_type["type"] = json!(["VerifiableCredential"]);
8970        assert!(verify_conformance_attestation(
8971            &wrong_type,
8972            kd(&wrong_type, &kp.public_key()),
8973            None,
8974            None,
8975            TNOW
8976        )
8977        .unwrap()
8978        .is_none());
8979
8980        // robot_did is required at build time.
8981        assert!(build_conformance_attestation(
8982            &seed,
8983            &BuildConformanceAttestation {
8984                issuer_did: "did:web:authority.example.com".into(),
8985                robot_did: String::new(),
8986                report,
8987                valid_from: "2026-01-01T00:00:00Z".into(),
8988                valid_until: None,
8989            },
8990        )
8991        .is_err());
8992    }
8993
8994    // -- post-quantum robot credentials ------------------------------------
8995
8996    fn classical_robot_credential(issuer: &str, seed: &[u8]) -> Value {
8997        let cred = json!({
8998            "@context": [VC_CONTEXT_V2, VOUCH_CONTEXT_V1],
8999            "type": ["VerifiableCredential", ROBOT_IDENTITY_TYPE],
9000            "issuer": issuer,
9001            "validFrom": "2026-01-01T00:00:00Z",
9002            "credentialSubject": {
9003                "id": issuer,
9004                "make": "Acme Robotics",
9005                "model": "AR-7",
9006                "serial": "SN-000123"
9007            }
9008        });
9009        let opts = BuildProofOptions::new(format!("{issuer}#key-1"), "2026-01-01T00:00:00Z");
9010        data_integrity::sign(&cred, seed, &opts).unwrap()
9011    }
9012
9013    // Cross-language interop: Rust verifies the Python-signed hybrid PQ robot
9014    // identity under the Ed25519 key and the ML-DSA-44 multikey from the vector.
9015    #[test]
9016    fn verifies_python_pq_robot_identity_interop_vector() {
9017        let vector = load_vector();
9018        let ed_pub = jwk_pub(&vector["robot_public_key_jwk"]);
9019        let ml_multikey = vector["robot_mldsa44_public_multikey"].as_str().unwrap();
9020        let cred = vector["pq_robot_identity_credential"].clone();
9021
9022        // (b) the credential is detected as post-quantum.
9023        assert!(is_pq(&cred));
9024
9025        // (a) dual verify auto-detected from the proof, with the ML-DSA multikey.
9026        let ok = verify_robot_credential(
9027            &cred,
9028            kd(&cred, &ed_pub),
9029            Some(ml_multikey.as_bytes()),
9030            None,
9031            TNOW,
9032        )
9033        .expect("the Python hybrid PQ interop vector must verify in Rust");
9034        assert!(ok);
9035
9036        // verify_pq accepts the multikey string form directly.
9037        let resolved = mldsa44_public_from_multikey(ml_multikey).unwrap();
9038        assert!(verify_pq(&cred, &ed_pub, &resolved).unwrap());
9039    }
9040
9041    #[test]
9042    fn pq_sign_verify_roundtrip_and_rejects() {
9043        let issuer = "did:web:robot.example.com";
9044        let seed = [21u8; 32];
9045        let kp = Ed25519KeyPair::from_seed(&seed);
9046        let ml = MlDsa44KeyPair::generate().unwrap();
9047
9048        let classical = classical_robot_credential(issuer, &seed);
9049        assert!(!is_pq(&classical));
9050
9051        // Sign post-quantum; any prior proof is replaced by a proof set holding
9052        // one classical and one ML-DSA-44 proof.
9053        let signed = sign_pq(&classical, &seed, &ml, "2026-02-01T00:00:00Z").unwrap();
9054        assert!(is_pq(&signed));
9055        let proofs = signed["proof"].as_array().expect("proof set");
9056        assert_eq!(proofs.len(), 2);
9057        assert_eq!(
9058            proofs[0]["cryptosuite"],
9059            json!(hybrid::EDDSA_CRYPTOSUITE_ID)
9060        );
9061        assert_eq!(
9062            proofs[1]["cryptosuite"],
9063            json!(hybrid::MLDSA44_CRYPTOSUITE_ID)
9064        );
9065        // Each proof carries the Multibase encoding its cryptosuite specifies.
9066        assert!(proofs[0]["proofValue"].as_str().unwrap().starts_with('z'));
9067        assert!(proofs[1]["proofValue"].as_str().unwrap().starts_with('u'));
9068
9069        // Round-trip: both signatures validate under the correct keys.
9070        assert!(verify_pq(&signed, &kp.public_key(), &ml.public_key()).unwrap());
9071        assert!(verify_robot_credential(
9072            &signed,
9073            kd(&signed, &kp.public_key()),
9074            Some(&ml.public_key()),
9075            None,
9076            TNOW
9077        )
9078        .unwrap());
9079
9080        // The multikey string form is accepted too (as UTF-8 bytes).
9081        let ml_mk = multikey::encode_mldsa44_public(&ml.public_key()).unwrap();
9082        assert!(verify_robot_credential(
9083            &signed,
9084            kd(&signed, &kp.public_key()),
9085            Some(ml_mk.as_bytes()),
9086            None,
9087            TNOW
9088        )
9089        .unwrap());
9090
9091        // Tampering the body breaks verification.
9092        let mut tampered = signed.clone();
9093        tampered["credentialSubject"]["model"] = json!("AR-9");
9094        assert!(!verify_pq(&tampered, &kp.public_key(), &ml.public_key()).unwrap());
9095
9096        // Wrong Ed25519 key is rejected.
9097        let other_ed = Ed25519KeyPair::from_seed(&[99u8; 32]);
9098        assert!(!verify_pq(&signed, &other_ed.public_key(), &ml.public_key()).unwrap());
9099
9100        // Wrong ML-DSA-44 key is rejected.
9101        let other_ml = MlDsa44KeyPair::generate().unwrap();
9102        assert!(!verify_pq(&signed, &kp.public_key(), &other_ml.public_key()).unwrap());
9103
9104        // A hybrid credential without the ML-DSA key returns false, not true.
9105        assert!(
9106            !verify_robot_credential(&signed, kd(&signed, &kp.public_key()), None, None, TNOW)
9107                .unwrap()
9108        );
9109
9110        // Downgrade by extraction: an attacker strips the proof set to the lone
9111        // standalone classical proof. A verifier that supplies the ML-DSA key
9112        // (so requires post-quantum) must reject it, not accept it as classical.
9113        let proofs = signed["proof"].as_array().unwrap();
9114        let classical_proof = proofs
9115            .iter()
9116            .find(|p| p["cryptosuite"] == json!(hybrid::EDDSA_CRYPTOSUITE_ID))
9117            .unwrap()
9118            .clone();
9119        let mut stripped = signed.clone();
9120        stripped["proof"] = classical_proof;
9121        assert!(!is_pq(&stripped));
9122        assert!(
9123            !verify_robot_credential(
9124                &stripped,
9125                kd(&stripped, &kp.public_key()),
9126                Some(&ml.public_key()),
9127                None,
9128                TNOW
9129            )
9130            .unwrap(),
9131            "a stripped proof set must not verify when the caller requires post-quantum"
9132        );
9133        // The extracted classical proof is genuine, so a caller that only does
9134        // classical verification (no ML-DSA key) still accepts it.
9135        assert!(verify_robot_credential(
9136            &stripped,
9137            kd(&stripped, &kp.public_key()),
9138            None,
9139            None,
9140            TNOW
9141        )
9142        .unwrap());
9143    }
9144
9145    #[test]
9146    fn classical_credential_passes_dual_verify_without_pq_key() {
9147        let issuer = "did:web:robot.example.com";
9148        let seed = [22u8; 32];
9149        let kp = Ed25519KeyPair::from_seed(&seed);
9150        let classical = classical_robot_credential(issuer, &seed);
9151
9152        assert!(!is_pq(&classical));
9153        // A classical credential verifies through the dual path with no ML-DSA key.
9154        assert!(verify_robot_credential(
9155            &classical,
9156            kd(&classical, &kp.public_key()),
9157            None,
9158            None,
9159            TNOW
9160        )
9161        .unwrap());
9162
9163        // A wrong key still fails.
9164        let other = Ed25519KeyPair::from_seed(&[7u8; 32]);
9165        assert!(!verify_robot_credential(
9166            &classical,
9167            kd(&classical, &other.public_key()),
9168            None,
9169            None,
9170            TNOW
9171        )
9172        .unwrap());
9173    }
9174
9175    #[test]
9176    fn migrate_to_pq_resigns_classical_credential() {
9177        let issuer = "did:web:robot.example.com";
9178        let seed = [23u8; 32];
9179        let kp = Ed25519KeyPair::from_seed(&seed);
9180        let ml = MlDsa44KeyPair::generate().unwrap();
9181
9182        let classical = classical_robot_credential(issuer, &seed);
9183        assert!(verify_robot_credential(
9184            &classical,
9185            kd(&classical, &kp.public_key()),
9186            None,
9187            None,
9188            TNOW
9189        )
9190        .unwrap());
9191
9192        let migrated = migrate_to_pq(&classical, &seed, &ml, "2026-03-01T00:00:00Z").unwrap();
9193        assert!(is_pq(&migrated));
9194        // The body is preserved across migration.
9195        assert_eq!(
9196            migrated["credentialSubject"],
9197            classical["credentialSubject"]
9198        );
9199        assert!(verify_robot_credential(
9200            &migrated,
9201            kd(&migrated, &kp.public_key()),
9202            Some(&ml.public_key()),
9203            None,
9204            TNOW
9205        )
9206        .unwrap());
9207    }
9208
9209    // Cross-language interop: Rust verifies the Python-signed embodiment continuity
9210    // chain under the one agent key from the vector, ending on body-b, with no fork.
9211    #[test]
9212    fn verifies_python_embodiment_interop_vector() {
9213        let vector = load_vector();
9214        let agent_pub = jwk_pub(&vector["embodiment_agent_key"]);
9215        let chain: Vec<Value> = vector["embodiment_chain"]
9216            .as_array()
9217            .expect("embodiment_chain array")
9218            .clone();
9219
9220        let (ok, current) = verify_continuity_chain(
9221            &chain,
9222            Keys::Resolver(&any_did(&agent_pub)),
9223            None,
9224            None,
9225            "2026-06-01T00:00:00Z",
9226        )
9227        .unwrap();
9228        assert!(ok, "the Python embodiment chain must verify in Rust");
9229        assert_eq!(
9230            current.as_deref(),
9231            Some("did:web:body-b.example.com"),
9232            "the chain ends on body-b"
9233        );
9234
9235        let (no_fork, conflict) = check_no_fork(&chain).unwrap();
9236        assert!(no_fork, "the Python embodiment chain has no fork");
9237        assert!(conflict.is_none());
9238    }
9239
9240    #[test]
9241    fn embodiment_roundtrip_and_issuer_rule() {
9242        let agent_seed = [61u8; 32];
9243        let other_seed = [62u8; 32];
9244        let agent = Ed25519KeyPair::from_seed(&agent_seed);
9245        let other = Ed25519KeyPair::from_seed(&other_seed);
9246        let agent_did = "did:web:agent.example.com";
9247        let body_a = "did:web:body-a.example.com";
9248
9249        let cred = build_embodiment(
9250            &agent_seed,
9251            &BuildEmbodiment {
9252                agent_did: agent_did.into(),
9253                body_did: body_a.into(),
9254                body_hardware_root: "uROOTA".into(),
9255                from_body: None,
9256                embodied_at: "2026-01-01T00:00:00Z".into(),
9257                valid_until: None,
9258            },
9259        )
9260        .unwrap();
9261
9262        let subject = verify_embodiment(&cred, kd(&cred, &agent.public_key()), None, TNOW)
9263            .unwrap()
9264            .expect("embodiment verifies under the agent key");
9265        assert_eq!(subject["body"], json!(body_a));
9266        assert_eq!(subject["bodyHardwareRoot"], json!("uROOTA"));
9267
9268        // The issuer must equal the subject id: forge a credential issued by an
9269        // impostor over an unchanged subject (still the agent) and re-sign it. It
9270        // must be rejected even with a valid proof under the signing key, because a
9271        // mind only authorizes its own embodiment.
9272        let forged = {
9273            let mut bare = cred.clone();
9274            bare.as_object_mut().unwrap().remove("proof");
9275            bare["issuer"] = json!("did:web:impostor.example.com");
9276            let opts = BuildProofOptions::new(
9277                "did:web:impostor.example.com#key-1".to_string(),
9278                "2026-01-01T00:00:00Z",
9279            );
9280            data_integrity::sign(&bare, &other_seed, &opts).unwrap()
9281        };
9282        assert!(
9283            verify_embodiment(&forged, kd(&forged, &other.public_key()), None, TNOW)
9284                .unwrap()
9285                .is_none()
9286        );
9287    }
9288
9289    #[test]
9290    fn continuity_chain_links_and_rejects() {
9291        let agent_seed = [61u8; 32];
9292        let stranger_seed = [63u8; 32];
9293        let agent = Ed25519KeyPair::from_seed(&agent_seed);
9294        let stranger = Ed25519KeyPair::from_seed(&stranger_seed);
9295        let agent_did = "did:web:agent.example.com";
9296        let body_a = "did:web:body-a.example.com";
9297        let body_b = "did:web:body-b.example.com";
9298
9299        let e1 = build_embodiment(
9300            &agent_seed,
9301            &BuildEmbodiment {
9302                agent_did: agent_did.into(),
9303                body_did: body_a.into(),
9304                body_hardware_root: "uROOTA".into(),
9305                from_body: None,
9306                embodied_at: "2026-01-01T00:00:00Z".into(),
9307                valid_until: Some("2026-01-01T01:00:00Z".into()),
9308            },
9309        )
9310        .unwrap();
9311        let e2 = build_embodiment(
9312            &agent_seed,
9313            &BuildEmbodiment {
9314                agent_did: agent_did.into(),
9315                body_did: body_b.into(),
9316                body_hardware_root: "uROOTB".into(),
9317                from_body: Some(body_a.into()),
9318                embodied_at: "2026-01-01T01:00:00Z".into(),
9319                valid_until: None,
9320            },
9321        )
9322        .unwrap();
9323
9324        // A clean two-link chain ends at body-b: the first link opens on body-a
9325        // and the second link's fromBody re-binds to it.
9326        let (ok, current) = verify_continuity_chain(
9327            &[e1.clone(), e2.clone()],
9328            Keys::Resolver(&any_did(&agent.public_key())),
9329            None,
9330            None,
9331            "2026-06-01T00:00:00Z",
9332        )
9333        .unwrap();
9334        assert!(ok);
9335        assert_eq!(current.as_deref(), Some(body_b));
9336
9337        // Declaring the wrong origin body breaks the first link, since the first
9338        // link's fromBody must match the origin when given.
9339        let (bad_origin, _) = verify_continuity_chain(
9340            &[e1.clone(), e2.clone()],
9341            Keys::Resolver(&any_did(&agent.public_key())),
9342            Some(body_b),
9343            None,
9344            "2026-06-01T00:00:00Z",
9345        )
9346        .unwrap();
9347        assert!(!bad_origin);
9348
9349        // A broken link (second link's fromBody does not match the first's body)
9350        // fails the chain.
9351        let broken = build_embodiment(
9352            &agent_seed,
9353            &BuildEmbodiment {
9354                agent_did: agent_did.into(),
9355                body_did: body_b.into(),
9356                body_hardware_root: "uROOTB".into(),
9357                from_body: Some("did:web:body-x.example.com".into()),
9358                embodied_at: "2026-01-01T01:00:00Z".into(),
9359                valid_until: None,
9360            },
9361        )
9362        .unwrap();
9363        let (bad_link, _) = verify_continuity_chain(
9364            &[e1.clone(), broken],
9365            Keys::Resolver(&any_did(&agent.public_key())),
9366            None,
9367            None,
9368            "2026-06-01T00:00:00Z",
9369        )
9370        .unwrap();
9371        assert!(!bad_link);
9372
9373        // Every link must verify under the SAME agent key: a link signed by a
9374        // different key breaks the chain (a mind is one persistent identity).
9375        let e2_stranger = build_embodiment(
9376            &stranger_seed,
9377            &BuildEmbodiment {
9378                agent_did: agent_did.into(),
9379                body_did: body_b.into(),
9380                body_hardware_root: "uROOTB".into(),
9381                from_body: Some(body_a.into()),
9382                embodied_at: "2026-01-01T01:00:00Z".into(),
9383                valid_until: None,
9384            },
9385        )
9386        .unwrap();
9387        assert!(verify_embodiment(
9388            &e2_stranger,
9389            kd(&e2_stranger, &stranger.public_key()),
9390            None,
9391            "2026-06-01T00:00:00Z"
9392        )
9393        .unwrap()
9394        .is_some());
9395        let (mixed_keys, _) = verify_continuity_chain(
9396            &[e1, e2_stranger],
9397            Keys::Resolver(&any_did(&agent.public_key())),
9398            None,
9399            None,
9400            "2026-06-01T00:00:00Z",
9401        )
9402        .unwrap();
9403        assert!(!mixed_keys);
9404    }
9405
9406    #[test]
9407    fn fork_detection_flags_overlapping_bodies() {
9408        let agent_seed = [61u8; 32];
9409        let agent_did = "did:web:agent.example.com";
9410        let body_a = "did:web:body-a.example.com";
9411        let body_b = "did:web:body-b.example.com";
9412
9413        let build = |body: &str, root: &str, from: &str, until: &str| {
9414            build_embodiment(
9415                &agent_seed,
9416                &BuildEmbodiment {
9417                    agent_did: agent_did.into(),
9418                    body_did: body.into(),
9419                    body_hardware_root: root.into(),
9420                    from_body: None,
9421                    embodied_at: from.into(),
9422                    valid_until: Some(until.into()),
9423                },
9424            )
9425            .unwrap()
9426        };
9427
9428        // A clean handover: body-a's window ends exactly where body-b's begins.
9429        // Half-open intervals do not overlap, so this is not a fork.
9430        let clean_a = build(
9431            body_a,
9432            "uROOTA",
9433            "2026-01-01T00:00:00Z",
9434            "2026-01-01T01:00:00Z",
9435        );
9436        let clean_b = build(
9437            body_b,
9438            "uROOTB",
9439            "2026-01-01T01:00:00Z",
9440            "2026-01-01T02:00:00Z",
9441        );
9442        let (clean, conflict) = check_no_fork(&[clean_a, clean_b]).unwrap();
9443        assert!(clean);
9444        assert!(conflict.is_none());
9445
9446        // Overlapping windows on different bodies are a fork; the conflict names
9447        // both bodies.
9448        let fork_a = build(
9449            body_a,
9450            "uROOTA",
9451            "2026-01-01T00:00:00Z",
9452            "2026-01-01T02:00:00Z",
9453        );
9454        let fork_b = build(
9455            body_b,
9456            "uROOTB",
9457            "2026-01-01T01:00:00Z",
9458            "2026-01-01T03:00:00Z",
9459        );
9460        let (forked, conflict) = check_no_fork(&[fork_a, fork_b]).unwrap();
9461        assert!(!forked);
9462        let conflict = conflict.expect("a fork names the two conflicting bodies");
9463        assert_eq!(conflict.body_a, body_a);
9464        assert_eq!(conflict.body_b, body_b);
9465    }
9466
9467    // Custody handoff (Phase 5.16) -----------------------------------------
9468
9469    fn actor_keys_from_vector(map: &Value) -> Vec<ActorKey> {
9470        map.as_object()
9471            .expect("custody_actor_keys object")
9472            .iter()
9473            .map(|(did, jwk)| ActorKey {
9474                did: did.clone(),
9475                public_key: jwk_pub(jwk),
9476            })
9477            .collect()
9478    }
9479
9480    // Cross-language interop: Rust verifies the Python-signed custody chain under
9481    // the actor keys from the vector, ending on robot-b, and localizes the
9482    // condition change to the hop robot-a was responsible for.
9483    #[test]
9484    fn verifies_python_custody_interop_vector() {
9485        let vector = load_vector();
9486        let chain: Vec<Value> = vector["custody_chain"]
9487            .as_array()
9488            .expect("custody_chain array")
9489            .clone();
9490        let keys = actor_keys_from_vector(&vector["custody_actor_keys"]);
9491        let origin = vector["custody_origin_actor"].as_str().unwrap();
9492
9493        let (ok, current) =
9494            verify_handoff_chain(&chain, &keys, "tote-42", Some(origin), false, TNOW).unwrap();
9495        assert!(ok, "the Python custody chain must verify in Rust");
9496        assert_eq!(
9497            current.as_deref(),
9498            Some("did:web:robot-b.example.com"),
9499            "the chain ends holding at robot-b"
9500        );
9501
9502        let change = locate_condition_change(&chain).expect("the condition changed");
9503        assert_eq!(
9504            change.responsible_holder.as_deref(),
9505            Some("did:web:robot-a.example.com"),
9506            "robot-a held the task while its condition changed"
9507        );
9508        assert_eq!(change.from_condition, "intact");
9509        assert_eq!(change.to_condition, "damaged");
9510    }
9511
9512    #[test]
9513    fn handoff_roundtrip_and_receiver_rule() {
9514        let robot_seed = [71u8; 32];
9515        let other_seed = [72u8; 32];
9516        let robot = Ed25519KeyPair::from_seed(&robot_seed);
9517        let other = Ed25519KeyPair::from_seed(&other_seed);
9518        let worker = "did:web:worker-jane.example.com";
9519        let robot_a = "did:web:robot-a.example.com";
9520
9521        let cred = build_handoff(
9522            &robot_seed,
9523            &BuildHandoff {
9524                release: None,
9525                prev_handoff_id: None,
9526                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000105".into(),
9527                task_id: "tote-42".into(),
9528                from_actor: worker.into(),
9529                to_actor: robot_a.into(),
9530                condition: Some("intact".into()),
9531                handoff_at: "2026-01-01T00:00:00Z".into(),
9532                valid_until: None,
9533            },
9534        )
9535        .unwrap();
9536
9537        let subject = verify_handoff(
9538            &cred,
9539            kd(&cred, &robot.public_key()),
9540            HandoffCheck::default(),
9541            TNOW,
9542        )
9543        .unwrap()
9544        .expect("handoff verifies under the receiver key");
9545        assert_eq!(subject["fromActor"], json!(worker));
9546        assert_eq!(subject["toActor"], json!(robot_a));
9547
9548        // The issuer must be the receiver: forge a handoff issued by a different
9549        // party over the same subject and re-sign it. It must be rejected even with
9550        // a valid proof under the signing key, because a party attests its own
9551        // acceptance of custody.
9552        let forged = {
9553            let mut bare = cred.clone();
9554            bare.as_object_mut().unwrap().remove("proof");
9555            bare["issuer"] = json!("did:web:impostor.example.com");
9556            let opts = BuildProofOptions::new(
9557                "did:web:impostor.example.com#key-1".to_string(),
9558                "2026-01-01T00:00:00Z",
9559            );
9560            data_integrity::sign(&bare, &other_seed, &opts).unwrap()
9561        };
9562        assert!(verify_handoff(
9563            &forged,
9564            kd(&forged, &other.public_key()),
9565            HandoffCheck::default(),
9566            TNOW
9567        )
9568        .unwrap()
9569        .is_none());
9570    }
9571
9572    #[test]
9573    fn handoff_chain_links_and_rejects() {
9574        let a_seed = [73u8; 32];
9575        let b_seed = [74u8; 32];
9576        let a = Ed25519KeyPair::from_seed(&a_seed);
9577        let b = Ed25519KeyPair::from_seed(&b_seed);
9578        let worker = "did:web:worker-jane.example.com";
9579        let robot_a = "did:web:robot-a.example.com";
9580        let robot_b = "did:web:robot-b.example.com";
9581
9582        let h1 = build_handoff(
9583            &a_seed,
9584            &BuildHandoff {
9585                release: None,
9586                prev_handoff_id: None,
9587                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000106".into(),
9588                task_id: "tote-42".into(),
9589                from_actor: worker.into(),
9590                to_actor: robot_a.into(),
9591                condition: Some("intact".into()),
9592                handoff_at: "2026-01-01T00:00:00Z".into(),
9593                valid_until: None,
9594            },
9595        )
9596        .unwrap();
9597        let h2 = build_handoff(
9598            &b_seed,
9599            &BuildHandoff {
9600                release: None,
9601                prev_handoff_id: Some("urn:uuid:00000000-0000-4000-8000-000000000106".into()),
9602                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000107".into(),
9603                task_id: "tote-42".into(),
9604                from_actor: robot_a.into(),
9605                to_actor: robot_b.into(),
9606                condition: Some("damaged".into()),
9607                handoff_at: "2026-01-01T00:10:00Z".into(),
9608                valid_until: None,
9609            },
9610        )
9611        .unwrap();
9612
9613        let keys = vec![
9614            ActorKey {
9615                did: robot_a.into(),
9616                public_key: a.public_key().to_vec(),
9617            },
9618            ActorKey {
9619                did: robot_b.into(),
9620                public_key: b.public_key().to_vec(),
9621            },
9622        ];
9623
9624        // A clean two-link chain ends holding at robot-b: the first link's
9625        // fromActor is the origin worker and the second link re-binds to robot-a.
9626        let (ok, current) = verify_handoff_chain(
9627            &[h1.clone(), h2.clone()],
9628            &keys,
9629            "tote-42",
9630            Some(worker),
9631            false,
9632            TNOW,
9633        )
9634        .unwrap();
9635        assert!(ok);
9636        assert_eq!(current.as_deref(), Some(robot_b));
9637
9638        // Declaring the wrong origin actor breaks the first link.
9639        let (bad_origin, _) = verify_handoff_chain(
9640            &[h1.clone(), h2.clone()],
9641            &keys,
9642            "tote-42",
9643            Some(robot_b),
9644            false,
9645            TNOW,
9646        )
9647        .unwrap();
9648        assert!(!bad_origin);
9649
9650        // A broken link (second link's fromActor does not match the first's
9651        // toActor) fails the chain.
9652        let broken = build_handoff(
9653            &b_seed,
9654            &BuildHandoff {
9655                release: None,
9656                prev_handoff_id: Some("urn:uuid:00000000-0000-4000-8000-000000000106".into()),
9657                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000108".into(),
9658                task_id: "tote-42".into(),
9659                from_actor: "did:web:robot-x.example.com".into(),
9660                to_actor: robot_b.into(),
9661                condition: Some("damaged".into()),
9662                handoff_at: "2026-01-01T00:10:00Z".into(),
9663                valid_until: None,
9664            },
9665        )
9666        .unwrap();
9667        let (bad_link, _) = verify_handoff_chain(
9668            &[h1.clone(), broken],
9669            &keys,
9670            "tote-42",
9671            Some(worker),
9672            false,
9673            TNOW,
9674        )
9675        .unwrap();
9676        assert!(!bad_link);
9677
9678        // A missing receiver key for a link fails the chain.
9679        let partial = vec![ActorKey {
9680            did: robot_a.into(),
9681            public_key: a.public_key().to_vec(),
9682        }];
9683        let (no_key, _) = verify_handoff_chain(
9684            &[h1.clone(), h2.clone()],
9685            &partial,
9686            "tote-42",
9687            Some(worker),
9688            false,
9689            TNOW,
9690        )
9691        .unwrap();
9692        assert!(!no_key);
9693
9694        // holder_at reports who held the task at a moment: robot-a right after the
9695        // first handoff, robot-b right after the second.
9696        assert_eq!(
9697            holder_at(&[h1.clone(), h2.clone()], "2026-01-01T00:05:00Z").as_deref(),
9698            Some(robot_a)
9699        );
9700        assert_eq!(
9701            holder_at(&[h1.clone(), h2.clone()], "2026-01-01T00:15:00Z").as_deref(),
9702            Some(robot_b)
9703        );
9704
9705        // A chain whose condition never changes localizes nothing.
9706        let steady = build_handoff(
9707            &b_seed,
9708            &BuildHandoff {
9709                release: None,
9710                prev_handoff_id: None,
9711                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000109".into(),
9712                task_id: "tote-42".into(),
9713                from_actor: robot_a.into(),
9714                to_actor: robot_b.into(),
9715                condition: Some("intact".into()),
9716                handoff_at: "2026-01-01T00:10:00Z".into(),
9717                valid_until: None,
9718            },
9719        )
9720        .unwrap();
9721        assert!(locate_condition_change(&[h1, steady]).is_none());
9722    }
9723
9724    // Robot-to-infrastructure bounded access (Phase 5.17) ------------------
9725
9726    // Cross-language interop: Rust authorizes the Python-signed grant and request
9727    // from the vector under the operator and robot keys, offline.
9728    #[test]
9729    fn authorizes_python_access_interop_vector() {
9730        let vector = load_vector();
9731        let grant = vector["access_grant_credential"].clone();
9732        let request = vector["access_request_credential"].clone();
9733        let operator_pub = jwk_pub(&vector["access_operator_key"]);
9734        let robot_pub = jwk_pub(&vector["access_robot_key"]);
9735
9736        // The request was made at VALID_FROM; a resource checks it within the
9737        // 60 s age limit and remembers its nonce.
9738        let mut seen = HashSet::new();
9739        let res = authorize_access(
9740            &grant,
9741            &request,
9742            kd(&grant, &operator_pub),
9743            kd(&request, &robot_pub),
9744            RequestReplay::new(&mut seen),
9745            "2026-01-01T00:00:30Z",
9746        )
9747        .unwrap();
9748        assert!(
9749            res.ok,
9750            "the Python grant and request must authorize in Rust: {:?}",
9751            res.reasons
9752        );
9753        assert!(res.reasons.is_empty());
9754        // A replay of the same request is refused, and so is a stale one.
9755        let again = authorize_access(
9756            &grant,
9757            &request,
9758            kd(&grant, &operator_pub),
9759            kd(&request, &robot_pub),
9760            RequestReplay::new(&mut seen),
9761            "2026-01-01T00:00:30Z",
9762        )
9763        .unwrap();
9764        assert!(!again.ok);
9765        let mut fresh = HashSet::new();
9766        let stale = authorize_access(
9767            &grant,
9768            &request,
9769            kd(&grant, &operator_pub),
9770            kd(&request, &robot_pub),
9771            RequestReplay::new(&mut fresh),
9772            "2026-01-01T00:05:00Z",
9773        )
9774        .unwrap();
9775        assert!(!stale.ok);
9776    }
9777
9778    // Fused-sensor provenance (Phase 5.18) ---------------------------------
9779
9780    // Cross-language interop: Rust reproduces the exact inputs digest and fused
9781    // output hash Python pinned, and verifies the Python-signed attestation.
9782    #[test]
9783    fn verifies_python_fused_interop_vector() {
9784        let vector = load_vector();
9785        let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
9786
9787        let inputs: Vec<String> = vector["fused_input_frame_hashes"]
9788            .as_array()
9789            .unwrap()
9790            .iter()
9791            .map(|v| v.as_str().unwrap().to_string())
9792            .collect();
9793        assert_eq!(
9794            fusion_inputs_digest_version(&inputs, INPUTS_DIGEST_V1).unwrap(),
9795            vector["expected_fusion_inputs_digest"].as_str().unwrap()
9796        );
9797        assert_eq!(
9798            fusion_inputs_digest(&inputs).unwrap(),
9799            vector["expected_fusion_inputs_digest_v2"].as_str().unwrap()
9800        );
9801
9802        assert_eq!(
9803            hash_fused_output(b"world-model-0"),
9804            vector["expected_fused_output_hash"].as_str().unwrap()
9805        );
9806
9807        let cred = vector["fused_perception_attestation"].clone();
9808        let subject = verify_fused_attestation(&cred, kd(&cred, &robot_pub), None, TNOW)
9809            .unwrap()
9810            .expect("fused attestation verifies");
9811        assert_eq!(subject["fusionMethod"], "occupancy-grid-v1");
9812        assert_eq!(
9813            subject["inputsDigest"].as_str().unwrap(),
9814            vector["expected_fusion_inputs_digest_v2"].as_str().unwrap()
9815        );
9816    }
9817
9818    // Wear and degradation attestation (Phase 5.19) ------------------------
9819
9820    // Cross-language interop: Rust verifies the Python-signed wear history and
9821    // reproduces the physical scope narrowed for the pinned wear level.
9822    #[test]
9823    fn verifies_python_wear_interop_vector() {
9824        let vector = load_vector();
9825        let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
9826
9827        let chain: Vec<Value> = vector["wear_chain"].as_array().unwrap().clone();
9828        let latest = verify_wear_chain(&chain, Keys::Resolver(&any_did(&robot_pub)), TNOW)
9829            .unwrap()
9830            .expect("wear chain verifies");
9831        assert_eq!(latest["wearLevel"].as_f64().unwrap(), 0.3);
9832
9833        let scope = vector["wear_input_scope"].clone();
9834        let level = vector["wear_attenuation_level"].as_f64().unwrap();
9835        let narrowed = attenuate_for_wear(&scope, level).unwrap();
9836        assert_eq!(narrowed, vector["expected_attenuated_scope"]);
9837        assert_eq!(narrowed["maxForceN"].as_f64().unwrap(), 60.0);
9838        assert_eq!(narrowed["maxSpeedMps"].as_f64().unwrap(), 1.125);
9839        assert_eq!(narrowed["maxSpeedNearHumansMps"].as_f64().unwrap(), 0.1875);
9840        assert!(attenuates(&scope, &narrowed));
9841    }
9842
9843    // Bystander-consent evidence (Phase 5.20) ------------------------------
9844
9845    // Cross-language interop: Rust reproduces the capture hash Python pinned,
9846    // verifies the bystander-signed token is bound to that capture, and verifies
9847    // the robot-signed evidence with the token and the bystander key.
9848    #[test]
9849    fn verifies_python_consent_interop_vector() {
9850        let vector = load_vector();
9851        let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
9852        let bystander_pub = jwk_pub(&vector["consent_bystander_key"]);
9853
9854        let capture = b"bystander-frame-0";
9855        let capture_hash = hash_capture(capture);
9856        assert_eq!(
9857            capture_hash,
9858            vector["expected_consent_capture_hash"].as_str().unwrap()
9859        );
9860
9861        let token = vector["consent_token_credential"].clone();
9862        let robot_did = token["credentialSubject"]["robotDid"].as_str().unwrap();
9863        let tok_subject = verify_consent_token(
9864            &token,
9865            kd(&token, &bystander_pub),
9866            &capture_hash,
9867            robot_did,
9868            "2026-01-01T00:05:00Z",
9869        )
9870        .unwrap()
9871        .expect("consent token verifies bound to the capture");
9872        assert_eq!(tok_subject["captureHash"].as_str().unwrap(), capture_hash);
9873
9874        let evidence = vector["consent_evidence_credential"].clone();
9875        let bystander_did = token["issuer"].as_str().unwrap();
9876        let keys = [BystanderKey {
9877            did: bystander_did.to_string(),
9878            public_key: bystander_pub.clone(),
9879        }];
9880        let ev_subject = verify_consent_evidence(
9881            &evidence,
9882            kd(&evidence, &robot_pub),
9883            Some(capture),
9884            Some(std::slice::from_ref(&token)),
9885            Some(&keys),
9886            "2026-01-01T00:05:00Z",
9887        )
9888        .unwrap()
9889        .expect("consent evidence verifies with token and bystander key");
9890        assert_eq!(ev_subject["basis"].as_str().unwrap(), "explicit-consent");
9891    }
9892}
9893
9894#[cfg(test)]
9895mod robot_root_identity_tests {
9896    use super::*;
9897    use crate::keys::Ed25519KeyPair;
9898    #[allow(unused_imports)]
9899    use crate::robotics_verify::test_keys::{any_did, kd, TNOW};
9900    #[allow(unused_imports)]
9901    use crate::robotics_verify::Keys;
9902    use std::path::PathBuf;
9903
9904    const NOW: &str = "2026-07-01T00:00:00Z";
9905    const VALID_FROM: &str = "2026-01-01T00:00:00Z";
9906    const CREATED: &str = "2026-01-01T00:00:00Z";
9907    const VALID_SECONDS: i64 = 100 * 365 * 24 * 3600;
9908    // Matches the manufacturer seed recorded in the interop vector (0x04 x32).
9909    const MANUFACTURER_SEED: [u8; 32] = [0x04; 32];
9910    const FORGED_ID: &str = "urn:uuid:66666666-6666-6666-6666-666666666666";
9911
9912    fn load_vector() -> Value {
9913        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
9914            .join("../../test-vectors/root-of-trust/vector.json");
9915        let text = std::fs::read_to_string(&path)
9916            .unwrap_or_else(|e| panic!("read vector {}: {e}", path.display()));
9917        serde_json::from_str(&text).expect("vector is valid JSON")
9918    }
9919
9920    fn robot_pub(vector: &Value) -> Vec<u8> {
9921        let x = vector["robotPublicKey"]["x"].as_str().unwrap();
9922        URL_SAFE_NO_PAD.decode(x).unwrap()
9923    }
9924
9925    fn stray_multikey(seed: &[u8]) -> String {
9926        let kp = Ed25519KeyPair::from_seed_slice(seed).unwrap();
9927        multikey::encode_ed25519_public(&kp.public_key()).unwrap()
9928    }
9929
9930    fn stray_did(seed: &[u8]) -> String {
9931        Ed25519KeyPair::from_seed_slice(seed).unwrap().did_key()
9932    }
9933
9934    fn robot_attributes() -> Value {
9935        json!({ "make": "Acme Robotics", "model": "AR-7", "serial": "SN-000123" })
9936    }
9937
9938    // The committed Python-minted robot chain must verify in Rust: recognized
9939    // manufacturer provenance plus hardware-rooting.
9940    #[test]
9941    fn verifies_python_robot_identity_interop_vector() {
9942        let v = load_vector();
9943        let root = v["trustedRoot"].as_str().unwrap();
9944        let r = verify_robot_identity_chain(
9945            &v["robotAuthorityIdentity"],
9946            &v["robotRecognizedIssuer"],
9947            &v["robotHardwareCredential"],
9948            root,
9949            &robot_pub(&v),
9950            Some(&v["rootOfTrust"]),
9951            NOW,
9952            30,
9953        );
9954        assert!(r.ok, "robot chain must verify: {:?}", r.reason);
9955        assert_eq!(
9956            Some(r.hardware_rooted),
9957            v["expected"]["hardwareRooted"].as_bool(),
9958            "the manufacturer pinned the hardware-root key"
9959        );
9960        assert_eq!(r.robot_did.as_deref(), v["expected"]["robotDid"].as_str());
9961        assert_eq!(
9962            r.issuer_did.as_deref(),
9963            v["expected"]["robotIssuerDid"].as_str()
9964        );
9965        assert_eq!(r.root_did.as_deref(), Some(root));
9966        assert_eq!(
9967            v["expected"]["verifyRobotIdentityChain"].as_bool(),
9968            Some(true)
9969        );
9970    }
9971
9972    // Adversarial: pinning a different root breaks the recognition anchor.
9973    #[test]
9974    fn wrong_pinned_root_rejected() {
9975        let v = load_vector();
9976        let other_root = stray_did(&[0x09; 32]);
9977        let r = verify_robot_identity_chain(
9978            &v["robotAuthorityIdentity"],
9979            &v["robotRecognizedIssuer"],
9980            &v["robotHardwareCredential"],
9981            &other_root,
9982            &robot_pub(&v),
9983            None,
9984            NOW,
9985            30,
9986        );
9987        assert!(!r.ok);
9988        assert_eq!(r.reason.as_deref(), Some("recognized_issuer_not_from_root"));
9989    }
9990
9991    // Adversarial: the manufacturer vouched a key that is not the robot's real
9992    // key. Provenance holds but the hardware key does not match.
9993    #[test]
9994    fn manufacturer_vouched_a_different_key() {
9995        let v = load_vector();
9996        let root = v["trustedRoot"].as_str().unwrap();
9997        let robot_did = v["expected"]["robotDid"].as_str().unwrap();
9998        let forged = build_robot_identity(
9999            &MANUFACTURER_SEED,
10000            robot_did,
10001            &stray_multikey(&[0x09; 32]),
10002            &robot_attributes(),
10003            VALID_SECONDS,
10004            VALID_FROM,
10005            CREATED,
10006            None,
10007            FORGED_ID,
10008            None,
10009        )
10010        .unwrap();
10011        let r = verify_robot_identity_chain(
10012            &forged,
10013            &v["robotRecognizedIssuer"],
10014            &v["robotHardwareCredential"],
10015            root,
10016            &robot_pub(&v),
10017            Some(&v["rootOfTrust"]),
10018            NOW,
10019            30,
10020        );
10021        assert!(!r.ok);
10022        assert_eq!(r.reason.as_deref(), Some("hardware_key_mismatch"));
10023    }
10024
10025    // Adversarial: an impostor key is presented for the hardware credential, so
10026    // the secure-element attestation no longer verifies.
10027    #[test]
10028    fn impostor_key_fails_hardware_root() {
10029        let v = load_vector();
10030        let root = v["trustedRoot"].as_str().unwrap();
10031        let impostor = Ed25519KeyPair::from_seed(&[0x09; 32]).public_key();
10032        let r = verify_robot_identity_chain(
10033            &v["robotAuthorityIdentity"],
10034            &v["robotRecognizedIssuer"],
10035            &v["robotHardwareCredential"],
10036            root,
10037            &impostor,
10038            Some(&v["rootOfTrust"]),
10039            NOW,
10040            30,
10041        );
10042        assert!(!r.ok);
10043        assert_eq!(r.reason.as_deref(), Some("hardware_root_invalid"));
10044    }
10045}
10046
10047#[cfg(test)]
10048mod port_hardening_tests {
10049    use super::*;
10050    use crate::keys::Ed25519KeyPair;
10051    #[allow(unused_imports)]
10052    use crate::robotics_verify::test_keys::{any_did, kd, TNOW};
10053    #[allow(unused_imports)]
10054    use crate::robotics_verify::Keys;
10055    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
10056    use base64::Engine;
10057
10058    // A missing or empty input list is malformed: the log check fails closed
10059    // instead of reporting "every input was logged".
10060    #[test]
10061    fn fusion_inputs_check_fails_closed_on_an_empty_list() {
10062        let empty = json!({"credentialSubject": {"inputFrameHashes": []}});
10063        assert!(!verify_fusion_inputs(&empty, &[]).ok);
10064        let missing = json!({"credentialSubject": {}});
10065        assert!(!verify_fusion_inputs(&missing, &[]).ok);
10066        let odd = json!({"credentialSubject": {"inputFrameHashes": ["ua", 5]}});
10067        let res = verify_fusion_inputs(&odd, &[json!({"frameHash": "ua"})]);
10068        assert!(!res.ok);
10069        assert_eq!(res.missing, vec!["5".to_string()]);
10070    }
10071
10072    fn load_vector() -> Value {
10073        let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
10074            .join("../../test-vectors/robotics/vector.json");
10075        serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
10076    }
10077
10078    fn jwk_pub(jwk: &Value) -> Vec<u8> {
10079        URL_SAFE_NO_PAD.decode(jwk["x"].as_str().unwrap()).unwrap()
10080    }
10081
10082    fn lease(valid_until: &str) -> (Value, Vec<u8>) {
10083        let seed = [51u8; 32];
10084        let kp = Ed25519KeyPair::from_seed(&seed);
10085        let cred = build_delegation_lease(
10086            &seed,
10087            &BuildDelegationLease {
10088                issuer_did: "did:web:robot.example.com".into(),
10089                robot_did: "did:web:robot.example.com".into(),
10090                lease_id: "lease-h".into(),
10091                scope: json!({"maxForceN": 80.0}),
10092                parent_lease_id: None,
10093                valid_from: "2026-01-01T00:00:00Z".into(),
10094                valid_until: valid_until.into(),
10095            },
10096        )
10097        .unwrap();
10098        (cred, kp.public_key().to_vec())
10099    }
10100
10101    // The core needs a clock: an empty or malformed `now` is an error, never a
10102    // skipped window check, in every verifier that checks a window.
10103    #[test]
10104    fn a_missing_or_malformed_clock_is_an_error() {
10105        let (cred, key) = lease("2026-01-01T01:00:00Z");
10106        for bad in ["", "null", "not-a-date", "2026-01-01"] {
10107            assert!(
10108                verify_delegation_lease(
10109                    &cred,
10110                    kd(&cred, &key),
10111                    "did:web:robot.example.com",
10112                    None,
10113                    None,
10114                    bad
10115                )
10116                .is_err(),
10117                "{bad:?}"
10118            );
10119            assert!(
10120                lease_permits(
10121                    &json!({}),
10122                    &PhysicalAction::default(),
10123                    Some(&cred),
10124                    kd(&cred, &key),
10125                    None,
10126                    bad
10127                )
10128                .is_err(),
10129                "{bad:?}"
10130            );
10131            assert!(verify_action_authorization(&[], "a", "r", &[], 1, None, bad).is_err());
10132            assert!(verify_access_grant(&cred, kd(&cred, &key), None, bad).is_err());
10133            assert!(authorize_access(
10134                &cred,
10135                &cred,
10136                kd(&cred, &key),
10137                kd(&cred, &key),
10138                RequestReplay::new(&mut HashSet::new()),
10139                bad
10140            )
10141            .is_err());
10142            assert!(verify_consent_token(&cred, kd(&cred, &key), "h", "r", bad).is_err());
10143            assert!(
10144                verify_consent_evidence(&cred, kd(&cred, &key), None, None, None, bad).is_err()
10145            );
10146        }
10147    }
10148
10149    // The shared vector's expired lease is refused at any time after its window,
10150    // and accepted inside it.
10151    #[test]
10152    fn expired_vector_lease_refused_after_its_window() {
10153        let v = load_vector();
10154        let key = jwk_pub(&v["robot_public_key_jwk"]);
10155        let cred = &v["delegation_lease_expired_credential"];
10156        assert!(verify_delegation_lease(
10157            cred,
10158            kd(cred, &key),
10159            "did:web:robot.example.com",
10160            None,
10161            None,
10162            "2026-01-01T00:30:00Z"
10163        )
10164        .unwrap()
10165        .is_some());
10166        assert!(verify_delegation_lease(
10167            cred,
10168            kd(cred, &key),
10169            "did:web:robot.example.com",
10170            None,
10171            None,
10172            "2026-06-01T00:00:00Z"
10173        )
10174        .unwrap()
10175        .is_none());
10176    }
10177
10178    // A validity bound that is present must be a string that parses.
10179    #[test]
10180    fn non_string_window_bounds_are_invalid() {
10181        for (key, bad) in [
10182            ("validFrom", json!(5)),
10183            ("validFrom", json!(null)),
10184            ("validUntil", json!(["2099-01-01T00:00:00Z"])),
10185            ("validUntil", json!(4102444800i64)),
10186            ("validUntil", json!("")),
10187        ] {
10188            let mut cred = json!({
10189                "validFrom": "2026-01-01T00:00:00Z",
10190                "validUntil": "2026-01-01T01:00:00Z"
10191            });
10192            cred[key] = bad.clone();
10193            assert!(
10194                rv::window_reason(&cred, Window::IfPresent, 1_767_225_660 * 1_000_000_000, 0)
10195                    .is_some(),
10196                "{key}={bad}"
10197            );
10198        }
10199    }
10200
10201    // One malformed approval from a listed approver is skipped; it does not fail
10202    // the whole authorization (shared vector).
10203    #[test]
10204    fn malformed_approvals_are_skipped_not_fatal() {
10205        let v = load_vector();
10206        let approvals = v["quorum_approvals_with_malformed"]
10207            .as_array()
10208            .unwrap()
10209            .clone();
10210        let keys: Vec<ApproverKey> = v["quorum_approver_keys"]
10211            .as_object()
10212            .unwrap()
10213            .iter()
10214            .map(|(did, jwk)| ApproverKey {
10215                did: did.clone(),
10216                public_key: jwk_pub(jwk),
10217            })
10218            .collect();
10219        let (ok, approvers) = verify_action_authorization(
10220            &approvals,
10221            v["quorum_action_id"].as_str().unwrap(),
10222            "did:web:robot.example.com",
10223            &keys,
10224            2,
10225            None,
10226            v["quorum_now"].as_str().unwrap(),
10227        )
10228        .unwrap();
10229        let expected = &v["expected_quorum_with_malformed"];
10230        assert_eq!(json!(ok), expected["authorized"]);
10231        assert_eq!(json!(approvers), expected["approvers"]);
10232    }
10233
10234    // A malformed scope field the action is checked against is a violation.
10235    #[test]
10236    fn malformed_scope_fields_are_violations() {
10237        let force = PhysicalAction {
10238            force_n: Some(5000.0),
10239            ..Default::default()
10240        };
10241        for cap in [json!("100"), json!(null), json!(true), json!([100])] {
10242            let r = check_physical_action(&json!({"maxForceN": cap}), &force);
10243            assert!(!r.ok, "maxForceN={cap}");
10244        }
10245        let speed = PhysicalAction {
10246            speed_mps: Some(9.0),
10247            near_humans: true,
10248            ..Default::default()
10249        };
10250        let r = check_physical_action(
10251            &json!({"maxSpeedMps": 1.0, "maxSpeedNearHumansMps": null}),
10252            &speed,
10253        );
10254        assert!(!r.ok);
10255        let zone = PhysicalAction {
10256            zone: Some("A".into()),
10257            ..Default::default()
10258        };
10259        for zones in [json!("A"), json!({"A": true}), json!(7)] {
10260            assert!(!check_physical_action(&json!({"allowedZones": zones}), &zone).ok);
10261        }
10262        let late = PhysicalAction {
10263            time_hm: Some("23:00".into()),
10264            ..Default::default()
10265        };
10266        for ws in [
10267            json!("08:00-18:00"),
10268            json!({"start": "08:00", "end": "18:00"}),
10269            json!(["08:00"]),
10270            json!([{"start": 800, "end": "18:00"}]),
10271        ] {
10272            assert!(
10273                !check_physical_action(&json!({"shiftWindows": ws}), &late).ok,
10274                "{ws}"
10275            );
10276        }
10277        // Native NaN in an action never passes a cap.
10278        let nan = PhysicalAction {
10279            force_n: Some(f64::NAN),
10280            ..Default::default()
10281        };
10282        assert!(!check_physical_action(&json!({"maxForceN": 10.0}), &nan).ok);
10283    }
10284
10285    #[test]
10286    fn malformed_child_fields_never_attenuate() {
10287        let parent = json!({
10288            "maxForceN": 80.0,
10289            "allowedZones": ["A", "B"],
10290            "shiftWindows": [{"start": "08:00", "end": "18:00"}]
10291        });
10292        let good = json!({
10293            "maxForceN": 50.0,
10294            "allowedZones": ["A"],
10295            "shiftWindows": [{"start": "09:00", "end": "17:00"}]
10296        });
10297        assert!(attenuates(&parent, &good));
10298        for (k, bad) in [
10299            ("shiftWindows", json!("00:00-23:59")),
10300            ("shiftWindows", json!({"start": "00:00"})),
10301            ("shiftWindows", json!([{"start": 0, "end": "23:59"}])),
10302            ("maxForceN", json!("50")),
10303            ("maxForceN", json!(null)),
10304            ("allowedZones", json!("A")),
10305            ("allowedZones", json!(["A", 7])),
10306            ("maxSpeedMps", json!("unlimited")),
10307        ] {
10308            let mut child = good.clone();
10309            child[k] = bad.clone();
10310            assert!(!attenuates(&parent, &child), "{k}={bad}");
10311        }
10312        // A malformed parent cap refuses rather than being skipped.
10313        assert!(!attenuates(&json!({"maxForceN": "80"}), &good));
10314    }
10315
10316    #[test]
10317    fn nan_wear_level_is_refused() {
10318        assert!(attenuate_for_wear(&json!({"maxForceN": 80.0}), f64::NAN).is_err());
10319        assert!(attenuate_for_wear(&json!({"maxForceN": 80.0}), 0.5).is_ok());
10320    }
10321}