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
19#[allow(unused_imports)]
20use crate::prelude::*;
21
22use serde_json::{json, Map, Value};
23
24use crate::data_integrity::{self, BuildProofOptions};
25use crate::error::{CoreError, Result};
26use crate::keys;
27use crate::pq::{MlDsa44KeyPair, MLDSA44_PUBLIC_LEN};
28use crate::robotics_verify::{self as rv, Keys, VerifyOptions, Window};
29use crate::root_of_trust::{self, ACTION_ISSUE_ROBOT_IDENTITY};
30use crate::{hybrid, jcs, multikey};
31
32use crate::collections::HashSet;
33use aes_gcm::aead::{Aead, Payload};
34use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
35use base64::engine::general_purpose::URL_SAFE_NO_PAD;
36use base64::Engine;
37use sha2::{Digest, Sha256};
38
39pub const VC_CONTEXT_V2: &str = "https://www.w3.org/ns/credentials/v2";
40pub const VOUCH_CONTEXT_V1: &str = "https://vouch-protocol.com/contexts/v1";
41pub const ROBOT_IDENTITY_TYPE: &str = "RobotIdentityCredential";
42
43/// Multibase ('u') base64url-no-pad encoding, matching the Python/TS/Go `mb64`.
44pub(crate) fn mb64(bytes: &[u8]) -> String {
45    format!("u{}", URL_SAFE_NO_PAD.encode(bytes))
46}
47
48/// Decode a multibase ('u') base64url-no-pad string.
49pub(crate) fn unmb64(s: &str) -> Result<Vec<u8>> {
50    let body = s
51        .strip_prefix('u')
52        .ok_or_else(|| CoreError::Json("expected multibase 'u' prefix".into()))?;
53    URL_SAFE_NO_PAD
54        .decode(body)
55        .map_err(|e| CoreError::Json(format!("bad base64url: {e}")))
56}
57
58/// The canonical bytes a hardware root signs to bind a robot's identity key to
59/// its hardware: JCS of `{"key": robot_key_multibase, "robotDid": robot_did}`.
60pub fn robot_identity_binding(robot_did: &str, robot_key_multibase: &str) -> Vec<u8> {
61    jcs::canonicalize(&json!({
62        "key": robot_key_multibase,
63        "robotDid": robot_did,
64    }))
65}
66
67/// Parameters for [`mint_robot_identity`]. Timestamps are ISO-8601 strings the
68/// caller supplies. `attestation` is the hardware root's signature over
69/// [`robot_identity_binding`]; `root_public_multibase` is that root's public key.
70#[derive(Debug, Clone)]
71pub struct MintRobotIdentity {
72    pub robot_did: String,
73    pub make: String,
74    pub model: String,
75    pub serial: String,
76    pub owner: Option<String>,
77    pub root_kind: String,
78    pub root_public_multibase: String,
79    pub attestation: Vec<u8>,
80    /// Optional explicit lifecycle array; defaults to a single "commissioned" entry.
81    pub lifecycle: Option<Value>,
82    pub valid_from: String,
83    pub valid_until: Option<String>,
84}
85
86/// Mint a hardware-attested `RobotIdentityCredential`, signed by the robot's own
87/// Ed25519 seed. The hardware-root attestation is embedded as
88/// `credentialSubject.hardwareRoot.attestation`.
89pub fn mint_robot_identity(robot_seed: &[u8], params: &MintRobotIdentity) -> Result<Value> {
90    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
91    let lifecycle = params
92        .lifecycle
93        .clone()
94        .unwrap_or_else(|| json!([{ "event": "commissioned", "timestamp": params.valid_from }]));
95
96    let mut subject = Map::new();
97    subject.insert("id".into(), json!(params.robot_did));
98    subject.insert("make".into(), json!(params.make));
99    subject.insert("model".into(), json!(params.model));
100    subject.insert("serial".into(), json!(params.serial));
101    subject.insert(
102        "hardwareRoot".into(),
103        json!({
104            "kind": params.root_kind,
105            "publicKeyMultibase": params.root_public_multibase,
106            "attestation": mb64(&params.attestation),
107        }),
108    );
109    subject.insert("lifecycle".into(), lifecycle);
110    if let Some(owner) = &params.owner {
111        subject.insert("owner".into(), json!(owner));
112    }
113
114    let mut cred = Map::new();
115    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
116    cred.insert(
117        "type".into(),
118        json!(["VerifiableCredential", ROBOT_IDENTITY_TYPE]),
119    );
120    cred.insert("issuer".into(), json!(params.robot_did));
121    cred.insert("validFrom".into(), json!(params.valid_from));
122    cred.insert("credentialSubject".into(), Value::Object(subject));
123    // After the subject, as the reference writes it (the shared vectors keep
124    // that member order; JCS signing does not depend on it).
125    if let Some(vu) = &params.valid_until {
126        cred.insert("validUntil".into(), json!(vu));
127    }
128
129    let opts = BuildProofOptions::new(
130        format!("{}#key-1", params.robot_did),
131        params.valid_from.clone(),
132    );
133    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
134}
135
136/// Verify a credential through the shared issuer-binding helper
137/// ([`crate::robotics_verify`]) at `now_iso`. Errors only on a malformed
138/// `now_iso`; any problem with the credential itself is `Ok(None)`.
139pub(crate) fn bound(
140    credential: &Value,
141    keys: Keys<'_>,
142    expected_type: &str,
143    now_iso: &str,
144    window: Window,
145) -> Result<Option<rv::Verified>> {
146    let now = rv::require_now(now_iso)?;
147    Ok(rv::verify_robotics_credential(
148        credential,
149        keys,
150        Some(expected_type),
151        now,
152        VerifyOptions::window(window),
153    )
154    .ok())
155}
156
157/// True when a self-attestation names its issuer as `credentialSubject.id`.
158pub(crate) fn issuer_is_subject(v: &rv::Verified) -> bool {
159    v.subject.get("id").and_then(|x| x.as_str()) == Some(v.issuer.as_str())
160}
161
162/// Verify a `RobotIdentityCredential`: the credential proof bound to the robot
163/// as issuer (which must also be `credentialSubject.id`), the validity window
164/// at `now_iso` (validFrom required), AND the hardware-root attestation binding
165/// the robot key to the hardware. `robot_keys` is a `{robot_did: key}` source
166/// (or, for a did:key robot, the bare key). When `hardware_root_key` is given,
167/// the credential's hardware-root key must be exactly that key. Returns the
168/// credentialSubject on success, `None` if invalid.
169pub fn verify_robot_identity(
170    credential: &Value,
171    robot_keys: Keys<'_>,
172    hardware_root_key: Option<&[u8]>,
173    now_iso: &str,
174) -> Result<Option<Value>> {
175    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
176    let v = match bound(
177        credential,
178        robot_keys,
179        ROBOT_IDENTITY_TYPE,
180        now_iso,
181        Window::FromRequired,
182    )? {
183        Some(v) if issuer_is_subject(&v) => v,
184        _ => return Ok(None),
185    };
186    let robot_key =
187        match rv::resolve_issuer_key(&v.issuer, rv::pin_if_keyless(robot_keys, Some(&v.issuer))) {
188            Ok(k) => k,
189            Err(_) => return Ok(None),
190        };
191    let subject = match v.subject.as_object() {
192        Some(s) => s,
193        None => return Ok(None),
194    };
195    let hw = match subject.get("hardwareRoot").and_then(|h| h.as_object()) {
196        Some(h) => h,
197        None => return Ok(None),
198    };
199    let hw_mb = match hw.get("publicKeyMultibase").and_then(|v| v.as_str()) {
200        Some(s) => s,
201        None => return Ok(None),
202    };
203    let attestation_mb = match hw.get("attestation").and_then(|v| v.as_str()) {
204        Some(s) => s,
205        None => return Ok(None),
206    };
207
208    let decoded = match multikey::decode(hw_mb) {
209        Ok(d) if d.algorithm == "Ed25519" && d.raw_key.len() == 32 => d,
210        _ => return Ok(None),
211    };
212    if let Some(pin) = hardware_root_key {
213        if pin != decoded.raw_key.as_slice() {
214            return Ok(None);
215        }
216    }
217    let attestation = match unmb64(attestation_mb) {
218        Ok(a) => a,
219        Err(_) => return Ok(None),
220    };
221
222    let robot_key_mb = multikey::encode_ed25519_public(&robot_key)?;
223    let binding = robot_identity_binding(&v.issuer, &robot_key_mb);
224
225    if !matches!(
226        keys::verify(&decoded.raw_key, &binding, &attestation),
227        Ok(true)
228    ) {
229        return Ok(None);
230    }
231    Ok(Some(v.subject))
232}
233
234// ---------------------------------------------------------------------------
235// Root of Trust for robot identity (Phase 5.1, authority binding)
236// ---------------------------------------------------------------------------
237//
238// Byte-exact port of the Python reference `vouch/robotics/root_identity.py`.
239//
240// The Root of Trust for Machine Identity lets one pinned Vouch root recognize
241// issuers, and a recognized issuer bind a subject DID to attributes, verified
242// offline against that one pinned root. This extends it to robots. A recognized
243// manufacturer (an issuer the root granted the `issueRobotIdentity` action)
244// issues an identity that binds a robot's DID and its hardware-rooted key to
245// attributes such as make, model, serial, and owner. The robot separately holds
246// a hardware-attested `RobotIdentityCredential` proving its key is bound to a
247// secure element.
248//
249// [`verify_robot_identity_chain`] closes the loop: from one pinned root a
250// verifier confirms both that the robot is a legitimate robot from a recognized
251// manufacturer (the authority chain via [`root_of_trust::verify_identity_chain`])
252// and that the key the manufacturer vouched for is genuinely hardware-rooted (the
253// secure-element attestation via [`verify_robot_identity`]), and that the two
254// name the same robot and the same key. It follows the anchor-once model and the
255// reason-code style of the underlying root_of_trust.
256
257/// Outcome of [`verify_robot_identity_chain`].
258///
259/// `ok` is true only if the authority chain verified against the pinned root AND
260/// the robot's own credential names the same robot and the vouched key.
261/// `hardware_rooted` is true only when the manufacturer also bound the
262/// hardware-root key and the attestation was made by exactly that key. On failure `reason`
263/// carries a structured code matching the Python reference exactly.
264#[derive(Debug, Clone, PartialEq, Eq)]
265pub struct RobotIdentityChainResult {
266    pub ok: bool,
267    pub reason: Option<String>,
268    pub robot_did: Option<String>,
269    pub issuer_did: Option<String>,
270    pub root_did: Option<String>,
271    pub attributes: Option<Value>,
272    pub hardware_rooted: bool,
273}
274
275impl RobotIdentityChainResult {
276    /// A failure result carrying the reason code and the pinned root that was in
277    /// force when the check failed.
278    fn fail(reason: impl Into<String>, root_did: &str) -> Self {
279        Self {
280            ok: false,
281            reason: Some(reason.into()),
282            robot_did: None,
283            issuer_did: None,
284            root_did: Some(root_did.to_string()),
285            attributes: None,
286            hardware_rooted: false,
287        }
288    }
289}
290
291/// Issue an authority robot identity: a recognized manufacturer binds `robot_did`,
292/// its hardware-rooted key (`hardware_key_multibase`, the robot's Ed25519 key as a
293/// multikey), and identity `attributes` (make, model, serial, owner). The
294/// manufacturer (derived from `issuer_seed`) must be a recognized issuer for the
295/// `issueRobotIdentity` action.
296///
297/// The credential is an `AgentIdentityCredential` so the shared identity-chain
298/// verification applies, with a `kind` of "robot" and the hardware key carried in
299/// the bound identity attributes.
300///
301/// `hardware_root_key_multibase` is the public key of the robot's secure element
302/// as the manufacturer recorded it. Bound as `hardwareRootKey`, it lets a
303/// verifier tell the robot's hardware attestation comes from that exact
304/// hardware; without it the chain verifies but is never hardware-rooted.
305#[allow(clippy::too_many_arguments)]
306pub fn build_robot_identity(
307    issuer_seed: &[u8],
308    robot_did: &str,
309    hardware_key_multibase: &str,
310    attributes: &Value,
311    valid_seconds: i64,
312    valid_from: &str,
313    created: &str,
314    credential_status: Option<Value>,
315    credential_id: &str,
316    hardware_root_key_multibase: Option<&str>,
317) -> Result<Value> {
318    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); attributes; drop credential_status);
319    if robot_did.is_empty() {
320        return Err(CoreError::Json("robot_did is required".into()));
321    }
322    if hardware_key_multibase.is_empty() {
323        return Err(CoreError::Json("hardware_key_multibase is required".into()));
324    }
325    let bound = match attributes.as_object() {
326        Some(o) if !o.is_empty() => {
327            let mut m = o.clone();
328            m.insert("kind".into(), json!("robot"));
329            m.insert("hardwareKey".into(), json!(hardware_key_multibase));
330            if let Some(root) = hardware_root_key_multibase {
331                if root.is_empty() {
332                    return Err(CoreError::Json(
333                        "hardware_root_key_multibase must be a multikey string".into(),
334                    ));
335                }
336                m.insert("hardwareRootKey".into(), json!(root));
337            }
338            Value::Object(m)
339        }
340        _ => {
341            return Err(CoreError::Json(
342                "attributes must be a non-empty object".into(),
343            ))
344        }
345    };
346    root_of_trust::build_agent_identity(
347        issuer_seed,
348        robot_did,
349        &bound,
350        valid_seconds,
351        valid_from,
352        created,
353        credential_status,
354        credential_id,
355    )
356}
357
358/// Verify a robot's identity against a single pinned Vouch root, confirming both
359/// provenance and hardware-rooting.
360///
361/// From `trusted_root`, the pinned root DID:
362///
363///   1. The authority chain: the recognized manufacturer must be recognized by
364///      the pinned root for the `issueRobotIdentity` action, and the authority
365///      identity must be signed by that manufacturer (shared identity-chain verify).
366///   2. The vouched key: the authority identity must carry a hardware key.
367///   3. The robot credential: the robot's own `RobotIdentityCredential` must
368///      verify under the key the manufacturer vouched for, name the same robot,
369///      and carry a valid secure-element attestation.
370///   4. The hardware root: when the manufacturer bound a `hardwareRootKey`, the
371///      attestation's hardware key must be exactly that key (else
372///      `hardware_root_mismatch`), and only then is `hardware_rooted` true.
373///
374/// `robot_public_key` is the robot's raw 32-byte Ed25519 public key. `now_iso` is
375/// the current instant used for the temporal window; `clock_skew_seconds` is the
376/// allowed drift. Reason codes on failure match the Python reference exactly.
377#[allow(clippy::too_many_arguments)]
378pub fn verify_robot_identity_chain(
379    authority_identity: &Value,
380    recognized_issuer_credential: &Value,
381    robot_hardware_credential: &Value,
382    trusted_root: &str,
383    robot_public_key: &[u8],
384    root_credential: Option<&Value>,
385    now_iso: &str,
386    clock_skew_seconds: i64,
387) -> RobotIdentityChainResult {
388    crate::nesting::deep_guard!(RobotIdentityChainResult { ok: false, reason: Some(crate::nesting::TOO_DEEP.into()), robot_did: None, issuer_did: None, root_did: None, attributes: None, hardware_rooted: false }; authority_identity, recognized_issuer_credential, robot_hardware_credential, root_credential);
389    let chain = root_of_trust::verify_identity_chain(
390        authority_identity,
391        recognized_issuer_credential,
392        trusted_root,
393        root_credential,
394        None,
395        ACTION_ISSUE_ROBOT_IDENTITY,
396        now_iso,
397        clock_skew_seconds,
398    );
399    robot_identity_chain_tail(
400        chain,
401        robot_hardware_credential,
402        trusted_root,
403        robot_public_key,
404        now_iso,
405    )
406}
407
408/// The robot half of [`verify_robot_identity_chain`], after the authority
409/// chain (`chain`, walked for `issueRobotIdentity`): the vouched hardware key,
410/// the robot's own credential under `robot_public_key`, its subject and key,
411/// and the hardware root.
412pub fn robot_identity_chain_tail(
413    chain: root_of_trust::IdentityChainResult,
414    robot_hardware_credential: &Value,
415    trusted_root: &str,
416    robot_public_key: &[u8],
417    now_iso: &str,
418) -> RobotIdentityChainResult {
419    // `chain` is the caller's and is dropped here: a deep `attributes` is
420    // taken apart without recursion before the refusal.
421    if crate::nesting::too_deep_here(robot_hardware_credential)
422        || crate::nesting::too_deep_here(&chain.attributes)
423    {
424        if let Some(attributes) = chain.attributes {
425            crate::nesting::drop_flat(attributes);
426        }
427        return RobotIdentityChainResult::fail(crate::nesting::TOO_DEEP, trusted_root);
428    }
429    if !chain.ok {
430        return RobotIdentityChainResult {
431            ok: false,
432            reason: chain.reason,
433            robot_did: None,
434            issuer_did: None,
435            root_did: Some(trusted_root.to_string()),
436            attributes: None,
437            hardware_rooted: false,
438        };
439    }
440
441    let attributes = match &chain.attributes {
442        Some(v @ Value::Object(_)) => v.clone(),
443        _ => json!({}),
444    };
445    let hardware_key = match attributes.get("hardwareKey").and_then(|v| v.as_str()) {
446        Some(s) if !s.is_empty() => s.to_string(),
447        _ => return RobotIdentityChainResult::fail("identity_no_hardware_key", trusted_root),
448    };
449
450    // The robot's own credential must verify under the supplied key, accepted
451    // for whatever DID the credential names; the next two checks pin that DID
452    // to the manufacturer's subject and the key to the vouched key.
453    let any_did = |_: &str| Some(robot_public_key.to_vec());
454    let hw_subject = match verify_robot_identity(
455        robot_hardware_credential,
456        Keys::Resolver(&any_did),
457        None,
458        now_iso,
459    ) {
460        Ok(Some(s)) => s,
461        _ => return RobotIdentityChainResult::fail("hardware_root_invalid", trusted_root),
462    };
463    if hw_subject.get("id").and_then(|v| v.as_str()) != chain.agent_did.as_deref() {
464        return RobotIdentityChainResult::fail("hardware_subject_mismatch", trusted_root);
465    }
466
467    let robot_key_mb = match multikey::encode_ed25519_public(robot_public_key) {
468        Ok(mb) => mb,
469        Err(_) => return RobotIdentityChainResult::fail("hardware_key_unresolvable", trusted_root),
470    };
471    if robot_key_mb != hardware_key {
472        return RobotIdentityChainResult::fail("hardware_key_mismatch", trusted_root);
473    }
474
475    // Hardware-rooted only when the manufacturer bound the hardware-root key and
476    // the robot's attestation was made by exactly that key.
477    let mut hardware_rooted = false;
478    if let Some(pinned) = attributes.get("hardwareRootKey") {
479        let claimed = hw_subject
480            .get("hardwareRoot")
481            .and_then(|h| h.get("publicKeyMultibase"))
482            .and_then(|v| v.as_str());
483        if pinned.as_str().is_none() || claimed != pinned.as_str() {
484            return RobotIdentityChainResult::fail("hardware_root_mismatch", trusted_root);
485        }
486        hardware_rooted = true;
487    }
488
489    RobotIdentityChainResult {
490        ok: true,
491        reason: None,
492        robot_did: chain.agent_did,
493        issuer_did: chain.issuer_did,
494        root_did: Some(trusted_root.to_string()),
495        attributes: Some(attributes),
496        hardware_rooted,
497    }
498}
499
500// ---------------------------------------------------------------------------
501// Model and config provenance (Phase 5.2)
502// ---------------------------------------------------------------------------
503
504pub const MODEL_PROVENANCE_TYPE: &str = "ModelProvenanceAttestation";
505
506/// Multibase SHA-256 of the JCS-canonical config object. Python, TypeScript, Go,
507/// and Rust all canonicalize identically, so the digest is the same byte string
508/// in every language.
509pub fn config_hash(config: &Value) -> String {
510    let digest = Sha256::digest(jcs::canonicalize(config));
511    mb64(&digest)
512}
513
514/// Parameters for [`build_provenance_attestation`]. The issuer is the signer (the
515/// robot itself or an authority); `robot_did` names the robot the attestation is
516/// about.
517#[derive(Debug, Clone)]
518pub struct BuildProvenance {
519    pub issuer_did: String,
520    pub robot_did: String,
521    pub model_name: String,
522    pub weights_hash: String,
523    pub safety_policy: String,
524    pub config: Option<Value>,
525    pub version: Option<String>,
526    pub supersedes: Option<String>,
527    pub valid_from: String,
528    pub valid_until: Option<String>,
529}
530
531/// Build a signed `ModelProvenanceAttestation` for the software on a robot.
532pub fn build_provenance_attestation(signer_seed: &[u8], params: &BuildProvenance) -> Result<Value> {
533    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
534    let mut vla = Map::new();
535    vla.insert("modelName".into(), json!(params.model_name));
536    vla.insert("weightsHash".into(), json!(params.weights_hash));
537    vla.insert("safetyPolicy".into(), json!(params.safety_policy));
538    if let Some(v) = &params.version {
539        vla.insert("version".into(), json!(v));
540    }
541    if let Some(cfg) = &params.config {
542        vla.insert("configHash".into(), json!(config_hash(cfg)));
543    }
544
545    let mut subject = Map::new();
546    subject.insert("id".into(), json!(params.robot_did));
547    subject.insert("vla".into(), Value::Object(vla));
548    if let Some(s) = &params.supersedes {
549        subject.insert("supersedes".into(), json!(s));
550    }
551
552    let mut cred = Map::new();
553    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
554    cred.insert(
555        "type".into(),
556        json!(["VerifiableCredential", MODEL_PROVENANCE_TYPE]),
557    );
558    cred.insert("issuer".into(), json!(params.issuer_did));
559    cred.insert("validFrom".into(), json!(params.valid_from));
560    if let Some(vu) = &params.valid_until {
561        cred.insert("validUntil".into(), json!(vu));
562    }
563    cred.insert("credentialSubject".into(), Value::Object(subject));
564
565    let opts = BuildProofOptions::new(
566        format!("{}#key-1", params.issuer_did),
567        params.valid_from.clone(),
568    );
569    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
570}
571
572/// Verify a `ModelProvenanceAttestation`. When `config` is supplied, also check
573/// the recorded configHash reproduces. Returns the subject on success, `None`
574/// otherwise.
575pub fn verify_provenance_attestation(
576    attestation: &Value,
577    keys: Keys<'_>,
578    config: Option<&Value>,
579    now_iso: &str,
580) -> Result<Option<Value>> {
581    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); attestation, config);
582    let v = match bound(
583        attestation,
584        keys,
585        MODEL_PROVENANCE_TYPE,
586        now_iso,
587        Window::FromRequired,
588    )? {
589        Some(v) => v,
590        None => return Ok(None),
591    };
592    if let Some(cfg) = config {
593        let want = config_hash(cfg);
594        let got = v
595            .subject
596            .get("vla")
597            .and_then(|v| v.as_object())
598            .and_then(|v| v.get("configHash"))
599            .and_then(|v| v.as_str());
600        if got != Some(want.as_str()) {
601            return Ok(None);
602        }
603    }
604    Ok(Some(v.subject))
605}
606
607/// The reference a superseding attestation uses: multibase SHA-256 of the JCS
608/// form of the whole signed attestation (proof included).
609pub fn provenance_attestation_id(attestation: &Value) -> String {
610    mb64(&Sha256::digest(jcs::canonicalize(attestation)))
611}
612
613/// Verify an ordered OTA history of provenance attestations for `robot_did`:
614/// every attestation verifies and is about `robot_did`; each one after the
615/// first names the previous by [`provenance_attestation_id`] as `supersedes`
616/// and is dated no earlier. Each earlier attestation must still have been valid
617/// when the next was made, and the last at `now_iso`. Returns the latest
618/// subject on success.
619pub fn verify_provenance_chain(
620    attestations: &[Value],
621    keys: Keys<'_>,
622    robot_did: &str,
623    now_iso: &str,
624) -> Result<Option<Value>> {
625    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); attestations);
626    rv::require_now(now_iso)?;
627    if attestations.is_empty() || robot_did.is_empty() {
628        return Ok(None);
629    }
630    let mut prev: Option<&Value> = None;
631    let mut latest = None;
632    for (i, att) in attestations.iter().enumerate() {
633        let at: String = match attestations.get(i + 1) {
634            Some(next) => match next.get("validFrom").and_then(|v| v.as_str()) {
635                Some(t) if rv::time_ns(next.get("validFrom")).is_some() => t.to_string(),
636                _ => return Ok(None),
637            },
638            None => now_iso.to_string(),
639        };
640        let subject = match verify_provenance_attestation(att, keys, None, &at)? {
641            Some(s) if s.get("id").and_then(|v| v.as_str()) == Some(robot_did) => s,
642            _ => return Ok(None),
643        };
644        if let Some(p) = prev {
645            if subject.get("supersedes").and_then(|v| v.as_str())
646                != Some(provenance_attestation_id(p).as_str())
647            {
648                return Ok(None);
649            }
650            if rv::time_ns(att.get("validFrom")) < rv::time_ns(p.get("validFrom")) {
651                return Ok(None);
652            }
653        }
654        prev = Some(att);
655        latest = Some(subject);
656    }
657    Ok(latest)
658}
659
660// ---------------------------------------------------------------------------
661// Physical capability scope (Phase 5.3)
662// ---------------------------------------------------------------------------
663
664pub const PHYSICAL_SCOPE_TYPE: &str = "PhysicalCapabilityScope";
665
666/// An allowed time-of-day window, "HH:MM" start and end.
667#[derive(Debug, Clone)]
668pub struct ShiftWindow {
669    pub start: String,
670    pub end: String,
671}
672
673/// A proposed actuation to check against a scope. `None` numerics mean "not
674/// specified" (a meaningful zero is still `Some(0.0)`).
675#[derive(Debug, Clone, Default)]
676pub struct PhysicalAction {
677    pub force_n: Option<f64>,
678    pub speed_mps: Option<f64>,
679    pub near_humans: bool,
680    pub zone: Option<String>,
681    pub time_hm: Option<String>,
682}
683
684/// The outcome of [`check_physical_action`].
685#[derive(Debug, Clone)]
686pub struct CheckResult {
687    pub ok: bool,
688    pub reasons: Vec<String>,
689}
690
691/// Parameters for [`build_physical_scope_credential`]. The issuer is the signer
692/// (a fleet authority); `subject_did` is the robot the scope is granted to.
693#[derive(Debug, Clone, Default)]
694pub struct BuildPhysicalScope {
695    pub issuer_did: String,
696    pub subject_did: String,
697    pub max_force_n: Option<f64>,
698    pub max_speed_mps: Option<f64>,
699    pub max_speed_near_humans_mps: Option<f64>,
700    pub allowed_zones: Option<Vec<String>>,
701    pub shift_windows: Option<Vec<ShiftWindow>>,
702    pub valid_from: String,
703    pub valid_until: Option<String>,
704}
705
706/// Build a signed `PhysicalCapabilityScope` credential.
707pub fn build_physical_scope_credential(
708    signer_seed: &[u8],
709    params: &BuildPhysicalScope,
710) -> Result<Value> {
711    let mut scope = Map::new();
712    if let Some(v) = params.max_force_n {
713        scope.insert("maxForceN".into(), json!(v));
714    }
715    if let Some(v) = params.max_speed_mps {
716        scope.insert("maxSpeedMps".into(), json!(v));
717    }
718    if let Some(v) = params.max_speed_near_humans_mps {
719        scope.insert("maxSpeedNearHumansMps".into(), json!(v));
720    }
721    if let Some(zones) = &params.allowed_zones {
722        scope.insert("allowedZones".into(), json!(zones));
723    }
724    if let Some(ws) = &params.shift_windows {
725        let arr: Vec<Value> = ws
726            .iter()
727            .map(|w| json!({"start": w.start, "end": w.end}))
728            .collect();
729        scope.insert("shiftWindows".into(), Value::Array(arr));
730    }
731
732    let mut subject = Map::new();
733    subject.insert("id".into(), json!(params.subject_did));
734    subject.insert("physicalScope".into(), Value::Object(scope));
735
736    let mut cred = Map::new();
737    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
738    cred.insert(
739        "type".into(),
740        json!(["VerifiableCredential", PHYSICAL_SCOPE_TYPE]),
741    );
742    cred.insert("issuer".into(), json!(params.issuer_did));
743    cred.insert("validFrom".into(), json!(params.valid_from));
744    if let Some(vu) = &params.valid_until {
745        cred.insert("validUntil".into(), json!(vu));
746    }
747    cred.insert("credentialSubject".into(), Value::Object(subject));
748
749    let opts = BuildProofOptions::new(
750        format!("{}#key-1", params.issuer_did),
751        params.valid_from.clone(),
752    );
753    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
754}
755
756/// The numeric caps a physical scope may set.
757pub const CAP_KEYS: [&str; 3] = ["maxForceN", "maxSpeedMps", "maxSpeedNearHumansMps"];
758/// Every dimension a physical scope may set.
759pub const SCOPE_KEYS: [&str; 5] = [
760    "maxForceN",
761    "maxSpeedMps",
762    "maxSpeedNearHumansMps",
763    "allowedZones",
764    "shiftWindows",
765];
766
767/// Minutes since midnight for a strict `HH:MM` string (00:00-23:59), else `None`.
768pub fn parse_hm(value: &str) -> Option<u32> {
769    let b = value.as_bytes();
770    if b.len() != 5
771        || b[2] != b':'
772        || !b
773            .iter()
774            .enumerate()
775            .all(|(i, c)| i == 2 || c.is_ascii_digit())
776    {
777        return None;
778    }
779    let h = u32::from(b[0] - b'0') * 10 + u32::from(b[1] - b'0');
780    let m = u32::from(b[3] - b'0') * 10 + u32::from(b[4] - b'0');
781    if h > 23 || m > 59 {
782        return None;
783    }
784    Some(h * 60 + m)
785}
786
787/// A usable physical cap: a finite, non-negative JSON number (never a boolean).
788pub fn valid_cap(v: &Value) -> bool {
789    v.is_number() && v.as_f64().is_some_and(|n| n.is_finite() && n >= 0.0)
790}
791
792/// `(start, end)` minutes of a `{"start", "end"}` window with start <= end.
793pub fn parse_window(w: &Value) -> Option<(u32, u32)> {
794    let o = w.as_object()?;
795    let start = parse_hm(o.get("start")?.as_str()?)?;
796    let end = parse_hm(o.get("end")?.as_str()?)?;
797    (start <= end).then_some((start, end))
798}
799
800/// Every window of a list, or `None` if the list or any window is malformed.
801pub fn parse_windows(v: &Value) -> Option<Vec<(u32, u32)>> {
802    v.as_array()?.iter().map(parse_window).collect()
803}
804
805/// The zone ids of a list of strings, or `None` if malformed.
806pub fn parse_zones(v: &Value) -> Option<Vec<&str>> {
807    v.as_array()?.iter().map(|z| z.as_str()).collect()
808}
809
810/// Reasons the scope itself cannot be read; empty when every set dimension is
811/// well-formed.
812pub fn scope_problems(scope: &Value) -> Vec<String> {
813    crate::nesting::deep_guard!(vec![crate::nesting::TOO_DEEP.into()]; scope);
814    let o = match scope.as_object() {
815        Some(o) => o,
816        None => return vec!["scope_malformed: not an object".into()],
817    };
818    let mut problems = Vec::new();
819    for key in CAP_KEYS {
820        if o.get(key).is_some_and(|v| !valid_cap(v)) {
821            problems.push(format!(
822                "scope_malformed: {key} is not a finite non-negative number"
823            ));
824        }
825    }
826    if o.get("allowedZones")
827        .is_some_and(|v| parse_zones(v).is_none())
828    {
829        problems.push("scope_malformed: allowedZones is not a list of strings".into());
830    }
831    if o.get("shiftWindows")
832        .is_some_and(|v| parse_windows(v).is_none())
833    {
834        problems.push("scope_malformed: shiftWindows is not a list of HH:MM windows".into());
835    }
836    problems
837}
838
839/// Verify a `PhysicalCapabilityScope` credential and return its physicalScope:
840/// the proof bound to the issuer, the window at `now_iso` (validFrom
841/// required), a well-formed scope with no unknown dimension (a misspelt cap
842/// would otherwise limit nothing), and (when given) the subject `subject_did`.
843pub fn verify_physical_scope_credential(
844    credential: &Value,
845    keys: Keys<'_>,
846    subject_did: Option<&str>,
847    now_iso: &str,
848) -> Result<Option<Value>> {
849    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
850    let v = match bound(
851        credential,
852        keys,
853        PHYSICAL_SCOPE_TYPE,
854        now_iso,
855        Window::FromRequired,
856    )? {
857        Some(v) => v,
858        None => return Ok(None),
859    };
860    if subject_did.is_some_and(|d| v.subject.get("id").and_then(|x| x.as_str()) != Some(d)) {
861        return Ok(None);
862    }
863    let scope = match v.subject.get("physicalScope") {
864        Some(sc @ Value::Object(o)) if o.keys().all(|k| SCOPE_KEYS.contains(&k.as_str())) => sc,
865        _ => return Ok(None),
866    };
867    if !scope_problems(scope).is_empty() {
868        return Ok(None);
869    }
870    Ok(Some(scope.clone()))
871}
872
873/// Check a proposed physical action against a physical scope object, returning
874/// ok plus a reason for each violation. A scope dimension that is set but
875/// malformed, and an action value that is not a finite non-negative number or
876/// not a strict `HH:MM`, are violations. An empty zone or shift-window list
877/// allows nothing. Near humans, the speed cap is the lower of `maxSpeedMps`
878/// and `maxSpeedNearHumansMps`.
879pub fn check_physical_action(scope: &Value, action: &PhysicalAction) -> CheckResult {
880    crate::nesting::deep_guard!(CheckResult { ok: false, reasons: vec![crate::nesting::TOO_DEEP.into()] }; scope);
881    let mut reasons = scope_problems(scope);
882    if !reasons.is_empty() {
883        return CheckResult { ok: false, reasons };
884    }
885    let o = scope
886        .as_object()
887        .expect("scope_problems checked it is an object");
888    for (name, value) in [("force_n", action.force_n), ("speed_mps", action.speed_mps)] {
889        if let Some(v) = value {
890            if !v.is_finite() || v < 0.0 {
891                reasons.push(format!(
892                    "action_malformed: {name} is not a finite non-negative number"
893                ));
894            }
895        }
896    }
897    if !reasons.is_empty() {
898        return CheckResult { ok: false, reasons };
899    }
900    let cap = |k: &str| o.get(k).and_then(|v| v.as_f64());
901
902    if let (Some(force), Some(c)) = (action.force_n, cap("maxForceN")) {
903        if force > c {
904            reasons.push(format!("force_exceeded: {force}N > {c}N"));
905        }
906    }
907    if let Some(speed) = action.speed_mps {
908        let mut c = cap("maxSpeedMps");
909        if action.near_humans {
910            if let Some(near) = cap("maxSpeedNearHumansMps") {
911                c = Some(c.map_or(near, |g| g.min(near)));
912            }
913        }
914        if let Some(c) = c {
915            if speed > c {
916                let label = if action.near_humans {
917                    "near_humans "
918                } else {
919                    ""
920                };
921                reasons.push(format!("{label}speed_exceeded: {speed} m/s > {c} m/s"));
922            }
923        }
924    }
925    if let (Some(zone), Some(zones)) = (&action.zone, o.get("allowedZones").and_then(parse_zones)) {
926        if !zones.contains(&zone.as_str()) {
927            reasons.push(format!("zone_not_allowed: {zone}"));
928        }
929    }
930    if let (Some(hm), Some(ws)) = (&action.time_hm, o.get("shiftWindows")) {
931        match parse_hm(hm) {
932            None => reasons.push(format!("action_malformed: time_hm {hm:?} is not HH:MM")),
933            Some(t) => {
934                let windows = parse_windows(ws).unwrap_or_default();
935                if !windows.iter().any(|(s, e)| *s <= t && t <= *e) {
936                    reasons.push(format!("outside_shift_window: {hm}"));
937                }
938            }
939        }
940    }
941    CheckResult {
942        ok: reasons.is_empty(),
943        reasons,
944    }
945}
946
947/// Report whether `child` is a valid attenuation of `parent`: never broader on
948/// any physical dimension. Both scopes must be well-formed; for every dimension
949/// the parent sets, the child must set it too and be no broader (a cap no
950/// higher, a NON-EMPTY subset of zones, a NON-EMPTY list of windows each inside
951/// some parent window). Leaving a dimension out, or an empty list, is never an
952/// attenuation of a parent that limits it.
953pub fn attenuates(parent: &Value, child: &Value) -> bool {
954    crate::nesting::deep_guard!(false; parent, child);
955    if !scope_problems(parent).is_empty() || !scope_problems(child).is_empty() {
956        return false;
957    }
958    let (p, c) = match (parent.as_object(), child.as_object()) {
959        (Some(p), Some(c)) => (p, c),
960        _ => return false,
961    };
962    for key in CAP_KEYS {
963        if let Some(pv) = p.get(key).and_then(|v| v.as_f64()) {
964            match c.get(key).and_then(|v| v.as_f64()) {
965                Some(cv) if cv <= pv => {}
966                _ => return false,
967            }
968        }
969    }
970    if let Some(pz) = p.get("allowedZones").and_then(parse_zones) {
971        match c.get("allowedZones").and_then(parse_zones) {
972            Some(cz) if !cz.is_empty() && cz.iter().all(|z| pz.contains(z)) => {}
973            _ => return false,
974        }
975    }
976    if let Some(pw) = p.get("shiftWindows").and_then(parse_windows) {
977        match c.get("shiftWindows").and_then(parse_windows) {
978            Some(cw) if !cw.is_empty() => {
979                for (cs, ce) in cw {
980                    if !pw.iter().any(|(ps, pe)| *ps <= cs && ce <= *pe) {
981                        return false;
982                    }
983                }
984            }
985            _ => return false,
986        }
987    }
988    true
989}
990
991// ---------------------------------------------------------------------------
992// Robot-to-robot trust handshake (Phase 5.4)
993// ---------------------------------------------------------------------------
994
995pub const HELLO: &str = "handshake_hello";
996pub const ACCEPT: &str = "handshake_accept";
997pub const CONFIRM: &str = "handshake_confirm";
998
999/// Decides whether a peer DID is trusted: its did:web or did:webvh name must
1000/// be allowed, or `accept_unknown` is set. The name is the domain plus any
1001/// path, colon-joined (`did:web:a.example:agents` is `a.example:agents`), so a
1002/// bare-domain entry trusts the bare domain only and a path is trusted only
1003/// when the policy names it.
1004#[derive(Debug, Clone, Default)]
1005pub struct TrustPolicy {
1006    pub trusted_domains: HashSet<String>,
1007    pub accept_unknown: bool,
1008}
1009
1010impl TrustPolicy {
1011    pub fn new(domains: impl IntoIterator<Item = String>, accept_unknown: bool) -> Self {
1012        Self {
1013            trusted_domains: domains.into_iter().collect(),
1014            accept_unknown,
1015        }
1016    }
1017
1018    pub fn is_trusted(&self, did: &str) -> bool {
1019        if self.accept_unknown {
1020            return true;
1021        }
1022        match did_web_domain(did) {
1023            Some(d) => self.trusted_domains.contains(&d),
1024            None => false,
1025        }
1026    }
1027}
1028
1029/// The agreed cooperation session after a successful handshake.
1030#[derive(Debug, Clone)]
1031pub struct BoundedSession {
1032    pub session_id: String,
1033    pub initiator: String,
1034    pub responder: String,
1035    pub scope: Vec<String>,
1036    pub nonce: String,
1037    pub valid_until: Option<String>,
1038}
1039
1040/// The name a did:web or did:webvh DID is trusted under, or None: the domain,
1041/// then each path segment after a colon. Each prefix keeps its trailing colon,
1042/// so a did:webvh DID never reads as did:web. A did:webvh DID is parsed
1043/// strictly ([`crate::did_webvh::parse`]) and gives its host (percent-decoded
1044/// and lower-cased) and its percent-decoded path; one that does not parse has
1045/// no name. A did:web with an empty segment has no name.
1046fn did_web_domain(did: &str) -> Option<String> {
1047    if crate::did_webvh::is_did_webvh(did) {
1048        return crate::did_webvh::parse(did).ok().map(|parsed| {
1049            core::iter::once(parsed.host)
1050                .chain(parsed.path)
1051                .collect::<Vec<_>>()
1052                .join(":")
1053        });
1054    }
1055    let rest = did.strip_prefix("did:web:")?;
1056    if rest.split(':').any(str::is_empty) {
1057        None
1058    } else {
1059        Some(rest.to_string())
1060    }
1061}
1062
1063/// Parameters for [`build_hello`]. `nonce` and `issued_at` are caller-supplied so
1064/// the core stays deterministic; the wrapper SDKs generate them.
1065#[derive(Debug, Clone, Default)]
1066pub struct BuildHello {
1067    pub from_did: String,
1068    pub proposed_scope: Vec<String>,
1069    pub nonce: String,
1070    pub peer_did: Option<String>,
1071    pub issued_at: String,
1072}
1073
1074/// Open the handshake (initiator A): a proposed scope and a fresh nonce, signed.
1075pub fn build_hello(signer_seed: &[u8], params: &BuildHello) -> Result<Value> {
1076    let mut hello = Map::new();
1077    hello.insert("type".into(), json!(HELLO));
1078    hello.insert("from".into(), json!(params.from_did));
1079    hello.insert(
1080        "to".into(),
1081        match &params.peer_did {
1082            Some(p) => json!(p),
1083            None => Value::Null,
1084        },
1085    );
1086    hello.insert("nonce".into(), json!(params.nonce));
1087    hello.insert("proposedScope".into(), json!(params.proposed_scope));
1088    hello.insert("issuedAt".into(), json!(params.issued_at));
1089    let opts = BuildProofOptions::new(format!("{}#key-1", params.from_did), &params.issued_at);
1090    data_integrity::sign(&Value::Object(hello), signer_seed, &opts)
1091}
1092
1093/// The default clock skew for handshake freshness checks (seconds).
1094pub const DEFAULT_HANDSHAKE_SKEW_SECONDS: i64 = 30;
1095/// The oldest HELLO a responder answers (seconds).
1096pub const DEFAULT_MAX_HELLO_AGE_SECONDS: i64 = 300;
1097/// The longest session an ACCEPT may grant (validUntil - issuedAt).
1098pub const DEFAULT_MAX_SESSION_SECONDS: i64 = 3600;
1099
1100/// The message is `expected_type` and its proof is bound to the DID in `from`
1101/// (assertionMethod, verification method of that DID, key resolved from it).
1102fn handshake_message_ok(obj: &Value, keys: Keys<'_>, expected_type: &str) -> bool {
1103    if obj.get("type").and_then(|v| v.as_str()) != Some(expected_type) {
1104        return false;
1105    }
1106    if rv::input_too_large(obj, rv::MAX_CREDENTIAL_BYTES).is_some() {
1107        return false;
1108    }
1109    let sender = match obj.get("from").and_then(|v| v.as_str()) {
1110        Some(s) if s.starts_with("did:") => s,
1111        _ => return false,
1112    };
1113    if rv::proof_unbound_reason(obj.get("proof").unwrap_or(&Value::Null), sender).is_some() {
1114        return false;
1115    }
1116    // The handshake binds each message to the DID in `from`; whether that
1117    // party is trusted is the policy's decision (or the caller's own HELLO or
1118    // ACCEPT pins it), so `from` is the pinned issuer here.
1119    let key = match rv::resolve_issuer_key(sender, rv::pin_if_keyless(keys, Some(sender))) {
1120        Ok(k) => k,
1121        Err(_) => return false,
1122    };
1123    matches!(data_integrity::verify_proof(obj, &key), Ok(true))
1124}
1125
1126fn scope_list(v: Option<&Value>) -> Option<Vec<String>> {
1127    v?.as_array()?
1128        .iter()
1129        .map(|x| x.as_str().map(String::from))
1130        .collect()
1131}
1132
1133fn issued_recently(v: Option<&Value>, now_ns: i128, skew: i64, max_age: i64) -> bool {
1134    let issued = match rv::time_ns(v) {
1135        Some(t) => t,
1136        None => return false,
1137    };
1138    let second: i128 = 1_000_000_000;
1139    now_ns - i128::from(max_age.saturating_add(skew)) * second <= issued
1140        && issued <= now_ns + i128::from(skew) * second
1141}
1142
1143impl BoundedSession {
1144    /// True while `now_iso` is at or before the session's validUntil (required).
1145    pub fn is_current(&self, now_iso: &str) -> bool {
1146        match (
1147            self.valid_until
1148                .as_deref()
1149                .and_then(|u| crate::time::parse_protocol_time_ns(u).ok()),
1150            crate::time::parse_protocol_time_ns(now_iso).ok(),
1151        ) {
1152            (Some(u), Some(n)) => n <= u,
1153            _ => false,
1154        }
1155    }
1156}
1157
1158/// Parameters for [`build_accept`]. `issued_at` is the responder's clock (it
1159/// also judges the HELLO's age); `valid_until` bounds the session.
1160#[derive(Debug, Clone, Default)]
1161pub struct BuildAccept {
1162    pub from_did: String,
1163    pub offered_scope: Vec<String>,
1164    pub session_id: String,
1165    pub valid_until: String,
1166    pub created: String,
1167}
1168
1169/// Verify A's HELLO, check A's domain, intersect the scope, and sign an
1170/// acceptance (responder B). The HELLO's proof must be bound to its `from` DID
1171/// (`hello_keys` is a `{did: key}` source, or the bare key of a did:key
1172/// initiator); it must be addressed to this responder (`to` unset or this
1173/// responder's DID) and its `issuedAt` within [`DEFAULT_MAX_HELLO_AGE_SECONDS`]
1174/// (plus [`DEFAULT_HANDSHAKE_SKEW_SECONDS`]) of `params.created`. The trust
1175/// policy is applied to the verified `from`. The ACCEPT carries `issuedAt`.
1176pub fn build_accept(
1177    signer_seed: &[u8],
1178    hello: &Value,
1179    hello_keys: Keys<'_>,
1180    policy: &TrustPolicy,
1181    params: &BuildAccept,
1182) -> Result<Value> {
1183    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); hello);
1184    build_accept_with(
1185        signer_seed,
1186        hello,
1187        hello_keys,
1188        policy,
1189        params,
1190        HandshakeLimits::default(),
1191    )
1192}
1193
1194/// The time limits of the handshake: the clock skew allowed either way, the
1195/// oldest HELLO (for [`build_accept_with`]) or ACCEPT (for
1196/// [`verify_accept_with`]) accepted, and the longest session an ACCEPT may
1197/// grant.
1198#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1199pub struct HandshakeLimits {
1200    pub clock_skew_seconds: i64,
1201    pub max_age_seconds: i64,
1202    pub max_session_seconds: i64,
1203}
1204
1205impl Default for HandshakeLimits {
1206    fn default() -> Self {
1207        Self {
1208            clock_skew_seconds: DEFAULT_HANDSHAKE_SKEW_SECONDS,
1209            max_age_seconds: DEFAULT_MAX_HELLO_AGE_SECONDS,
1210            max_session_seconds: DEFAULT_MAX_SESSION_SECONDS,
1211        }
1212    }
1213}
1214
1215impl HandshakeLimits {
1216    fn check(&self) -> Result<()> {
1217        if !(0..=120).contains(&self.clock_skew_seconds) {
1218            return Err(CoreError::Json(
1219                "clock skew must be between 0 and 120 seconds".into(),
1220            ));
1221        }
1222        if self.max_age_seconds < 0 || self.max_session_seconds < 1 {
1223            return Err(CoreError::Json(
1224                "handshake age and session limits must be positive".into(),
1225            ));
1226        }
1227        Ok(())
1228    }
1229}
1230
1231/// [`build_accept`] with the caller's [`HandshakeLimits`].
1232pub fn build_accept_with(
1233    signer_seed: &[u8],
1234    hello: &Value,
1235    hello_keys: Keys<'_>,
1236    policy: &TrustPolicy,
1237    params: &BuildAccept,
1238    limits: HandshakeLimits,
1239) -> Result<Value> {
1240    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); hello);
1241    limits.check()?;
1242    let now = rv::require_now(&params.created)?;
1243    if !handshake_message_ok(hello, hello_keys, HELLO) {
1244        return Err(CoreError::Json(
1245            "HELLO is not signed by the DID it is from".into(),
1246        ));
1247    }
1248    match hello.get("to") {
1249        None | Some(Value::Null) => {}
1250        Some(Value::String(t)) if *t == params.from_did => {}
1251        _ => return Err(CoreError::Json("HELLO is addressed to another node".into())),
1252    }
1253    if !issued_recently(
1254        hello.get("issuedAt"),
1255        now,
1256        limits.clock_skew_seconds,
1257        limits.max_age_seconds,
1258    ) {
1259        return Err(CoreError::Json(
1260            "HELLO is stale, from the future, or has no valid issuedAt".into(),
1261        ));
1262    }
1263    let proposed = scope_list(hello.get("proposedScope"));
1264    let nonce = hello
1265        .get("nonce")
1266        .and_then(|v| v.as_str())
1267        .filter(|n| !n.is_empty());
1268    let (proposed, nonce) = match (proposed, nonce) {
1269        (Some(p), Some(n)) => (p, n),
1270        _ => return Err(CoreError::Json("HELLO is malformed".into())),
1271    };
1272    let initiator = hello.get("from").and_then(|v| v.as_str()).unwrap_or("");
1273    if !policy.is_trusted(initiator) {
1274        return Err(CoreError::Json(format!(
1275            "peer {initiator} is not in this trust domain's policy"
1276        )));
1277    }
1278    if rv::time_ns(Some(&json!(params.valid_until))).is_none_or(|u| u <= now) {
1279        return Err(CoreError::Json(
1280            "valid_until must be a protocol time after created".into(),
1281        ));
1282    }
1283
1284    let offered: HashSet<&str> = params.offered_scope.iter().map(|s| s.as_str()).collect();
1285    let mut bounded: Vec<String> = proposed
1286        .into_iter()
1287        .filter(|s| offered.contains(s.as_str()))
1288        .collect::<HashSet<_>>()
1289        .into_iter()
1290        .collect();
1291    bounded.sort();
1292
1293    let mut accept = Map::new();
1294    accept.insert("type".into(), json!(ACCEPT));
1295    accept.insert("from".into(), json!(params.from_did));
1296    accept.insert("to".into(), json!(initiator));
1297    accept.insert("sessionId".into(), json!(params.session_id));
1298    accept.insert("nonce".into(), json!(nonce));
1299    accept.insert("boundedScope".into(), json!(bounded));
1300    accept.insert("issuedAt".into(), json!(params.created));
1301    accept.insert("validUntil".into(), json!(params.valid_until));
1302    let opts = BuildProofOptions::new(format!("{}#key-1", params.from_did), &params.created);
1303    data_integrity::sign(&Value::Object(accept), signer_seed, &opts)
1304}
1305
1306/// Verify B's ACCEPT against the HELLO that A sent (initiator A). The ACCEPT's
1307/// proof must be bound to its `from` DID; it must be addressed to A (`to` ==
1308/// the HELLO's `from`), come from the node the HELLO was addressed to (a HELLO
1309/// addressed to nobody needs a `policy` that trusts the responder), echo the
1310/// HELLO's nonce (and `expected_nonce` when given), carry a bounded scope that
1311/// is a subset of what A proposed, and not have expired at `now_iso`.
1312pub fn verify_accept(
1313    accept: &Value,
1314    accept_keys: Keys<'_>,
1315    hello: &Value,
1316    expected_nonce: Option<&str>,
1317    policy: Option<&TrustPolicy>,
1318    now_iso: &str,
1319) -> Result<Option<BoundedSession>> {
1320    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); accept, hello);
1321    verify_accept_with(
1322        accept,
1323        accept_keys,
1324        hello,
1325        expected_nonce,
1326        policy,
1327        HandshakeLimits::default(),
1328        now_iso,
1329    )
1330}
1331
1332/// [`verify_accept`] with the caller's [`HandshakeLimits`].
1333pub fn verify_accept_with(
1334    accept: &Value,
1335    accept_keys: Keys<'_>,
1336    hello: &Value,
1337    expected_nonce: Option<&str>,
1338    policy: Option<&TrustPolicy>,
1339    limits: HandshakeLimits,
1340    now_iso: &str,
1341) -> Result<Option<BoundedSession>> {
1342    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); accept, hello);
1343    limits.check()?;
1344    let now = rv::require_now(now_iso)?;
1345    if !hello.is_object() || !handshake_message_ok(accept, accept_keys, ACCEPT) {
1346        return Ok(None);
1347    }
1348    let responder = accept
1349        .get("from")
1350        .and_then(|v| v.as_str())
1351        .unwrap_or("")
1352        .to_string();
1353    if accept.get("to") != hello.get("from") {
1354        return Ok(None);
1355    }
1356    match hello.get("to") {
1357        Some(Value::String(t)) if *t != responder => return Ok(None),
1358        Some(Value::String(_)) => {}
1359        _ if policy.is_none() => return Ok(None),
1360        _ => {}
1361    }
1362    if let Some(p) = policy {
1363        if !p.is_trusted(&responder) {
1364            return Ok(None);
1365        }
1366    }
1367    let nonce = match accept.get("nonce").and_then(|v| v.as_str()) {
1368        Some(n) if Some(n) == hello.get("nonce").and_then(|v| v.as_str()) => n.to_string(),
1369        _ => return Ok(None),
1370    };
1371    if expected_nonce.is_some_and(|e| e != nonce) {
1372        return Ok(None);
1373    }
1374    let (bounded, proposed) = match (
1375        scope_list(accept.get("boundedScope")),
1376        scope_list(hello.get("proposedScope")),
1377    ) {
1378        (Some(b), Some(p)) if b.iter().all(|x| p.contains(x)) => (b, p),
1379        _ => return Ok(None),
1380    };
1381    let _ = proposed;
1382    let sid = match non_empty_str(accept, "sessionId") {
1383        Some(s) => s.to_string(),
1384        None => return Ok(None),
1385    };
1386    let session = BoundedSession {
1387        session_id: sid,
1388        initiator: accept
1389            .get("to")
1390            .and_then(|v| v.as_str())
1391            .unwrap_or("")
1392            .to_string(),
1393        responder,
1394        scope: bounded,
1395        nonce,
1396        valid_until: accept
1397            .get("validUntil")
1398            .and_then(|v| v.as_str())
1399            .map(String::from),
1400    };
1401    if !session.is_current(now_iso) {
1402        return Ok(None);
1403    }
1404    // issuedAt is required: no older than the HELLO age limit, not ahead of
1405    // the clock beyond the skew, and the session it grants is bounded.
1406    if !issued_recently(
1407        accept.get("issuedAt"),
1408        now,
1409        limits.clock_skew_seconds,
1410        limits.max_age_seconds,
1411    ) {
1412        return Ok(None);
1413    }
1414    match (
1415        rv::time_ns(accept.get("issuedAt")),
1416        rv::time_ns(accept.get("validUntil")),
1417    ) {
1418        (Some(i), Some(u))
1419            if u > i && u - i <= i128::from(limits.max_session_seconds) * 1_000_000_000 => {}
1420        _ => return Ok(None),
1421    }
1422    Ok(Some(session))
1423}
1424
1425/// Sign A's confirmation of the bounded session to B. Refuses an expired
1426/// session (checked at `created`).
1427pub fn build_confirm(
1428    signer_seed: &[u8],
1429    from_did: &str,
1430    session: &BoundedSession,
1431    created: &str,
1432) -> Result<Value> {
1433    rv::require_now(created)?;
1434    if !session.is_current(created) {
1435        return Err(CoreError::Json("the session has expired".into()));
1436    }
1437    let mut confirm = Map::new();
1438    confirm.insert("type".into(), json!(CONFIRM));
1439    confirm.insert("from".into(), json!(from_did));
1440    confirm.insert("to".into(), json!(session.responder));
1441    confirm.insert("sessionId".into(), json!(session.session_id));
1442    confirm.insert("nonce".into(), json!(session.nonce));
1443    confirm.insert("acceptedScope".into(), json!(session.scope));
1444    let opts = BuildProofOptions::new(format!("{from_did}#key-1"), created);
1445    data_integrity::sign(&Value::Object(confirm), signer_seed, &opts)
1446}
1447
1448/// Verify A's CONFIRM closes the session B accepted (responder B). `accept` is
1449/// the ACCEPT B sent. The CONFIRM's proof must be bound to its `from` DID,
1450/// which must be the initiator (the ACCEPT's `to`); it must be addressed to
1451/// B, name the same session and nonce, accept a scope within the bounded
1452/// scope, and arrive while the session is still valid at `now_iso`.
1453pub fn verify_confirm(
1454    confirm: &Value,
1455    confirm_keys: Keys<'_>,
1456    accept: &Value,
1457    now_iso: &str,
1458) -> Result<bool> {
1459    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); confirm, accept);
1460    let now = rv::require_now(now_iso)?;
1461    if !accept.is_object() || !handshake_message_ok(confirm, confirm_keys, CONFIRM) {
1462        return Ok(false);
1463    }
1464    if confirm.get("from") != accept.get("to") || confirm.get("to") != accept.get("from") {
1465        return Ok(false);
1466    }
1467    if confirm.get("sessionId") != accept.get("sessionId")
1468        || confirm.get("nonce") != accept.get("nonce")
1469    {
1470        return Ok(false);
1471    }
1472    match (
1473        scope_list(confirm.get("acceptedScope")),
1474        scope_list(accept.get("boundedScope")),
1475    ) {
1476        (Some(a), Some(b)) if a.iter().all(|x| b.contains(x)) => {}
1477        _ => return Ok(false),
1478    }
1479    Ok(rv::time_ns(accept.get("validUntil")).is_some_and(|u| now <= u))
1480}
1481
1482// ---------------------------------------------------------------------------
1483// Black box and kill switch (Phase 5.5)
1484// ---------------------------------------------------------------------------
1485
1486/// Version 1.1 entries bind their header (every field but the ciphertext and
1487/// the hash) into AES-GCM as associated data; 1.0 entries do not.
1488pub const BLACKBOX_VERSION: &str = "1.1";
1489/// The pre-1.1 entry version, still opened (without associated data).
1490pub const BLACKBOX_LEGACY_VERSION: &str = "1.0";
1491/// A signed black-box head: entry count plus last hash.
1492pub const BLACKBOX_HEAD_TYPE: &str = "BlackBoxHeadCredential";
1493/// Size cap for a log handed to a verifier (before canonicalization).
1494pub const MAX_LOG_BYTES: usize = 64 * 1024 * 1024;
1495pub const KILLSWITCH_TYPE: &str = "KillSwitchCredential";
1496pub const EMERGENCY_STOP: &str = "emergency_stop";
1497
1498/// The prevHash of the first entry: multibase of 32 zero bytes.
1499pub fn genesis_prev_hash() -> String {
1500    mb64(&[0u8; 32])
1501}
1502
1503/// The entry header bound into AES-GCM: JCS of every field but the ciphertext
1504/// and the entry hash.
1505fn entry_aad(entry: &Map<String, Value>) -> Vec<u8> {
1506    let mut header = entry.clone();
1507    header.remove("ciphertext");
1508    header.remove("entryHash");
1509    jcs::canonicalize(&Value::Object(header))
1510}
1511
1512fn entry_hash(body: &Map<String, Value>) -> Result<String> {
1513    let mut clean = body.clone();
1514    clean.remove("entryHash");
1515    let canonical = jcs::canonicalize(&Value::Object(clean));
1516    Ok(mb64(&Sha256::digest(canonical)))
1517}
1518
1519/// Build one black-box entry statelessly: encrypt `payload` under `key`, link it
1520/// to `prev_hash` at `seq`, and return the entry with its `entryHash`. The
1521/// stateful [`BlackBoxLog`] and the FFI layer both build on this. The encrypted
1522/// blob is nonce(12) || ciphertext || tag(16).
1523pub fn blackbox_append_entry(
1524    key: &[u8],
1525    seq: u64,
1526    event: &str,
1527    payload: &Value,
1528    timestamp: &str,
1529    prev_hash: &str,
1530) -> Result<Value> {
1531    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); payload);
1532    blackbox_append_entry_with_nonce(key, seq, event, payload, timestamp, prev_hash, None)
1533}
1534
1535/// [`blackbox_append_entry`] with the host's own 12-byte AES-GCM nonce (a
1536/// host with its own random source or a secure element). A nonce must never
1537/// be used twice under one key; without one the core draws a random nonce.
1538pub fn blackbox_append_entry_with_nonce(
1539    key: &[u8],
1540    seq: u64,
1541    event: &str,
1542    payload: &Value,
1543    timestamp: &str,
1544    prev_hash: &str,
1545    host_nonce: Option<&[u8]>,
1546) -> Result<Value> {
1547    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); payload);
1548    if key.len() != 32 {
1549        return Err(CoreError::Crypto(
1550            "black box key must be 32 bytes (AES-256)".into(),
1551        ));
1552    }
1553    let mut nonce = [0u8; 12];
1554    match host_nonce {
1555        Some(n) if n.len() == 12 => nonce.copy_from_slice(n),
1556        Some(_) => return Err(CoreError::Crypto("black box nonce must be 12 bytes".into())),
1557        None => {
1558            crate::random::fill(&mut nonce).map_err(|e| CoreError::Crypto(format!("rng: {e}")))?
1559        }
1560    }
1561    let plaintext = jcs::canonicalize(payload);
1562    let mut body = Map::new();
1563    body.insert("version".into(), json!(BLACKBOX_VERSION));
1564    body.insert("seq".into(), json!(seq));
1565    body.insert("timestamp".into(), json!(timestamp));
1566    body.insert("event".into(), json!(event));
1567    body.insert("prevHash".into(), json!(prev_hash));
1568    let aad = entry_aad(&body);
1569    let cipher =
1570        Aes256Gcm::new_from_slice(key).map_err(|e| CoreError::Crypto(format!("aes key: {e}")))?;
1571    let ct = cipher
1572        .encrypt(
1573            Nonce::from_slice(&nonce),
1574            Payload {
1575                msg: plaintext.as_ref(),
1576                aad: &aad,
1577            },
1578        )
1579        .map_err(|e| CoreError::Crypto(format!("encrypt: {e}")))?;
1580    let mut blob = Vec::with_capacity(nonce.len() + ct.len());
1581    blob.extend_from_slice(&nonce);
1582    blob.extend_from_slice(&ct);
1583    body.insert("ciphertext".into(), json!(mb64(&blob)));
1584    let h = entry_hash(&body)?;
1585    body.insert("entryHash".into(), json!(h));
1586    Ok(Value::Object(body))
1587}
1588
1589/// An append-only, AES-256-GCM-encrypted, JCS hash-linked event log. The key is
1590/// 32 bytes. The encrypted blob is nonce(12) || ciphertext || tag(16), matching
1591/// Python, TypeScript, and Go.
1592pub struct BlackBoxLog {
1593    key: Vec<u8>,
1594    genesis: String,
1595    entries: Vec<Value>,
1596    head: String,
1597}
1598
1599impl BlackBoxLog {
1600    /// Build a log. A `None` genesis uses [`genesis_prev_hash`].
1601    pub fn new(key: &[u8], genesis_prev_hash_override: Option<&str>) -> Result<Self> {
1602        if key.len() != 32 {
1603            return Err(CoreError::Crypto(
1604                "black box key must be 32 bytes (AES-256)".into(),
1605            ));
1606        }
1607        let genesis = genesis_prev_hash_override
1608            .map(String::from)
1609            .unwrap_or_else(genesis_prev_hash);
1610        Ok(Self {
1611            key: key.to_vec(),
1612            head: genesis.clone(),
1613            genesis,
1614            entries: Vec::new(),
1615        })
1616    }
1617
1618    /// Encrypt `payload`, link it to the chain head, and return the new entry.
1619    pub fn append(&mut self, event: &str, payload: &Value, timestamp: &str) -> Result<Value> {
1620        crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); payload);
1621        let entry = blackbox_append_entry(
1622            &self.key,
1623            self.entries.len() as u64,
1624            event,
1625            payload,
1626            timestamp,
1627            &self.head,
1628        )?;
1629        self.head = entry
1630            .get("entryHash")
1631            .and_then(|v| v.as_str())
1632            .unwrap_or("")
1633            .to_string();
1634        self.entries.push(entry.clone());
1635        Ok(entry)
1636    }
1637
1638    pub fn head(&self) -> &str {
1639        &self.head
1640    }
1641
1642    pub fn genesis(&self) -> &str {
1643        &self.genesis
1644    }
1645
1646    pub fn entries(&self) -> &[Value] {
1647        &self.entries
1648    }
1649
1650    /// The number of entries, the count a signed head carries.
1651    pub fn count(&self) -> usize {
1652        self.entries.len()
1653    }
1654
1655    pub fn open(&self, entry: &Value) -> Result<Value> {
1656        crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); entry);
1657        open_entry(entry, &self.key)
1658    }
1659}
1660
1661/// Decrypt a black-box entry payload with the log key.
1662pub fn open_entry(entry: &Value, key: &[u8]) -> Result<Value> {
1663    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); entry);
1664    let obj = entry
1665        .as_object()
1666        .ok_or_else(|| CoreError::Json("entry has no ciphertext".into()))?;
1667    let ct_mb = obj
1668        .get("ciphertext")
1669        .and_then(|v| v.as_str())
1670        .ok_or_else(|| CoreError::Json("entry has no ciphertext".into()))?;
1671    // 1.1 entries open with their header as associated data, so a changed
1672    // label, time, sequence number or link fails to decrypt. 1.0 entries were
1673    // written before the header was bound and open without it.
1674    let aad = match obj.get("version").and_then(|v| v.as_str()) {
1675        Some(BLACKBOX_VERSION) => entry_aad(obj),
1676        Some(BLACKBOX_LEGACY_VERSION) => Vec::new(),
1677        other => {
1678            return Err(CoreError::Json(format!(
1679                "unsupported black-box entry version {other:?}"
1680            )))
1681        }
1682    };
1683    let blob = unmb64(ct_mb)?;
1684    if blob.len() < 12 + 16 {
1685        return Err(CoreError::Crypto("ciphertext too short".into()));
1686    }
1687    let cipher =
1688        Aes256Gcm::new_from_slice(key).map_err(|e| CoreError::Crypto(format!("aes key: {e}")))?;
1689    let (nonce, rest) = blob.split_at(12);
1690    let pt = cipher
1691        .decrypt(
1692            Nonce::from_slice(nonce),
1693            Payload {
1694                msg: rest,
1695                aad: &aad,
1696            },
1697        )
1698        .map_err(|_| CoreError::Crypto("decryption failed".into()))?;
1699    crate::nesting::check_text(&pt)?;
1700    serde_json::from_slice(&pt).map_err(|e| CoreError::Json(format!("payload decode: {e}")))
1701}
1702
1703/// The outcome of [`verify_blackbox_chain`].
1704#[derive(Debug, Clone)]
1705pub struct ChainResult {
1706    pub ok: bool,
1707    pub reason: Option<String>,
1708}
1709
1710/// Verify the hash chain over the (still-encrypted) entries. Tamper-evident
1711/// without the key. A `None` genesis uses [`genesis_prev_hash`].
1712pub fn verify_blackbox_chain(
1713    entries: &[Value],
1714    genesis_prev_hash_override: Option<&str>,
1715) -> ChainResult {
1716    crate::nesting::deep_guard!(ChainResult { ok: false, reason: Some(crate::nesting::TOO_DEEP.into()) }; entries);
1717    verify_blackbox_chain_capped(entries, genesis_prev_hash_override, MAX_LOG_BYTES)
1718}
1719
1720/// [`verify_blackbox_chain`] with the host's size limit for the log.
1721pub fn verify_blackbox_chain_capped(
1722    entries: &[Value],
1723    genesis_prev_hash_override: Option<&str>,
1724    max_bytes: usize,
1725) -> ChainResult {
1726    crate::nesting::deep_guard!(ChainResult { ok: false, reason: Some(crate::nesting::TOO_DEEP.into()) }; entries);
1727    let mut progress = ChainProgress::start(genesis_prev_hash_override);
1728    verify_chain_segment(&mut progress, entries, max_bytes);
1729    progress.result()
1730}
1731
1732/// Where a hash-chain check stands after the first entries of a log: the
1733/// number the next entry must carry, the hash it must link to, and the first
1734/// failure. A long log is checked one segment at a time by passing this from
1735/// one [`verify_chain_segment`] call to the next, so memory stays bounded by
1736/// one segment however long the log is. The verdict is the one
1737/// [`verify_blackbox_chain`] gives for the whole log.
1738#[derive(Debug, Clone, PartialEq, Eq)]
1739pub struct ChainProgress {
1740    /// The prevHash of entry 0.
1741    pub genesis: String,
1742    /// The number of entries checked so far (the next entry's seq).
1743    pub next_seq: u64,
1744    /// The entryHash of the last entry checked, or the genesis.
1745    pub last_hash: String,
1746    /// The first failure; once set, later segments are not read.
1747    pub failure: Option<String>,
1748}
1749
1750impl ChainProgress {
1751    /// The start of a log. A `None` genesis uses [`genesis_prev_hash`].
1752    pub fn start(genesis_prev_hash_override: Option<&str>) -> Self {
1753        let genesis = genesis_prev_hash_override
1754            .map(String::from)
1755            .unwrap_or_else(genesis_prev_hash);
1756        Self {
1757            last_hash: genesis.clone(),
1758            genesis,
1759            next_seq: 0,
1760            failure: None,
1761        }
1762    }
1763
1764    /// The verdict over every entry checked so far.
1765    pub fn result(&self) -> ChainResult {
1766        ChainResult {
1767            ok: self.failure.is_none(),
1768            reason: self.failure.clone(),
1769        }
1770    }
1771}
1772
1773/// The reason a segment of log entries nests too deeply or is larger than
1774/// `max_bytes`, measured as [`rv::input_too_large`] measures the same entries
1775/// in one list, without copying them.
1776fn entries_too_large(entries: &[Value], max_bytes: usize) -> Option<String> {
1777    use crate::attenuation::json_nesting_exceeds;
1778    if entries
1779        .iter()
1780        .any(|e| json_nesting_exceeds(e, rv::MAX_NESTING - 1))
1781    {
1782        return Some(format!("input nests more than {} levels", rv::MAX_NESTING));
1783    }
1784    let mut total = 2 + entries.len();
1785    for e in entries {
1786        if total > max_bytes {
1787            break;
1788        }
1789        total += rv::approx_size(e, max_bytes - total);
1790    }
1791    if total > max_bytes {
1792        return Some(format!("input larger than {max_bytes} bytes"));
1793    }
1794    None
1795}
1796
1797/// Check the next `entries` of a log (one segment) and move `progress` past
1798/// them. Every hash-linked log (black box, safety ledger, perception log)
1799/// verifies through here, whole or in segments.
1800pub fn verify_chain_segment(progress: &mut ChainProgress, entries: &[Value], max_bytes: usize) {
1801    #[cfg(not(feature = "std"))]
1802    if crate::nesting::Nested::nests_past(&entries, crate::nesting::NO_STD_MAX_NESTING) {
1803        progress
1804            .failure
1805            .get_or_insert_with(|| crate::nesting::TOO_DEEP.into());
1806        return;
1807    }
1808    #[cfg(not(feature = "std"))]
1809    if crate::nesting::Nested::nests_past(&entries, crate::nesting::NO_STD_MAX_NESTING) {
1810        progress
1811            .failure
1812            .get_or_insert_with(|| crate::nesting::TOO_DEEP.into());
1813        return;
1814    }
1815    if progress.failure.is_some() {
1816        return;
1817    }
1818    if let Some(big) = entries_too_large(entries, max_bytes) {
1819        progress.failure = Some(big);
1820        return;
1821    }
1822    for entry in entries {
1823        let i = progress.next_seq;
1824        let obj = match entry.as_object() {
1825            Some(o) => o,
1826            None => {
1827                progress.failure = Some(format!("entry {i} is not an object"));
1828                return;
1829            }
1830        };
1831        if entry.get("seq").and_then(|v| v.as_u64()) != Some(i) {
1832            progress.failure = Some(format!("entry {i} seq mismatch"));
1833            return;
1834        }
1835        if entry.get("prevHash").and_then(|v| v.as_str()).unwrap_or("") != progress.last_hash {
1836            progress.failure = Some(format!("entry {i} prevHash does not link"));
1837            return;
1838        }
1839        let want = match entry_hash(obj) {
1840            Ok(w) => w,
1841            Err(_) => {
1842                progress.failure = Some(format!("entry {i} hash error"));
1843                return;
1844            }
1845        };
1846        let eh = entry
1847            .get("entryHash")
1848            .and_then(|v| v.as_str())
1849            .unwrap_or("");
1850        if eh != want {
1851            progress.failure = Some(format!("entry {i} entryHash mismatch (tampered)"));
1852            return;
1853        }
1854        // A resumed state can carry any number; one past u64::MAX is no seq.
1855        let Some(next) = progress.next_seq.checked_add(1) else {
1856            progress.failure = Some(format!("entry {i} seq mismatch"));
1857            return;
1858        };
1859        progress.last_hash = want;
1860        progress.next_seq = next;
1861    }
1862}
1863
1864/// The end of a segmented check against a signed head: the same verdict
1865/// [`verify_chain_against_head`] gives for the whole log.
1866pub fn finish_chain_against_head(
1867    progress: &ChainProgress,
1868    head: Option<&Value>,
1869    count: Option<&Value>,
1870) -> ChainResult {
1871    crate::nesting::deep_guard!(ChainResult { ok: false, reason: Some(crate::nesting::TOO_DEEP.into()) }; head, count);
1872    if progress.failure.is_some() {
1873        return progress.result();
1874    }
1875    let fail = |r: String| ChainResult {
1876        ok: false,
1877        reason: Some(r),
1878    };
1879    let n = match count.and_then(|c| rv::strict_int(Some(c))) {
1880        Some(n) if n >= 0 => n,
1881        _ => return fail("anchored count is not a non-negative integer".into()),
1882    };
1883    if i128::from(progress.next_seq) != i128::from(n) {
1884        return fail(format!(
1885            "log has {} entries, the signed head says {n}",
1886            progress.next_seq
1887        ));
1888    }
1889    if head.and_then(|h| h.as_str()) != Some(progress.last_hash.as_str()) {
1890        return fail("log does not end at the signed head".into());
1891    }
1892    ChainResult {
1893        ok: true,
1894        reason: None,
1895    }
1896}
1897
1898/// Parameters for [`build_killswitch_credential`].
1899#[derive(Debug, Clone, Default)]
1900pub struct BuildKillswitch {
1901    pub issuer_did: String,
1902    pub target: String,
1903    pub reason: String,
1904    pub command: Option<String>,
1905    pub scope: Option<Vec<String>>,
1906    pub valid_from: String,
1907    pub valid_until: Option<String>,
1908}
1909
1910/// Build a signed `KillSwitchCredential` proving who issued an emergency stop.
1911pub fn build_killswitch_credential(
1912    authority_seed: &[u8],
1913    params: &BuildKillswitch,
1914) -> Result<Value> {
1915    let command = params
1916        .command
1917        .clone()
1918        .unwrap_or_else(|| EMERGENCY_STOP.to_string());
1919    let mut subject = Map::new();
1920    subject.insert("id".into(), json!(params.target));
1921    subject.insert("command".into(), json!(command));
1922    subject.insert("reason".into(), json!(params.reason));
1923    subject.insert("issuedBy".into(), json!(params.issuer_did));
1924    if let Some(scope) = &params.scope {
1925        subject.insert("scope".into(), json!(scope));
1926    }
1927
1928    let mut cred = Map::new();
1929    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
1930    cred.insert(
1931        "type".into(),
1932        json!(["VerifiableCredential", KILLSWITCH_TYPE]),
1933    );
1934    cred.insert("issuer".into(), json!(params.issuer_did));
1935    cred.insert("validFrom".into(), json!(params.valid_from));
1936    if let Some(vu) = &params.valid_until {
1937        cred.insert("validUntil".into(), json!(vu));
1938    }
1939    cred.insert("credentialSubject".into(), Value::Object(subject));
1940
1941    let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), &params.valid_from);
1942    data_integrity::sign(&Value::Object(cred), authority_seed, &opts)
1943}
1944
1945/// Verify a `KillSwitchCredential`. When `trusted_authorities` is supplied, the
1946/// issuer DID MUST be in it. Returns the subject on success.
1947pub fn verify_killswitch_credential(
1948    credential: &Value,
1949    keys: Keys<'_>,
1950    trusted_authorities: Option<&HashSet<String>>,
1951    now_iso: &str,
1952) -> Result<Option<Value>> {
1953    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
1954    let now = rv::require_now(now_iso)?;
1955    let opts = VerifyOptions {
1956        trusted_issuers: trusted_authorities,
1957        ..VerifyOptions::window(Window::FromRequired)
1958    };
1959    let v = match rv::verify_robotics_credential(credential, keys, Some(KILLSWITCH_TYPE), now, opts)
1960    {
1961        Ok(v) => v,
1962        Err(_) => return Ok(None),
1963    };
1964    // issuedBy, when present, must be the bound issuer.
1965    if let Some(by) = v.subject.get("issuedBy") {
1966        if by.as_str() != Some(v.issuer.as_str()) {
1967            return Ok(None);
1968        }
1969    }
1970    Ok(Some(v.subject))
1971}
1972
1973/// Verify the hash links AND that the log ends at a known head: `head` and
1974/// `count` come from something signed (a head credential, a safety-record
1975/// summary, a perception attestation). A log cut short, extended or rebuilt
1976/// does not end at that head with that many entries.
1977pub fn verify_chain_against_head(
1978    entries: &[Value],
1979    head: Option<&Value>,
1980    count: Option<&Value>,
1981    genesis_prev_hash_override: Option<&str>,
1982) -> ChainResult {
1983    crate::nesting::deep_guard!(ChainResult { ok: false, reason: Some(crate::nesting::TOO_DEEP.into()) }; entries, head, count);
1984    verify_chain_against_head_capped(
1985        entries,
1986        head,
1987        count,
1988        genesis_prev_hash_override,
1989        MAX_LOG_BYTES,
1990    )
1991}
1992
1993/// [`verify_chain_against_head`] with the host's size limit for the log.
1994pub fn verify_chain_against_head_capped(
1995    entries: &[Value],
1996    head: Option<&Value>,
1997    count: Option<&Value>,
1998    genesis_prev_hash_override: Option<&str>,
1999    max_bytes: usize,
2000) -> ChainResult {
2001    crate::nesting::deep_guard!(ChainResult { ok: false, reason: Some(crate::nesting::TOO_DEEP.into()) }; entries, head, count);
2002    let mut progress = ChainProgress::start(genesis_prev_hash_override);
2003    verify_chain_segment(&mut progress, entries, max_bytes);
2004    finish_chain_against_head(&progress, head, count)
2005}
2006
2007/// Sign the head of a black-box log (entry count plus last hash). The robot is
2008/// the issuer and the subject.
2009pub fn build_blackbox_head(
2010    robot_seed: &[u8],
2011    robot_did: &str,
2012    head: &str,
2013    entry_count: u64,
2014    valid_from: &str,
2015    valid_until: Option<&str>,
2016) -> Result<Value> {
2017    let mut cred = Map::new();
2018    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
2019    cred.insert(
2020        "type".into(),
2021        json!(["VerifiableCredential", BLACKBOX_HEAD_TYPE]),
2022    );
2023    cred.insert("issuer".into(), json!(robot_did));
2024    cred.insert("validFrom".into(), json!(valid_from));
2025    if let Some(vu) = valid_until {
2026        cred.insert("validUntil".into(), json!(vu));
2027    }
2028    cred.insert(
2029        "credentialSubject".into(),
2030        json!({"id": robot_did, "logHead": head, "entryCount": entry_count}),
2031    );
2032    let opts = BuildProofOptions::new(format!("{robot_did}#key-1"), valid_from);
2033    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
2034}
2035
2036/// Verify a log against the robot's signed head: the head credential must
2037/// verify bound to the robot as issuer and subject, and the log must link and
2038/// end at the signed head with exactly the signed number of entries.
2039pub fn verify_blackbox_head(
2040    credential: &Value,
2041    robot_keys: Keys<'_>,
2042    entries: &[Value],
2043    genesis_prev_hash_override: Option<&str>,
2044    now_iso: &str,
2045) -> Result<ChainResult> {
2046    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, entries);
2047    let mut progress = ChainProgress::start(genesis_prev_hash_override);
2048    verify_chain_segment(&mut progress, entries, MAX_LOG_BYTES);
2049    finish_chain_against_head_credential(credential, robot_keys, &progress, now_iso)
2050}
2051
2052/// The end of a segmented check against the robot's signed head credential:
2053/// the same verdict [`verify_blackbox_head`] gives for the whole log.
2054pub fn finish_chain_against_head_credential(
2055    credential: &Value,
2056    robot_keys: Keys<'_>,
2057    progress: &ChainProgress,
2058    now_iso: &str,
2059) -> Result<ChainResult> {
2060    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
2061    let now = rv::require_now(now_iso)?;
2062    let v = match rv::verify_robotics_credential(
2063        credential,
2064        robot_keys,
2065        Some(BLACKBOX_HEAD_TYPE),
2066        now,
2067        VerifyOptions::window(Window::FromRequired),
2068    ) {
2069        Ok(v) => v,
2070        Err(r) => {
2071            return Ok(ChainResult {
2072                ok: false,
2073                reason: Some(r),
2074            })
2075        }
2076    };
2077    if !issuer_is_subject(&v) {
2078        return Ok(ChainResult {
2079            ok: false,
2080            reason: Some("head is not issued by the robot it describes".into()),
2081        });
2082    }
2083    Ok(finish_chain_against_head(
2084        progress,
2085        v.subject.get("logHead"),
2086        v.subject.get("entryCount"),
2087    ))
2088}
2089
2090// ---------------------------------------------------------------------------
2091// Halos safety-evidence recorder (NVIDIA Halos integration)
2092// ---------------------------------------------------------------------------
2093//
2094// Byte-exact port of the Python reference `vouch/robotics/halos.py`.
2095//
2096// Halos certifies that a robot's stack is functionally safe and secure by design.
2097// It does not, on its own, produce a verifiable record of what a specific robot
2098// did or bind that record to the robot's identity. This is the evidence layer
2099// under a Halos-certified stack: the robot seals its black-box chain head and
2100// entry count into a signed `HalosSafetyEvidenceCredential` that binds them to its
2101// identity, to the Halos stack elements it ran on, and to a time window. A
2102// verifier that holds the credential and the entries confirms, without the
2103// black-box key, that the record is unaltered, was not truncated or extended since
2104// it was sealed, and is attributable to that robot. This composes the existing
2105// black-box and credential primitives and adds no new cryptography.
2106
2107pub const HALOS_SAFETY_EVIDENCE_TYPE: &str = "HalosSafetyEvidenceCredential";
2108
2109/// Format Unix epoch seconds as "YYYY-MM-DDTHH:MM:SSZ" for a whole-second UTC
2110/// instant. Howard Hinnant's civil-from-days algorithm, matching the rest of the
2111/// core so a `valid_seconds` lifetime renders identically across languages.
2112fn halos_epoch_to_iso(epoch: i64) -> String {
2113    let days = epoch.div_euclid(86400);
2114    let secs = epoch.rem_euclid(86400);
2115    let z = days + 719468;
2116    let era = (if z >= 0 { z } else { z - 146096 }) / 146097;
2117    let doe = z - era * 146097;
2118    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
2119    let y = yoe + era * 400;
2120    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
2121    let mp = (5 * doy + 2) / 153;
2122    let d = doy - (153 * mp + 2) / 5 + 1;
2123    let m = if mp < 10 { mp + 3 } else { mp - 9 };
2124    let year = if m <= 2 { y + 1 } else { y };
2125    let hh = secs / 3600;
2126    let mm = (secs % 3600) / 60;
2127    let ss = secs % 60;
2128    format!("{year:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}Z")
2129}
2130
2131/// Parameters for [`build_safety_evidence`]. The robot DID is derived from
2132/// `signer_seed` (a did:key), mirroring the Python signer. `blackbox_head` and
2133/// `entry_count` seal the robot's black-box chain; `halos_stack` names the
2134/// certified configuration; `window` covers the recorded events. Timestamps are
2135/// caller-supplied ISO-8601 strings.
2136#[derive(Debug, Clone)]
2137pub struct BuildSafetyEvidence {
2138    pub halos_stack: Value,
2139    pub window_from: String,
2140    pub window_to: String,
2141    pub blackbox_head: String,
2142    pub entry_count: u64,
2143    pub robot_identity: Option<String>,
2144    pub valid_seconds: Option<i64>,
2145    pub valid_from: String,
2146    pub created: String,
2147    /// The robot's DID, when it is not the did:key of the signing key (a
2148    /// did:web robot); without it the issuer is that did:key.
2149    pub robot_did: Option<String>,
2150}
2151
2152/// Seal a robot's Halos safety-event record into a signed
2153/// `HalosSafetyEvidenceCredential`. The robot signs a credential binding the
2154/// black-box chain head and entry count to its identity, to the Halos stack
2155/// elements it ran on, and to the time window.
2156pub fn build_safety_evidence(signer_seed: &[u8], params: &BuildSafetyEvidence) -> Result<Value> {
2157    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
2158    match params.halos_stack.as_object() {
2159        Some(o) if !o.is_empty() => {}
2160        _ => return Err(CoreError::Json("halos_stack is required".into())),
2161    }
2162    if params.window_from.is_empty() || params.window_to.is_empty() {
2163        return Err(CoreError::Json(
2164            "window with 'from' and 'to' is required".into(),
2165        ));
2166    }
2167
2168    let robot_did = match params.robot_did.as_deref().filter(|d| !d.is_empty()) {
2169        Some(d) if d.starts_with("did:") => d.to_string(),
2170        Some(_) => return Err(CoreError::Json("robot_did must be a DID".into())),
2171        None => {
2172            let kp = keys::Ed25519KeyPair::from_seed_slice(signer_seed)?;
2173            keys::ed25519_to_did_key(&kp.public_key())?
2174        }
2175    };
2176
2177    let mut subject = Map::new();
2178    subject.insert("id".into(), json!(robot_did));
2179    subject.insert("blackboxHead".into(), json!(params.blackbox_head));
2180    subject.insert("entryCount".into(), json!(params.entry_count));
2181    subject.insert("halosStack".into(), params.halos_stack.clone());
2182    subject.insert(
2183        "window".into(),
2184        json!({ "from": params.window_from, "to": params.window_to }),
2185    );
2186    if let Some(robot_identity) = &params.robot_identity {
2187        subject.insert("robotIdentity".into(), json!(robot_identity));
2188    }
2189
2190    let mut cred = Map::new();
2191    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
2192    cred.insert(
2193        "type".into(),
2194        json!(["VerifiableCredential", HALOS_SAFETY_EVIDENCE_TYPE]),
2195    );
2196    cred.insert("issuer".into(), json!(robot_did));
2197    cred.insert("validFrom".into(), json!(params.valid_from));
2198    if let Some(valid_seconds) = params.valid_seconds {
2199        let from = crate::time::iso_to_epoch_seconds(&params.valid_from)?;
2200        cred.insert(
2201            "validUntil".into(),
2202            json!(halos_epoch_to_iso(from + valid_seconds)),
2203        );
2204    }
2205    cred.insert("credentialSubject".into(), Value::Object(subject));
2206
2207    let opts = BuildProofOptions::new(format!("{robot_did}#key-1"), &params.created);
2208    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
2209}
2210
2211/// Verify a `HalosSafetyEvidenceCredential`: the robot's proof and that the issuer
2212/// is the robot (`credentialSubject.id`). When `entries` is supplied, also checks
2213/// that the black-box chain is intact, that its length matches the sealed entry
2214/// count, and that its head matches the sealed head, so a truncated, extended,
2215/// reordered, or tampered record is rejected. Returns `(ok, credentialSubject)`.
2216pub fn verify_safety_evidence(
2217    credential: &Value,
2218    robot_keys: Keys<'_>,
2219    entries: Option<&[Value]>,
2220    now_iso: &str,
2221) -> Result<(bool, Option<Value>)> {
2222    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, entries);
2223    let v = match bound(
2224        credential,
2225        robot_keys,
2226        HALOS_SAFETY_EVIDENCE_TYPE,
2227        now_iso,
2228        Window::FromRequired,
2229    )? {
2230        Some(v) if issuer_is_subject(&v) => v,
2231        _ => return Ok((false, None)),
2232    };
2233    let subject = v.subject;
2234    let count = match rv::strict_int(subject.get("entryCount")) {
2235        Some(n) if n >= 0 => n,
2236        _ => return Ok((false, None)),
2237    };
2238
2239    if let Some(entries) = entries {
2240        if !verify_blackbox_chain(entries, None).ok {
2241            return Ok((false, None));
2242        }
2243        if count != entries.len() as i64 {
2244            return Ok((false, None));
2245        }
2246        let head = match entries.last() {
2247            Some(last) => last
2248                .get("entryHash")
2249                .and_then(|v| v.as_str())
2250                .unwrap_or("")
2251                .to_string(),
2252            None => genesis_prev_hash(),
2253        };
2254        if Some(head.as_str()) != subject.get("blackboxHead").and_then(|v| v.as_str()) {
2255            return Ok((false, None));
2256        }
2257    }
2258
2259    Ok((true, Some(subject)))
2260}
2261
2262// ---------------------------------------------------------------------------
2263// Scannable robot passport (Phase 5.6)
2264// ---------------------------------------------------------------------------
2265
2266pub const ROBOT_PASSPORT_TYPE: &str = "RobotPassport";
2267pub const PASSPORT_URI_SCHEME: &str = "vouch-passport:";
2268pub const STATUS_ACTIVE: &str = "active";
2269pub const STATUS_SUSPENDED: &str = "suspended";
2270pub const STATUS_DECOMMISSIONED: &str = "decommissioned";
2271
2272/// Parameters for [`build_passport`]. The issuer is the signer (the robot or an
2273/// authority); `robot_did` is the robot the passport describes.
2274#[derive(Debug, Clone, Default)]
2275pub struct BuildPassport {
2276    pub issuer_did: String,
2277    pub robot_did: String,
2278    pub make: String,
2279    pub model: String,
2280    pub owner: String,
2281    pub authorized_actions: Vec<String>,
2282    pub certification: Option<String>,
2283    pub status: Option<String>,
2284    pub valid_from: String,
2285    pub valid_until: Option<String>,
2286}
2287
2288/// Build a signed `RobotPassport` credential.
2289pub fn build_passport(signer_seed: &[u8], params: &BuildPassport) -> Result<Value> {
2290    let status = params
2291        .status
2292        .clone()
2293        .unwrap_or_else(|| STATUS_ACTIVE.to_string());
2294    let mut subject = Map::new();
2295    subject.insert("id".into(), json!(params.robot_did));
2296    subject.insert("make".into(), json!(params.make));
2297    subject.insert("model".into(), json!(params.model));
2298    subject.insert("owner".into(), json!(params.owner));
2299    subject.insert("authorizedActions".into(), json!(params.authorized_actions));
2300    subject.insert("status".into(), json!(status));
2301    if let Some(c) = &params.certification {
2302        subject.insert("certification".into(), json!(c));
2303    }
2304
2305    let mut cred = Map::new();
2306    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
2307    cred.insert(
2308        "type".into(),
2309        json!(["VerifiableCredential", ROBOT_PASSPORT_TYPE]),
2310    );
2311    cred.insert("issuer".into(), json!(params.issuer_did));
2312    cred.insert("validFrom".into(), json!(params.valid_from));
2313    if let Some(vu) = &params.valid_until {
2314        cred.insert("validUntil".into(), json!(vu));
2315    }
2316    cred.insert("credentialSubject".into(), Value::Object(subject));
2317
2318    let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), &params.valid_from);
2319    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
2320}
2321
2322/// Encode a passport into a compact `vouch-passport:` URI for a QR or NFC tag.
2323pub fn encode_passport(passport: &Value) -> String {
2324    format!(
2325        "{}{}",
2326        PASSPORT_URI_SCHEME,
2327        mb64(&jcs::canonicalize(passport))
2328    )
2329}
2330
2331/// Decode a `vouch-passport:` URI back into the passport credential.
2332pub fn decode_passport(uri: &str) -> Result<Value> {
2333    let body = uri
2334        .strip_prefix(PASSPORT_URI_SCHEME)
2335        .ok_or_else(|| CoreError::Json(format!("not a {PASSPORT_URI_SCHEME} URI")))?;
2336    if body.len() > 2 * rv::MAX_CREDENTIAL_BYTES {
2337        return Err(CoreError::Json("passport URI too large".into()));
2338    }
2339    let raw = unmb64(body)?;
2340    crate::nesting::check_text(&raw)?;
2341    let decoded: Value = serde_json::from_slice(&raw)
2342        .map_err(|e| CoreError::Json(format!("passport decode: {e}")))?;
2343    if !decoded.is_object() {
2344        return Err(CoreError::Json("passport payload is not an object".into()));
2345    }
2346    Ok(decoded)
2347}
2348
2349/// Verify a passport: the proof bound to the issuer (`keys` is a `{did: key}`
2350/// source, or the bare key of a did:key issuer), the validity window at
2351/// `now_iso` (validFrom required, strict times), `authorizedActions` a list of
2352/// strings, and (when given) the issuer in `trusted_issuers`. A suspended or
2353/// decommissioned status still verifies; the caller reads it from the subject.
2354pub fn verify_passport(
2355    passport: &Value,
2356    keys: Keys<'_>,
2357    trusted_issuers: Option<&HashSet<String>>,
2358    now_iso: &str,
2359) -> Result<Option<Value>> {
2360    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); passport);
2361    let now = rv::require_now(now_iso)?;
2362    let opts = VerifyOptions {
2363        trusted_issuers,
2364        ..VerifyOptions::window(Window::FromRequired)
2365    };
2366    let v = match rv::verify_robotics_credential(
2367        passport,
2368        keys,
2369        Some(ROBOT_PASSPORT_TYPE),
2370        now,
2371        opts,
2372    ) {
2373        Ok(v) => v,
2374        Err(_) => return Ok(None),
2375    };
2376    match v.subject.get("authorizedActions") {
2377        None => {}
2378        Some(Value::Array(a)) if a.iter().all(|x| x.is_string()) => {}
2379        _ => return Ok(None),
2380    }
2381    Ok(Some(v.subject))
2382}
2383
2384pub fn verify_passport_uri(
2385    uri: &str,
2386    keys: Keys<'_>,
2387    trusted_issuers: Option<&HashSet<String>>,
2388    now_iso: &str,
2389) -> Result<Option<Value>> {
2390    rv::require_now(now_iso)?;
2391    match decode_passport(uri) {
2392        Ok(p) => verify_passport(&p, keys, trusted_issuers, now_iso),
2393        Err(_) => Ok(None),
2394    }
2395}
2396
2397/// Verify a passport (a credential object or a `vouch-passport:` URI) as
2398/// [`verify_passport`] does and return the human-facing summary the Python
2399/// reference returns: robot, make, model, owner, authorizedActions,
2400/// certification, status, and the verified `issuer`.
2401pub fn verify_passport_summary(
2402    passport: &Value,
2403    keys: Keys<'_>,
2404    trusted_issuers: Option<&HashSet<String>>,
2405    now_iso: &str,
2406) -> Result<Option<Value>> {
2407    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); passport);
2408    let cred = match passport {
2409        Value::String(uri) => match decode_passport(uri) {
2410            Ok(p) => p,
2411            Err(_) => return Ok(None),
2412        },
2413        other => other.clone(),
2414    };
2415    let subject = match verify_passport(&cred, keys, trusted_issuers, now_iso)? {
2416        Some(s) => s,
2417        None => return Ok(None),
2418    };
2419    let issuer = rv::issuer_id(cred.get("issuer")).unwrap_or("").to_string();
2420    let g = |k: &str| subject.get(k).cloned().unwrap_or(Value::Null);
2421    Ok(Some(json!({
2422        "robot": g("id"),
2423        "make": g("make"),
2424        "model": g("model"),
2425        "owner": g("owner"),
2426        "authorizedActions": subject.get("authorizedActions").cloned().unwrap_or(json!([])),
2427        "certification": g("certification"),
2428        "status": g("status"),
2429        "issuer": issuer,
2430    })))
2431}
2432
2433// ---------------------------------------------------------------------------
2434// Liveness heartbeat with safety-envelope conformance (Phase 5.7)
2435// ---------------------------------------------------------------------------
2436
2437pub const ROBOT_HEARTBEAT_TYPE: &str = "RobotHeartbeatCredential";
2438
2439/// Default number of missed intervals tolerated before trust is considered stale.
2440pub const DEFAULT_GRACE_INTERVALS: i64 = 2;
2441
2442/// One observed motion sample. `None` numerics mean "not specified" (a meaningful
2443/// zero is still `Some(0.0)`), matching [`PhysicalAction`].
2444#[derive(Debug, Clone, Default)]
2445pub struct MotionSample {
2446    pub force_n: Option<f64>,
2447    pub speed_mps: Option<f64>,
2448    pub near_humans: bool,
2449    pub zone: Option<String>,
2450    pub time_hm: Option<String>,
2451}
2452
2453/// Collector for per-interval motion telemetry. It accumulates aggregates of what
2454/// the robot physically did over a heartbeat interval and, when given a physical
2455/// scope, counts how many samples fell outside the declared envelope. The
2456/// physical analogue of the agent behavioral digest.
2457///
2458/// With `scope` set to `None` the digest still reports observed maxima but cannot
2459/// judge conformance, so it reports `withinEnvelope` true with a zero breach
2460/// count, mirroring the Python `MotionCollector`.
2461#[derive(Debug, Clone, Default)]
2462pub struct MotionCollector {
2463    scope: Option<Value>,
2464    samples: u64,
2465    max_force: f64,
2466    max_speed: f64,
2467    max_speed_near: f64,
2468    zone_breaches: u64,
2469    breaches: u64,
2470}
2471
2472impl MotionCollector {
2473    /// A collector that judges samples against `scope` (the
2474    /// `credentialSubject.physicalScope` object). Pass `None` to only aggregate.
2475    pub fn new(scope: Option<Value>) -> Self {
2476        Self {
2477            scope,
2478            ..Default::default()
2479        }
2480    }
2481
2482    /// Record a single observed motion sample, updating the running aggregates and
2483    /// (when a scope is set) the breach counts.
2484    pub fn record(&mut self, sample: &MotionSample) -> Result<()> {
2485        crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); self);
2486        if let Some(f) = sample.force_n {
2487            if !f.is_finite() || f < 0.0 {
2488                return Err(CoreError::Json(format!(
2489                    "force_n must be a finite non-negative number, got {f}"
2490                )));
2491            }
2492        }
2493        if let Some(s) = sample.speed_mps {
2494            if !s.is_finite() || s < 0.0 {
2495                return Err(CoreError::Json(format!(
2496                    "speed_mps must be a finite non-negative number, got {s}"
2497                )));
2498            }
2499        }
2500
2501        self.samples += 1;
2502        if let Some(f) = sample.force_n {
2503            self.max_force = self.max_force.max(f);
2504        }
2505        if let Some(s) = sample.speed_mps {
2506            self.max_speed = self.max_speed.max(s);
2507            if sample.near_humans {
2508                self.max_speed_near = self.max_speed_near.max(s);
2509            }
2510        }
2511
2512        if let Some(scope) = &self.scope {
2513            let action = PhysicalAction {
2514                force_n: sample.force_n,
2515                speed_mps: sample.speed_mps,
2516                near_humans: sample.near_humans,
2517                zone: sample.zone.clone(),
2518                time_hm: sample.time_hm.clone(),
2519            };
2520            let result = check_physical_action(scope, &action);
2521            if !result.ok {
2522                self.breaches += 1;
2523                if result
2524                    .reasons
2525                    .iter()
2526                    .any(|r| r.starts_with("zone_not_allowed"))
2527                {
2528                    self.zone_breaches += 1;
2529                }
2530            }
2531        }
2532        Ok(())
2533    }
2534
2535    /// Return the `motionDigest` object for embedding in a heartbeat credential.
2536    pub fn digest(&self) -> Value {
2537        crate::nesting::deep_guard!(Value::Null; self);
2538        json!({
2539            "samples": self.samples,
2540            "maxForceN": self.max_force,
2541            "maxSpeedMps": self.max_speed,
2542            "maxSpeedNearHumansMps": self.max_speed_near,
2543            "zoneBreaches": self.zone_breaches,
2544            "breachCount": self.breaches,
2545            "withinEnvelope": self.breaches == 0,
2546        })
2547    }
2548
2549    /// Clear all state. Call after submitting a heartbeat to start fresh.
2550    pub fn reset(&mut self) {
2551        self.samples = 0;
2552        self.max_force = 0.0;
2553        self.max_speed = 0.0;
2554        self.max_speed_near = 0.0;
2555        self.zone_breaches = 0;
2556        self.breaches = 0;
2557    }
2558}
2559
2560fn digest_non_negative_int(digest: &Map<String, Value>, name: &str) -> Result<()> {
2561    match digest.get(name) {
2562        Some(v) if v.is_u64() => Ok(()),
2563        Some(Value::Number(n)) if n.as_i64().map(|i| i >= 0).unwrap_or(false) => Ok(()),
2564        Some(_) => Err(CoreError::Json(format!(
2565            "motionDigest.{name} must be a non-negative integer"
2566        ))),
2567        None => Err(CoreError::Json(format!("motionDigest.{name} is required"))),
2568    }
2569}
2570
2571/// Structural validation of a `motionDigest` object. Does not judge whether the
2572/// values are acceptable; that is policy, expressed through [`is_live`].
2573pub fn validate_motion_digest(digest: &Value) -> Result<()> {
2574    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); digest);
2575    let obj = digest
2576        .as_object()
2577        .ok_or_else(|| CoreError::Json("motionDigest must be an object".into()))?;
2578
2579    for name in ["samples", "zoneBreaches", "breachCount"] {
2580        digest_non_negative_int(obj, name)?;
2581    }
2582    for name in ["maxForceN", "maxSpeedMps", "maxSpeedNearHumansMps"] {
2583        match obj.get(name) {
2584            Some(Value::Bool(_)) | None => {
2585                return Err(CoreError::Json(format!("motionDigest.{name} is required")))
2586            }
2587            Some(v) => {
2588                let n = rv::finite_number(Some(v)).ok_or_else(|| {
2589                    CoreError::Json(format!("motionDigest.{name} must be a finite number"))
2590                })?;
2591                if n < 0.0 {
2592                    return Err(CoreError::Json(format!(
2593                        "motionDigest.{name} must be non-negative"
2594                    )));
2595                }
2596            }
2597        }
2598    }
2599    let within = match obj.get("withinEnvelope") {
2600        Some(Value::Bool(b)) => *b,
2601        Some(_) => {
2602            return Err(CoreError::Json(
2603                "motionDigest.withinEnvelope must be a boolean".into(),
2604            ))
2605        }
2606        None => {
2607            return Err(CoreError::Json(
2608                "motionDigest.withinEnvelope is required".into(),
2609            ))
2610        }
2611    };
2612    let n = |k: &str| obj.get(k).and_then(|v| v.as_u64()).unwrap_or(0);
2613    if within != (n("breachCount") == 0) {
2614        return Err(CoreError::Json(
2615            "motionDigest.withinEnvelope disagrees with breachCount".into(),
2616        ));
2617    }
2618    if n("zoneBreaches") > n("breachCount") {
2619        return Err(CoreError::Json(
2620            "motionDigest.zoneBreaches exceeds breachCount".into(),
2621        ));
2622    }
2623    Ok(())
2624}
2625
2626/// The longest heartbeat cadence a verifier accepts from the heartbeat itself.
2627pub const MAX_INTERVAL_SECONDS: i64 = 3600;
2628
2629/// Parameters for [`build_robot_heartbeat`]. The robot self-issues the credential
2630/// with its own Ed25519 seed; `motion_digest` is produced by a [`MotionCollector`]
2631/// over the interval and `interval_seconds` is the declared heartbeat cadence.
2632#[derive(Debug, Clone)]
2633pub struct BuildRobotHeartbeat {
2634    pub robot_did: String,
2635    pub session_id: String,
2636    pub interval_index: i64,
2637    pub interval_seconds: i64,
2638    pub motion_digest: Value,
2639    pub valid_from: String,
2640}
2641
2642/// Build a signed `RobotHeartbeatCredential`.
2643pub fn build_robot_heartbeat(robot_seed: &[u8], params: &BuildRobotHeartbeat) -> Result<Value> {
2644    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
2645    if params.interval_index < 0 {
2646        return Err(CoreError::Json(
2647            "interval_index must be non-negative".into(),
2648        ));
2649    }
2650    if params.interval_seconds <= 0 {
2651        return Err(CoreError::Json("interval_seconds must be positive".into()));
2652    }
2653    validate_motion_digest(&params.motion_digest)?;
2654
2655    let mut subject = Map::new();
2656    subject.insert("id".into(), json!(params.robot_did));
2657    subject.insert("sessionId".into(), json!(params.session_id));
2658    subject.insert("intervalIndex".into(), json!(params.interval_index));
2659    subject.insert("intervalSeconds".into(), json!(params.interval_seconds));
2660    subject.insert("motionDigest".into(), params.motion_digest.clone());
2661
2662    let mut cred = Map::new();
2663    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
2664    cred.insert(
2665        "type".into(),
2666        json!(["VerifiableCredential", ROBOT_HEARTBEAT_TYPE]),
2667    );
2668    cred.insert("issuer".into(), json!(params.robot_did));
2669    cred.insert("validFrom".into(), json!(params.valid_from));
2670    cred.insert("credentialSubject".into(), Value::Object(subject));
2671
2672    let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), &params.valid_from);
2673    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
2674}
2675
2676/// Verify a `RobotHeartbeatCredential`: the credential proof bound to the robot
2677/// as issuer (which must also be `credentialSubject.id`), a validFrom no later
2678/// than `now_iso`, and the structural validity of the embedded motion digest. Returns the subject on
2679/// success. Whether the robot is currently trusted is a separate, time-dependent
2680/// question answered by [`is_live`].
2681pub fn verify_robot_heartbeat(
2682    credential: &Value,
2683    robot_keys: Keys<'_>,
2684    now_iso: &str,
2685) -> Result<Option<Value>> {
2686    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
2687    let v = match bound(
2688        credential,
2689        robot_keys,
2690        ROBOT_HEARTBEAT_TYPE,
2691        now_iso,
2692        Window::FromRequired,
2693    )? {
2694        Some(v) if issuer_is_subject(&v) => v,
2695        _ => return Ok(None),
2696    };
2697    let digest = v
2698        .subject
2699        .get("motionDigest")
2700        .cloned()
2701        .unwrap_or(Value::Null);
2702    if validate_motion_digest(&digest).is_err() {
2703        return Ok(None);
2704    }
2705    Ok(Some(v.subject))
2706}
2707
2708/// Decide whether a robot is currently trusted, given its most recent heartbeat
2709/// (verify it with [`verify_robot_heartbeat`] first). Live only when: the
2710/// heartbeat was issued within `grace_intervals` cadence periods of `now_iso`
2711/// (the cadence is the verifier's `interval_seconds` when given, else the
2712/// heartbeat's declared interval capped at [`MAX_INTERVAL_SECONDS`]); the
2713/// motion digest covers at least one sample; and the digest is well-formed and
2714/// reports withinEnvelope true. Malformed input returns `false`.
2715pub fn is_live(
2716    credential: &Value,
2717    now_iso: &str,
2718    interval_seconds: Option<i64>,
2719    grace_intervals: i64,
2720) -> Result<bool> {
2721    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
2722    is_live_capped(
2723        credential,
2724        now_iso,
2725        interval_seconds,
2726        grace_intervals,
2727        MAX_INTERVAL_SECONDS,
2728    )
2729}
2730
2731/// [`is_live`] with the caller's cap on a declared cadence instead of
2732/// [`MAX_INTERVAL_SECONDS`].
2733pub fn is_live_capped(
2734    credential: &Value,
2735    now_iso: &str,
2736    interval_seconds: Option<i64>,
2737    grace_intervals: i64,
2738    max_interval_seconds: i64,
2739) -> Result<bool> {
2740    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
2741    if max_interval_seconds < 1 {
2742        return Err(CoreError::Json(
2743            "max_interval_seconds must be at least 1".into(),
2744        ));
2745    }
2746    if grace_intervals < 1 {
2747        return Err(CoreError::Json("grace_intervals must be at least 1".into()));
2748    }
2749    let subject = match credential
2750        .get("credentialSubject")
2751        .and_then(|s| s.as_object())
2752    {
2753        Some(s) => s,
2754        None => return Ok(false),
2755    };
2756    let digest = match subject.get("motionDigest") {
2757        Some(d) if validate_motion_digest(d).is_ok() => d,
2758        _ => return Ok(false),
2759    };
2760    if digest.get("samples").and_then(|v| v.as_u64()).unwrap_or(0) == 0
2761        || digest.get("withinEnvelope") != Some(&Value::Bool(true))
2762    {
2763        return Ok(false);
2764    }
2765    let cadence = match interval_seconds {
2766        Some(c) => c,
2767        None => match rv::strict_int(subject.get("intervalSeconds")) {
2768            Some(d) if d > 0 => d.min(max_interval_seconds),
2769            _ => return Ok(false),
2770        },
2771    };
2772    if cadence <= 0 {
2773        return Ok(false);
2774    }
2775    let issued = match rv::time_ns(credential.get("validFrom")) {
2776        Some(t) => t,
2777        None => return Ok(false),
2778    };
2779    let moment = match crate::time::parse_protocol_time_ns(now_iso) {
2780        Ok(t) => t,
2781        Err(_) => return Ok(false),
2782    };
2783    let cadence_ns = i128::from(cadence) * 1_000_000_000;
2784    // A heartbeat from the future (clock skew beyond one cadence) is not trusted.
2785    if moment + cadence_ns < issued {
2786        return Ok(false);
2787    }
2788    Ok(moment <= issued + cadence_ns * i128::from(grace_intervals))
2789}
2790
2791// ---------------------------------------------------------------------------
2792// Per-credential revocation (Phase 5.8)
2793// ---------------------------------------------------------------------------
2794
2795pub use crate::status_list::{BITSTRING_STATUS_LIST_ENTRY_TYPE, STATUS_PURPOSE_REVOCATION};
2796
2797/// Build a BitstringStatusList `credentialStatus` entry referencing a bit index in
2798/// a published status list credential. Mirrors the agent-side
2799/// `status_list.build_status_list_entry`. `entry_id`, when `None`, defaults to
2800/// `{status_list_credential}#{status_list_index}`.
2801pub fn build_status_list_entry(
2802    status_list_credential: &str,
2803    status_list_index: i64,
2804    status_purpose: &str,
2805    entry_id: Option<&str>,
2806) -> Result<Value> {
2807    if !matches!(status_purpose, "revocation" | "suspension" | "message") {
2808        return Err(CoreError::Json(format!(
2809            "status_purpose must be one of revocation, suspension, message, got {status_purpose:?}"
2810        )));
2811    }
2812    if status_list_index < 0 {
2813        return Err(CoreError::Json(
2814            "status_list_index must be non-negative".into(),
2815        ));
2816    }
2817    if status_list_credential.is_empty() {
2818        return Err(CoreError::Json(
2819            "status_list_credential URL is required".into(),
2820        ));
2821    }
2822    let id = entry_id
2823        .map(String::from)
2824        .unwrap_or_else(|| format!("{status_list_credential}#{status_list_index}"));
2825    Ok(json!({
2826        "id": id,
2827        "type": BITSTRING_STATUS_LIST_ENTRY_TYPE,
2828        "statusPurpose": status_purpose,
2829        "statusListIndex": status_list_index.to_string(),
2830        "statusListCredential": status_list_credential,
2831    }))
2832}
2833
2834/// Parameters for [`attach_credential_status`].
2835#[derive(Debug, Clone)]
2836pub struct AttachCredentialStatus {
2837    pub status_list_credential: String,
2838    pub status_list_index: i64,
2839    pub status_purpose: String,
2840    pub entry_id: Option<String>,
2841    /// `validFrom`-style timestamp used as the proof `created` when re-signing.
2842    pub created: String,
2843}
2844
2845/// Add a BitstringStatusList `credentialStatus` entry to a robot credential and
2846/// re-sign it under `signer_seed`, so the proof covers the status binding. If the
2847/// credential already carries a `credentialStatus`, the new entry is appended (the
2848/// field becomes a list), matching the Verifiable Credentials data model. Any
2849/// pre-existing proof is replaced.
2850pub fn attach_credential_status(
2851    credential: &Value,
2852    signer_seed: &[u8],
2853    params: &AttachCredentialStatus,
2854) -> Result<Value> {
2855    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
2856    let entry = build_status_list_entry(
2857        &params.status_list_credential,
2858        params.status_list_index,
2859        &params.status_purpose,
2860        params.entry_id.as_deref(),
2861    )?;
2862
2863    let mut obj = credential
2864        .as_object()
2865        .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
2866        .clone();
2867
2868    match obj.get("credentialStatus").cloned() {
2869        None => {
2870            obj.insert("credentialStatus".into(), entry);
2871        }
2872        Some(Value::Array(mut existing)) => {
2873            existing.push(entry);
2874            obj.insert("credentialStatus".into(), Value::Array(existing));
2875        }
2876        Some(existing) => {
2877            obj.insert("credentialStatus".into(), json!([existing, entry]));
2878        }
2879    }
2880
2881    // Re-sign: the proof must cover the credentialStatus we just added.
2882    obj.remove("proof");
2883    let issuer = obj.get("issuer").and_then(|v| v.as_str()).unwrap_or("");
2884    let opts = BuildProofOptions::new(format!("{issuer}#key-1"), &params.created);
2885    data_integrity::sign(&Value::Object(obj), signer_seed, &opts)
2886}
2887
2888fn status_entries(credential: &Value) -> Result<Vec<Value>> {
2889    match credential.get("credentialStatus") {
2890        None => Ok(Vec::new()),
2891        Some(Value::Array(a)) => Ok(a.iter().filter(|e| e.is_object()).cloned().collect()),
2892        Some(v) if v.is_object() => Ok(vec![v.clone()]),
2893        Some(_) => Err(CoreError::Json(
2894            "credentialStatus must be an object or a list of objects".into(),
2895        )),
2896    }
2897}
2898
2899/// Return `true` if the robot credential's status bit for `status_purpose` is
2900/// set in the supplied status list. Returns `false` only when the credential
2901/// carries no status entry for that purpose, or every entry for that purpose
2902/// that references this list has its bit clear (every matching entry is
2903/// checked). Errors when the credential has an entry for this purpose but none
2904/// references the supplied list (the list cannot answer), or when the list's
2905/// issuer is not the credential's issuer. The caller verifies the list's proof
2906/// first.
2907pub fn check_credential_status(
2908    credential: &Value,
2909    status_list_credential: &Value,
2910    status_purpose: &str,
2911) -> Result<bool> {
2912    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, status_list_credential);
2913    check_status_inner(credential, status_list_credential, status_purpose, None)
2914}
2915
2916/// [`check_credential_status`], and the status list's own signature must
2917/// verify: issued by the issuer it names, under that issuer's key from `keys`
2918/// (see [`crate::robotics_dtn::verify_status_list_signature`]), checked at
2919/// `now_iso` with 30 s of skew. A list whose signature fails is an error.
2920pub fn check_credential_status_signed(
2921    credential: &Value,
2922    status_list_credential: &Value,
2923    status_purpose: &str,
2924    keys: Keys<'_>,
2925    now_iso: &str,
2926) -> Result<bool> {
2927    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, status_list_credential);
2928    check_status_inner(
2929        credential,
2930        status_list_credential,
2931        status_purpose,
2932        Some((keys, now_iso)),
2933    )
2934}
2935
2936fn check_status_inner(
2937    credential: &Value,
2938    status_list_credential: &Value,
2939    status_purpose: &str,
2940    signed_by: Option<(Keys<'_>, &str)>,
2941) -> Result<bool> {
2942    let entries: Vec<Value> = status_entries(credential)?
2943        .into_iter()
2944        .filter(|e| e.get("statusPurpose").and_then(|v| v.as_str()) == Some(status_purpose))
2945        .collect();
2946    if entries.is_empty() {
2947        return Ok(false);
2948    }
2949    let referenced_id = status_list_credential.get("id");
2950    let matching: Vec<&Value> = entries
2951        .iter()
2952        .filter(|e| e.get("statusListCredential") == referenced_id)
2953        .collect();
2954    if matching.is_empty() {
2955        return Err(CoreError::Json(
2956            "the credential has a status entry for this purpose, but none references this list"
2957                .into(),
2958        ));
2959    }
2960    if rv::issuer_id(status_list_credential.get("issuer"))
2961        != rv::issuer_id(credential.get("issuer"))
2962    {
2963        return Err(CoreError::Json(
2964            "the status list is not from the credential's issuer".into(),
2965        ));
2966    }
2967    if let Some((keys, now_iso)) = signed_by {
2968        if !crate::robotics_dtn::verify_status_list_signature(
2969            status_list_credential,
2970            keys,
2971            now_iso,
2972            30,
2973        )? {
2974            return Err(CoreError::Json(
2975                "the status list signature does not verify".into(),
2976            ));
2977        }
2978    }
2979    for entry in matching {
2980        if crate::status_list::verify_status(entry, status_list_credential)? {
2981            return Ok(true);
2982        }
2983    }
2984    Ok(false)
2985}
2986
2987// ---------------------------------------------------------------------------
2988// Accountable safety record (Phase 5.9)
2989// ---------------------------------------------------------------------------
2990
2991pub const SAFETY_RECORD_TYPE: &str = "RobotSafetyRecordCredential";
2992pub const SAFETY_LOG_VERSION: &str = "1.0";
2993
2994/// Standard safety event types: the interoperable set a verifier and an insurer
2995/// can rely on. Implementers MAY use additional types.
2996pub const EVENT_TYPES: [&str; 6] = [
2997    "incident",
2998    "near_miss",
2999    "manual_override",
3000    "kill_switch",
3001    "envelope_breach",
3002    "maintenance",
3003];
3004
3005/// Severity bands, ordered from least to most serious.
3006pub const SEVERITIES: [&str; 5] = ["info", "low", "medium", "high", "critical"];
3007
3008/// Append-only, plaintext, hash-linked safety event ledger. Reuses the black-box
3009/// chain semantics ([`entry_hash`], [`genesis_prev_hash`]) so the two logs verify
3010/// the same way, but entries are plaintext: a safety record is meant to be read
3011/// and trusted by third parties.
3012pub struct SafetyEventLog {
3013    genesis: String,
3014    entries: Vec<Value>,
3015    head: String,
3016    seq_base: u64,
3017}
3018
3019impl SafetyEventLog {
3020    /// Build a log. A `None` genesis uses [`genesis_prev_hash`].
3021    pub fn new(genesis_prev_hash_override: Option<&str>) -> Self {
3022        let genesis = genesis_prev_hash_override
3023            .map(String::from)
3024            .unwrap_or_else(genesis_prev_hash);
3025        Self {
3026            head: genesis.clone(),
3027            genesis,
3028            entries: Vec::new(),
3029            seq_base: 0,
3030        }
3031    }
3032
3033    /// Continue a log whose head is `prev_hash` and whose next entry is
3034    /// number `next_seq` (a host that keeps the log itself appends one entry
3035    /// at a time this way).
3036    pub fn resume(prev_hash: &str, next_seq: u64) -> Self {
3037        let mut log = Self::new(Some(prev_hash));
3038        log.seq_base = next_seq;
3039        log
3040    }
3041
3042    /// Append one safety event, link it to the chain head, and return the entry.
3043    pub fn append(
3044        &mut self,
3045        event_type: &str,
3046        severity: &str,
3047        details: Option<&Value>,
3048        actor: Option<&str>,
3049        timestamp: &str,
3050    ) -> Result<Value> {
3051        crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); details);
3052        if !EVENT_TYPES.contains(&event_type) {
3053            return Err(CoreError::Json(format!(
3054                "event_type must be one of {EVENT_TYPES:?}, got {event_type:?}"
3055            )));
3056        }
3057        if !SEVERITIES.contains(&severity) {
3058            return Err(CoreError::Json(format!(
3059                "severity must be one of {SEVERITIES:?}, got {severity:?}"
3060            )));
3061        }
3062
3063        let mut body = Map::new();
3064        body.insert("version".into(), json!(SAFETY_LOG_VERSION));
3065        body.insert(
3066            "seq".into(),
3067            json!(self.seq_base + self.entries.len() as u64),
3068        );
3069        body.insert("timestamp".into(), json!(timestamp));
3070        body.insert("eventType".into(), json!(event_type));
3071        body.insert("severity".into(), json!(severity));
3072        body.insert("prevHash".into(), json!(self.head));
3073        if let Some(d) = details {
3074            body.insert("details".into(), d.clone());
3075        }
3076        if let Some(a) = actor {
3077            body.insert("actor".into(), json!(a));
3078        }
3079        let h = entry_hash(&body)?;
3080        body.insert("entryHash".into(), json!(h));
3081        self.head = h;
3082        let entry = Value::Object(body);
3083        self.entries.push(entry.clone());
3084        Ok(entry)
3085    }
3086
3087    pub fn head(&self) -> &str {
3088        &self.head
3089    }
3090
3091    pub fn genesis(&self) -> &str {
3092        &self.genesis
3093    }
3094
3095    pub fn entries(&self) -> &[Value] {
3096        &self.entries
3097    }
3098
3099    /// Produce a summary object for embedding in a safety-record credential.
3100    pub fn summarize(&self) -> Value {
3101        summarize_entries(&self.entries, Some(&self.head))
3102    }
3103}
3104
3105/// Verify the hash chain over the ledger entries. Tamper-evident. Shares the
3106/// black-box chain verifier so the two logs verify identically.
3107pub fn verify_safety_log(
3108    entries: &[Value],
3109    genesis_prev_hash_override: Option<&str>,
3110) -> ChainResult {
3111    crate::nesting::deep_guard!(ChainResult { ok: false, reason: Some(crate::nesting::TOO_DEEP.into()) }; entries);
3112    verify_blackbox_chain(entries, genesis_prev_hash_override)
3113}
3114
3115/// Summarize ledger entries into counts by event type (sorted) and by severity
3116/// (info..critical), the total event count, and (when supplied) the ledger head
3117/// hash that anchors the summary to a specific chain state.
3118pub fn summarize_entries(entries: &[Value], head: Option<&str>) -> Value {
3119    crate::nesting::deep_guard!(Value::Null; entries);
3120    let mut sorted_types: Vec<&str> = EVENT_TYPES.to_vec();
3121    sorted_types.sort_unstable();
3122
3123    let mut event_counts = Map::new();
3124    for t in &sorted_types {
3125        event_counts.insert((*t).to_string(), json!(0));
3126    }
3127    let mut severity_counts = Map::new();
3128    for s in SEVERITIES {
3129        severity_counts.insert(s.to_string(), json!(0));
3130    }
3131
3132    for e in entries {
3133        if let Some(et) = e.get("eventType").and_then(|v| v.as_str()) {
3134            if let Some(c) = event_counts.get_mut(et).and_then(|v| v.as_u64()) {
3135                event_counts.insert(et.to_string(), json!(c + 1));
3136            }
3137        }
3138        if let Some(sv) = e.get("severity").and_then(|v| v.as_str()) {
3139            if let Some(c) = severity_counts.get_mut(sv).and_then(|v| v.as_u64()) {
3140                severity_counts.insert(sv.to_string(), json!(c + 1));
3141            }
3142        }
3143    }
3144
3145    let mut summary = Map::new();
3146    summary.insert("eventCounts".into(), Value::Object(event_counts));
3147    summary.insert("severityCounts".into(), Value::Object(severity_counts));
3148    summary.insert("totalEvents".into(), json!(entries.len() as u64));
3149    if let Some(h) = head {
3150        summary.insert("logHead".into(), json!(h));
3151    }
3152    Value::Object(summary)
3153}
3154
3155/// Structural validation of a safety summary.
3156pub fn validate_safety_summary(summary: &Value) -> Result<()> {
3157    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); summary);
3158    let obj = summary
3159        .as_object()
3160        .ok_or_else(|| CoreError::Json("summary must be an object".into()))?;
3161    for name in ["eventCounts", "severityCounts"] {
3162        let block = obj
3163            .get(name)
3164            .and_then(|v| v.as_object())
3165            .ok_or_else(|| CoreError::Json(format!("summary.{name} must be an object")))?;
3166        for (k, v) in block {
3167            let ok = v.is_u64() || v.as_i64().map(|i| i >= 0).unwrap_or(false);
3168            if v.is_boolean() || !ok {
3169                return Err(CoreError::Json(format!(
3170                    "summary.{name}[{k:?}] must be a non-negative integer"
3171                )));
3172            }
3173        }
3174    }
3175    let total_ok = obj
3176        .get("totalEvents")
3177        .map(|v| (v.is_u64() || v.as_i64().map(|i| i >= 0).unwrap_or(false)) && !v.is_boolean())
3178        .unwrap_or(false);
3179    if !total_ok {
3180        return Err(CoreError::Json(
3181            "summary.totalEvents must be a non-negative integer".into(),
3182        ));
3183    }
3184    Ok(())
3185}
3186
3187/// Parameters for [`build_safety_record`]. The issuer (an owner, an auditor, or
3188/// the robot itself) attests `summary`, produced by [`SafetyEventLog::summarize`]
3189/// or [`summarize_entries`].
3190#[derive(Debug, Clone)]
3191pub struct BuildSafetyRecord {
3192    pub issuer_did: String,
3193    pub robot_did: String,
3194    pub summary: Value,
3195    pub period_start: Option<String>,
3196    pub period_end: Option<String>,
3197    pub valid_from: String,
3198    pub valid_until: Option<String>,
3199}
3200
3201/// Build a signed `RobotSafetyRecordCredential` summarizing a robot's safety
3202/// ledger.
3203pub fn build_safety_record(signer_seed: &[u8], params: &BuildSafetyRecord) -> Result<Value> {
3204    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
3205    validate_safety_summary(&params.summary)?;
3206
3207    let mut subject = Map::new();
3208    subject.insert("id".into(), json!(params.robot_did));
3209    if let Some(s) = params.summary.as_object() {
3210        for (k, v) in s {
3211            subject.insert(k.clone(), v.clone());
3212        }
3213    }
3214    if params.period_start.is_some() || params.period_end.is_some() {
3215        let mut period = Map::new();
3216        if let Some(start) = &params.period_start {
3217            period.insert("start".into(), json!(start));
3218        }
3219        if let Some(end) = &params.period_end {
3220            period.insert("end".into(), json!(end));
3221        }
3222        subject.insert("period".into(), Value::Object(period));
3223    }
3224
3225    let mut cred = Map::new();
3226    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
3227    cred.insert(
3228        "type".into(),
3229        json!(["VerifiableCredential", SAFETY_RECORD_TYPE]),
3230    );
3231    cred.insert("issuer".into(), json!(params.issuer_did));
3232    cred.insert("validFrom".into(), json!(params.valid_from));
3233    if let Some(vu) = &params.valid_until {
3234        cred.insert("validUntil".into(), json!(vu));
3235    }
3236    cred.insert("credentialSubject".into(), Value::Object(subject));
3237
3238    let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), &params.valid_from);
3239    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
3240}
3241
3242/// Options for [`verify_safety_record`].
3243#[derive(Default, Clone, Copy)]
3244pub struct SafetyRecordCheck<'a> {
3245    /// The ledger entries: they must link, end at the summary's `logHead` with
3246    /// exactly `totalEvents` entries, and reproduce the summary's counts.
3247    pub entries: Option<&'a [Value]>,
3248    /// The record must be about this robot.
3249    pub robot_did: Option<&'a str>,
3250    /// The issuer must be in this set.
3251    pub trusted_issuers: Option<&'a HashSet<String>>,
3252}
3253
3254/// Verify a `RobotSafetyRecordCredential`: the issuer's proof bound to the
3255/// issuer, the validity window at `now_iso` (validFrom required), and the
3256/// structure of the embedded summary, plus the [`SafetyRecordCheck`] options.
3257/// Returns the credentialSubject on success.
3258pub fn verify_safety_record(
3259    credential: &Value,
3260    keys: Keys<'_>,
3261    check: SafetyRecordCheck<'_>,
3262    now_iso: &str,
3263) -> Result<Option<Value>> {
3264    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, check);
3265    let now = rv::require_now(now_iso)?;
3266    let opts = VerifyOptions {
3267        trusted_issuers: check.trusted_issuers,
3268        ..VerifyOptions::window(Window::FromRequired)
3269    };
3270    let v =
3271        match rv::verify_robotics_credential(credential, keys, Some(SAFETY_RECORD_TYPE), now, opts)
3272        {
3273            Ok(v) => v,
3274            Err(_) => return Ok(None),
3275        };
3276    let subject = v.subject;
3277    if validate_safety_summary(&subject).is_err() {
3278        return Ok(None);
3279    }
3280    if let Some(robot) = check.robot_did {
3281        if subject.get("id").and_then(|x| x.as_str()) != Some(robot) {
3282            return Ok(None);
3283        }
3284    }
3285    if let Some(entries) = check.entries {
3286        if !verify_chain_against_head(
3287            entries,
3288            subject.get("logHead"),
3289            subject.get("totalEvents"),
3290            None,
3291        )
3292        .ok
3293        {
3294            return Ok(None);
3295        }
3296        let recount = summarize_entries(entries, None);
3297        if recount.get("eventCounts") != subject.get("eventCounts")
3298            || recount.get("severityCounts") != subject.get("severityCounts")
3299        {
3300            return Ok(None);
3301        }
3302    }
3303    Ok(Some(subject))
3304}
3305
3306// ---------------------------------------------------------------------------
3307// Perception provenance (Phase 5.10)
3308// ---------------------------------------------------------------------------
3309
3310pub const PERCEPTION_TYPE: &str = "PerceptionProvenanceCredential";
3311pub const PERCEPTION_LOG_VERSION: &str = "1.0";
3312
3313/// Standard sensor modalities: the interoperable set a verifier can rely on.
3314/// Implementers MAY use additional values.
3315pub const MODALITIES: [&str; 6] = ["camera", "lidar", "radar", "depth", "audio", "thermal"];
3316
3317/// Multibase (base64url) SHA-256 of a raw sensor frame. Only the hash travels in
3318/// the log and the attestation; the frame stays wherever the deployment keeps it.
3319pub fn hash_frame(frame: &[u8]) -> String {
3320    mb64(&Sha256::digest(frame))
3321}
3322
3323/// Append-only, plaintext, hash-linked log of sensor-frame provenance records.
3324/// Reuses the black-box chain semantics ([`entry_hash`], [`genesis_prev_hash`]),
3325/// so a perception log verifies the same way as the safety ledger. Each entry
3326/// binds a sequence number, a timestamp, the sensor id, the modality, the frame
3327/// hash, and the hash of the previous entry; the frames are not stored.
3328pub struct PerceptionLog {
3329    genesis: String,
3330    entries: Vec<Value>,
3331    head: String,
3332    seq_base: u64,
3333}
3334
3335impl PerceptionLog {
3336    /// Build a log. A `None` genesis uses [`genesis_prev_hash`].
3337    pub fn new(genesis_prev_hash_override: Option<&str>) -> Self {
3338        let genesis = genesis_prev_hash_override
3339            .map(String::from)
3340            .unwrap_or_else(genesis_prev_hash);
3341        Self {
3342            head: genesis.clone(),
3343            genesis,
3344            entries: Vec::new(),
3345            seq_base: 0,
3346        }
3347    }
3348
3349    /// Continue a log whose head is `prev_hash` and whose next entry is
3350    /// number `next_seq`.
3351    pub fn resume(prev_hash: &str, next_seq: u64) -> Self {
3352        let mut log = Self::new(Some(prev_hash));
3353        log.seq_base = next_seq;
3354        log
3355    }
3356
3357    /// Append one frame-provenance record, link it to the chain head, and return
3358    /// the entry. Provide either the raw `frame` (it is hashed) or a precomputed
3359    /// `frame_hash`, not both.
3360    pub fn record(
3361        &mut self,
3362        sensor_id: &str,
3363        modality: &str,
3364        frame: Option<&[u8]>,
3365        frame_hash: Option<&str>,
3366        timestamp: &str,
3367    ) -> Result<Value> {
3368        if !MODALITIES.contains(&modality) {
3369            return Err(CoreError::Json(format!(
3370                "modality must be one of {MODALITIES:?}, got {modality:?}"
3371            )));
3372        }
3373        if sensor_id.is_empty() {
3374            return Err(CoreError::Json("sensor_id is required".into()));
3375        }
3376        if frame.is_some() && frame_hash.is_some() {
3377            return Err(CoreError::Json(
3378                "provide either frame or frame_hash, not both".into(),
3379            ));
3380        }
3381        let resolved = match (frame, frame_hash) {
3382            (Some(f), None) => hash_frame(f),
3383            (None, Some(h)) if !h.is_empty() => h.to_string(),
3384            _ => return Err(CoreError::Json("frame or frame_hash is required".into())),
3385        };
3386
3387        let mut body = Map::new();
3388        body.insert("version".into(), json!(PERCEPTION_LOG_VERSION));
3389        body.insert(
3390            "seq".into(),
3391            json!(self.seq_base + self.entries.len() as u64),
3392        );
3393        body.insert("timestamp".into(), json!(timestamp));
3394        body.insert("sensorId".into(), json!(sensor_id));
3395        body.insert("modality".into(), json!(modality));
3396        body.insert("frameHash".into(), json!(resolved));
3397        body.insert("prevHash".into(), json!(self.head));
3398        let h = entry_hash(&body)?;
3399        body.insert("entryHash".into(), json!(h));
3400        self.head = h;
3401        let entry = Value::Object(body);
3402        self.entries.push(entry.clone());
3403        Ok(entry)
3404    }
3405
3406    pub fn head(&self) -> &str {
3407        &self.head
3408    }
3409
3410    pub fn genesis(&self) -> &str {
3411        &self.genesis
3412    }
3413
3414    pub fn entries(&self) -> &[Value] {
3415        &self.entries
3416    }
3417
3418    /// The number of records, the count a perception attestation anchors.
3419    pub fn count(&self) -> usize {
3420        self.entries.len()
3421    }
3422}
3423
3424/// Verify the hash chain over the perception log entries. Tamper-evident. Shares
3425/// the black-box chain verifier so every hash-linked log verifies identically.
3426pub fn verify_perception_log(
3427    entries: &[Value],
3428    genesis_prev_hash_override: Option<&str>,
3429) -> ChainResult {
3430    crate::nesting::deep_guard!(ChainResult { ok: false, reason: Some(crate::nesting::TOO_DEEP.into()) }; entries);
3431    verify_blackbox_chain(entries, genesis_prev_hash_override)
3432}
3433
3434/// Parameters for [`build_perception_attestation`]. The robot self-issues the
3435/// credential with its own Ed25519 seed. `captured_at`, when `None`, defaults to
3436/// `valid_from`. When `log_head` is supplied, the attestation also anchors the
3437/// segment of frames up to that chain head.
3438#[derive(Debug, Clone)]
3439pub struct BuildPerception {
3440    pub robot_did: String,
3441    pub sensor_id: String,
3442    pub modality: String,
3443    pub frame_hash: String,
3444    pub captured_at: Option<String>,
3445    pub log_head: Option<String>,
3446    /// The number of log entries up to `log_head`, so a verifier can tell a
3447    /// segment was not cut short.
3448    pub log_count: Option<u64>,
3449    pub valid_from: String,
3450    pub valid_until: Option<String>,
3451}
3452
3453/// Build a signed `PerceptionProvenanceCredential` attesting that a robot's sensor
3454/// captured a specific frame. Software frame-hash signing: the robot signs the
3455/// provenance of the captured frame with its own key.
3456pub fn build_perception_attestation(robot_seed: &[u8], params: &BuildPerception) -> Result<Value> {
3457    if !MODALITIES.contains(&params.modality.as_str()) {
3458        return Err(CoreError::Json(format!(
3459            "modality must be one of {MODALITIES:?}, got {:?}",
3460            params.modality
3461        )));
3462    }
3463    if params.frame_hash.is_empty() {
3464        return Err(CoreError::Json("frame_hash is required".into()));
3465    }
3466
3467    let captured = params
3468        .captured_at
3469        .clone()
3470        .unwrap_or_else(|| params.valid_from.clone());
3471
3472    let mut subject = Map::new();
3473    subject.insert("id".into(), json!(params.robot_did));
3474    subject.insert("sensorId".into(), json!(params.sensor_id));
3475    subject.insert("modality".into(), json!(params.modality));
3476    subject.insert("frameHash".into(), json!(params.frame_hash));
3477    subject.insert("capturedAt".into(), json!(captured));
3478    if let Some(head) = &params.log_head {
3479        subject.insert("logHead".into(), json!(head));
3480    }
3481    if let Some(n) = params.log_count {
3482        subject.insert("logCount".into(), json!(n));
3483    }
3484
3485    let mut cred = Map::new();
3486    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
3487    cred.insert(
3488        "type".into(),
3489        json!(["VerifiableCredential", PERCEPTION_TYPE]),
3490    );
3491    cred.insert("issuer".into(), json!(params.robot_did));
3492    cred.insert("validFrom".into(), json!(params.valid_from));
3493    if let Some(vu) = &params.valid_until {
3494        cred.insert("validUntil".into(), json!(vu));
3495    }
3496    cred.insert("credentialSubject".into(), Value::Object(subject));
3497
3498    let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), &params.valid_from);
3499    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
3500}
3501
3502/// Verify a `PerceptionProvenanceCredential`: the robot's proof and, when the raw
3503/// `frame` is supplied, that its hash reproduces the attested `frameHash`. Returns
3504/// the credentialSubject on success, `None` if invalid.
3505pub fn verify_perception_attestation(
3506    credential: &Value,
3507    keys: Keys<'_>,
3508    frame: Option<&[u8]>,
3509    now_iso: &str,
3510) -> Result<Option<Value>> {
3511    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
3512    let v = match bound(
3513        credential,
3514        keys,
3515        PERCEPTION_TYPE,
3516        now_iso,
3517        Window::FromRequired,
3518    )? {
3519        Some(v) if issuer_is_subject(&v) => v,
3520        _ => return Ok(None),
3521    };
3522    let frame_hash = v.subject.get("frameHash").and_then(|v| v.as_str());
3523    let modality = v.subject.get("modality").and_then(|v| v.as_str());
3524    match (frame_hash, modality) {
3525        (Some(fh), Some(m)) if !fh.is_empty() && MODALITIES.contains(&m) => {}
3526        _ => return Ok(None),
3527    }
3528    if let Some(f) = frame {
3529        if hash_frame(f) != frame_hash.unwrap_or("") {
3530            return Ok(None);
3531        }
3532    }
3533    Ok(Some(v.subject))
3534}
3535
3536/// Verify a perception log against the robot's signed head: the attestation
3537/// must verify and carry `logHead` and `logCount`, and the log must link and
3538/// end at that head with exactly that many entries.
3539pub fn verify_perception_segment(
3540    entries: &[Value],
3541    attestation: &Value,
3542    keys: Keys<'_>,
3543    genesis_prev_hash_override: Option<&str>,
3544    now_iso: &str,
3545) -> Result<ChainResult> {
3546    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); entries, attestation);
3547    let subject = match verify_perception_attestation(attestation, keys, None, now_iso)? {
3548        Some(s) => s,
3549        None => {
3550            return Ok(ChainResult {
3551                ok: false,
3552                reason: Some("attestation does not verify".into()),
3553            })
3554        }
3555    };
3556    if subject.get("logHead").is_none() || subject.get("logCount").is_none() {
3557        return Ok(ChainResult {
3558            ok: false,
3559            reason: Some("attestation does not anchor a log head and count".into()),
3560        });
3561    }
3562    Ok(verify_chain_against_head(
3563        entries,
3564        subject.get("logHead"),
3565        subject.get("logCount"),
3566        genesis_prev_hash_override,
3567    ))
3568}
3569
3570// ---------------------------------------------------------------------------
3571// Delegation lease (Phase 5.11)
3572// ---------------------------------------------------------------------------
3573
3574pub const DELEGATION_LEASE_TYPE: &str = "DelegationLeaseCredential";
3575
3576/// Parameters for [`build_delegation_lease`]. The issuer is the signer (an
3577/// authority or the holder of a parent lease); `robot_did` is the subject the
3578/// lease is granted to. `scope` is a physicalScope object (the same shape as a
3579/// `PhysicalCapabilityScope` credentialSubject.physicalScope). Leases are
3580/// short-lived by design, so the window is bounded by `valid_from`/`valid_until`.
3581/// Set `parent_lease_id` when sub-granting from another lease.
3582#[derive(Debug, Clone)]
3583pub struct BuildDelegationLease {
3584    pub issuer_did: String,
3585    pub robot_did: String,
3586    pub lease_id: String,
3587    pub scope: Value,
3588    pub parent_lease_id: Option<String>,
3589    pub valid_from: String,
3590    pub valid_until: String,
3591}
3592
3593/// Build a signed `DelegationLeaseCredential` granting `robot_did` a bounded
3594/// physical scope for a fixed window. The window is verifiable entirely offline.
3595pub fn build_delegation_lease(signer_seed: &[u8], params: &BuildDelegationLease) -> Result<Value> {
3596    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
3597    if params.lease_id.is_empty() {
3598        return Err(CoreError::Json("lease_id is required".into()));
3599    }
3600    if !params.scope.is_object() {
3601        return Err(CoreError::Json(
3602            "scope must be a physicalScope object".into(),
3603        ));
3604    }
3605
3606    let mut subject = Map::new();
3607    subject.insert("id".into(), json!(params.robot_did));
3608    subject.insert("leaseId".into(), json!(params.lease_id));
3609    subject.insert("physicalScope".into(), params.scope.clone());
3610    if let Some(parent) = &params.parent_lease_id {
3611        subject.insert("parentLeaseId".into(), json!(parent));
3612    }
3613
3614    let mut cred = Map::new();
3615    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
3616    cred.insert(
3617        "type".into(),
3618        json!(["VerifiableCredential", DELEGATION_LEASE_TYPE]),
3619    );
3620    cred.insert("issuer".into(), json!(params.issuer_did));
3621    cred.insert("validFrom".into(), json!(params.valid_from));
3622    cred.insert("validUntil".into(), json!(params.valid_until));
3623    cred.insert("credentialSubject".into(), Value::Object(subject));
3624
3625    let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), &params.valid_from);
3626    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
3627}
3628
3629/// Verify a `DelegationLeaseCredential` offline: the issuer's proof bound to the
3630/// issuer (`keys` is a `{did: key}` source, or the bare key of a did:key
3631/// issuer), validFrom and validUntil both present with `now_iso` inside, the
3632/// lease is for `expected_robot` (required), it carries a `leaseId` and a
3633/// well-formed scope, the issuer is in `trusted_issuers` when given, and (when
3634/// `parent_scope` is supplied) the scope attenuates the parent. Returns the
3635/// credentialSubject on success, `None` if invalid.
3636pub fn verify_delegation_lease(
3637    credential: &Value,
3638    keys: Keys<'_>,
3639    expected_robot: &str,
3640    parent_scope: Option<&Value>,
3641    trusted_issuers: Option<&HashSet<String>>,
3642    now_iso: &str,
3643) -> Result<Option<Value>> {
3644    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, parent_scope);
3645    if expected_robot.is_empty() {
3646        return Err(CoreError::Json("expected_robot is required".into()));
3647    }
3648    let now = rv::require_now(now_iso)?;
3649    let opts = VerifyOptions {
3650        trusted_issuers,
3651        ..VerifyOptions::window(Window::Required)
3652    };
3653    let v = match rv::verify_robotics_credential(
3654        credential,
3655        keys,
3656        Some(DELEGATION_LEASE_TYPE),
3657        now,
3658        opts,
3659    ) {
3660        Ok(v) => v,
3661        Err(_) => return Ok(None),
3662    };
3663    if v.subject.get("id").and_then(|x| x.as_str()) != Some(expected_robot)
3664        || non_empty_str(&v.subject, "leaseId").is_none()
3665    {
3666        return Ok(None);
3667    }
3668    let scope = match v.subject.get("physicalScope") {
3669        Some(sc) if sc.is_object() && scope_problems(sc).is_empty() => sc,
3670        _ => return Ok(None),
3671    };
3672    if parent_scope.is_some_and(|p| !attenuates(p, scope)) {
3673        return Ok(None);
3674    }
3675    Ok(Some(v.subject))
3676}
3677
3678/// Verify a chain of leases from a trusted root down to `expected_robot`
3679/// (`leases` runs root to leaf). The root is issued by one of `root_issuers`
3680/// and has no `parentLeaseId`; each later lease names the previous `leaseId`
3681/// as its `parentLeaseId`, is issued by the party the previous lease was
3682/// granted to, has a window inside the previous window, and attenuates the
3683/// previous scope. Every lease is current at `now_iso`; the leaf is for
3684/// `expected_robot`. Returns the leaf subject on success.
3685pub fn verify_lease_chain(
3686    leases: &[Value],
3687    keys: Keys<'_>,
3688    expected_robot: &str,
3689    root_issuers: &HashSet<String>,
3690    now_iso: &str,
3691) -> Result<Option<Value>> {
3692    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); leases);
3693    rv::require_now(now_iso)?;
3694    if leases.is_empty() || root_issuers.is_empty() {
3695        return Ok(None);
3696    }
3697    let mut prev: Option<(&Value, Value)> = None;
3698    for (i, lease) in leases.iter().enumerate() {
3699        let holder = lease
3700            .get("credentialSubject")
3701            .and_then(|s| s.get("id"))
3702            .and_then(|v| v.as_str())
3703            .unwrap_or("");
3704        let target = if i + 1 == leases.len() {
3705            expected_robot
3706        } else {
3707            holder
3708        };
3709        if target.is_empty() {
3710            return Ok(None);
3711        }
3712        let parent_scope = prev.as_ref().and_then(|(_, ps)| ps.get("physicalScope"));
3713        // The root must be one of `root_issuers`; each child must be issued by
3714        // the holder the verified parent names. Both are named sets, so did:key
3715        // parties verify under their own keys with no key source.
3716        let holder_set: HashSet<String> = prev
3717            .as_ref()
3718            .and_then(|(_, ps)| ps.get("id"))
3719            .and_then(|v| v.as_str())
3720            .filter(|h| !h.is_empty())
3721            .map(|h| [h.to_string()].into_iter().collect())
3722            .unwrap_or_default();
3723        let subject = match verify_delegation_lease(
3724            lease,
3725            keys,
3726            target,
3727            parent_scope,
3728            Some(if prev.is_none() {
3729                root_issuers
3730            } else {
3731                &holder_set
3732            }),
3733            now_iso,
3734        )? {
3735            Some(s) => s,
3736            None => return Ok(None),
3737        };
3738        match &prev {
3739            Some((p_lease, p_sub)) => {
3740                if subject.get("parentLeaseId") != p_sub.get("leaseId") {
3741                    return Ok(None);
3742                }
3743                if rv::issuer_id(lease.get("issuer")) != p_sub.get("id").and_then(|v| v.as_str()) {
3744                    return Ok(None);
3745                }
3746                let t = |c: &Value, k: &str| rv::time_ns(c.get(k));
3747                if t(lease, "validFrom") < t(p_lease, "validFrom")
3748                    || t(lease, "validUntil") > t(p_lease, "validUntil")
3749                {
3750                    return Ok(None);
3751                }
3752            }
3753            None => {
3754                if subject.get("parentLeaseId").is_some() {
3755                    return Ok(None);
3756                }
3757            }
3758        }
3759        prev = Some((lease, subject));
3760    }
3761    Ok(prev.map(|(_, s)| s))
3762}
3763
3764/// Decide whether a verified lease permits a proposed physical action. The full
3765/// lease `credential` is required and is verified again here (`keys` and
3766/// `trusted_issuers` as in [`verify_delegation_lease`], with `subject.id` as the
3767/// expected robot), so its window is read from signed data: a copy with a
3768/// re-dated `validUntil` no longer verifies. Its subject must equal `subject`,
3769/// its window must contain `now_iso`, and the action must fit the scope.
3770pub fn lease_permits(
3771    subject: &Value,
3772    action: &PhysicalAction,
3773    credential: Option<&Value>,
3774    keys: Keys<'_>,
3775    trusted_issuers: Option<&HashSet<String>>,
3776    now_iso: &str,
3777) -> Result<bool> {
3778    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); subject, credential);
3779    let now = rv::require_now(now_iso)?;
3780    let cred = match credential {
3781        Some(c) if c.is_object() && subject.is_object() => c,
3782        _ => return Ok(false),
3783    };
3784    let robot = match subject.get("id").and_then(|v| v.as_str()) {
3785        Some(r) if !r.is_empty() => r,
3786        _ => return Ok(false),
3787    };
3788    match verify_delegation_lease(cred, keys, robot, None, trusted_issuers, now_iso)? {
3789        Some(v) if &v == subject => {}
3790        _ => return Ok(false),
3791    }
3792    if rv::window_reason(cred, Window::Required, now, 0).is_some() {
3793        return Ok(false);
3794    }
3795    match subject.get("physicalScope") {
3796        Some(scope) if scope.is_object() => Ok(check_physical_action(scope, action).ok),
3797        _ => Ok(false),
3798    }
3799}
3800
3801// ---------------------------------------------------------------------------
3802// Physical quorum (Phase 5.12)
3803// ---------------------------------------------------------------------------
3804
3805pub const ACTION_APPROVAL_TYPE: &str = "PhysicalActionApprovalCredential";
3806pub const APPROVE: &str = "approve";
3807pub const REJECT: &str = "reject";
3808/// How long an approval lasts when its builder gives no end.
3809pub const DEFAULT_APPROVAL_SECONDS: i64 = 300;
3810/// The longest approval lifetime a verifier accepts.
3811pub const MAX_APPROVAL_SECONDS: i64 = 900;
3812
3813/// Parameters for [`build_action_approval`]. The approver is the signer; the
3814/// approval is over a specific physical action `action_id` that `robot_did`
3815/// would perform. `decision` is "approve" or "reject".
3816#[derive(Debug, Clone)]
3817pub struct BuildActionApproval {
3818    pub approver_did: String,
3819    pub action_id: String,
3820    pub robot_did: String,
3821    pub decision: String,
3822    pub valid_from: String,
3823    pub valid_until: Option<String>,
3824}
3825
3826/// Build a signed `PhysicalActionApprovalCredential` by one approver for a
3827/// specific physical action.
3828pub fn build_action_approval(approver_seed: &[u8], params: &BuildActionApproval) -> Result<Value> {
3829    if params.decision != APPROVE && params.decision != REJECT {
3830        return Err(CoreError::Json(format!(
3831            "decision must be {APPROVE:?} or {REJECT:?}, got {:?}",
3832            params.decision
3833        )));
3834    }
3835    if params.action_id.is_empty() {
3836        return Err(CoreError::Json("action_id is required".into()));
3837    }
3838
3839    let mut subject = Map::new();
3840    subject.insert("id".into(), json!(params.approver_did));
3841    subject.insert("actionId".into(), json!(params.action_id));
3842    subject.insert("robotDid".into(), json!(params.robot_did));
3843    subject.insert("decision".into(), json!(params.decision));
3844
3845    let mut cred = Map::new();
3846    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
3847    cred.insert(
3848        "type".into(),
3849        json!(["VerifiableCredential", ACTION_APPROVAL_TYPE]),
3850    );
3851    cred.insert("issuer".into(), json!(params.approver_did));
3852    cred.insert("validFrom".into(), json!(params.valid_from));
3853    // An approval is short-lived: without an explicit end it lasts
3854    // DEFAULT_APPROVAL_SECONDS, and a verifier refuses one without validUntil.
3855    let valid_until = match &params.valid_until {
3856        Some(vu) => vu.clone(),
3857        None => crate::time::epoch_seconds_to_iso(
3858            crate::time::iso_to_epoch_seconds(&params.valid_from)? + DEFAULT_APPROVAL_SECONDS,
3859        ),
3860    };
3861    cred.insert("validUntil".into(), json!(valid_until));
3862    cred.insert("credentialSubject".into(), Value::Object(subject));
3863
3864    let opts = BuildProofOptions::new(format!("{}#key-1", params.approver_did), &params.valid_from);
3865    data_integrity::sign(&Value::Object(cred), approver_seed, &opts)
3866}
3867
3868/// One approver's public key, looked up by issuer DID, for
3869/// [`verify_action_authorization`].
3870#[derive(Debug, Clone)]
3871pub struct ApproverKey {
3872    pub did: String,
3873    pub public_key: Vec<u8>,
3874}
3875
3876/// Verify that a high-consequence physical action is authorized by a quorum.
3877///
3878/// Each approval must carry a proof bound to its issuer and verified with the
3879/// issuer's key from `approver_keys`, name the issuer as its subject, match
3880/// `action_id` and `robot_did`, and carry both validFrom and validUntil with
3881/// `now_iso` inside and a lifetime of at most [`MAX_APPROVAL_SECONDS`]. When
3882/// `approver_set` is supplied, the approver must be in it. Each approver's
3883/// latest decision counts (at the same instant a rejection wins); any latest
3884/// rejection vetoes the action. Otherwise it is authorized when at least
3885/// `threshold` approvers with DISTINCT signing keys approve: two DIDs mapped to
3886/// the same key count once. Returns `(authorized, sorted approving DIDs)`.
3887pub fn verify_action_authorization(
3888    approvals: &[Value],
3889    action_id: &str,
3890    robot_did: &str,
3891    approver_keys: &[ApproverKey],
3892    threshold: i64,
3893    approver_set: Option<&HashSet<String>>,
3894    now_iso: &str,
3895) -> Result<(bool, Vec<String>)> {
3896    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); approvals);
3897    verify_action_authorization_with(
3898        approvals,
3899        action_id,
3900        robot_did,
3901        approver_keys,
3902        threshold,
3903        approver_set,
3904        MAX_APPROVAL_SECONDS,
3905        now_iso,
3906    )
3907}
3908
3909/// [`verify_action_authorization`] with the caller's longest approval
3910/// lifetime instead of [`MAX_APPROVAL_SECONDS`].
3911#[allow(clippy::too_many_arguments)]
3912pub fn verify_action_authorization_with(
3913    approvals: &[Value],
3914    action_id: &str,
3915    robot_did: &str,
3916    approver_keys: &[ApproverKey],
3917    threshold: i64,
3918    approver_set: Option<&HashSet<String>>,
3919    max_approval_seconds: i64,
3920    now_iso: &str,
3921) -> Result<(bool, Vec<String>)> {
3922    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); approvals);
3923    if max_approval_seconds < 1 {
3924        return Err(CoreError::Json(
3925            "max_approval_seconds must be at least 1".into(),
3926        ));
3927    }
3928    if threshold < 1 {
3929        return Err(CoreError::Json("threshold must be at least 1".into()));
3930    }
3931    let now = rv::require_now(now_iso)?;
3932    let map: alloc::collections::BTreeMap<String, Vec<u8>> =
3933        Keys::map_of(approver_keys.iter().map(|k| (k.did.clone(), &k.public_key)));
3934    let keys = Keys::Map(&map);
3935
3936    // The approver set is a named member set: with no key on file, its
3937    // did:key members verify under their own keys. A freshly minted did:key
3938    // is never an approver by itself.
3939    let opts = VerifyOptions {
3940        trusted_issuers: approver_set,
3941        ..VerifyOptions::window(Window::Required)
3942    };
3943    let mut latest: alloc::collections::BTreeMap<String, (i128, bool)> =
3944        alloc::collections::BTreeMap::new();
3945    for approval in approvals {
3946        let mut early = false;
3947        let v = match rv::verify_robotics_credential(
3948            approval,
3949            keys,
3950            Some(ACTION_APPROVAL_TYPE),
3951            now,
3952            opts,
3953        ) {
3954            Ok(v) if issuer_is_subject(&v) => v,
3955            Err(why) if why == "credential window: not_yet_valid" => {
3956                // A rejection dated slightly ahead of the verifier's clock
3957                // still vetoes: re-check everything else at its own start. An
3958                // early approval never counts.
3959                let at = match rv::time_ns(approval.get("validFrom")) {
3960                    Some(t) => t,
3961                    None => continue,
3962                };
3963                match rv::verify_robotics_credential(
3964                    approval,
3965                    keys,
3966                    Some(ACTION_APPROVAL_TYPE),
3967                    at,
3968                    opts,
3969                ) {
3970                    Ok(v) if issuer_is_subject(&v) => {
3971                        early = true;
3972                        v
3973                    }
3974                    _ => continue,
3975                }
3976            }
3977            _ => continue,
3978        };
3979        if v.subject.get("actionId").and_then(|x| x.as_str()) != Some(action_id)
3980            || v.subject.get("robotDid").and_then(|x| x.as_str()) != Some(robot_did)
3981        {
3982            continue;
3983        }
3984        let reject = match v.subject.get("decision").and_then(|x| x.as_str()) {
3985            Some(APPROVE) => false,
3986            Some(REJECT) => true,
3987            _ => continue,
3988        };
3989        if early && !reject {
3990            continue;
3991        }
3992        if let Some(set) = approver_set {
3993            if !set.contains(&v.issuer) {
3994                continue;
3995            }
3996        }
3997        let (start, end) = match (
3998            rv::time_ns(approval.get("validFrom")),
3999            rv::time_ns(approval.get("validUntil")),
4000        ) {
4001            (Some(a), Some(b)) => (a, b),
4002            _ => continue,
4003        };
4004        if end - start > i128::from(max_approval_seconds) * 1_000_000_000 {
4005            continue;
4006        }
4007        let newer = match latest.get(&v.issuer) {
4008            None => true,
4009            Some((t, _)) => start > *t || (start == *t && reject),
4010        };
4011        if newer {
4012            latest.insert(v.issuer, (start, reject));
4013        }
4014    }
4015
4016    if latest.values().any(|(_, reject)| *reject) {
4017        return Ok((false, Vec::new()));
4018    }
4019    let mut approvers: Vec<String> = Vec::new();
4020    let mut seen: HashSet<Vec<u8>> = HashSet::new();
4021    for issuer in latest.keys() {
4022        let raw = match map.get(issuer) {
4023            Some(k) => k.clone(),
4024            None => match crate::keys::did_key_to_ed25519(issuer) {
4025                Ok(k) if issuer.starts_with("did:key:") => k,
4026                _ => continue,
4027            },
4028        };
4029        if seen.insert(raw) {
4030            approvers.push(issuer.clone());
4031        }
4032    }
4033    approvers.sort();
4034    Ok((approvers.len() as i64 >= threshold, approvers))
4035}
4036
4037// ---------------------------------------------------------------------------
4038// Robot lifecycle: ownership transfer, key rotation, decommission (Phase 5.13)
4039// ---------------------------------------------------------------------------
4040
4041pub const OWNERSHIP_TRANSFER_TYPE: &str = "RobotOwnershipTransferCredential";
4042pub const KEY_ROTATION_TYPE: &str = "RobotKeyRotationCredential";
4043pub const DECOMMISSION_TYPE: &str = "RobotDecommissionCredential";
4044
4045/// Parameters for [`build_ownership_transfer`]. The signer is the current owner;
4046/// `from_owner` defaults to `issuer_did` (the current owner's DID). Setting
4047/// `prev_transfer_id` links this transfer to the previous one, forming a chain:
4048/// it must be the previous transfer's `id`. `credential_id` is this transfer's
4049/// own `id` (the caller supplies it; use a fresh `urn:uuid:`).
4050#[derive(Debug, Clone)]
4051pub struct BuildOwnershipTransfer {
4052    pub issuer_did: String,
4053    pub robot_did: String,
4054    pub to_owner: String,
4055    pub from_owner: Option<String>,
4056    pub prev_transfer_id: Option<String>,
4057    pub credential_id: String,
4058    pub valid_from: String,
4059}
4060
4061/// Build a signed transfer of `robot_did` from the current owner to `to_owner`.
4062/// The signer is the current owner; `from_owner` defaults to `issuer_did`.
4063pub fn build_ownership_transfer(
4064    current_owner_seed: &[u8],
4065    params: &BuildOwnershipTransfer,
4066) -> Result<Value> {
4067    if params.robot_did.is_empty() || params.to_owner.is_empty() {
4068        return Err(CoreError::Json(
4069            "robot_did and to_owner are required".into(),
4070        ));
4071    }
4072    if params.credential_id.is_empty() {
4073        return Err(CoreError::Json("credential_id is required".into()));
4074    }
4075    let seller = params
4076        .from_owner
4077        .clone()
4078        .unwrap_or_else(|| params.issuer_did.clone());
4079
4080    let mut subject = Map::new();
4081    subject.insert("id".into(), json!(params.robot_did));
4082    subject.insert("fromOwner".into(), json!(seller));
4083    subject.insert("toOwner".into(), json!(params.to_owner));
4084    if let Some(prev) = &params.prev_transfer_id {
4085        subject.insert("prevTransferId".into(), json!(prev));
4086    }
4087
4088    let mut cred = Map::new();
4089    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
4090    cred.insert("id".into(), json!(params.credential_id));
4091    cred.insert(
4092        "type".into(),
4093        json!(["VerifiableCredential", OWNERSHIP_TRANSFER_TYPE]),
4094    );
4095    cred.insert("issuer".into(), json!(params.issuer_did));
4096    cred.insert("validFrom".into(), json!(params.valid_from));
4097    cred.insert("credentialSubject".into(), Value::Object(subject));
4098
4099    let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), &params.valid_from);
4100    data_integrity::sign(&Value::Object(cred), current_owner_seed, &opts)
4101}
4102
4103fn non_empty_str<'v>(v: &'v Value, key: &str) -> Option<&'v str> {
4104    v.get(key)
4105        .and_then(|x| x.as_str())
4106        .filter(|s| !s.is_empty())
4107}
4108
4109/// Verify a transfer: the current owner's proof bound to the issuer, the
4110/// issuer is the `fromOwner` (only the current owner can transfer the robot),
4111/// `toOwner` and the robot `id` are non-empty strings, validFrom no later than
4112/// `now_iso`, and (when given) the transfer is for `robot_did`. `owner_keys` is
4113/// a `{owner_did: key}` source (or the bare key of a did:key owner).
4114pub fn verify_ownership_transfer(
4115    credential: &Value,
4116    owner_keys: Keys<'_>,
4117    robot_did: Option<&str>,
4118    now_iso: &str,
4119) -> Result<Option<Value>> {
4120    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
4121    let v = match bound(
4122        credential,
4123        owner_keys,
4124        OWNERSHIP_TRANSFER_TYPE,
4125        now_iso,
4126        Window::FromRequired,
4127    )? {
4128        Some(v) => v,
4129        None => return Ok(None),
4130    };
4131    let ok = non_empty_str(&v.subject, "toOwner").is_some()
4132        && non_empty_str(&v.subject, "fromOwner") == Some(v.issuer.as_str())
4133        && non_empty_str(&v.subject, "id").is_some()
4134        && robot_did.is_none_or(|r| v.subject.get("id").and_then(|x| x.as_str()) == Some(r));
4135    Ok(if ok { Some(v.subject) } else { None })
4136}
4137
4138/// One owner's public key, looked up by owner DID, for [`verify_custody_chain`].
4139#[derive(Debug, Clone)]
4140pub struct OwnerKey {
4141    pub did: String,
4142    pub public_key: Vec<u8>,
4143}
4144
4145/// Verify an ordered list of transfer credentials forms a valid chain of custody
4146/// for `robot_did`: every link verifies under the owner who signed it (keys
4147/// from `public_keys`), names the previous link's `id` as its
4148/// `prevTransferId`, is dated no earlier than the previous link, each
4149/// `toOwner` is the next link's `fromOwner`, and the first `fromOwner` is
4150/// `origin_owner`. Returns `(ok, current_owner)`.
4151///
4152/// `origin_owner` is required: with no known first owner, anyone could sign a
4153/// first transfer of any robot from themselves. Without it the chain is
4154/// refused. Each link's signer is pinned (the origin, then each `toOwner`), so
4155/// a did:key owner verifies under its own key even with no entry in
4156/// `public_keys`.
4157pub fn verify_custody_chain(
4158    transfers: &[Value],
4159    public_keys: &[OwnerKey],
4160    robot_did: &str,
4161    origin_owner: Option<&str>,
4162    now_iso: &str,
4163) -> Result<(bool, Option<String>)> {
4164    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); transfers);
4165    rv::require_now(now_iso)?;
4166    if robot_did.is_empty() || origin_owner.is_none_or(str::is_empty) {
4167        return Ok((false, None));
4168    }
4169    let map = Keys::map_of(public_keys.iter().map(|k| (k.did.clone(), &k.public_key)));
4170    let mut expected_from: Option<String> = origin_owner.map(String::from);
4171    let mut current_owner: Option<String> = origin_owner.map(String::from);
4172    let mut prev_id: Option<String> = None;
4173    let mut prev_time: Option<i128> = None;
4174    for (i, transfer) in transfers.iter().enumerate() {
4175        let keys = rv::pin_if_keyless(Keys::Map(&map), expected_from.as_deref());
4176        let subject = match verify_ownership_transfer(transfer, keys, Some(robot_did), now_iso)? {
4177            Some(s) => s,
4178            None => return Ok((false, None)),
4179        };
4180        if let Some(expected) = &expected_from {
4181            if subject.get("fromOwner").and_then(|v| v.as_str()) != Some(expected.as_str()) {
4182                return Ok((false, None));
4183            }
4184        }
4185        let this_time = match rv::time_ns(transfer.get("validFrom")) {
4186            Some(t) if prev_time.is_none_or(|p| t >= p) => t,
4187            _ => return Ok((false, None)),
4188        };
4189        if i > 0 {
4190            match &prev_id {
4191                Some(p) if subject.get("prevTransferId").and_then(|v| v.as_str()) == Some(p) => {}
4192                _ => return Ok((false, None)),
4193            }
4194        }
4195        prev_id = non_empty_str(transfer, "id").map(String::from);
4196        prev_time = Some(this_time);
4197        current_owner = subject
4198            .get("toOwner")
4199            .and_then(|v| v.as_str())
4200            .map(String::from);
4201        expected_from = current_owner.clone();
4202    }
4203    Ok((true, current_owner))
4204}
4205
4206/// Parameters for [`build_key_rotation`]. The credential is signed by the old key
4207/// (the `signer_seed`) and issued under `robot_did`; the old key's public multibase
4208/// is recorded as `previousKey` and `new_key_multibase` as the authorized successor.
4209#[derive(Debug, Clone)]
4210pub struct BuildKeyRotation {
4211    pub robot_did: String,
4212    pub new_key_multibase: String,
4213    pub reason: Option<String>,
4214    pub valid_from: String,
4215}
4216
4217/// Build a key-rotation credential in which the robot's current (old) key
4218/// authorizes a new key. Signed by the old key, so anyone trusting the old key
4219/// can trust the new one. `old_key_seed` is the seed of the current key.
4220pub fn build_key_rotation(old_key_seed: &[u8], params: &BuildKeyRotation) -> Result<Value> {
4221    if params.new_key_multibase.is_empty() {
4222        return Err(CoreError::Json("new_key_multibase is required".into()));
4223    }
4224    let old_kp = keys::Ed25519KeyPair::from_seed_slice(old_key_seed)?;
4225
4226    let mut subject = Map::new();
4227    subject.insert("id".into(), json!(params.robot_did));
4228    subject.insert("previousKey".into(), json!(old_kp.public_multikey()));
4229    subject.insert("newKey".into(), json!(params.new_key_multibase));
4230    if let Some(reason) = &params.reason {
4231        subject.insert("reason".into(), json!(reason));
4232    }
4233
4234    let mut cred = Map::new();
4235    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
4236    cred.insert(
4237        "type".into(),
4238        json!(["VerifiableCredential", KEY_ROTATION_TYPE]),
4239    );
4240    cred.insert("issuer".into(), json!(params.robot_did));
4241    cred.insert("validFrom".into(), json!(params.valid_from));
4242    cred.insert("credentialSubject".into(), Value::Object(subject));
4243
4244    let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), &params.valid_from);
4245    data_integrity::sign(&Value::Object(cred), old_key_seed, &opts)
4246}
4247
4248/// The raw Ed25519 key of a `z...` multikey, or `None`.
4249fn multikey_raw(v: Option<&Value>) -> Option<Vec<u8>> {
4250    let s = v.and_then(|x| x.as_str()).filter(|s| s.starts_with('z'))?;
4251    match multikey::decode(s) {
4252        Ok(d) if d.algorithm == "Ed25519" && d.raw_key.len() == 32 => Some(d.raw_key),
4253        _ => None,
4254    }
4255}
4256
4257/// Verify a key rotation: the robot's OLD key signed it, binding the new key.
4258///
4259/// The rotation is a self-attestation: the issuer must be the robot
4260/// (`credentialSubject.id`), `previousKey` must decode to exactly the key the
4261/// caller trusts as the robot's current key (`old_keys`: a bare key, or a
4262/// `{robot_did: key}` source), the proof is checked under that key, and
4263/// `newKey` must decode and differ. When given, the rotation must be for
4264/// `robot_did`. Returns the credentialSubject (with `newKey` the successor).
4265pub fn verify_key_rotation(
4266    credential: &Value,
4267    old_keys: Keys<'_>,
4268    robot_did: Option<&str>,
4269    now_iso: &str,
4270) -> Result<Option<Value>> {
4271    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
4272    let now = rv::require_now(now_iso)?;
4273    let issuer = match rv::issuer_id(credential.get("issuer")) {
4274        Some(i) => i.to_string(),
4275        None => return Ok(None),
4276    };
4277    let trusted: Option<Vec<u8>> = match old_keys {
4278        Keys::Embedded | Keys::Pinned(_) => None,
4279        Keys::Bare(k) => Some(k.to_vec()),
4280        Keys::One(did, k) => (did == issuer).then(|| k.to_vec()),
4281        Keys::Map(m) => m.get(&issuer).cloned(),
4282        Keys::Resolver(f) => f(&issuer),
4283    };
4284    let trusted = match trusted {
4285        Some(t) if t.len() == 32 => t,
4286        _ => return Ok(None),
4287    };
4288    let previous = credential
4289        .get("credentialSubject")
4290        .and_then(|s| s.get("previousKey"));
4291    if multikey_raw(previous) != Some(trusted.clone()) {
4292        return Ok(None);
4293    }
4294    let v = match rv::verify_robotics_credential(
4295        credential,
4296        Keys::One(&issuer, &trusted),
4297        Some(KEY_ROTATION_TYPE),
4298        now,
4299        VerifyOptions::window(Window::FromRequired),
4300    ) {
4301        Ok(v) if issuer_is_subject(&v) => v,
4302        _ => return Ok(None),
4303    };
4304    if robot_did.is_some_and(|r| r != v.issuer) {
4305        return Ok(None);
4306    }
4307    match multikey_raw(v.subject.get("newKey")) {
4308        Some(n) if n != trusted => Ok(Some(v.subject)),
4309        _ => Ok(None),
4310    }
4311}
4312
4313/// Verify an ordered list of key rotations forms one linear key history from
4314/// `origin_key_multibase`. Each rotation must be signed by the key it rotates
4315/// from, decoded from the multibase itself; every rotation is for the same
4316/// robot (`robot_did` when given, else the first rotation's robot) and dated no
4317/// earlier than the one before; a key that appears twice (a fork or a cycle)
4318/// is refused. Returns `(ok, current_key)`.
4319pub fn verify_key_history(
4320    rotations: &[Value],
4321    origin_key_multibase: &str,
4322    robot_did: Option<&str>,
4323    now_iso: &str,
4324) -> Result<(bool, Option<String>)> {
4325    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); rotations);
4326    rv::require_now(now_iso)?;
4327    let origin = match multikey_raw(Some(&json!(origin_key_multibase))) {
4328        Some(o) => o,
4329        None => return Ok((false, None)),
4330    };
4331    let mut current_key = origin_key_multibase.to_string();
4332    let mut current_raw = origin.clone();
4333    let mut seen: HashSet<Vec<u8>> = HashSet::from([origin]);
4334    let mut pinned: Option<String> = robot_did.map(String::from);
4335    let mut prev_time: Option<i128> = None;
4336    for rotation in rotations {
4337        let subject = match verify_key_rotation(
4338            rotation,
4339            Keys::Bare(&current_raw),
4340            pinned.as_deref(),
4341            now_iso,
4342        )? {
4343            Some(s) => s,
4344            None => return Ok((false, None)),
4345        };
4346        if pinned.is_none() {
4347            pinned = subject.get("id").and_then(|v| v.as_str()).map(String::from);
4348        }
4349        match rv::time_ns(rotation.get("validFrom")) {
4350            Some(t) if prev_time.is_none_or(|p| t >= p) => prev_time = Some(t),
4351            _ => return Ok((false, None)),
4352        }
4353        let new_raw = match multikey_raw(subject.get("newKey")) {
4354            Some(n) if !seen.contains(&n) => n,
4355            _ => return Ok((false, None)),
4356        };
4357        seen.insert(new_raw.clone());
4358        current_raw = new_raw;
4359        current_key = subject
4360            .get("newKey")
4361            .and_then(|v| v.as_str())
4362            .unwrap_or("")
4363            .to_string();
4364    }
4365    Ok((true, Some(current_key)))
4366}
4367
4368/// Parameters for [`build_decommission`]. The signer is the owner or an authority;
4369/// `final_disposition` records the outcome (for example recycled, destroyed, or
4370/// transferred to parts). When `valid_until` is set it bounds the credential.
4371#[derive(Debug, Clone)]
4372pub struct BuildDecommission {
4373    pub issuer_did: String,
4374    pub robot_did: String,
4375    pub reason: String,
4376    pub final_disposition: Option<String>,
4377    pub valid_from: String,
4378    pub valid_until: Option<String>,
4379}
4380
4381/// Build a signed decommission credential retiring `robot_did`. After
4382/// decommissioning, a verifier should refuse to trust the robot. `decommissionedBy`
4383/// is the issuer DID.
4384pub fn build_decommission(signer_seed: &[u8], params: &BuildDecommission) -> Result<Value> {
4385    if params.reason.is_empty() {
4386        return Err(CoreError::Json("reason is required".into()));
4387    }
4388    let mut subject = Map::new();
4389    subject.insert("id".into(), json!(params.robot_did));
4390    subject.insert("reason".into(), json!(params.reason));
4391    subject.insert("decommissionedBy".into(), json!(params.issuer_did));
4392    if let Some(disposition) = &params.final_disposition {
4393        subject.insert("finalDisposition".into(), json!(disposition));
4394    }
4395
4396    let mut cred = Map::new();
4397    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
4398    cred.insert(
4399        "type".into(),
4400        json!(["VerifiableCredential", DECOMMISSION_TYPE]),
4401    );
4402    cred.insert("issuer".into(), json!(params.issuer_did));
4403    cred.insert("validFrom".into(), json!(params.valid_from));
4404    if let Some(vu) = &params.valid_until {
4405        cred.insert("validUntil".into(), json!(vu));
4406    }
4407    cred.insert("credentialSubject".into(), Value::Object(subject));
4408
4409    let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), &params.valid_from);
4410    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
4411}
4412
4413/// Verify a decommission credential: the proof bound to the issuer, the
4414/// window at `now_iso` (validFrom required), `decommissionedBy` (when present)
4415/// equal to the issuer, the issuer in `trusted_authorities` when supplied, and
4416/// (when given) the credential is about `robot_did`.
4417pub fn verify_decommission(
4418    credential: &Value,
4419    keys: Keys<'_>,
4420    trusted_authorities: Option<&HashSet<String>>,
4421    robot_did: Option<&str>,
4422    now_iso: &str,
4423) -> Result<Option<Value>> {
4424    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
4425    let now = rv::require_now(now_iso)?;
4426    let opts = VerifyOptions {
4427        trusted_issuers: trusted_authorities,
4428        ..VerifyOptions::window(Window::FromRequired)
4429    };
4430    let v = match rv::verify_robotics_credential(
4431        credential,
4432        keys,
4433        Some(DECOMMISSION_TYPE),
4434        now,
4435        opts,
4436    ) {
4437        Ok(v) => v,
4438        Err(_) => return Ok(None),
4439    };
4440    if let Some(by) = v.subject.get("decommissionedBy") {
4441        if by.as_str() != Some(v.issuer.as_str()) {
4442            return Ok(None);
4443        }
4444    }
4445    if robot_did.is_some_and(|r| v.subject.get("id").and_then(|x| x.as_str()) != Some(r)) {
4446        return Ok(None);
4447    }
4448    Ok(Some(v.subject))
4449}
4450
4451// ---------------------------------------------------------------------------
4452// Regulatory conformance profiles (Phase 5.14)
4453// ---------------------------------------------------------------------------
4454//
4455// A conformance profile is a machine-checkable mapping from Vouch robotics
4456// credentials to the clauses of a public safety or AI regulation. Given the
4457// credentials a robot presents, the checker reports which clauses are satisfied
4458// and cites each one, and an issuer can sign a point-in-time conformance
4459// attestation an auditor or notified body can consume. The profiles are plain
4460// data so every language reproduces them identically.
4461//
4462// This is the open layer: declarative profiles, a deterministic checker, and a
4463// signed point-in-time attestation over the full report. It is a reference
4464// crosswalk to make conformance verifiable in the open, not legal advice.
4465
4466pub const CONFORMANCE_ATTESTATION_TYPE: &str = "RobotConformanceAttestation";
4467
4468/// How well-sourced a requirement's clause citation is. A profile can be a
4469/// useful crosswalk while its citations are only as good as the sources that
4470/// were available, and a reader is entitled to know which. Every report and
4471/// every signed attestation carries these, so a conformance result never
4472/// implies more authority over the regulation than it has.
4473///
4474/// The clause text was read from the official published source.
4475pub const CITATION_VERIFIED_PRIMARY: &str = "verified-primary";
4476/// The mapping is believed sound, but the clause number comes from secondary
4477/// sources rather than the standard or official journal itself. The default,
4478/// because it is the honest default.
4479pub const CITATION_UNVERIFIED_SECONDARY: &str = "unverified-secondary";
4480/// Not a clause reference at all, only a description of the topic. An assessor
4481/// cannot look it up.
4482pub const CITATION_DESCRIPTIVE: &str = "descriptive";
4483
4484/// Every citation provenance value, in report order.
4485pub const CITATION_STATUSES: &[&str] = &[
4486    CITATION_VERIFIED_PRIMARY,
4487    CITATION_UNVERIFIED_SECONDARY,
4488    CITATION_DESCRIPTIVE,
4489];
4490
4491// Citation notes shared by several requirements. Macros rather than consts so
4492// they can be `concat!`-ed into the longer per-requirement notes, byte-for-byte
4493// identical with the Python, TypeScript and Go profiles.
4494macro_rules! iso_paywall_note {
4495    () => {
4496        "Clause number taken from secondary sources; the standard is paywalled \
4497         and the text has not been read."
4498    };
4499}
4500
4501macro_rules! iso_10218_note {
4502    () => {
4503        concat!(
4504            iso_paywall_note!(),
4505            " ISO 10218-1/-2:2011 were superseded by the 2025 editions (in \
4506             force 1 April 2025); this mapping still cites the 2011 clause \
4507             numbering and has not been migrated."
4508        )
4509    };
4510}
4511
4512macro_rules! oj_note {
4513    () => {
4514        "Article number taken from a third-party reproduction of the Official \
4515         Journal text, not from EUR-Lex itself."
4516    };
4517}
4518
4519macro_rules! ul_note {
4520    () => {
4521        "UL 3300 (now ANSI/CAN/UL 3300:2024) is paywalled and no clause \
4522         numbering was available; this names the topic only and cannot be \
4523         looked up."
4524    };
4525}
4526
4527/// One requirement in a profile: a clause of a regulation mapped to the
4528/// credential type and field paths that satisfy it.
4529struct ProfileRequirement {
4530    id: &'static str,
4531    clause: &'static str,
4532    title: &'static str,
4533    credential: &'static str,
4534    fields: &'static [&'static str],
4535    /// Subject paths that must hold boolean `true`, for requirements where mere
4536    /// presence is not evidence: a heartbeat reporting an envelope breach is not
4537    /// evidence of having stayed inside the envelope. This is the boolean subset
4538    /// of the `expect` map the Python, TypeScript and Go profiles carry; the
4539    /// built-in profiles use only boolean expectations.
4540    expect_true: &'static [&'static str],
4541    /// Provenance of the `clause` reference above, one of [`CITATION_STATUSES`].
4542    citation: &'static str,
4543    /// Anything a reader should know about the citation, such as a known
4544    /// conflict between sources.
4545    citation_note: Option<&'static str>,
4546}
4547
4548/// A built-in conformance profile: a regime, a version, and its requirements.
4549struct ConformanceProfile {
4550    regime: &'static str,
4551    version: &'static str,
4552    requirements: &'static [ProfileRequirement],
4553}
4554
4555const ISO_10218_REQUIREMENTS: &[ProfileRequirement] = &[
4556    ProfileRequirement {
4557        id: "iso10218-identification",
4558        clause: "ISO 10218-1:2011, 5.2",
4559        title: "Robot identification bound to its hardware",
4560        credential: "RobotIdentityCredential",
4561        fields: &["hardwareRoot.kind", "hardwareRoot.attestation"],
4562        expect_true: &[],
4563        citation: CITATION_UNVERIFIED_SECONDARY,
4564        citation_note: Some(iso_10218_note!()),
4565    },
4566    ProfileRequirement {
4567        id: "iso10218-software-integrity",
4568        clause: "ISO 10218-1:2011, 5.3",
4569        title: "Control software and configuration integrity",
4570        credential: "ModelProvenanceAttestation",
4571        fields: &["vla.weightsHash"],
4572        expect_true: &[],
4573        citation: CITATION_UNVERIFIED_SECONDARY,
4574        citation_note: Some(iso_10218_note!()),
4575    },
4576    ProfileRequirement {
4577        id: "iso10218-limits",
4578        clause: "ISO 10218-1:2011, 5.6",
4579        title: "Limiting of speed, force, and workspace",
4580        credential: "PhysicalCapabilityScope",
4581        fields: &[
4582            "physicalScope.maxForceN",
4583            "physicalScope.maxSpeedMps",
4584            "physicalScope.allowedZones",
4585        ],
4586        expect_true: &[],
4587        citation: CITATION_UNVERIFIED_SECONDARY,
4588        citation_note: Some(iso_10218_note!()),
4589    },
4590    ProfileRequirement {
4591        id: "iso10218-records",
4592        clause: "ISO 10218-2:2011, 5.2",
4593        title: "Records of safety-relevant events",
4594        credential: "RobotSafetyRecordCredential",
4595        fields: &["totalEvents", "logHead"],
4596        expect_true: &[],
4597        citation: CITATION_UNVERIFIED_SECONDARY,
4598        citation_note: Some(iso_10218_note!()),
4599    },
4600];
4601
4602const ISO_TS_15066_REQUIREMENTS: &[ProfileRequirement] = &[
4603    ProfileRequirement {
4604        id: "iso15066-power-force-limiting",
4605        clause: "ISO/TS 15066:2016, 5.5.4",
4606        title: "Power and force limiting near humans",
4607        credential: "PhysicalCapabilityScope",
4608        fields: &[
4609            "physicalScope.maxSpeedNearHumansMps",
4610            "physicalScope.maxForceN",
4611        ],
4612        expect_true: &[],
4613        citation: CITATION_UNVERIFIED_SECONDARY,
4614        citation_note: Some(concat!(
4615            iso_paywall_note!(),
4616            " Secondary sources disagree on whether power and force limiting \
4617             is 5.5.4 or 5.5.2; confirm against the published table of \
4618             contents before relying on the number."
4619        )),
4620    },
4621    ProfileRequirement {
4622        id: "iso15066-collaborative-workspace",
4623        clause: "ISO/TS 15066:2016, 5.5.2",
4624        title: "Defined collaborative workspace",
4625        credential: "PhysicalCapabilityScope",
4626        fields: &["physicalScope.allowedZones"],
4627        expect_true: &[],
4628        citation: CITATION_UNVERIFIED_SECONDARY,
4629        citation_note: Some(concat!(
4630            iso_paywall_note!(),
4631            " Shares the unresolved 5.5.2/5.5.4 numbering conflict with \
4632             iso15066-power-force-limiting."
4633        )),
4634    },
4635    ProfileRequirement {
4636        id: "iso15066-monitoring",
4637        clause: "ISO/TS 15066:2016, 5.2",
4638        title: "Continuous monitoring of the collaborative operation",
4639        credential: "RobotHeartbeatCredential",
4640        fields: &["motionDigest"],
4641        expect_true: &["motionDigest.withinEnvelope"],
4642        citation: CITATION_UNVERIFIED_SECONDARY,
4643        citation_note: Some(iso_paywall_note!()),
4644    },
4645];
4646
4647const EU_MACHINERY_REQUIREMENTS: &[ProfileRequirement] = &[
4648    ProfileRequirement {
4649        id: "eu-mr-identification",
4650        clause: "Reg (EU) 2023/1230, Annex III 1.7.4",
4651        title: "Machinery identification and traceability",
4652        credential: "RobotIdentityCredential",
4653        fields: &["make", "model", "serial"],
4654        expect_true: &[],
4655        citation: CITATION_UNVERIFIED_SECONDARY,
4656        citation_note: Some(oj_note!()),
4657    },
4658    ProfileRequirement {
4659        id: "eu-mr-software-integrity",
4660        clause: "Reg (EU) 2023/1230, Annex III 1.1.9",
4661        title: "Protection against corruption of safety software",
4662        credential: "ModelProvenanceAttestation",
4663        fields: &["vla.weightsHash", "vla.safetyPolicy"],
4664        expect_true: &[],
4665        citation: CITATION_UNVERIFIED_SECONDARY,
4666        citation_note: Some(concat!(
4667            oj_note!(),
4668            " The Annex III subclause for protection against corruption has \
4669             not been confirmed and may need to be re-pointed."
4670        )),
4671    },
4672    ProfileRequirement {
4673        id: "eu-mr-safe-limits",
4674        clause: "Reg (EU) 2023/1230, Annex III 1.2.1",
4675        title: "Safety and reliability of control systems and limits",
4676        credential: "PhysicalCapabilityScope",
4677        fields: &["physicalScope.maxForceN"],
4678        expect_true: &[],
4679        citation: CITATION_UNVERIFIED_SECONDARY,
4680        citation_note: Some(oj_note!()),
4681    },
4682    ProfileRequirement {
4683        id: "eu-mr-records",
4684        clause: "Reg (EU) 2023/1230, Annex III 1.2.1",
4685        title: "Recording of safety-relevant data",
4686        credential: "RobotSafetyRecordCredential",
4687        fields: &["totalEvents", "logHead"],
4688        expect_true: &[],
4689        citation: CITATION_UNVERIFIED_SECONDARY,
4690        citation_note: Some(oj_note!()),
4691    },
4692];
4693
4694const EU_AI_ACT_REQUIREMENTS: &[ProfileRequirement] = &[
4695    ProfileRequirement {
4696        id: "eu-aia-record-keeping",
4697        clause: "Reg (EU) 2024/1689, Art. 12",
4698        title: "Automatic recording of events (logging)",
4699        credential: "RobotSafetyRecordCredential",
4700        fields: &["logHead"],
4701        expect_true: &[],
4702        citation: CITATION_UNVERIFIED_SECONDARY,
4703        citation_note: Some(oj_note!()),
4704    },
4705    ProfileRequirement {
4706        id: "eu-aia-transparency",
4707        clause: "Reg (EU) 2024/1689, Art. 13",
4708        title: "Model and configuration transparency",
4709        credential: "ModelProvenanceAttestation",
4710        fields: &["vla.modelName", "vla.configHash"],
4711        expect_true: &[],
4712        citation: CITATION_UNVERIFIED_SECONDARY,
4713        citation_note: Some(oj_note!()),
4714    },
4715    ProfileRequirement {
4716        id: "eu-aia-human-oversight",
4717        clause: "Reg (EU) 2024/1689, Art. 14",
4718        title: "Human oversight through enforced operating limits",
4719        credential: "PhysicalCapabilityScope",
4720        fields: &["physicalScope.maxSpeedNearHumansMps"],
4721        expect_true: &[],
4722        citation: CITATION_UNVERIFIED_SECONDARY,
4723        citation_note: Some(concat!(
4724            oj_note!(),
4725            " Art. 14 also requires a means for the overseer to intervene or \
4726             stop the system, which an operating-limit scope alone does not \
4727             evidence."
4728        )),
4729    },
4730    ProfileRequirement {
4731        id: "eu-aia-accuracy-robustness",
4732        clause: "Reg (EU) 2024/1689, Art. 15",
4733        title: "Accuracy and robustness traceable to a known build",
4734        credential: "ModelProvenanceAttestation",
4735        fields: &["vla.weightsHash"],
4736        expect_true: &[],
4737        citation: CITATION_UNVERIFIED_SECONDARY,
4738        citation_note: Some(oj_note!()),
4739    },
4740];
4741
4742const UL_3300_REQUIREMENTS: &[ProfileRequirement] = &[
4743    ProfileRequirement {
4744        id: "ul3300-identity",
4745        clause: "UL 3300, identification",
4746        title: "Robot identity bound to its hardware",
4747        credential: "RobotIdentityCredential",
4748        fields: &["hardwareRoot.kind", "hardwareRoot.attestation"],
4749        expect_true: &[],
4750        citation: CITATION_DESCRIPTIVE,
4751        citation_note: Some(ul_note!()),
4752    },
4753    ProfileRequirement {
4754        id: "ul3300-operating-limits",
4755        clause: "UL 3300, operating limits",
4756        title: "Enforced speed and zone limits",
4757        credential: "PhysicalCapabilityScope",
4758        fields: &["physicalScope.maxSpeedMps", "physicalScope.allowedZones"],
4759        expect_true: &[],
4760        citation: CITATION_DESCRIPTIVE,
4761        citation_note: Some(ul_note!()),
4762    },
4763    ProfileRequirement {
4764        id: "ul3300-perception-integrity",
4765        clause: "UL 3300, sensing integrity",
4766        title: "Integrity of perception used for safe operation",
4767        credential: "PerceptionProvenanceCredential",
4768        fields: &["frameHash"],
4769        expect_true: &[],
4770        citation: CITATION_DESCRIPTIVE,
4771        citation_note: Some(ul_note!()),
4772    },
4773    ProfileRequirement {
4774        id: "ul3300-records",
4775        clause: "UL 3300, incident records",
4776        title: "Records of safety-relevant incidents",
4777        credential: "RobotSafetyRecordCredential",
4778        fields: &["totalEvents", "logHead"],
4779        expect_true: &[],
4780        citation: CITATION_DESCRIPTIVE,
4781        citation_note: Some(ul_note!()),
4782    },
4783];
4784
4785/// Return a built-in profile by id, or `None` if it is unknown. The five profiles
4786/// cover ISO 10218-1/-2 (industrial), ISO/TS 15066 (collaborative), the EU
4787/// Machinery Regulation 2023/1230, the EU AI Act high-risk requirements, and
4788/// UL 3300 (service and mobile robots).
4789fn conformance_profile(profile_id: &str) -> Option<ConformanceProfile> {
4790    match profile_id {
4791        "iso-10218" => Some(ConformanceProfile {
4792            regime: "ISO 10218-1/-2 industrial robots",
4793            version: "2011 (superseded by the 2025 editions; mapping not yet migrated)",
4794            requirements: ISO_10218_REQUIREMENTS,
4795        }),
4796        "iso-ts-15066" => Some(ConformanceProfile {
4797            regime: "ISO/TS 15066 collaborative robots",
4798            version: "2016",
4799            requirements: ISO_TS_15066_REQUIREMENTS,
4800        }),
4801        "eu-machinery-2023-1230" => Some(ConformanceProfile {
4802            regime: "EU Machinery Regulation 2023/1230",
4803            version: "2023",
4804            requirements: EU_MACHINERY_REQUIREMENTS,
4805        }),
4806        "eu-ai-act-high-risk" => Some(ConformanceProfile {
4807            regime: "EU AI Act high-risk systems",
4808            version: "2024",
4809            requirements: EU_AI_ACT_REQUIREMENTS,
4810        }),
4811        "ul-3300" => Some(ConformanceProfile {
4812            regime: "UL 3300 service, communication, and mobile robots",
4813            version: "2022 (see ANSI/CAN/UL 3300:2024)",
4814            requirements: UL_3300_REQUIREMENTS,
4815        }),
4816        _ => None,
4817    }
4818}
4819
4820/// A built-in conformance profile as JSON (`{regime, version, requirements:
4821/// [{id, clause, title, credential, fields, expect, citation,
4822/// citationNote?}]}`), or `null` for an unknown id.
4823pub fn conformance_profile_json(profile_id: &str) -> Value {
4824    let Some(p) = conformance_profile(profile_id) else {
4825        return Value::Null;
4826    };
4827    let requirements: Vec<Value> = p
4828        .requirements
4829        .iter()
4830        .map(|r| {
4831            let expect: Map<String, Value> = r
4832                .expect_true
4833                .iter()
4834                .map(|f| (f.to_string(), Value::Bool(true)))
4835                .collect();
4836            let mut m = Map::new();
4837            m.insert("id".into(), json!(r.id));
4838            m.insert("clause".into(), json!(r.clause));
4839            m.insert("title".into(), json!(r.title));
4840            m.insert("credential".into(), json!(r.credential));
4841            m.insert("fields".into(), json!(r.fields));
4842            m.insert("expect".into(), Value::Object(expect));
4843            m.insert("citation".into(), json!(r.citation));
4844            if let Some(n) = r.citation_note {
4845                m.insert("citationNote".into(), json!(n));
4846            }
4847            Value::Object(m)
4848        })
4849        .collect();
4850    json!({"regime": p.regime, "version": p.version, "requirements": requirements})
4851}
4852
4853/// The type array of a credential, accepting a JSON string or an array of strings.
4854fn credential_types(credential: &Value) -> Vec<&str> {
4855    match credential.get("type") {
4856        Some(Value::String(s)) => vec![s.as_str()],
4857        Some(Value::Array(items)) => items.iter().filter_map(|v| v.as_str()).collect(),
4858        _ => Vec::new(),
4859    }
4860}
4861
4862/// Follow a dot-separated path from the credentialSubject, returning the value at
4863/// the leaf or `None` if any segment is missing or not an object.
4864fn path_value<'a>(subject: &'a Value, path: &str) -> Option<&'a Value> {
4865    let mut node = subject;
4866    for part in path.split('.') {
4867        match node {
4868            Value::Object(map) => match map.get(part) {
4869                Some(v) => node = v,
4870                None => return None,
4871            },
4872            _ => return None,
4873        }
4874    }
4875    Some(node)
4876}
4877
4878/// True when a value is present and non-empty: not null, and not an empty array
4879/// or empty object. Any other value (including `false`, `0`, or `""`) counts.
4880fn value_present(value: &Value) -> bool {
4881    match value {
4882        Value::Null => false,
4883        Value::Array(a) => !a.is_empty(),
4884        Value::Object(o) => !o.is_empty(),
4885        _ => true,
4886    }
4887}
4888
4889/// True when `credential` satisfies `requirement`: its type array includes the
4890/// requirement's credential type, its credentialSubject has a non-null,
4891/// non-empty value at every field path, and every `expect_true` path holds
4892/// boolean `true`. Presence alone is not evidence: a heartbeat that reports an
4893/// envelope breach does not evidence having stayed inside the envelope.
4894fn credential_satisfies(credential: &Value, requirement: &ProfileRequirement) -> bool {
4895    if !credential_types(credential).contains(&requirement.credential) {
4896        return false;
4897    }
4898    let empty = Value::Object(Map::new());
4899    let subject = credential.get("credentialSubject").unwrap_or(&empty);
4900    for path in requirement.fields {
4901        match path_value(subject, path) {
4902            Some(v) if value_present(v) => {}
4903            _ => return false,
4904        }
4905    }
4906    for path in requirement.expect_true {
4907        if path_value(subject, path) != Some(&Value::Bool(true)) {
4908            return false;
4909        }
4910    }
4911    true
4912}
4913
4914/// Check the presented `credentials` against the named profile and return a
4915/// deterministic report. Each requirement is satisfied when some presented
4916/// credential matches its type and has every required field. The caller is
4917/// expected to have verified the credentials' signatures first; this checks
4918/// structure and coverage, not proofs.
4919///
4920/// Every requirement carries the provenance of its clause citation, and the
4921/// report totals them, so a result never reads as more authoritative about the
4922/// regulation than its sources are.
4923///
4924/// The report has exactly `{profileId, regime, version, conforms,
4925/// satisfiedCount, totalCount, citations:{...},
4926/// requirements:[{id, clause, title, satisfied, citation, citationNote?}]}`.
4927pub fn check_conformance(credentials: &[Value], profile_id: &str) -> Result<Value> {
4928    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credentials);
4929    check_conformance_for(credentials, profile_id, None)
4930}
4931
4932/// [`check_conformance`] bound to one robot: with `robot_did`, only credentials
4933/// whose `credentialSubject.id` is that robot count (so another robot's
4934/// credential mixed into the set cannot fill a gap), and the report carries
4935/// `robotDid`.
4936pub fn check_conformance_for(
4937    credentials: &[Value],
4938    profile_id: &str,
4939    robot_did: Option<&str>,
4940) -> Result<Value> {
4941    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credentials);
4942    let prof = conformance_profile(profile_id)
4943        .ok_or_else(|| CoreError::Json(format!("unknown conformance profile: {profile_id}")))?;
4944    if robot_did.is_some_and(str::is_empty) {
4945        return Err(CoreError::Json("robot_did must be a non-empty DID".into()));
4946    }
4947    let presented: Vec<&Value> = credentials
4948        .iter()
4949        .filter(|c| c.is_object())
4950        .filter(|c| {
4951            robot_did.is_none_or(|r| {
4952                c.get("credentialSubject")
4953                    .and_then(|s| s.get("id"))
4954                    .and_then(|x| x.as_str())
4955                    == Some(r)
4956            })
4957        })
4958        .collect();
4959
4960    let mut results: Vec<Value> = Vec::with_capacity(prof.requirements.len());
4961    let mut satisfied = 0i64;
4962    let mut citations = Map::new();
4963    for status in CITATION_STATUSES {
4964        citations.insert((*status).into(), json!(0i64));
4965    }
4966    for requirement in prof.requirements {
4967        let ok = presented
4968            .iter()
4969            .any(|c| credential_satisfies(c, requirement));
4970        if ok {
4971            satisfied += 1;
4972        }
4973        let seen = citations
4974            .get(requirement.citation)
4975            .and_then(|v| v.as_i64())
4976            .unwrap_or(0);
4977        citations.insert(requirement.citation.into(), json!(seen + 1));
4978        let mut result = Map::new();
4979        result.insert("id".into(), json!(requirement.id));
4980        result.insert("clause".into(), json!(requirement.clause));
4981        result.insert("title".into(), json!(requirement.title));
4982        result.insert("satisfied".into(), json!(ok));
4983        result.insert("citation".into(), json!(requirement.citation));
4984        if let Some(note) = requirement.citation_note {
4985            result.insert("citationNote".into(), json!(note));
4986        }
4987        results.push(Value::Object(result));
4988    }
4989    let total = prof.requirements.len() as i64;
4990
4991    let mut report = Map::new();
4992    report.insert("profileId".into(), json!(profile_id));
4993    report.insert("regime".into(), json!(prof.regime));
4994    report.insert("version".into(), json!(prof.version));
4995    report.insert("conforms".into(), json!(satisfied == total));
4996    report.insert("satisfiedCount".into(), json!(satisfied));
4997    report.insert("totalCount".into(), json!(total));
4998    report.insert("citations".into(), Value::Object(citations));
4999    report.insert("requirements".into(), Value::Array(results));
5000    if let Some(r) = robot_did {
5001        report.insert("robotDid".into(), json!(r));
5002    }
5003    Ok(Value::Object(report))
5004}
5005
5006/// Multibase SHA-256 of the JCS-canonical report, for binding into an
5007/// attestation. Every language canonicalizes identically, so the digest is the
5008/// same byte string everywhere.
5009pub fn report_digest(report: &Value) -> String {
5010    mb64(&Sha256::digest(jcs::canonicalize(report)))
5011}
5012
5013/// Parameters for [`build_conformance_attestation`]. The signer is the robot, its
5014/// owner, or an assessing authority; `robot_did` names the robot the attestation
5015/// is about. `report` is produced by [`check_conformance`] and is embedded and
5016/// bound by digest. When `valid_seconds` is set it bounds the attestation.
5017#[derive(Debug, Clone)]
5018pub struct BuildConformanceAttestation {
5019    pub issuer_did: String,
5020    pub robot_did: String,
5021    pub report: Value,
5022    pub valid_from: String,
5023    pub valid_until: Option<String>,
5024}
5025
5026/// Build a signed point-in-time `RobotConformanceAttestation` for `robot_did`
5027/// over a `report` produced by [`check_conformance`]. The report is embedded and
5028/// bound by digest.
5029pub fn build_conformance_attestation(
5030    signer_seed: &[u8],
5031    params: &BuildConformanceAttestation,
5032) -> Result<Value> {
5033    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
5034    if params.robot_did.is_empty() {
5035        return Err(CoreError::Json("robot_did is required".into()));
5036    }
5037    let report = params
5038        .report
5039        .as_object()
5040        .ok_or_else(|| CoreError::Json("report must come from check_conformance".into()))?;
5041    if !report.contains_key("profileId") || !report.contains_key("conforms") {
5042        return Err(CoreError::Json(
5043            "report must come from check_conformance".into(),
5044        ));
5045    }
5046
5047    let mut subject = Map::new();
5048    subject.insert("id".into(), json!(params.robot_did));
5049    subject.insert(
5050        "profileId".into(),
5051        report.get("profileId").cloned().unwrap_or(Value::Null),
5052    );
5053    subject.insert(
5054        "regime".into(),
5055        report.get("regime").cloned().unwrap_or(Value::Null),
5056    );
5057    subject.insert(
5058        "conforms".into(),
5059        report.get("conforms").cloned().unwrap_or(Value::Null),
5060    );
5061    subject.insert(
5062        "satisfiedCount".into(),
5063        report.get("satisfiedCount").cloned().unwrap_or(Value::Null),
5064    );
5065    subject.insert(
5066        "totalCount".into(),
5067        report.get("totalCount").cloned().unwrap_or(Value::Null),
5068    );
5069    subject.insert(
5070        "citations".into(),
5071        report
5072            .get("citations")
5073            .cloned()
5074            .unwrap_or_else(|| Value::Object(Map::new())),
5075    );
5076    subject.insert("reportDigest".into(), json!(report_digest(&params.report)));
5077    subject.insert("report".into(), params.report.clone());
5078
5079    let mut cred = Map::new();
5080    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
5081    cred.insert(
5082        "type".into(),
5083        json!(["VerifiableCredential", CONFORMANCE_ATTESTATION_TYPE]),
5084    );
5085    cred.insert("issuer".into(), json!(params.issuer_did));
5086    cred.insert("validFrom".into(), json!(params.valid_from));
5087    if let Some(vu) = &params.valid_until {
5088        cred.insert("validUntil".into(), json!(vu));
5089    }
5090    cred.insert("credentialSubject".into(), Value::Object(subject));
5091
5092    let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), &params.valid_from);
5093    data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
5094}
5095
5096/// Verify a conformance attestation: the issuer's proof bound to the issuer,
5097/// the window at `now_iso` (validFrom required), that the embedded report
5098/// matches its bound digest, that every summary field (profileId, regime,
5099/// conforms, satisfiedCount, totalCount) matches the report, and that
5100/// `conforms` is a boolean. When given, the attestation must be about
5101/// `robot_did` and its issuer must be in `trusted_issuers`. Returns the
5102/// credentialSubject on success, `None` if invalid.
5103pub fn verify_conformance_attestation(
5104    credential: &Value,
5105    keys: Keys<'_>,
5106    robot_did: Option<&str>,
5107    trusted_issuers: Option<&HashSet<String>>,
5108    now_iso: &str,
5109) -> Result<Option<Value>> {
5110    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
5111    let now = rv::require_now(now_iso)?;
5112    let opts = VerifyOptions {
5113        trusted_issuers,
5114        ..VerifyOptions::window(Window::FromRequired)
5115    };
5116    let v = match rv::verify_robotics_credential(
5117        credential,
5118        keys,
5119        Some(CONFORMANCE_ATTESTATION_TYPE),
5120        now,
5121        opts,
5122    ) {
5123        Ok(v) => v,
5124        Err(_) => return Ok(None),
5125    };
5126    let subject = v.subject;
5127    let embedded = match subject.get("report") {
5128        Some(r) if r.is_object() => r,
5129        _ => return Ok(None),
5130    };
5131    if subject.get("reportDigest").and_then(|v| v.as_str())
5132        != Some(report_digest(embedded).as_str())
5133    {
5134        return Ok(None);
5135    }
5136    for name in [
5137        "profileId",
5138        "regime",
5139        "conforms",
5140        "satisfiedCount",
5141        "totalCount",
5142    ] {
5143        if subject.get(name) != embedded.get(name) {
5144            return Ok(None);
5145        }
5146    }
5147    if !subject.get("conforms").is_some_and(|c| c.is_boolean()) {
5148        return Ok(None);
5149    }
5150    // A report bound to one robot cannot be attested as being about another.
5151    if embedded.get("robotDid").is_some() && embedded.get("robotDid") != subject.get("id") {
5152        return Ok(None);
5153    }
5154    if robot_did.is_some_and(|r| subject.get("id").and_then(|x| x.as_str()) != Some(r)) {
5155        return Ok(None);
5156    }
5157    Ok(Some(subject))
5158}
5159
5160// ---------------------------------------------------------------------------
5161// Post-quantum robot credentials (Phase 5.13)
5162// ---------------------------------------------------------------------------
5163//
5164// A robot fielded today lives for ten to twenty years, longer than classical
5165// Ed25519 is expected to stay safe, so a robot identity signed now could be
5166// forged once a quantum computer arrives. This section makes the hybrid
5167// post-quantum cryptosuite (`hybrid-eddsa-mldsa44-jcs-2026`, a classical
5168// Ed25519 signature alongside an ML-DSA-44 signature) available for robot
5169// credentials so they stay unforgeable across the robot's whole service life.
5170//
5171//   - sign_pq: attach a hybrid proof to a robot credential.
5172//   - verify_robot_credential: verify a robot credential whether it carries a
5173//     classical or a hybrid proof, auto-detected from the proof, so a fleet can
5174//     move to PQ gradually without breaking the classical credentials already in
5175//     the field.
5176//   - migrate_to_pq: re-sign a fielded robot's classical credential under PQ.
5177//
5178// This is the open layer: hybrid signing, backward-compatible verification, and
5179// a software re-signing migration path. It reuses the proof set of
5180// [`crate::hybrid`] and the ML-DSA-44 and multikey helpers rather than
5181// re-deriving any cryptography.
5182
5183/// The classical (Ed25519-only) robot credential cryptosuite.
5184pub const CLASSICAL_CRYPTOSUITE: &str = data_integrity::CRYPTOSUITE_ID;
5185/// The ML-DSA-44 proof a post-quantum robot credential carries next to its
5186/// classical proof, in a proof set.
5187pub const POST_QUANTUM_CRYPTOSUITE: &str = hybrid::MLDSA44_CRYPTOSUITE_ID;
5188
5189/// Coerce an ML-DSA-44 public key supplied either as raw 1312-byte bytes or as a
5190/// Multikey string into raw bytes. Errors on the wrong length or a non-ML-DSA
5191/// multikey.
5192pub fn coerce_mldsa44_public(mldsa44_public: &[u8]) -> Result<Vec<u8>> {
5193    if mldsa44_public.len() != MLDSA44_PUBLIC_LEN {
5194        return Err(CoreError::InvalidKeyLength {
5195            expected: MLDSA44_PUBLIC_LEN,
5196            got: mldsa44_public.len(),
5197        });
5198    }
5199    Ok(mldsa44_public.to_vec())
5200}
5201
5202/// Coerce an ML-DSA-44 Multikey string into raw public-key bytes. Errors if the
5203/// multikey does not carry an ML-DSA-44 key.
5204pub fn mldsa44_public_from_multikey(multikey_str: &str) -> Result<Vec<u8>> {
5205    let decoded = multikey::decode(multikey_str)?;
5206    if decoded.algorithm != "ML-DSA-44" {
5207        return Err(CoreError::InvalidMultikey(format!(
5208            "expected an ML-DSA-44 multikey, got {}",
5209            decoded.algorithm
5210        )));
5211    }
5212    coerce_mldsa44_public(&decoded.raw_key)
5213}
5214
5215fn pq_verification_method(credential: &Value) -> String {
5216    let issuer = credential
5217        .as_object()
5218        .and_then(|o| o.get("issuer"))
5219        .and_then(|v| v.as_str())
5220        .unwrap_or("");
5221    format!("{issuer}#key-1")
5222}
5223
5224/// The ML-DSA-44 verification method slot, matching the `#key-2` convention the
5225/// language SDKs derive for the post-quantum member of a proof set.
5226fn pq_mldsa_verification_method(credential: &Value) -> String {
5227    let issuer = credential
5228        .as_object()
5229        .and_then(|o| o.get("issuer"))
5230        .and_then(|v| v.as_str())
5231        .unwrap_or("");
5232    format!("{issuer}#key-2")
5233}
5234
5235/// Attach a hybrid (classical Ed25519 plus post-quantum ML-DSA-44) Data Integrity
5236/// proof to a pre-built robot `credential`. Any existing proof is replaced. The
5237/// robot signs with its Ed25519 seed and its ML-DSA-44 key pair; `created` is the
5238/// caller-supplied ISO-8601 instant, keeping the core deterministic.
5239pub fn sign_pq(
5240    credential: &Value,
5241    ed25519_seed: &[u8],
5242    mldsa: &MlDsa44KeyPair,
5243    created: &str,
5244) -> Result<Value> {
5245    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
5246    let ed_vm = pq_verification_method(credential);
5247    let ml_vm = pq_mldsa_verification_method(credential);
5248    hybrid::sign_dual(credential, ed25519_seed, mldsa, &ed_vm, &ml_vm, created)
5249}
5250
5251/// Return true if `credential` carries a post-quantum proof: a `proof` array
5252/// holding an ML-DSA-44 proof. One proof object is never post-quantum (the
5253/// earlier composite proof is refused by every verifier).
5254pub fn is_pq(credential: &Value) -> bool {
5255    crate::nesting::deep_guard!(false; credential);
5256    match credential.as_object().and_then(|o| o.get("proof")) {
5257        Some(Value::Array(proofs)) => proofs
5258            .iter()
5259            .any(|p| hybrid::Suite::of_proof(p) == Some(hybrid::Suite::Mldsa44)),
5260        _ => false,
5261    }
5262}
5263
5264/// Verify a post-quantum robot credential: a proof set whose Ed25519 and
5265/// ML-DSA-44 signatures both validate. One proof object is refused, the
5266/// earlier composite proof included.
5267fn verify_pq_proof_set(
5268    credential: &Value,
5269    ed25519_public_key: &[u8],
5270    mldsa44_public_key: &[u8],
5271) -> Result<bool> {
5272    match credential.as_object().and_then(|o| o.get("proof")) {
5273        Some(Value::Array(_)) => {
5274            hybrid::verify_dual(credential, ed25519_public_key, mldsa44_public_key)
5275        }
5276        _ => Ok(false),
5277    }
5278}
5279
5280/// Verify a hybrid robot credential. Both the Ed25519 and the ML-DSA-44 signature
5281/// MUST validate. `mldsa44_public_key` is raw 1312-byte bytes or an ML-DSA-44
5282/// Multikey string (pass `mldsa44_multikey` for the string form).
5283pub fn verify_pq(
5284    credential: &Value,
5285    ed25519_public_key: &[u8],
5286    mldsa44_public_key: &[u8],
5287) -> Result<bool> {
5288    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
5289    let resolved_ml = coerce_mldsa44_public(mldsa44_public_key)?;
5290    verify_pq_proof_set(credential, ed25519_public_key, &resolved_ml)
5291}
5292
5293/// [`verify_robot_credential`] with the ML-DSA-44 key taken from a key source
5294/// like the Ed25519 key: a bare key, or a `{did: key}` map / resolver from which
5295/// the entry for the credential's issuer is used (no entry fails a
5296/// post-quantum credential). Map values are raw 1312-byte keys or ML-DSA-44
5297/// Multikey strings as UTF-8 bytes.
5298pub fn verify_robot_credential_keyed(
5299    credential: &Value,
5300    ed_keys: Keys<'_>,
5301    mldsa44_keys: Option<Keys<'_>>,
5302    expected_type: Option<&str>,
5303    now_iso: &str,
5304) -> Result<bool> {
5305    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
5306    let ml = match mldsa44_keys {
5307        None => return verify_robot_credential(credential, ed_keys, None, expected_type, now_iso),
5308        Some(k) => k,
5309    };
5310    let issuer = rv::issuer_id(credential.get("issuer"))
5311        .unwrap_or("")
5312        .to_string();
5313    let picked: Option<Vec<u8>> = match ml {
5314        Keys::Embedded | Keys::Pinned(_) => None,
5315        Keys::Bare(k) => Some(k.to_vec()),
5316        Keys::One(d, k) => (d == issuer).then(|| k.to_vec()),
5317        Keys::Map(m) => m.get(&issuer).cloned(),
5318        Keys::Resolver(f) => f(&issuer),
5319    };
5320    match picked {
5321        Some(k) => verify_robot_credential(credential, ed_keys, Some(&k), expected_type, now_iso),
5322        // A post-quantum credential needs its issuer's ML-DSA key; a classical
5323        // one given an ML-DSA source is refused by the same rule as a bare key.
5324        None => Ok(false),
5325    }
5326}
5327
5328/// The backward-compatible robot credential verify a fleet uses while
5329/// migrating to post-quantum: auto-detects a hybrid proof set.
5330///
5331/// Every proof must be bound to the issuer (`proofPurpose` assertionMethod and
5332/// a verification method of the issuer DID), and the Ed25519 key must belong to
5333/// the issuer (the key inside a did:key, or `ed_keys` as a `{did: key}`
5334/// source for any other DID). Present validity bounds must be strict protocol
5335/// times with `now_iso` inside. When `expected_type` is given the credential
5336/// must carry it. A post-quantum credential requires `mldsa44_public_key`;
5337/// supplying one for a classical credential refuses it (so a stripped ML-DSA
5338/// proof cannot pass as classical). Malformed input returns `false`.
5339pub fn verify_robot_credential(
5340    credential: &Value,
5341    ed_keys: Keys<'_>,
5342    mldsa44_public_key: Option<&[u8]>,
5343    expected_type: Option<&str>,
5344    now_iso: &str,
5345) -> Result<bool> {
5346    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
5347    let now = rv::require_now(now_iso)?;
5348    if !credential.is_object() {
5349        return Ok(false);
5350    }
5351    if is_pq(credential) {
5352        let ml = match mldsa44_public_key {
5353            Some(k) => k,
5354            None => return Ok(false),
5355        };
5356        let issuer = match rv::issuer_id(credential.get("issuer")) {
5357            Some(i) => i,
5358            None => return Ok(false),
5359        };
5360        if rv::input_too_large(credential, rv::MAX_CREDENTIAL_BYTES).is_some() {
5361            return Ok(false);
5362        }
5363        let types: Vec<&str> = match credential.get("type") {
5364            Some(Value::String(t)) => vec![t.as_str()],
5365            Some(Value::Array(a)) if a.iter().all(|t| t.is_string()) => {
5366                a.iter().filter_map(|t| t.as_str()).collect()
5367            }
5368            _ => return Ok(false),
5369        };
5370        if expected_type.is_some_and(|e| !types.contains(&e)) {
5371            return Ok(false);
5372        }
5373        let members: Vec<&Value> = match credential.get("proof") {
5374            Some(Value::Array(a)) => a.iter().collect(),
5375            Some(p) => vec![p],
5376            None => return Ok(false),
5377        };
5378        if members.is_empty()
5379            || members
5380                .iter()
5381                .any(|m| rv::proof_unbound_reason(m, issuer).is_some())
5382        {
5383            return Ok(false);
5384        }
5385        if rv::window_reason(credential, Window::IfPresent, now, 0).is_some() {
5386            return Ok(false);
5387        }
5388        let ed = match rv::resolve_issuer_key(issuer, ed_keys) {
5389            Ok(k) => k,
5390            Err(_) => return Ok(false),
5391        };
5392        let resolved_ml = match resolve_mldsa44_public(ml) {
5393            Ok(m) => m,
5394            Err(_) => return Ok(false),
5395        };
5396        return Ok(verify_pq_proof_set(credential, &ed, &resolved_ml).unwrap_or(false));
5397    }
5398    if mldsa44_public_key.is_some() {
5399        return Ok(false);
5400    }
5401    Ok(rv::verify_robotics_credential(
5402        credential,
5403        ed_keys,
5404        expected_type,
5405        now,
5406        VerifyOptions::window(Window::IfPresent),
5407    )
5408    .is_ok())
5409}
5410
5411/// Resolve an ML-DSA-44 public key given either raw bytes or a Multikey string.
5412/// A 1312-byte input is the raw key; otherwise it is parsed as a UTF-8 Multikey.
5413pub fn resolve_mldsa44_public(mldsa44_public_key: &[u8]) -> Result<Vec<u8>> {
5414    if mldsa44_public_key.len() == MLDSA44_PUBLIC_LEN {
5415        return Ok(mldsa44_public_key.to_vec());
5416    }
5417    let s = core::str::from_utf8(mldsa44_public_key).map_err(|_| {
5418        CoreError::InvalidMultikey("ML-DSA-44 key must be raw bytes or a Multikey string".into())
5419    })?;
5420    mldsa44_public_from_multikey(s)
5421}
5422
5423/// Re-sign a fielded robot's classical `credential` under the hybrid PQ
5424/// cryptosuite, preserving its body. The robot holds its current Ed25519 seed and
5425/// an ML-DSA-44 key pair; `created` is the caller-supplied re-signing instant.
5426pub fn migrate_to_pq(
5427    credential: &Value,
5428    ed25519_seed: &[u8],
5429    mldsa: &MlDsa44KeyPair,
5430    created: &str,
5431) -> Result<Value> {
5432    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
5433    sign_pq(credential, ed25519_seed, mldsa, created)
5434}
5435
5436// ---------------------------------------------------------------------------
5437// Cross-embodiment identity continuity (Phase 5.15)
5438// ---------------------------------------------------------------------------
5439//
5440// An AI agent (a policy with its own Vouch identity) can run on one robot body
5441// today and a different body tomorrow. An embodiment credential binds the agent
5442// identity to a specific body (a hardware-rooted robot identity) and that body's
5443// hardware root for a period, signed by the agent's own persistent key. Linking
5444// each embodiment to the previous forms a continuity chain a verifier walks to
5445// confirm the same accountable agent persisted across bodies, re-binding to each
5446// body's hardware root as it moved. A fork check confirms the agent was never
5447// actively embodied in two bodies at once.
5448//
5449// This is the inverse of the ownership custody chain: there one body passes
5450// between owners; here one mind passes between bodies, and the constant that
5451// signs every link is the agent identity itself.
5452//
5453// This is the open layer: plain signed embodiment credentials, continuity-chain
5454// verification, and software fork detection. It reuses the core proof path
5455// ([`data_integrity`]) rather than re-deriving any cryptography.
5456
5457pub const EMBODIMENT_TYPE: &str = "AgentEmbodimentCredential";
5458
5459/// Parameters for [`build_embodiment`]. The signer is the agent's own persistent
5460/// key; `agent_did` is both issuer and subject id, so the whole continuity chain
5461/// is signed by one accountable identity. `from_body`, when set, links this
5462/// embodiment to the body the agent left, forming the chain. `valid_until`, when
5463/// set, bounds the active window (used by [`check_no_fork`]).
5464#[derive(Debug, Clone)]
5465pub struct BuildEmbodiment {
5466    pub agent_did: String,
5467    pub body_did: String,
5468    pub body_hardware_root: String,
5469    pub from_body: Option<String>,
5470    pub embodied_at: String,
5471    pub valid_until: Option<String>,
5472}
5473
5474/// Build a signed embodiment credential: the agent `agent_did` authorizes running
5475/// on `body_did`, re-binding to that body's hardware root `body_hardware_root`.
5476/// Signed by the agent's own persistent key. `from_body` links this embodiment to
5477/// the body the agent left.
5478pub fn build_embodiment(agent_seed: &[u8], params: &BuildEmbodiment) -> Result<Value> {
5479    if params.agent_did.is_empty()
5480        || params.body_did.is_empty()
5481        || params.body_hardware_root.is_empty()
5482    {
5483        return Err(CoreError::Json(
5484            "agent_did, body_did, and body_hardware_root are required".into(),
5485        ));
5486    }
5487
5488    let mut subject = Map::new();
5489    subject.insert("id".into(), json!(params.agent_did));
5490    subject.insert("body".into(), json!(params.body_did));
5491    subject.insert("bodyHardwareRoot".into(), json!(params.body_hardware_root));
5492    if let Some(from_body) = &params.from_body {
5493        subject.insert("fromBody".into(), json!(from_body));
5494    }
5495
5496    let mut cred = Map::new();
5497    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
5498    cred.insert(
5499        "type".into(),
5500        json!(["VerifiableCredential", EMBODIMENT_TYPE]),
5501    );
5502    cred.insert("issuer".into(), json!(params.agent_did));
5503    cred.insert("validFrom".into(), json!(params.embodied_at));
5504    if let Some(vu) = &params.valid_until {
5505        cred.insert("validUntil".into(), json!(vu));
5506    }
5507    cred.insert("credentialSubject".into(), Value::Object(subject));
5508
5509    let opts = BuildProofOptions::new(format!("{}#key-1", params.agent_did), &params.embodied_at);
5510    data_integrity::sign(&Value::Object(cred), agent_seed, &opts)
5511}
5512
5513/// Verify an embodiment credential: the agent's proof bound to the agent as
5514/// issuer (a mind authorizes its own embodiment, so the issuer must be
5515/// `credentialSubject.id`), the window at `now_iso` (validFrom required), and
5516/// that the subject carries a `body` and a `bodyHardwareRoot`. When
5517/// `body_hardware_roots` (body DID -> trusted hardware-root key) is given, the
5518/// credential's `bodyHardwareRoot` must match the entry for its body. Returns
5519/// the credentialSubject on success, `None` if invalid.
5520pub fn verify_embodiment(
5521    credential: &Value,
5522    agent_keys: Keys<'_>,
5523    body_hardware_roots: Option<&alloc::collections::BTreeMap<String, String>>,
5524    now_iso: &str,
5525) -> Result<Option<Value>> {
5526    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
5527    let v = match bound(
5528        credential,
5529        agent_keys,
5530        EMBODIMENT_TYPE,
5531        now_iso,
5532        Window::FromRequired,
5533    )? {
5534        Some(v) if issuer_is_subject(&v) => v,
5535        _ => return Ok(None),
5536    };
5537    let body = non_empty_str(&v.subject, "body");
5538    let root = non_empty_str(&v.subject, "bodyHardwareRoot");
5539    let (body, root) = match (body, root) {
5540        (Some(b), Some(r)) => (b, r),
5541        _ => return Ok(None),
5542    };
5543    if let Some(roots) = body_hardware_roots {
5544        if roots.get(body).map(String::as_str) != Some(root) {
5545            return Ok(None);
5546        }
5547    }
5548    Ok(Some(v.subject))
5549}
5550
5551/// Verify an ordered list of embodiment credentials forms a valid continuity
5552/// chain: every link verifies under the same agent (the persistent mind), each
5553/// link's `fromBody` matches the previous link's `body`, and (when given) the
5554/// first `fromBody` is `origin_body`. Links start in order; each earlier link
5555/// must still have been valid when the next one started, and the last link
5556/// must be valid at `now_iso`. The verified links are then checked for forks.
5557/// Returns `(ok, current_body)`.
5558pub fn verify_continuity_chain(
5559    embodiments: &[Value],
5560    agent_keys: Keys<'_>,
5561    origin_body: Option<&str>,
5562    body_hardware_roots: Option<&alloc::collections::BTreeMap<String, String>>,
5563    now_iso: &str,
5564) -> Result<(bool, Option<String>)> {
5565    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); embodiments);
5566    rv::require_now(now_iso)?;
5567    let mut expected_from: Option<String> = origin_body.map(String::from);
5568    let mut current_body: Option<String> = origin_body.map(String::from);
5569    let mut agent: Option<String> = None;
5570    let mut prev_start: Option<i128> = None;
5571    for (i, embodiment) in embodiments.iter().enumerate() {
5572        let at: String = match embodiments.get(i + 1) {
5573            Some(next) => match next.get("validFrom").and_then(|v| v.as_str()) {
5574                Some(t) if rv::time_ns(next.get("validFrom")).is_some() => t.to_string(),
5575                _ => return Ok((false, None)),
5576            },
5577            None => now_iso.to_string(),
5578        };
5579        let subject = match verify_embodiment(embodiment, agent_keys, body_hardware_roots, &at)? {
5580            Some(s) => s,
5581            None => return Ok((false, None)),
5582        };
5583        let id = subject.get("id").and_then(|v| v.as_str()).map(String::from);
5584        match &agent {
5585            None => agent = id,
5586            Some(a) if id.as_deref() == Some(a.as_str()) => {}
5587            _ => return Ok((false, None)),
5588        }
5589        match rv::time_ns(embodiment.get("validFrom")) {
5590            Some(t) if prev_start.is_none_or(|p| t >= p) => prev_start = Some(t),
5591            _ => return Ok((false, None)),
5592        }
5593        if let Some(expected) = &expected_from {
5594            if subject.get("fromBody").and_then(|v| v.as_str()) != Some(expected.as_str()) {
5595                return Ok((false, None));
5596            }
5597        }
5598        current_body = subject
5599            .get("body")
5600            .and_then(|v| v.as_str())
5601            .map(String::from);
5602        expected_from = current_body.clone();
5603    }
5604    if !check_no_fork(embodiments)?.0 {
5605        return Ok((false, None));
5606    }
5607    Ok((true, current_body))
5608}
5609
5610/// Two conflicting bodies surfaced by [`check_no_fork`].
5611#[derive(Debug, Clone, PartialEq, Eq)]
5612pub struct ForkConflict {
5613    pub body_a: String,
5614    pub body_b: String,
5615}
5616
5617/// Half-open intervals [start, end); a missing end is open-ended (+infinity). A
5618/// clean handover sets one window's end to the next window's start, which does not
5619/// overlap.
5620fn windows_overlap(start_a: i128, end_a: Option<i128>, start_b: i128, end_b: Option<i128>) -> bool {
5621    let a_before_b = end_a.map(|e| e <= start_b).unwrap_or(false);
5622    let b_before_a = end_b.map(|e| e <= start_a).unwrap_or(false);
5623    !(a_before_b || b_before_a)
5624}
5625
5626/// Confirm no two embodiments place the agent in different bodies with overlapping
5627/// active windows. Each embodiment is active from `validFrom` to `validUntil` (a
5628/// missing `validUntil` is treated as open-ended). Two embodiments on different
5629/// bodies whose windows overlap are a fork. Returns `(ok, conflict)` where
5630/// conflict, when present, names the two conflicting bodies.
5631pub fn check_no_fork(embodiments: &[Value]) -> Result<(bool, Option<ForkConflict>)> {
5632    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); embodiments);
5633    let mut windows: Vec<(String, i128, Option<i128>)> = Vec::with_capacity(embodiments.len());
5634    for embodiment in embodiments {
5635        let subject = embodiment
5636            .get("credentialSubject")
5637            .and_then(|s| s.as_object());
5638        let body = subject
5639            .and_then(|s| s.get("body"))
5640            .and_then(|v| v.as_str())
5641            .filter(|s| !s.is_empty());
5642        let start = rv::time_ns(embodiment.get("validFrom"));
5643        let (body, start) = match (body, start) {
5644            (Some(b), Some(s)) => (b.to_string(), s),
5645            _ => return Ok((false, None)),
5646        };
5647        // A present end must be a strict time; only an absent end is open-ended.
5648        let end = match embodiment.get("validUntil") {
5649            None => None,
5650            Some(v) => match rv::time_ns(Some(v)) {
5651                Some(t) => Some(t),
5652                None => return Ok((false, None)),
5653            },
5654        };
5655        windows.push((body, start, end));
5656    }
5657
5658    let Some(first) = first_forked_index(&windows) else {
5659        return Ok((true, None));
5660    };
5661    let (body_i, start_i, end_i) = &windows[first];
5662    for (body_j, start_j, end_j) in &windows[first + 1..] {
5663        if body_i != body_j && windows_overlap(*start_i, *end_i, *start_j, *end_j) {
5664            return Ok((
5665                false,
5666                Some(ForkConflict {
5667                    body_a: body_i.clone(),
5668                    body_b: body_j.clone(),
5669                }),
5670            ));
5671        }
5672    }
5673    unreachable!("the forked window has a partner")
5674}
5675
5676/// The most windows on one body a segmented fork check keeps at once (the
5677/// windows whose ends still matter). A real history holds a handful; a
5678/// history that needs more is refused and must be checked whole.
5679pub const MAX_FORK_WINDOWS: usize = 4096;
5680
5681/// Why a segmented fork check failed for a reason other than a fork.
5682#[derive(Debug, Clone, PartialEq, Eq)]
5683pub enum ForkFailure {
5684    /// An embodiment has no body, no valid `validFrom`, or a `validUntil`
5685    /// that is not a protocol time. The whole check answers `(false, None)`.
5686    Malformed(u64),
5687    /// An embodiment starts before the one before it. The segmented check
5688    /// reads a history in `validFrom` order.
5689    OutOfOrder(u64),
5690    /// More than [`MAX_FORK_WINDOWS`] windows on one body overlap at once.
5691    TooManyWindows(u64),
5692}
5693
5694/// Where a fork check stands after the first embodiments of a history, so a
5695/// long history is checked one segment at a time with bounded memory. The
5696/// history must be in `validFrom` order (the order a history is recorded
5697/// in); for such a history the verdict after the last segment is the one
5698/// [`check_no_fork`] gives for the whole list, conflict included.
5699///
5700/// The bookkeeping: while no fork has been seen, every window still open at
5701/// the latest start is on one body (two such windows on different bodies
5702/// would overlap). `windows` keeps, for that body, the points where the
5703/// latest end so far grows: `(start, latest end up to that start)`, with
5704/// `None` for an open end. A later window on another body forks exactly
5705/// when some kept window that starts before its end also ends after its
5706/// start.
5707#[derive(Debug, Clone, PartialEq, Eq)]
5708pub struct ForkProgress {
5709    /// Embodiments checked so far.
5710    pub count: u64,
5711    /// The latest `validFrom` seen, in nanoseconds.
5712    pub last_start: Option<i128>,
5713    /// The body every open window is on.
5714    pub body: Option<String>,
5715    /// `(start, latest end)` steps for `body`, oldest first.
5716    pub windows: Vec<(i128, Option<i128>)>,
5717    /// The first fork, as [`check_no_fork`] reports it.
5718    pub conflict: Option<ForkConflict>,
5719    /// A failure that is not a fork.
5720    pub failure: Option<ForkFailure>,
5721}
5722
5723impl Default for ForkProgress {
5724    fn default() -> Self {
5725        Self::start()
5726    }
5727}
5728
5729/// `a` ends after instant `t` (an open end is after everything).
5730fn ends_after(end: Option<i128>, t: i128) -> bool {
5731    end.is_none_or(|e| e > t)
5732}
5733
5734impl ForkProgress {
5735    pub fn start() -> Self {
5736        Self {
5737            count: 0,
5738            last_start: None,
5739            body: None,
5740            windows: Vec::new(),
5741            conflict: None,
5742            failure: None,
5743        }
5744    }
5745
5746    /// The verdict over every embodiment checked so far: `(ok, conflict)`
5747    /// as [`check_no_fork`] gives it, plus a reason when not ok.
5748    pub fn result(&self) -> (bool, Option<ForkConflict>, Option<String>) {
5749        match &self.failure {
5750            Some(ForkFailure::Malformed(i)) => (
5751                false,
5752                None,
5753                Some(format!(
5754                    "embodiment {i} has no body, or a bad validFrom or validUntil"
5755                )),
5756            ),
5757            Some(ForkFailure::OutOfOrder(i)) => (
5758                false,
5759                None,
5760                Some(format!(
5761                    "embodiment {i} starts before the one before it; a segmented check reads the history in validFrom order"
5762                )),
5763            ),
5764            Some(ForkFailure::TooManyWindows(i)) => (
5765                false,
5766                None,
5767                Some(format!(
5768                    "at embodiment {i} more than {MAX_FORK_WINDOWS} windows on one body are open at once; check this history whole"
5769                )),
5770            ),
5771            None => match &self.conflict {
5772                Some(c) => (
5773                    false,
5774                    Some(c.clone()),
5775                    Some("the agent is in two bodies at once".into()),
5776                ),
5777                None => (true, None, None),
5778            },
5779        }
5780    }
5781}
5782
5783/// Check the next `embodiments` of a history (one segment) for forks and
5784/// move `progress` past them.
5785pub fn check_no_fork_segment(progress: &mut ForkProgress, embodiments: &[Value]) {
5786    #[cfg(not(feature = "std"))]
5787    if crate::nesting::Nested::nests_past(&embodiments, crate::nesting::NO_STD_MAX_NESTING) {
5788        progress.failure = Some(ForkFailure::Malformed(progress.count));
5789        return;
5790    }
5791    #[cfg(not(feature = "std"))]
5792    if crate::nesting::Nested::nests_past(&embodiments, crate::nesting::NO_STD_MAX_NESTING) {
5793        progress.failure = Some(ForkFailure::Malformed(progress.count));
5794        return;
5795    }
5796    for embodiment in embodiments {
5797        let i = progress.count;
5798        progress.count = progress.count.saturating_add(1);
5799        if matches!(
5800            progress.failure,
5801            Some(ForkFailure::Malformed(_)) | Some(ForkFailure::OutOfOrder(_))
5802        ) {
5803            continue;
5804        }
5805        let body = embodiment
5806            .get("credentialSubject")
5807            .and_then(|s| s.as_object())
5808            .and_then(|s| s.get("body"))
5809            .and_then(|v| v.as_str())
5810            .filter(|s| !s.is_empty());
5811        let start = rv::time_ns(embodiment.get("validFrom"));
5812        let end = match embodiment.get("validUntil") {
5813            None => Ok(None),
5814            Some(v) => rv::time_ns(Some(v)).map(Some).ok_or(()),
5815        };
5816        let (body, start, end) = match (body, start, end) {
5817            (Some(b), Some(s), Ok(e)) => (b, s, e),
5818            _ => {
5819                // The whole check answers (false, None) for a malformed
5820                // entry anywhere in the list, a fork or not.
5821                progress.failure = Some(ForkFailure::Malformed(i));
5822                continue;
5823            }
5824        };
5825        if progress.conflict.is_some() || progress.failure.is_some() {
5826            // The verdict is set; only a malformed entry can still change it.
5827            continue;
5828        }
5829        if progress.last_start.is_some_and(|p| start < p) {
5830            progress.failure = Some(ForkFailure::OutOfOrder(i));
5831            continue;
5832        }
5833        progress.last_start = Some(start);
5834        // Steps whose latest end is not after this start can never overlap
5835        // this or any later window (later windows start no earlier).
5836        let live = progress
5837            .windows
5838            .iter()
5839            .position(|(_, e)| ends_after(*e, start))
5840            .unwrap_or(progress.windows.len());
5841        progress.windows.drain(..live);
5842        if progress.windows.is_empty() {
5843            progress.body = None;
5844        }
5845        let same_body = progress.body.as_deref() == Some(body);
5846        if !same_body && progress.body.is_some() {
5847            // The latest end over the open windows on the other body that
5848            // start before this window's end. A window that ends after it
5849            // starts is past every kept start.
5850            let latest = progress
5851                .windows
5852                .iter()
5853                .take_while(|(s, _)| end.is_none_or(|e| *s < e))
5854                .last()
5855                .map(|(_, e)| *e);
5856            if let Some(latest) = latest {
5857                if ends_after(latest, start) {
5858                    progress.conflict = Some(ForkConflict {
5859                        body_a: progress.body.clone().unwrap_or_default(),
5860                        body_b: body.to_string(),
5861                    });
5862                    continue;
5863                }
5864            }
5865        }
5866        // A window that ends at or before its start never overlaps a later
5867        // window, so it is not kept.
5868        if !ends_after(end, start) {
5869            continue;
5870        }
5871        if !same_body {
5872            progress.body = Some(body.to_string());
5873            progress.windows.clear();
5874        }
5875        let grows = match progress.windows.last() {
5876            None => true,
5877            Some((_, latest)) => match (latest, end) {
5878                (None, _) => false,
5879                (Some(_), None) => true,
5880                (Some(l), Some(e)) => e > *l,
5881            },
5882        };
5883        if grows {
5884            if progress.windows.len() >= MAX_FORK_WINDOWS {
5885                progress.failure = Some(ForkFailure::TooManyWindows(i));
5886                continue;
5887            }
5888            progress.windows.push((start, end));
5889        }
5890    }
5891}
5892
5893/// The smallest i whose window overlaps a later window on another body, or
5894/// None: the window a pairwise scan in list order reports first, found in
5895/// O(n log n).
5896///
5897/// Times become ranks. Walking the list from the end, a Fenwick tree indexed by
5898/// start rank holds the later windows; each node keeps the latest end for its
5899/// range plus the latest end on any other body. Window i overlaps a later
5900/// window j on another body exactly when some j with start_j < end_i, on
5901/// another body, has end_j > start_i.
5902fn first_forked_index(windows: &[(String, i128, Option<i128>)]) -> Option<usize> {
5903    let mut times: Vec<i128> = windows
5904        .iter()
5905        .flat_map(|(_, s, e)| core::iter::once(*s).chain(*e))
5906        .collect();
5907    times.sort_unstable();
5908    times.dedup();
5909    let size = times.len();
5910    let rank = |t: i128| times.binary_search(&t).expect("every time is ranked") as i64;
5911    let mut body_ids: crate::collections::HashMap<&str, i64> = crate::collections::HashMap::new();
5912    let ranked: Vec<(i64, i64, i64)> = windows
5913        .iter()
5914        .map(|(b, s, e)| {
5915            let next = body_ids.len() as i64;
5916            let id = *body_ids.entry(b.as_str()).or_insert(next);
5917            (id, rank(*s), e.map_or(size as i64, rank))
5918        })
5919        .collect();
5920
5921    let mut tree = vec![TopTwo::EMPTY; size + 1];
5922    let mut first = None;
5923    for i in (0..ranked.len()).rev() {
5924        let (body, start, end) = ranked[i];
5925        let mut acc = TopTwo::EMPTY;
5926        let mut k = (end as usize).min(size);
5927        while k > 0 {
5928            acc.add(tree[k].end, tree[k].body);
5929            acc.add(tree[k].other_end, tree[k].other_body);
5930            k &= k - 1;
5931        }
5932        let other_end = if acc.body != body {
5933            acc.end
5934        } else {
5935            acc.other_end
5936        };
5937        if other_end > start {
5938            first = Some(i);
5939        }
5940        let mut k = start as usize + 1;
5941        while k <= size {
5942            tree[k].add(end, body);
5943            k += k & k.wrapping_neg();
5944        }
5945    }
5946    first
5947}
5948
5949/// The latest end in a range, and the latest end on a body other than its own.
5950#[derive(Clone, Copy)]
5951struct TopTwo {
5952    end: i64,
5953    body: i64,
5954    other_end: i64,
5955    other_body: i64,
5956}
5957
5958impl TopTwo {
5959    const EMPTY: TopTwo = TopTwo {
5960        end: -1,
5961        body: -1,
5962        other_end: -1,
5963        other_body: -1,
5964    };
5965
5966    fn add(&mut self, end: i64, body: i64) {
5967        if body < 0 {
5968            return;
5969        }
5970        if body == self.body {
5971            self.end = self.end.max(end);
5972        } else if body == self.other_body {
5973            if end > self.other_end {
5974                self.other_end = end;
5975                if self.other_end > self.end {
5976                    core::mem::swap(&mut self.end, &mut self.other_end);
5977                    core::mem::swap(&mut self.body, &mut self.other_body);
5978                }
5979            }
5980        } else if end > self.end {
5981            self.other_end = self.end;
5982            self.other_body = self.body;
5983            self.end = end;
5984            self.body = body;
5985        } else if end > self.other_end {
5986            self.other_end = end;
5987            self.other_body = body;
5988        }
5989    }
5990}
5991
5992// ---------------------------------------------------------------------------
5993// Physical custody handoff (Phase 5.16)
5994// ---------------------------------------------------------------------------
5995//
5996// A physical task or object passes across a chain of actors, human and robot: a
5997// person picks an item, hands it to a robot, that robot hands it to another
5998// robot, which places it. Each handoff is a signed custody transition, so a
5999// physical-world event traces to the exact hop and the actor responsible.
6000//
6001// A custody handoff credential records that a receiving actor accepted custody
6002// of a task or object from a releasing actor, signed by the receiver. Linking
6003// each handoff to the previous forms a chain a verifier walks to establish who
6004// held the task at any time. A condition attested at each handoff lets a state
6005// change be localized to the specific hop whose holder was responsible.
6006//
6007// This is the open layer: signed handoff credentials, chain verification, a
6008// holder-at-time helper, and software condition localization. It reuses the core
6009// proof path ([`data_integrity`]) rather than re-deriving any cryptography.
6010
6011pub const CUSTODY_HANDOFF_TYPE: &str = "CustodyHandoffCredential";
6012
6013/// A signed custody release: the actor handing a task over states that it
6014/// releases custody to the receiver. The receiver embeds it in its handoff.
6015pub const CUSTODY_RELEASE_TYPE: &str = "CustodyReleaseCredential";
6016
6017/// Build a signed custody release by `releaser_did` (the signer) for
6018/// `task_id` to `to_actor`, dated `released_at`.
6019pub fn build_release(
6020    releaser_seed: &[u8],
6021    releaser_did: &str,
6022    task_id: &str,
6023    to_actor: &str,
6024    released_at: &str,
6025) -> Result<Value> {
6026    if task_id.is_empty() || to_actor.is_empty() {
6027        return Err(CoreError::Json("task_id and to_actor are required".into()));
6028    }
6029    let cred = json!({
6030        "@context": [VC_CONTEXT_V2, VOUCH_CONTEXT_V1],
6031        "type": ["VerifiableCredential", CUSTODY_RELEASE_TYPE],
6032        "issuer": releaser_did,
6033        "validFrom": released_at,
6034        "credentialSubject": {"id": task_id, "fromActor": releaser_did, "toActor": to_actor},
6035    });
6036    let opts = BuildProofOptions::new(format!("{releaser_did}#key-1"), released_at);
6037    data_integrity::sign(&cred, releaser_seed, &opts)
6038}
6039
6040/// Parameters for [`build_handoff`]. The signer is the receiver (`to_actor`), the
6041/// party taking responsibility. `condition`, when set, attests the state of the
6042/// task or object as received, which lets a later state change be localized to
6043/// a hop. `release` is the releasing actor's signed [`build_release`]
6044/// credential (a chain verifier requires it). `prev_handoff_id` is the previous
6045/// handoff's `id`; `credential_id` is this handoff's own `id`. `valid_until`,
6046/// when set, bounds the handoff's active window.
6047#[derive(Debug, Clone)]
6048pub struct BuildHandoff {
6049    pub task_id: String,
6050    pub from_actor: String,
6051    pub to_actor: String,
6052    pub condition: Option<String>,
6053    pub handoff_at: String,
6054    pub valid_until: Option<String>,
6055    pub release: Option<Value>,
6056    pub prev_handoff_id: Option<String>,
6057    pub credential_id: String,
6058}
6059
6060/// Build a signed custody handoff: the receiving actor `to_actor` accepts custody
6061/// of `task_id` from `from_actor`, signed by the receiver. The issuer is the
6062/// receiver, so a party attests its own acceptance of custody.
6063pub fn build_handoff(receiver_seed: &[u8], params: &BuildHandoff) -> Result<Value> {
6064    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
6065    if params.task_id.is_empty() || params.from_actor.is_empty() || params.to_actor.is_empty() {
6066        return Err(CoreError::Json(
6067            "task_id, from_actor, and to_actor are required".into(),
6068        ));
6069    }
6070    if params.credential_id.is_empty() {
6071        return Err(CoreError::Json("credential_id is required".into()));
6072    }
6073
6074    let mut subject = Map::new();
6075    subject.insert("id".into(), json!(params.task_id));
6076    subject.insert("fromActor".into(), json!(params.from_actor));
6077    subject.insert("toActor".into(), json!(params.to_actor));
6078    if let Some(condition) = &params.condition {
6079        subject.insert("condition".into(), json!(condition));
6080    }
6081    if let Some(release) = &params.release {
6082        subject.insert("release".into(), release.clone());
6083    }
6084    if let Some(prev) = &params.prev_handoff_id {
6085        subject.insert("prevHandoffId".into(), json!(prev));
6086    }
6087
6088    let mut cred = Map::new();
6089    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
6090    cred.insert("id".into(), json!(params.credential_id));
6091    cred.insert(
6092        "type".into(),
6093        json!(["VerifiableCredential", CUSTODY_HANDOFF_TYPE]),
6094    );
6095    cred.insert("issuer".into(), json!(params.to_actor));
6096    cred.insert("validFrom".into(), json!(params.handoff_at));
6097    if let Some(vu) = &params.valid_until {
6098        cred.insert("validUntil".into(), json!(vu));
6099    }
6100    cred.insert("credentialSubject".into(), Value::Object(subject));
6101
6102    let opts = BuildProofOptions::new(format!("{}#key-1", params.to_actor), &params.handoff_at);
6103    data_integrity::sign(&Value::Object(cred), receiver_seed, &opts)
6104}
6105
6106/// True when the handoff `subject` embeds a release signed by its `fromActor`
6107/// that names the same task and receiver.
6108fn release_ok(subject: &Value, releaser_keys: Keys<'_>, now_ns: i128) -> bool {
6109    let release = match subject.get("release") {
6110        Some(r) => r,
6111        None => return false,
6112    };
6113    let v = match rv::verify_robotics_credential(
6114        release,
6115        releaser_keys,
6116        Some(CUSTODY_RELEASE_TYPE),
6117        now_ns,
6118        VerifyOptions::window(Window::FromRequired),
6119    ) {
6120        Ok(v) => v,
6121        Err(_) => return false,
6122    };
6123    let s = |x: &Value, k: &str| x.get(k).and_then(|y| y.as_str()).map(String::from);
6124    Some(v.issuer.clone()) == s(subject, "fromActor")
6125        && s(&v.subject, "fromActor").as_deref() == Some(v.issuer.as_str())
6126        && s(&v.subject, "id") == s(subject, "id")
6127        && s(&v.subject, "toActor") == s(subject, "toActor")
6128}
6129
6130/// Options for [`verify_handoff`].
6131#[derive(Clone, Copy, Default)]
6132pub struct HandoffCheck<'a> {
6133    /// The handoff must be for this task.
6134    pub task_id: Option<&'a str>,
6135    /// Key source for the releasing actor; giving one requires the release.
6136    pub releaser_keys: Option<Keys<'a>>,
6137    /// Require the releasing actor's signed release (keys from the receiver
6138    /// source when no `releaser_keys` is given).
6139    pub require_release: bool,
6140    /// The releasing actor the caller expects. The release must be signed by
6141    /// it and name it as `fromActor`; with no releaser key a did:key releaser
6142    /// verifies under its own key only when this names it, and the receiver
6143    /// is then pinned to the toActor that verified release names.
6144    pub from_actor: Option<&'a str>,
6145}
6146
6147/// Verify a custody handoff: the receiver's proof bound to the issuer, the
6148/// issuer is the receiving actor (`toActor`), `id` / `fromActor` / `toActor`
6149/// are non-empty strings, and the window at `now_iso` (validFrom required).
6150/// With [`HandoffCheck`] options, the task is pinned and the embedded release
6151/// must be signed by the `fromActor` and name the same task and receiver.
6152pub fn verify_handoff(
6153    credential: &Value,
6154    receiver_keys: Keys<'_>,
6155    check: HandoffCheck<'_>,
6156    now_iso: &str,
6157) -> Result<Option<Value>> {
6158    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
6159    let now = rv::require_now(now_iso)?;
6160    let releaser_keys = rv::pin_if_keyless(
6161        check.releaser_keys.unwrap_or(receiver_keys),
6162        check.from_actor,
6163    );
6164    // With no receiver key, the receiver is pinned to the toActor named by the
6165    // release the pinned releaser signed.
6166    let mut receiver_pin: Option<String> = None;
6167    if check.from_actor.is_some() && rv::no_key_source(&receiver_keys) {
6168        if let Some(rel) = credential
6169            .get("credentialSubject")
6170            .and_then(|s| s.get("release"))
6171        {
6172            if let Ok(r) = rv::verify_robotics_credential(
6173                rel,
6174                releaser_keys,
6175                Some(CUSTODY_RELEASE_TYPE),
6176                now,
6177                VerifyOptions::window(Window::FromRequired),
6178            ) {
6179                if r.subject.get("fromActor").and_then(|x| x.as_str()) == Some(r.issuer.as_str()) {
6180                    receiver_pin = non_empty_str(&r.subject, "toActor").map(String::from);
6181                }
6182            }
6183        }
6184    }
6185    let v = match rv::verify_robotics_credential(
6186        credential,
6187        rv::pin_if_keyless(receiver_keys, receiver_pin.as_deref()),
6188        Some(CUSTODY_HANDOFF_TYPE),
6189        now,
6190        VerifyOptions::window(Window::FromRequired),
6191    ) {
6192        Ok(v) => v,
6193        Err(_) => return Ok(None),
6194    };
6195    for f in ["id", "fromActor", "toActor"] {
6196        if non_empty_str(&v.subject, f).is_none() {
6197            return Ok(None);
6198        }
6199    }
6200    if v.subject.get("toActor").and_then(|x| x.as_str()) != Some(v.issuer.as_str()) {
6201        return Ok(None);
6202    }
6203    if check
6204        .task_id
6205        .is_some_and(|t| v.subject.get("id").and_then(|x| x.as_str()) != Some(t))
6206    {
6207        return Ok(None);
6208    }
6209    if check
6210        .from_actor
6211        .is_some_and(|f| v.subject.get("fromActor").and_then(|x| x.as_str()) != Some(f))
6212    {
6213        return Ok(None);
6214    }
6215    if (check.require_release || check.releaser_keys.is_some() || check.from_actor.is_some())
6216        && !release_ok(&v.subject, releaser_keys, now)
6217    {
6218        return Ok(None);
6219    }
6220    Ok(Some(v.subject))
6221}
6222
6223/// One actor's public key, looked up by actor DID, for [`verify_handoff_chain`].
6224#[derive(Debug, Clone)]
6225pub struct ActorKey {
6226    pub did: String,
6227    pub public_key: Vec<u8>,
6228}
6229
6230/// Verify an ordered list of handoff credentials forms a valid custody chain for
6231/// `task_id`: every handoff verifies under its receiver's key and (with
6232/// `require_release`) carries a release signed by its releasing actor (keys for
6233/// both from `public_keys`); each `toActor` matches the next link's
6234/// `fromActor`; each link after the first names the previous link's `id` as
6235/// `prevHandoffId`; links are in time order; and the first `fromActor` is
6236/// `origin_actor`. Each earlier link must still have been valid when the next
6237/// began, and the last at `now_iso`. Returns `(ok, current_holder)`.
6238///
6239/// `origin_actor` is required: with no known first holder, anyone could sign a
6240/// first link handing the task from themselves. Each link's releaser is pinned
6241/// (the origin, then each `toActor`), so did:key actors verify under their own
6242/// keys even with no entry in `public_keys`.
6243pub fn verify_handoff_chain(
6244    handoffs: &[Value],
6245    public_keys: &[ActorKey],
6246    task_id: &str,
6247    origin_actor: Option<&str>,
6248    require_release: bool,
6249    now_iso: &str,
6250) -> Result<(bool, Option<String>)> {
6251    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); handoffs);
6252    rv::require_now(now_iso)?;
6253    if task_id.is_empty() || origin_actor.is_none_or(str::is_empty) {
6254        return Ok((false, None));
6255    }
6256    let map = Keys::map_of(public_keys.iter().map(|k| (k.did.clone(), &k.public_key)));
6257    let keys = Keys::Map(&map);
6258    let mut expected_from: Option<String> = origin_actor.map(String::from);
6259    let mut current_holder: Option<String> = origin_actor.map(String::from);
6260    let mut prev_id: Option<String> = None;
6261    let mut prev_time: Option<i128> = None;
6262    for (i, handoff) in handoffs.iter().enumerate() {
6263        let at: String = match handoffs.get(i + 1) {
6264            Some(next) => match next.get("validFrom").and_then(|v| v.as_str()) {
6265                Some(t) if rv::time_ns(next.get("validFrom")).is_some() => t.to_string(),
6266                _ => return Ok((false, None)),
6267            },
6268            None => now_iso.to_string(),
6269        };
6270        let check = HandoffCheck {
6271            task_id: Some(task_id),
6272            releaser_keys: if require_release { Some(keys) } else { None },
6273            require_release,
6274            from_actor: if require_release {
6275                expected_from.as_deref()
6276            } else {
6277                None
6278            },
6279        };
6280        let subject = match verify_handoff(handoff, keys, check, &at)? {
6281            Some(s) => s,
6282            None => return Ok((false, None)),
6283        };
6284        if let Some(expected) = &expected_from {
6285            if subject.get("fromActor").and_then(|v| v.as_str()) != Some(expected.as_str()) {
6286                return Ok((false, None));
6287            }
6288        }
6289        match rv::time_ns(handoff.get("validFrom")) {
6290            Some(t) if prev_time.is_none_or(|p| t >= p) => prev_time = Some(t),
6291            _ => return Ok((false, None)),
6292        }
6293        if i > 0 {
6294            match &prev_id {
6295                Some(p) if subject.get("prevHandoffId").and_then(|v| v.as_str()) == Some(p) => {}
6296                _ => return Ok((false, None)),
6297            }
6298        }
6299        prev_id = non_empty_str(handoff, "id").map(String::from);
6300        current_holder = subject
6301            .get("toActor")
6302            .and_then(|v| v.as_str())
6303            .map(String::from);
6304        expected_from = current_holder.clone();
6305    }
6306    Ok((true, current_holder))
6307}
6308
6309/// Return the actor holding the task at protocol time `at`: the receiver
6310/// (`toActor`) of the most recent handoff whose `validFrom` is at or before
6311/// `at`. Returns `None` if no handoff had occurred yet or `at` is not a strict
6312/// protocol time. `handoffs` is assumed in chain order.
6313pub fn holder_at(handoffs: &[Value], at: &str) -> Option<String> {
6314    crate::nesting::deep_guard!(None; handoffs);
6315    let when = crate::time::parse_protocol_time_ns(at).ok()?;
6316    let mut holder: Option<String> = None;
6317    for handoff in handoffs {
6318        if let Some(start) = rv::time_ns(handoff.get("validFrom")) {
6319            if start <= when {
6320                holder = handoff
6321                    .get("credentialSubject")
6322                    .and_then(|s| s.get("toActor"))
6323                    .and_then(|v| v.as_str())
6324                    .map(String::from);
6325            }
6326        }
6327    }
6328    holder
6329}
6330
6331/// A condition change localized to the hop responsible for it, surfaced by
6332/// [`locate_condition_change`].
6333#[derive(Debug, Clone, PartialEq, Eq)]
6334pub struct ConditionChange {
6335    pub responsible_holder: Option<String>,
6336    pub from_condition: String,
6337    pub to_condition: String,
6338}
6339
6340/// Find the first hop where the attested condition differs from the previous
6341/// handoff. The holder responsible for the change is the actor who held the task
6342/// during it (the previous handoff's receiver). Returns the change, or `None` if
6343/// the condition never changed. Handoffs without a condition are skipped for the
6344/// comparison.
6345pub fn locate_condition_change(handoffs: &[Value]) -> Option<ConditionChange> {
6346    crate::nesting::deep_guard!(None; handoffs);
6347    let mut prev_condition: Option<String> = None;
6348    let mut prev_holder: Option<String> = None;
6349    for handoff in handoffs {
6350        let subject = handoff.get("credentialSubject");
6351        let condition = subject
6352            .and_then(|s| s.get("condition"))
6353            .and_then(|v| v.as_str());
6354        let condition = match condition {
6355            Some(c) => c,
6356            None => continue,
6357        };
6358        if let Some(prev) = &prev_condition {
6359            if condition != prev {
6360                return Some(ConditionChange {
6361                    responsible_holder: prev_holder,
6362                    from_condition: prev.clone(),
6363                    to_condition: condition.to_string(),
6364                });
6365            }
6366        }
6367        prev_condition = Some(condition.to_string());
6368        prev_holder = subject
6369            .and_then(|s| s.get("toActor"))
6370            .and_then(|v| v.as_str())
6371            .map(String::from);
6372    }
6373    None
6374}
6375
6376// ---------------------------------------------------------------------------
6377// Robot-to-infrastructure bounded access (Phase 5.17)
6378// ---------------------------------------------------------------------------
6379//
6380// A robot in a warehouse, hospital, or building needs to open doors, call
6381// elevators, dock at chargers, and operate machines. This gives it a bounded,
6382// revocable, auditable way to do so. The infrastructure operator issues an access
6383// grant naming a resource, the permitted operations, an optional zone, and a time
6384// window, signed by the operator. The robot presents a signed access request for a
6385// specific operation on a specific resource, and the resource authorizes it
6386// offline: the grant must be valid and operator-signed, the request valid and
6387// robot-signed, the operation permitted, and the moment inside the window. The
6388// grant plus the request is a tamper-evident, attributable record of the access.
6389//
6390// This is the open layer: signed grants and requests, an offline authorize
6391// decision, shrink-only attenuation, and the audit record. Hardware-enforced
6392// actuation in the resource and managed fleet access-policy orchestration are out
6393// of scope for the open layer.
6394
6395pub const ACCESS_GRANT_TYPE: &str = "InfrastructureAccessGrant";
6396pub const ACCESS_REQUEST_TYPE: &str = "InfrastructureAccessRequest";
6397
6398/// Parameters for [`build_access_grant`]. The signer is the operator; the grant
6399/// names the robot, the resource, the permitted operations, an optional zone, and
6400/// a validity window. `valid_until`, when set, bounds the window (the wrapper
6401/// derives it from a `valid_seconds` lifetime added to `granted_at`, keeping the
6402/// core's clock caller-supplied).
6403#[derive(Debug, Clone)]
6404pub struct BuildAccessGrant {
6405    pub operator_did: String,
6406    pub robot_did: String,
6407    pub resource: String,
6408    pub operations: Vec<String>,
6409    pub zone: Option<String>,
6410    pub granted_at: String,
6411    pub valid_until: Option<String>,
6412}
6413
6414/// Build a signed access grant: the operator grants `robot_did` permission to
6415/// perform `operations` on `resource` (optionally within `zone`) for the window.
6416/// Signed by the operator.
6417pub fn build_access_grant(operator_seed: &[u8], params: &BuildAccessGrant) -> Result<Value> {
6418    if params.robot_did.is_empty() || params.resource.is_empty() {
6419        return Err(CoreError::Json(
6420            "robot_did and resource are required".into(),
6421        ));
6422    }
6423    if params.operations.is_empty() {
6424        return Err(CoreError::Json(
6425            "operations must be a non-empty list".into(),
6426        ));
6427    }
6428
6429    let mut subject = Map::new();
6430    subject.insert("id".into(), json!(params.robot_did));
6431    subject.insert("resource".into(), json!(params.resource));
6432    subject.insert("operations".into(), json!(params.operations));
6433    if let Some(zone) = &params.zone {
6434        subject.insert("zone".into(), json!(zone));
6435    }
6436
6437    let mut cred = Map::new();
6438    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
6439    cred.insert(
6440        "type".into(),
6441        json!(["VerifiableCredential", ACCESS_GRANT_TYPE]),
6442    );
6443    cred.insert("issuer".into(), json!(params.operator_did));
6444    cred.insert("validFrom".into(), json!(params.granted_at));
6445    if let Some(vu) = &params.valid_until {
6446        cred.insert("validUntil".into(), json!(vu));
6447    }
6448    cred.insert("credentialSubject".into(), Value::Object(subject));
6449
6450    let opts = BuildProofOptions::new(format!("{}#key-1", params.operator_did), &params.granted_at);
6451    data_integrity::sign(&Value::Object(cred), operator_seed, &opts)
6452}
6453
6454/// Verify an access grant: the operator's proof bound to the issuer
6455/// (`operator_keys` is a `{did: key}` source, or the bare key of a did:key
6456/// operator), validFrom and validUntil present strict protocol times with
6457/// `now_iso` inside, a non-empty string `resource`, a non-empty list of string
6458/// `operations`, and (when given) the operator in `trusted_operators`. Returns
6459/// the credentialSubject on success, `None` if invalid.
6460pub fn verify_access_grant(
6461    credential: &Value,
6462    operator_keys: Keys<'_>,
6463    trusted_operators: Option<&HashSet<String>>,
6464    now_iso: &str,
6465) -> Result<Option<Value>> {
6466    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
6467    let now = rv::require_now(now_iso)?;
6468    let opts = VerifyOptions {
6469        trusted_issuers: trusted_operators,
6470        ..VerifyOptions::window(Window::Required)
6471    };
6472    let v = match rv::verify_robotics_credential(
6473        credential,
6474        operator_keys,
6475        Some(ACCESS_GRANT_TYPE),
6476        now,
6477        opts,
6478    ) {
6479        Ok(v) => v,
6480        Err(_) => return Ok(None),
6481    };
6482    if non_empty_str(&v.subject, "resource").is_none() {
6483        return Ok(None);
6484    }
6485    match v.subject.get("operations") {
6486        Some(Value::Array(ops)) if !ops.is_empty() && ops.iter().all(|o| o.is_string()) => {}
6487        _ => return Ok(None),
6488    }
6489    Ok(Some(v.subject))
6490}
6491
6492/// Parameters for [`build_access_request`]. The signer is the robot; the request
6493/// names the resource and the single operation the robot wants to perform.
6494#[derive(Debug, Clone)]
6495pub struct BuildAccessRequest {
6496    pub robot_did: String,
6497    pub resource: String,
6498    pub operation: String,
6499    pub requested_at: String,
6500    /// A one-time value the resource remembers to refuse a replay.
6501    pub nonce: String,
6502}
6503
6504/// Build a signed access request: the robot requests to perform `operation` on
6505/// `resource`. Signed by the robot.
6506pub fn build_access_request(robot_seed: &[u8], params: &BuildAccessRequest) -> Result<Value> {
6507    if params.robot_did.is_empty() || params.resource.is_empty() || params.operation.is_empty() {
6508        return Err(CoreError::Json(
6509            "robot_did, resource, and operation are required".into(),
6510        ));
6511    }
6512    if params.nonce.is_empty() {
6513        return Err(CoreError::Json("nonce is required".into()));
6514    }
6515
6516    let mut subject = Map::new();
6517    subject.insert("id".into(), json!(params.robot_did));
6518    subject.insert("resource".into(), json!(params.resource));
6519    subject.insert("operation".into(), json!(params.operation));
6520    subject.insert("nonce".into(), json!(params.nonce));
6521
6522    let mut cred = Map::new();
6523    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
6524    cred.insert(
6525        "type".into(),
6526        json!(["VerifiableCredential", ACCESS_REQUEST_TYPE]),
6527    );
6528    cred.insert("issuer".into(), json!(params.robot_did));
6529    cred.insert("validFrom".into(), json!(params.requested_at));
6530    cred.insert("credentialSubject".into(), Value::Object(subject));
6531
6532    let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), &params.requested_at);
6533    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
6534}
6535
6536/// The outcome of an offline access authorization: `ok` plus any reasons it
6537/// failed. Surfaced by [`authorize_access`].
6538#[derive(Debug, Clone)]
6539pub struct AuthorizeResult {
6540    pub ok: bool,
6541    pub reasons: Vec<String>,
6542}
6543
6544/// Decide, offline, whether to allow the requested access. The grant must verify
6545/// under the operator's key and be in window, the request must verify bound to
6546/// the robot as issuer (and name it as subject) with validFrom no later than
6547/// `now_iso` (keys are `{did: key}` sources, or bare keys of did:key parties), the grant and request must
6548/// name the same robot and resource, and the requested operation must be permitted
6549/// by the grant. Returns an [`AuthorizeResult`] with the reasons for any refusal.
6550/// How old an access request may be by default (seconds).
6551pub const DEFAULT_MAX_REQUEST_AGE_SECONDS: i64 = 60;
6552
6553/// Replay limits for [`authorize_access`]: the request may be no older than
6554/// `max_age_seconds` and not from the future (both with `clock_skew_seconds`),
6555/// and its nonce must not be in `seen_nonces` (it is added when access is
6556/// allowed).
6557pub struct RequestReplay<'a> {
6558    pub seen_nonces: &'a mut HashSet<String>,
6559    pub max_age_seconds: i64,
6560    pub clock_skew_seconds: i64,
6561    /// With no operator key, the grant verifies only when its did:key
6562    /// operator is in this non-empty set.
6563    pub trusted_operators: Option<&'a HashSet<String>>,
6564}
6565
6566impl<'a> RequestReplay<'a> {
6567    /// The default limits (60 s age, 30 s skew) over `seen_nonces`.
6568    pub fn new(seen_nonces: &'a mut HashSet<String>) -> Self {
6569        Self {
6570            seen_nonces,
6571            max_age_seconds: DEFAULT_MAX_REQUEST_AGE_SECONDS,
6572            clock_skew_seconds: 30,
6573            trusted_operators: None,
6574        }
6575    }
6576}
6577
6578pub fn authorize_access(
6579    grant: &Value,
6580    request: &Value,
6581    operator_keys: Keys<'_>,
6582    robot_keys: Keys<'_>,
6583    replay: RequestReplay<'_>,
6584    now_iso: &str,
6585) -> Result<AuthorizeResult> {
6586    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); grant, request);
6587    let current = rv::require_now(now_iso)?;
6588    let mut reasons: Vec<String> = Vec::new();
6589
6590    let grant_subject =
6591        match verify_access_grant(grant, operator_keys, replay.trusted_operators, now_iso)? {
6592            Some(s) => s,
6593            None => {
6594                reasons.push("grant invalid or out of window".into());
6595                return Ok(AuthorizeResult { ok: false, reasons });
6596            }
6597        };
6598
6599    // With no robot key, only the robot the verified grant names may sign.
6600    let granted_robot = grant_subject
6601        .get("id")
6602        .and_then(|v| v.as_str())
6603        .map(String::from);
6604    let req_subject = match bound(
6605        request,
6606        rv::pin_if_keyless(robot_keys, granted_robot.as_deref()),
6607        ACCESS_REQUEST_TYPE,
6608        now_iso,
6609        Window::FromRequired,
6610    )? {
6611        Some(v) if issuer_is_subject(&v) => v.subject,
6612        _ => {
6613            reasons.push("request invalid".into());
6614            return Ok(AuthorizeResult { ok: false, reasons });
6615        }
6616    };
6617    let second: i128 = 1_000_000_000;
6618    let skew = i128::from(replay.clock_skew_seconds) * second;
6619    match rv::time_ns(request.get("validFrom")) {
6620        Some(issued) if issued > current + skew => {
6621            reasons.push("request is dated in the future".into())
6622        }
6623        Some(issued) if current - issued > i128::from(replay.max_age_seconds) * second + skew => {
6624            reasons.push("request is too old".into())
6625        }
6626        Some(_) => {}
6627        None => reasons.push("request is dated in the future".into()),
6628    }
6629    let nonce = non_empty_str(&req_subject, "nonce").map(String::from);
6630    match &nonce {
6631        None => reasons.push("request carries no nonce".into()),
6632        Some(n) if replay.seen_nonces.contains(n) => {
6633            reasons.push("request was already used (replay)".into())
6634        }
6635        Some(_) => {}
6636    }
6637    if !reasons.is_empty() {
6638        return Ok(AuthorizeResult { ok: false, reasons });
6639    }
6640    let req_id = req_subject.get("id").and_then(|v| v.as_str());
6641
6642    if grant_subject.get("id").and_then(|v| v.as_str()) != req_id {
6643        reasons.push("grant and request name different robots".into());
6644    }
6645    if grant_subject.get("resource").and_then(|v| v.as_str())
6646        != req_subject.get("resource").and_then(|v| v.as_str())
6647    {
6648        reasons.push("grant and request name different resources".into());
6649    }
6650    let operation = req_subject.get("operation").and_then(|v| v.as_str());
6651    let permitted = grant_subject
6652        .get("operations")
6653        .and_then(|v| v.as_array())
6654        .map(|ops| operation.is_some() && ops.iter().any(|o| o.as_str() == operation))
6655        .unwrap_or(false);
6656    if !permitted {
6657        reasons.push("operation not permitted by the grant".into());
6658    }
6659    if reasons.is_empty() {
6660        if let Some(n) = nonce {
6661            replay.seen_nonces.insert(n);
6662        }
6663    }
6664
6665    Ok(AuthorizeResult {
6666        ok: reasons.is_empty(),
6667        reasons,
6668    })
6669}
6670
6671/// Return true if `child` is a valid attenuation of `parent`: the same resource, a
6672/// subset of the operations, and the same zone (or the parent had no zone). A
6673/// sub-grant may only narrow, never widen, the access it inherits.
6674pub fn attenuates_grant(parent: &Value, child: &Value) -> bool {
6675    crate::nesting::deep_guard!(false; parent, child);
6676    let p = parent.get("credentialSubject");
6677    let c = child.get("credentialSubject");
6678    let p_resource = p.and_then(|s| s.get("resource")).and_then(|v| v.as_str());
6679    let c_resource = c.and_then(|s| s.get("resource")).and_then(|v| v.as_str());
6680    if p_resource != c_resource {
6681        return false;
6682    }
6683    let p_ops: HashSet<&str> = p
6684        .and_then(|s| s.get("operations"))
6685        .and_then(|v| v.as_array())
6686        .map(|a| a.iter().filter_map(|o| o.as_str()).collect())
6687        .unwrap_or_default();
6688    let c_ops: HashSet<&str> = c
6689        .and_then(|s| s.get("operations"))
6690        .and_then(|v| v.as_array())
6691        .map(|a| a.iter().filter_map(|o| o.as_str()).collect())
6692        .unwrap_or_default();
6693    if !c_ops.is_subset(&p_ops) {
6694        return false;
6695    }
6696    let p_zone = p.and_then(|s| s.get("zone")).and_then(|v| v.as_str());
6697    let c_zone = c.and_then(|s| s.get("zone")).and_then(|v| v.as_str());
6698    if p_zone.is_some() && c_zone != p_zone {
6699        return false;
6700    }
6701    true
6702}
6703
6704// ---------------------------------------------------------------------------
6705// Fused-sensor provenance (Phase 5.18)
6706// ---------------------------------------------------------------------------
6707//
6708// Perception provenance signs individual sensor frames. A robot rarely acts on
6709// one frame, though: it fuses many frames, from cameras, lidar, radar, and other
6710// sensors, into a single world model, an object set, an occupancy grid, or a
6711// pose estimate, and acts on that. This binds a fused output to the exact set of
6712// input frames that produced it and the fusion method that produced it, signed by
6713// the robot, so a manipulated fusion result or a silently dropped or substituted
6714// input is detectable at the provenance layer.
6715//
6716// A fused-perception attestation carries the hash of the fused output, an ordered
6717// list of the input frame hashes, a digest over those inputs, and a fusion method
6718// identifier, signed by the robot. A verifier reproduces the input digest from the
6719// listed inputs and, when it holds the raw fused output, reproduces its hash, so
6720// the attestation commits to exactly those inputs and that output. Checking each
6721// listed input against the robot's signed perception log confirms every fused
6722// input traces to a frame the robot actually recorded.
6723//
6724// This is the open layer: the robot signs the binding of a fused output to its
6725// inputs in software, reusing the perception frame hashes. Hardware sensor
6726// attestation and managed sensor-fusion orchestration are out of scope for the
6727// open layer.
6728
6729pub const FUSED_PERCEPTION_TYPE: &str = "FusedPerceptionAttestation";
6730
6731/// Multibase (base64url) SHA-256 of a raw fused output. Only the hash travels in
6732/// the attestation; the fused output stays wherever the deployment keeps it.
6733pub fn hash_fused_output(output: &[u8]) -> String {
6734    mb64(&Sha256::digest(output))
6735}
6736
6737/// Input-digest version 1: SHA-256 of the hashes joined by "\n" (the
6738/// original; assumed when an attestation names no version).
6739pub const INPUTS_DIGEST_V1: &str = "1";
6740/// Input-digest version 2: SHA-256 of the JCS JSON array of the hashes (the
6741/// default for new attestations).
6742pub const INPUTS_DIGEST_V2: &str = "2";
6743
6744/// Deterministic multibase digest over an ordered list of input frame hashes
6745/// (version 2, the default). It commits to the exact inputs and their order.
6746pub fn fusion_inputs_digest(input_frame_hashes: &[String]) -> Result<String> {
6747    fusion_inputs_digest_version(input_frame_hashes, INPUTS_DIGEST_V2)
6748}
6749
6750/// [`fusion_inputs_digest`] under a named version. Version 1 refuses a hash
6751/// that contains "\n" (otherwise two different lists could share a digest).
6752pub fn fusion_inputs_digest_version(
6753    input_frame_hashes: &[String],
6754    version: &str,
6755) -> Result<String> {
6756    if input_frame_hashes.is_empty() {
6757        return Err(CoreError::Json(
6758            "input_frame_hashes must be a non-empty list".into(),
6759        ));
6760    }
6761    for h in input_frame_hashes {
6762        if h.is_empty() {
6763            return Err(CoreError::Json(
6764                "each input frame hash must be a non-empty string".into(),
6765            ));
6766        }
6767    }
6768    match version {
6769        INPUTS_DIGEST_V2 => Ok(mb64(&Sha256::digest(jcs::canonicalize(&json!(
6770            input_frame_hashes
6771        ))))),
6772        INPUTS_DIGEST_V1 => {
6773            if input_frame_hashes.iter().any(|h| h.contains('\n')) {
6774                return Err(CoreError::Json(
6775                    "a version 1 input digest cannot carry a hash containing a newline".into(),
6776                ));
6777            }
6778            Ok(mb64(&Sha256::digest(
6779                input_frame_hashes.join("\n").as_bytes(),
6780            )))
6781        }
6782        other => Err(CoreError::Json(format!(
6783            "unknown inputs digest version {other:?}"
6784        ))),
6785    }
6786}
6787
6788/// Parameters for [`build_fused_attestation`]. The robot self-issues the
6789/// credential with its own Ed25519 seed. Provide either the raw `fused_output` (it
6790/// is hashed) or a precomputed `fused_output_hash`, not both. `captured_at`, when
6791/// `None`, defaults to `valid_from`.
6792#[derive(Debug, Clone)]
6793pub struct BuildFusedAttestation {
6794    pub robot_did: String,
6795    pub fusion_method: String,
6796    pub input_frame_hashes: Vec<String>,
6797    pub fused_output: Option<Vec<u8>>,
6798    pub fused_output_hash: Option<String>,
6799    pub captured_at: Option<String>,
6800    pub valid_from: String,
6801    pub valid_until: Option<String>,
6802}
6803
6804/// Build a signed `FusedPerceptionAttestation`: the robot attests that a fused
6805/// output was produced by `fusion_method` from the frames named in
6806/// `input_frame_hashes`. The attestation carries a digest over the ordered inputs,
6807/// so the set of inputs is tamper-evident. Signed by the robot.
6808pub fn build_fused_attestation(robot_seed: &[u8], params: &BuildFusedAttestation) -> Result<Value> {
6809    if params.robot_did.is_empty() {
6810        return Err(CoreError::Json("robot_did is required".into()));
6811    }
6812    if params.fusion_method.is_empty() {
6813        return Err(CoreError::Json("fusion_method is required".into()));
6814    }
6815    if params.input_frame_hashes.is_empty() {
6816        return Err(CoreError::Json(
6817            "input_frame_hashes must be a non-empty list".into(),
6818        ));
6819    }
6820    if params.fused_output.is_some() && params.fused_output_hash.is_some() {
6821        return Err(CoreError::Json(
6822            "provide either fused_output or fused_output_hash, not both".into(),
6823        ));
6824    }
6825    let fused_output_hash = match (&params.fused_output, &params.fused_output_hash) {
6826        (Some(o), None) => hash_fused_output(o),
6827        (None, Some(h)) if !h.is_empty() => h.clone(),
6828        _ => {
6829            return Err(CoreError::Json(
6830                "fused_output or fused_output_hash is required".into(),
6831            ))
6832        }
6833    };
6834
6835    let captured = params
6836        .captured_at
6837        .clone()
6838        .unwrap_or_else(|| params.valid_from.clone());
6839
6840    let mut subject = Map::new();
6841    subject.insert("id".into(), json!(params.robot_did));
6842    subject.insert("fusionMethod".into(), json!(params.fusion_method));
6843    subject.insert("fusedOutputHash".into(), json!(fused_output_hash));
6844    subject.insert("inputFrameHashes".into(), json!(params.input_frame_hashes));
6845    subject.insert(
6846        "inputsDigest".into(),
6847        json!(fusion_inputs_digest(&params.input_frame_hashes)?),
6848    );
6849    subject.insert("inputsDigestVersion".into(), json!(INPUTS_DIGEST_V2));
6850    subject.insert("capturedAt".into(), json!(captured));
6851
6852    let mut cred = Map::new();
6853    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
6854    cred.insert(
6855        "type".into(),
6856        json!(["VerifiableCredential", FUSED_PERCEPTION_TYPE]),
6857    );
6858    cred.insert("issuer".into(), json!(params.robot_did));
6859    cred.insert("validFrom".into(), json!(params.valid_from));
6860    if let Some(vu) = &params.valid_until {
6861        cred.insert("validUntil".into(), json!(vu));
6862    }
6863    cred.insert("credentialSubject".into(), Value::Object(subject));
6864
6865    let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), &params.valid_from);
6866    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
6867}
6868
6869/// Verify a `FusedPerceptionAttestation`: the robot's proof bound to the robot
6870/// as issuer (which must also be `credentialSubject.id`), the window at
6871/// `now_iso` (validFrom required), that the digest over
6872/// the listed inputs reproduces the attested `inputsDigest` (so the inputs are
6873/// internally consistent and tamper-evident), and, when the raw `fused_output` is
6874/// supplied, that its hash reproduces the attested `fusedOutputHash`. Returns the
6875/// credentialSubject on success, `None` if invalid.
6876pub fn verify_fused_attestation(
6877    credential: &Value,
6878    keys: Keys<'_>,
6879    fused_output: Option<&[u8]>,
6880    now_iso: &str,
6881) -> Result<Option<Value>> {
6882    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
6883    let v = match bound(
6884        credential,
6885        keys,
6886        FUSED_PERCEPTION_TYPE,
6887        now_iso,
6888        Window::FromRequired,
6889    )? {
6890        Some(v) if issuer_is_subject(&v) => v,
6891        _ => return Ok(None),
6892    };
6893    let subject = v.subject;
6894    let fused_output_hash = non_empty_str(&subject, "fusedOutputHash");
6895    let inputs: Vec<String> = match subject.get("inputFrameHashes") {
6896        Some(Value::Array(a)) if !a.is_empty() && a.iter().all(|e| e.is_string()) => a
6897            .iter()
6898            .filter_map(|e| e.as_str().map(String::from))
6899            .collect(),
6900        _ => return Ok(None),
6901    };
6902    if fused_output_hash.is_none() {
6903        return Ok(None);
6904    }
6905    let version = match subject.get("inputsDigestVersion") {
6906        None => INPUTS_DIGEST_V1,
6907        Some(Value::String(v)) if v == INPUTS_DIGEST_V1 || v == INPUTS_DIGEST_V2 => v.as_str(),
6908        _ => return Ok(None),
6909    };
6910    match fusion_inputs_digest_version(&inputs, version) {
6911        Ok(d) => {
6912            if Some(d.as_str()) != subject.get("inputsDigest").and_then(|v| v.as_str()) {
6913                return Ok(None);
6914            }
6915        }
6916        Err(_) => return Ok(None),
6917    }
6918    if let Some(o) = fused_output {
6919        if Some(hash_fused_output(o).as_str()) != fused_output_hash {
6920            return Ok(None);
6921        }
6922    }
6923    Ok(Some(subject))
6924}
6925
6926/// The outcome of confirming an attestation's inputs against a perception log:
6927/// `ok` plus the input frame hashes not found. Surfaced by [`verify_fusion_inputs`].
6928#[derive(Debug, Clone)]
6929pub struct FusionInputsResult {
6930    pub ok: bool,
6931    pub missing: Vec<String>,
6932}
6933
6934/// Confirm every input frame the attestation names was actually recorded in the
6935/// robot's perception log. Returns `ok` plus `missing`, the input frame hashes that
6936/// do not appear as a recorded frame, so a dropped or substituted fused input is
6937/// named rather than hidden.
6938pub fn verify_fusion_inputs(credential: &Value, log_entries: &[Value]) -> FusionInputsResult {
6939    crate::nesting::deep_guard!(FusionInputsResult { ok: false, missing: Vec::new() }; credential, log_entries);
6940    let recorded: HashSet<&str> = log_entries
6941        .iter()
6942        .filter_map(|e| e.get("frameHash").and_then(|v| v.as_str()))
6943        .filter(|h| !h.is_empty())
6944        .collect();
6945    // A missing or empty input list is malformed: fail closed.
6946    let inputs = match credential
6947        .get("credentialSubject")
6948        .and_then(|s| s.get("inputFrameHashes"))
6949        .and_then(|v| v.as_array())
6950    {
6951        Some(a) if !a.is_empty() => a,
6952        _ => {
6953            return FusionInputsResult {
6954                ok: false,
6955                missing: Vec::new(),
6956            }
6957        }
6958    };
6959    let missing: Vec<String> = inputs
6960        .iter()
6961        .filter(|h| !h.as_str().is_some_and(|s| recorded.contains(s)))
6962        .map(|h| match h.as_str() {
6963            Some(s) => s.to_string(),
6964            None => h.to_string(),
6965        })
6966        .collect();
6967    FusionInputsResult {
6968        ok: missing.is_empty(),
6969        missing,
6970    }
6971}
6972
6973// ---------------------------------------------------------------------------
6974// Wear and degradation attestation (Phase 5.19)
6975// ---------------------------------------------------------------------------
6976//
6977// A robot does not stay as capable as it left the factory. Actuators wear, joints
6978// develop backlash, sensors drift out of calibration, and error rates creep up.
6979// This lets a robot sign its own degradation state, bound to its identity and
6980// hash-linked over time so the history is tamper-evident, and derives a narrowed
6981// physical capability scope from that state, so a worn robot operates inside a
6982// tighter, verifiable envelope instead of trusting the static limit it shipped
6983// with.
6984//
6985// A wear attestation carries a normalized wear level (0 for as-new, 1 for fully
6986// worn) and optional detailed metrics, signed by the robot. Linking each
6987// attestation to the previous one by its proof value forms a chain a verifier
6988// walks to see how the robot degraded over its life. `attenuate_for_wear` derives
6989// a physical scope whose numeric caps are scaled down by the wear level, and the
6990// result is a valid attenuation of the original scope, so the same attenuation
6991// rule the rest of Vouch uses carries the derating.
6992//
6993// This is the open layer: the robot signs its wear state and derives the narrowed
6994// scope credential in software. Firmware-level enforcement of the narrowed
6995// envelope and managed predictive-maintenance modeling are out of scope for the
6996// open layer.
6997
6998pub const WEAR_ATTESTATION_TYPE: &str = "RobotWearAttestation";
6999
7000/// Numeric caps that scale down with wear. Zones and shift windows are preserved
7001/// unchanged, so the derived scope stays a valid attenuation of the original.
7002const WEAR_DERATED_CAPS: [&str; 3] = ["maxForceN", "maxSpeedMps", "maxSpeedNearHumansMps"];
7003
7004/// Parameters for [`build_wear_attestation`]. The robot self-issues the credential
7005/// with its own Ed25519 seed. `metrics`, when present, is carried through into the
7006/// subject unchanged. `prev_proof`, when present, links this attestation to the
7007/// previous one, forming a wear history. `attested_at`, when `None`, defaults to
7008/// `valid_from`.
7009#[derive(Debug, Clone)]
7010pub struct BuildWearAttestation {
7011    pub robot_did: String,
7012    pub wear_level: f64,
7013    pub metrics: Option<Value>,
7014    pub prev_proof: Option<String>,
7015    pub attested_at: Option<String>,
7016    pub valid_from: String,
7017    pub valid_until: Option<String>,
7018}
7019
7020/// Build a signed `RobotWearAttestation`: the robot attests its own degradation as
7021/// a normalized `wear_level` in `[0, 1]`, optionally with detailed `metrics`. When
7022/// `prev_proof` is the proof value of the previous attestation, the new one links
7023/// to it, forming a tamper-evident wear history. Signed by the robot.
7024pub fn build_wear_attestation(robot_seed: &[u8], params: &BuildWearAttestation) -> Result<Value> {
7025    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
7026    if params.robot_did.is_empty() {
7027        return Err(CoreError::Json("robot_did is required".into()));
7028    }
7029    if params.wear_level < 0.0 || params.wear_level > 1.0 {
7030        return Err(CoreError::Json(
7031            "wear_level must be between 0.0 and 1.0".into(),
7032        ));
7033    }
7034
7035    let attested = params
7036        .attested_at
7037        .clone()
7038        .unwrap_or_else(|| params.valid_from.clone());
7039
7040    let mut subject = Map::new();
7041    subject.insert("id".into(), json!(params.robot_did));
7042    subject.insert("wearLevel".into(), json!(params.wear_level));
7043    subject.insert("attestedAt".into(), json!(attested));
7044    if let Some(m) = &params.metrics {
7045        subject.insert("metrics".into(), m.clone());
7046    }
7047    if let Some(prev) = &params.prev_proof {
7048        subject.insert("prevProof".into(), json!(prev));
7049    }
7050
7051    let mut cred = Map::new();
7052    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
7053    cred.insert(
7054        "type".into(),
7055        json!(["VerifiableCredential", WEAR_ATTESTATION_TYPE]),
7056    );
7057    cred.insert("issuer".into(), json!(params.robot_did));
7058    cred.insert("validFrom".into(), json!(params.valid_from));
7059    if let Some(vu) = &params.valid_until {
7060        cred.insert("validUntil".into(), json!(vu));
7061    }
7062    cred.insert("credentialSubject".into(), Value::Object(subject));
7063
7064    let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), &params.valid_from);
7065    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
7066}
7067
7068/// Verify a `RobotWearAttestation`: the robot's proof bound to the robot as
7069/// issuer (which must also be `credentialSubject.id`), the window at `now_iso`
7070/// (validFrom required), and that the wear level is a finite number in [0, 1]. Returns the credentialSubject on
7071/// success, `None` if invalid.
7072pub fn verify_wear_attestation(
7073    credential: &Value,
7074    keys: Keys<'_>,
7075    now_iso: &str,
7076) -> Result<Option<Value>> {
7077    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
7078    let v = match bound(
7079        credential,
7080        keys,
7081        WEAR_ATTESTATION_TYPE,
7082        now_iso,
7083        Window::FromRequired,
7084    )? {
7085        Some(v) if issuer_is_subject(&v) => v,
7086        _ => return Ok(None),
7087    };
7088    match rv::finite_number(v.subject.get("wearLevel")) {
7089        Some(level) if (0.0..=1.0).contains(&level) => Ok(Some(v.subject)),
7090        _ => Ok(None),
7091    }
7092}
7093
7094/// Verify an ordered wear history: each attestation verifies under the same
7095/// robot, each one after the first links to the previous by its proof value,
7096/// and they are in time order. Each earlier attestation must still have been
7097/// valid when the next was made, and the last at `now_iso`. Returns the latest
7098/// credentialSubject on success, `None` if the chain is empty or invalid.
7099pub fn verify_wear_chain(
7100    attestations: &[Value],
7101    keys: Keys<'_>,
7102    now_iso: &str,
7103) -> Result<Option<Value>> {
7104    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); attestations);
7105    rv::require_now(now_iso)?;
7106    if attestations.is_empty() {
7107        return Ok(None);
7108    }
7109    let mut prev_proof: Option<String> = None;
7110    let mut prev_time: Option<i128> = None;
7111    let mut robot: Option<String> = None;
7112    let mut latest: Option<Value> = None;
7113    for (i, att) in attestations.iter().enumerate() {
7114        let at: String = match attestations.get(i + 1) {
7115            Some(next) => match next.get("validFrom").and_then(|v| v.as_str()) {
7116                Some(t) if rv::time_ns(next.get("validFrom")).is_some() => t.to_string(),
7117                _ => return Ok(None),
7118            },
7119            None => now_iso.to_string(),
7120        };
7121        let subject = match verify_wear_attestation(att, keys, &at)? {
7122            Some(s) => s,
7123            None => return Ok(None),
7124        };
7125        let id = subject.get("id").and_then(|v| v.as_str()).map(String::from);
7126        match &robot {
7127            None => robot = id,
7128            Some(r) if id.as_deref() == Some(r.as_str()) => {}
7129            _ => return Ok(None),
7130        }
7131        if let Some(prev) = &prev_proof {
7132            if subject.get("prevProof").and_then(|v| v.as_str()) != Some(prev.as_str()) {
7133                return Ok(None);
7134            }
7135        }
7136        match rv::time_ns(att.get("validFrom")) {
7137            Some(t) if prev_time.is_none_or(|p| t >= p) => prev_time = Some(t),
7138            _ => return Ok(None),
7139        }
7140        prev_proof = att
7141            .get("proof")
7142            .and_then(|p| p.get("proofValue"))
7143            .and_then(|v| v.as_str())
7144            .map(String::from);
7145        latest = Some(subject);
7146    }
7147    Ok(latest)
7148}
7149
7150/// Derive a physical scope narrowed for the given wear level: each numeric cap is
7151/// scaled by `(1 - wear_level)`, and the allowed zones and shift windows are
7152/// carried through unchanged. The result is a valid attenuation of `scope` (never
7153/// broader on any dimension), so the same attenuation check the rest of Vouch uses
7154/// accepts it. A wear level of 0 returns the caps unchanged.
7155pub fn attenuate_for_wear(scope: &Value, wear_level: f64) -> Result<Value> {
7156    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); scope);
7157    // `contains` is false for NaN, so a NaN wear level is refused here rather
7158    // than turning every cap into NaN (which a NaN-unaware check would ignore).
7159    if !(0.0..=1.0).contains(&wear_level) {
7160        return Err(CoreError::Json(
7161            "wear_level must be between 0.0 and 1.0".into(),
7162        ));
7163    }
7164    let problems = scope_problems(scope);
7165    if !problems.is_empty() {
7166        return Err(CoreError::Json(problems.join("; ")));
7167    }
7168    let factor = 1.0 - wear_level;
7169    let empty = Map::new();
7170    let src = scope.as_object().unwrap_or(&empty);
7171    let mut narrowed = Map::new();
7172    for (key, value) in src {
7173        if WEAR_DERATED_CAPS.contains(&key.as_str()) {
7174            if let Some(n) = value.as_f64() {
7175                narrowed.insert(key.clone(), json!(n * factor));
7176                continue;
7177            }
7178        }
7179        narrowed.insert(key.clone(), value.clone());
7180    }
7181    Ok(Value::Object(narrowed))
7182}
7183
7184// ---------------------------------------------------------------------------
7185// Bystander-consent evidence (Phase 5.20)
7186// ---------------------------------------------------------------------------
7187//
7188// A robot working in a shared or public space captures people incidentally
7189// through its cameras and microphones. This lets the robot record, at capture
7190// time, the basis on which a capture was permitted, bound to the specific capture
7191// and to the robot's identity, and lets a bystander (or their device) sign a
7192// consent token bound to that one capture. Only hashes and a consent basis are
7193// stored, never an image or a bystander's identifying data, so the evidence is
7194// verifiable without retaining anyone's biometrics.
7195//
7196// A bystander consent token is signed by the bystander over the hash of the
7197// capture and the robot's DID, so it verifies only against the capture it was
7198// given for and cannot be replayed to a different recording. A bystander-consent
7199// evidence credential is signed by the robot, binding the capture hash to a
7200// consent basis (an explicit token, posted notice, a legitimate interest, or a
7201// redaction that was applied) and, when the basis is explicit consent, to the
7202// tokens that cover it.
7203//
7204// This is the open layer: the cryptographic binding of a consent basis to a
7205// capture, and its verification, holding only hashes. On-device biometric
7206// detection and redaction, and managed consent-registry orchestration, are out of
7207// scope for the open layer.
7208
7209pub const CONSENT_EVIDENCE_TYPE: &str = "BystanderConsentEvidence";
7210pub const CONSENT_TOKEN_TYPE: &str = "BystanderConsentToken";
7211
7212/// Accepted consent bases: the interoperable set a verifier can rely on.
7213/// Implementers MAY use additional values.
7214pub const CONSENT_BASES: [&str; 4] = [
7215    "explicit-consent",
7216    "posted-notice",
7217    "legitimate-interest",
7218    "redacted",
7219];
7220
7221/// Multibase (base64url) SHA-256 of a raw capture. Only the hash travels in the
7222/// token and the evidence; the capture stays wherever the deployment keeps it.
7223pub fn hash_capture(capture: &[u8]) -> String {
7224    mb64(&Sha256::digest(capture))
7225}
7226
7227/// Parameters for [`build_consent_token`]. The signer is the bystander; the token
7228/// binds their consent to one capture (named by `capture_hash`) by one robot
7229/// (`robot_did`). `valid_until`, when set, bounds the window (the wrapper derives
7230/// it from a `valid_seconds` lifetime added to `granted_at`, keeping the core's
7231/// clock caller-supplied). `scope`, when set, records what the consent covers.
7232#[derive(Debug, Clone)]
7233pub struct BuildConsentToken {
7234    pub bystander_did: String,
7235    pub capture_hash: String,
7236    pub robot_did: String,
7237    pub scope: Option<String>,
7238    pub granted_at: String,
7239    pub valid_until: Option<String>,
7240}
7241
7242/// Build a signed `BystanderConsentToken`: a bystander grants consent for a
7243/// specific capture (named by `capture_hash`) by a specific robot (`robot_did`),
7244/// signed by the bystander. Binding the token to the capture hash means it cannot
7245/// be replayed to a different recording. Signed by the bystander.
7246pub fn build_consent_token(bystander_seed: &[u8], params: &BuildConsentToken) -> Result<Value> {
7247    if params.bystander_did.is_empty()
7248        || params.capture_hash.is_empty()
7249        || params.robot_did.is_empty()
7250    {
7251        return Err(CoreError::Json(
7252            "bystander_did, capture_hash, and robot_did are required".into(),
7253        ));
7254    }
7255
7256    let mut subject = Map::new();
7257    subject.insert("id".into(), json!(params.bystander_did));
7258    subject.insert("captureHash".into(), json!(params.capture_hash));
7259    subject.insert("robotDid".into(), json!(params.robot_did));
7260    if let Some(scope) = &params.scope {
7261        subject.insert("scope".into(), json!(scope));
7262    }
7263
7264    let mut cred = Map::new();
7265    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
7266    cred.insert(
7267        "type".into(),
7268        json!(["VerifiableCredential", CONSENT_TOKEN_TYPE]),
7269    );
7270    cred.insert("issuer".into(), json!(params.bystander_did));
7271    cred.insert("validFrom".into(), json!(params.granted_at));
7272    if let Some(vu) = &params.valid_until {
7273        cred.insert("validUntil".into(), json!(vu));
7274    }
7275    cred.insert("credentialSubject".into(), Value::Object(subject));
7276
7277    let opts = BuildProofOptions::new(
7278        format!("{}#key-1", params.bystander_did),
7279        &params.granted_at,
7280    );
7281    data_integrity::sign(&Value::Object(cred), bystander_seed, &opts)
7282}
7283
7284/// Verify a `BystanderConsentToken`: the bystander's proof bound to the issuer
7285/// (`bystander_keys` is a `{did: key}` source, or the bare key of a did:key
7286/// bystander), that the issuer is the bystander (`credentialSubject.id`), that
7287/// the token is bound to this capture and this robot, and that it is within its
7288/// window at `now_iso` (validFrom required, strict times). Returns the
7289/// credentialSubject on success, `None` if invalid.
7290pub fn verify_consent_token(
7291    token: &Value,
7292    bystander_keys: Keys<'_>,
7293    capture_hash: &str,
7294    robot_did: &str,
7295    now_iso: &str,
7296) -> Result<Option<Value>> {
7297    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); token);
7298    let v = match bound(
7299        token,
7300        bystander_keys,
7301        CONSENT_TOKEN_TYPE,
7302        now_iso,
7303        Window::FromRequired,
7304    )? {
7305        Some(v) if issuer_is_subject(&v) => v,
7306        _ => return Ok(None),
7307    };
7308    if v.subject.get("captureHash").and_then(|v| v.as_str()) != Some(capture_hash)
7309        || v.subject.get("robotDid").and_then(|v| v.as_str()) != Some(robot_did)
7310    {
7311        return Ok(None);
7312    }
7313    Ok(Some(v.subject))
7314}
7315
7316/// Parameters for [`build_consent_evidence`]. The signer is the robot; the
7317/// evidence records that a capture (named by `capture_hash`) was permitted on
7318/// `basis`, one of [`CONSENT_BASES`]. `consent_tokens`, when the basis is explicit
7319/// consent, are the bystander tokens that cover it, committed by their proof value.
7320/// `redaction_hash`, when set, records that a redacted output was produced.
7321/// `valid_until`, when set, bounds the window.
7322#[derive(Debug, Clone)]
7323pub struct BuildConsentEvidence {
7324    pub robot_did: String,
7325    pub capture_hash: String,
7326    pub basis: String,
7327    pub consent_tokens: Vec<Value>,
7328    pub redaction_hash: Option<String>,
7329    pub valid_from: String,
7330    pub valid_until: Option<String>,
7331}
7332
7333/// A privacy-preserving reference to a token: its proof value. Never embeds a
7334/// bystander's identifying data.
7335fn consent_token_ref(token: &Value) -> Result<String> {
7336    token
7337        .get("proof")
7338        .and_then(|p| p.get("proofValue"))
7339        .and_then(|v| v.as_str())
7340        .map(String::from)
7341        .ok_or_else(|| CoreError::Json("consent token is missing a proof value".into()))
7342}
7343
7344/// Build a signed `BystanderConsentEvidence` credential: the robot records that a
7345/// capture (named by `capture_hash`) was permitted on `basis`, one of
7346/// [`CONSENT_BASES`]. When the basis is explicit consent, the `consent_tokens` are
7347/// the bystander tokens that cover it, and the evidence commits to them by their
7348/// proof value (never embedding a bystander's identifying data). Signed by the
7349/// robot.
7350pub fn build_consent_evidence(robot_seed: &[u8], params: &BuildConsentEvidence) -> Result<Value> {
7351    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
7352    if params.robot_did.is_empty() || params.capture_hash.is_empty() {
7353        return Err(CoreError::Json(
7354            "robot_did and capture_hash are required".into(),
7355        ));
7356    }
7357    if !CONSENT_BASES.contains(&params.basis.as_str()) {
7358        return Err(CoreError::Json(format!(
7359            "basis must be one of {:?}, got {:?}",
7360            CONSENT_BASES, params.basis
7361        )));
7362    }
7363    if params.basis == "explicit-consent" && params.consent_tokens.is_empty() {
7364        return Err(CoreError::Json(
7365            "explicit-consent basis requires at least one consent token".into(),
7366        ));
7367    }
7368
7369    let mut subject = Map::new();
7370    subject.insert("id".into(), json!(params.robot_did));
7371    subject.insert("captureHash".into(), json!(params.capture_hash));
7372    subject.insert("basis".into(), json!(params.basis));
7373    if !params.consent_tokens.is_empty() {
7374        let mut refs = Vec::with_capacity(params.consent_tokens.len());
7375        for t in &params.consent_tokens {
7376            refs.push(consent_token_ref(t)?);
7377        }
7378        subject.insert("consentTokenRefs".into(), json!(refs));
7379    }
7380    if let Some(rh) = &params.redaction_hash {
7381        subject.insert("redactionHash".into(), json!(rh));
7382    }
7383
7384    let mut cred = Map::new();
7385    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
7386    cred.insert(
7387        "type".into(),
7388        json!(["VerifiableCredential", CONSENT_EVIDENCE_TYPE]),
7389    );
7390    cred.insert("issuer".into(), json!(params.robot_did));
7391    cred.insert("validFrom".into(), json!(params.valid_from));
7392    if let Some(vu) = &params.valid_until {
7393        cred.insert("validUntil".into(), json!(vu));
7394    }
7395    cred.insert("credentialSubject".into(), Value::Object(subject));
7396
7397    let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), &params.valid_from);
7398    data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
7399}
7400
7401/// One bystander's public key, looked up by bystander DID, for
7402/// [`verify_consent_evidence`].
7403#[derive(Debug, Clone)]
7404pub struct BystanderKey {
7405    pub did: String,
7406    pub public_key: Vec<u8>,
7407}
7408
7409/// Verify a `BystanderConsentEvidence` credential: the robot's proof bound to
7410/// the robot as issuer (which must also be `credentialSubject.id`), the window
7411/// at `now_iso` (validFrom required), and an accepted basis. When `capture` is
7412/// supplied, its hash must reproduce the attested capture hash.
7413///
7414/// An explicit-consent evidence is only as good as its tokens, so for that
7415/// basis `consent_tokens` and `bystander_keys` are required: every committed
7416/// reference must be matched by a token that verifies, is bound to this
7417/// capture and this robot, and is in its window. For other bases, tokens that
7418/// are supplied are checked the same way. Returns the credentialSubject on
7419/// success, `None` if invalid.
7420pub fn verify_consent_evidence(
7421    evidence: &Value,
7422    robot_keys: Keys<'_>,
7423    capture: Option<&[u8]>,
7424    consent_tokens: Option<&[Value]>,
7425    bystander_keys: Option<&[BystanderKey]>,
7426    now_iso: &str,
7427) -> Result<Option<Value>> {
7428    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); evidence, consent_tokens);
7429    let v = match bound(
7430        evidence,
7431        robot_keys,
7432        CONSENT_EVIDENCE_TYPE,
7433        now_iso,
7434        Window::FromRequired,
7435    )? {
7436        Some(v) if issuer_is_subject(&v) => v,
7437        _ => return Ok(None),
7438    };
7439    let subject = v.subject;
7440    let basis = subject.get("basis").and_then(|v| v.as_str());
7441    match basis {
7442        Some(b) if CONSENT_BASES.contains(&b) => {}
7443        _ => return Ok(None),
7444    }
7445    let capture_hash = match non_empty_str(&subject, "captureHash") {
7446        Some(h) => h.to_string(),
7447        None => return Ok(None),
7448    };
7449    if let Some(c) = capture {
7450        if hash_capture(c) != capture_hash {
7451            return Ok(None);
7452        }
7453    }
7454
7455    let refs: Vec<&str> = match subject.get("consentTokenRefs") {
7456        None => Vec::new(),
7457        Some(Value::Array(a)) if a.iter().all(|r| r.is_string()) => {
7458            a.iter().filter_map(|r| r.as_str()).collect()
7459        }
7460        _ => return Ok(None),
7461    };
7462    let explicit = basis == Some("explicit-consent");
7463    if explicit && refs.is_empty() {
7464        return Ok(None);
7465    }
7466    if explicit && (consent_tokens.is_none() || bystander_keys.is_none()) {
7467        return Ok(None);
7468    }
7469
7470    if let (Some(tokens), Some(keys)) = (consent_tokens, bystander_keys) {
7471        let map = Keys::map_of(keys.iter().map(|k| (k.did.clone(), &k.public_key)));
7472        let mut matched: HashSet<String> = HashSet::new();
7473        for token in tokens {
7474            let tok_ok = !map.is_empty()
7475                && verify_consent_token(token, Keys::Map(&map), &capture_hash, &v.issuer, now_iso)?
7476                    .is_some();
7477            if !tok_ok {
7478                return Ok(None);
7479            }
7480            let r = match consent_token_ref(token) {
7481                Ok(r) if refs.contains(&r.as_str()) => r,
7482                _ => return Ok(None),
7483            };
7484            matched.insert(r);
7485        }
7486        if explicit {
7487            let all: HashSet<String> = refs.iter().map(|r| r.to_string()).collect();
7488            if matched != all {
7489                return Ok(None);
7490            }
7491        }
7492    }
7493
7494    Ok(Some(subject))
7495}
7496
7497// What the no_std depth guard checks in the JSON these types carry.
7498crate::nesting::nested_fields!(MintRobotIdentity; lifecycle);
7499crate::nesting::nested_fields!(BuildProvenance; config);
7500crate::nesting::nested_fields!(BuildSafetyEvidence; halos_stack);
7501crate::nesting::nested_fields!(BuildRobotHeartbeat; motion_digest);
7502crate::nesting::nested_fields!(BuildSafetyRecord; summary);
7503crate::nesting::nested_fields!(BuildDelegationLease; scope);
7504crate::nesting::nested_fields!(BuildConformanceAttestation; report);
7505crate::nesting::nested_fields!(BuildHandoff; release);
7506crate::nesting::nested_fields!(BuildWearAttestation; metrics);
7507crate::nesting::nested_fields!(BuildConsentEvidence; consent_tokens);
7508crate::nesting::nested_fields!(SafetyRecordCheck<'_>; entries);
7509crate::nesting::nested_fields!(MotionCollector; scope);
7510
7511#[cfg(test)]
7512mod tests {
7513    use super::*;
7514    use crate::keys::Ed25519KeyPair;
7515    #[allow(unused_imports)]
7516    use crate::robotics_verify::test_keys::{any_did, kd, TNOW};
7517    #[allow(unused_imports)]
7518    use crate::robotics_verify::Keys;
7519    use std::fs;
7520
7521    fn load_vector() -> Value {
7522        let raw = fs::read_to_string("../../test-vectors/robotics/vector.json")
7523            .expect("interop vector present");
7524        serde_json::from_str(&raw).unwrap()
7525    }
7526
7527    fn software_root_attest(root_seed: &[u8], robot_did: &str, robot_key_mb: &str) -> Vec<u8> {
7528        let kp = Ed25519KeyPair::from_seed_slice(root_seed).unwrap();
7529        let binding = robot_identity_binding(robot_did, robot_key_mb);
7530        kp.sign(&binding).to_vec()
7531    }
7532
7533    // Cross-language interop: Go and TypeScript verify this same Python-minted
7534    // credential; the Rust core must too.
7535    #[test]
7536    fn verifies_python_interop_vector() {
7537        let raw = fs::read_to_string("../../test-vectors/robotics/vector.json")
7538            .expect("interop vector present");
7539        let vector: Value = serde_json::from_str(&raw).unwrap();
7540        let jwk_x = vector["robot_public_key_jwk"]["x"].as_str().unwrap();
7541        let robot_pub = URL_SAFE_NO_PAD.decode(jwk_x).unwrap();
7542        let cred = vector["robot_identity_credential"].clone();
7543
7544        let subject = verify_robot_identity(&cred, kd(&cred, &robot_pub), None, TNOW).unwrap();
7545        let subject = subject.expect("the Python interop vector must verify in Rust");
7546        assert_eq!(subject["make"], json!("Acme Robotics"));
7547    }
7548
7549    #[test]
7550    fn mint_verify_roundtrip() {
7551        let robot_seed = [3u8; 32];
7552        let root_seed = [7u8; 32];
7553        let robot_did = "did:web:robot.example.com";
7554        let robot_kp = Ed25519KeyPair::from_seed(&robot_seed);
7555        let root_kp = Ed25519KeyPair::from_seed(&root_seed);
7556
7557        let attestation = software_root_attest(&root_seed, robot_did, &robot_kp.public_multikey());
7558        let params = MintRobotIdentity {
7559            robot_did: robot_did.into(),
7560            make: "Acme".into(),
7561            model: "AR-7".into(),
7562            serial: "SN-1".into(),
7563            owner: Some("did:web:owner.example.com".into()),
7564            root_kind: "TPM".into(),
7565            root_public_multibase: root_kp.public_multikey(),
7566            attestation,
7567            lifecycle: None,
7568            valid_from: "2026-01-01T00:00:00Z".into(),
7569            valid_until: None,
7570        };
7571        let cred = mint_robot_identity(&robot_seed, &params).unwrap();
7572        let subject =
7573            verify_robot_identity(&cred, kd(&cred, &robot_kp.public_key()), None, TNOW).unwrap();
7574        assert!(subject.is_some(), "round-trip identity must verify");
7575    }
7576
7577    // Cross-language interop: this HalosSafetyEvidenceCredential, its black-box
7578    // entries, and the robot public key were produced by the Python reference
7579    // (vouch/robotics/halos.py) from a fixed Ed25519 seed (0x05 x32), a fixed
7580    // black-box key, and a fixed `created` timestamp. The Rust verify must accept
7581    // it, and must reject a tampered entry or a wrong entry count.
7582    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"}}"#;
7583
7584    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"}]"#;
7585
7586    // Robot public key (raw 32-byte Ed25519) as base64url-no-pad.
7587    const PY_HALOS_ROBOT_PUB: &str = "bnoc3Smwt4_ROvTFWY_v9O8qlxZuPKby5Pv8zYBQW_E";
7588
7589    #[test]
7590    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
7591    fn build_verify_safety_evidence_roundtrip() {
7592        let robot_seed = [5u8; 32];
7593        let robot_kp = Ed25519KeyPair::from_seed(&robot_seed);
7594
7595        // A black-box chain the robot recorded.
7596        let mut log = BlackBoxLog::new(&[9u8; 32], None).unwrap();
7597        log.append(
7598            "hazard_detected",
7599            &json!({"zone": "cell-3"}),
7600            "2026-01-01T00:00:01Z",
7601        )
7602        .unwrap();
7603        log.append(
7604            "slow_stop",
7605            &json!({"reason": "human"}),
7606            "2026-01-01T00:00:02Z",
7607        )
7608        .unwrap();
7609        let entries: Vec<Value> = log.entries().to_vec();
7610
7611        let params = BuildSafetyEvidence {
7612            halos_stack: json!({"igxSom": "IGX-Orin-64", "halosCore": "1.4.0"}),
7613            window_from: "2026-01-01T00:00:00Z".into(),
7614            window_to: "2026-01-01T00:00:10Z".into(),
7615            blackbox_head: log.head().to_string(),
7616            entry_count: entries.len() as u64,
7617            robot_identity: Some("urn:uuid:robot-identity-1".into()),
7618            valid_seconds: Some(3600),
7619            valid_from: "2026-01-01T00:00:00Z".into(),
7620            created: "2026-01-01T00:00:00Z".into(),
7621            robot_did: None,
7622        };
7623        let cred = build_safety_evidence(&robot_seed, &params).unwrap();
7624
7625        // The issuer is the did:key derived from the seed and the validUntil is
7626        // rendered from the valid_seconds lifetime.
7627        assert_eq!(
7628            cred["issuer"],
7629            json!("did:key:z6MkmtWtY63GQVBrpMyRJWEzsnxfsGkemu6CtMDwGTv4RYj2")
7630        );
7631        assert_eq!(cred["validUntil"], json!("2026-01-01T01:00:00Z"));
7632
7633        let (ok, subject) = verify_safety_evidence(
7634            &cred,
7635            kd(&cred, &robot_kp.public_key()),
7636            Some(&entries),
7637            TNOW,
7638        )
7639        .unwrap();
7640        assert!(ok, "a Rust-built evidence credential must verify in Rust");
7641        assert_eq!(subject.unwrap()["entryCount"], json!(2));
7642
7643        // A credential whose issuer is not the subject id is rejected.
7644        let mut forged = cred.clone();
7645        forged["issuer"] = json!("did:key:z6Mkother");
7646        let (ok_forged, _) =
7647            verify_safety_evidence(&forged, kd(&forged, &robot_kp.public_key()), None, TNOW)
7648                .unwrap();
7649        assert!(!ok_forged, "issuer must equal credentialSubject.id");
7650    }
7651
7652    #[test]
7653    fn verifies_python_halos_evidence() {
7654        let credential: Value = serde_json::from_str(PY_HALOS_CREDENTIAL).unwrap();
7655        let entries: Vec<Value> = serde_json::from_str(PY_HALOS_ENTRIES).unwrap();
7656        let robot_pub = URL_SAFE_NO_PAD.decode(PY_HALOS_ROBOT_PUB).unwrap();
7657
7658        // The Python-produced credential and its entries verify in Rust.
7659        let (ok, subject) = verify_safety_evidence(
7660            &credential,
7661            kd(&credential, &robot_pub),
7662            Some(&entries),
7663            TNOW,
7664        )
7665        .unwrap();
7666        assert!(ok, "the Python Halos evidence must verify in Rust");
7667        let subject = subject.expect("subject present on success");
7668        assert_eq!(subject["entryCount"], json!(3));
7669        assert_eq!(
7670            subject["blackboxHead"],
7671            json!("utfv4sSWc6TH-n0HrNqB35Hacy3lYVksU0QYz6gbHol8")
7672        );
7673
7674        // The proof and issuer binding hold even without the entries.
7675        let (ok_no_entries, _) =
7676            verify_safety_evidence(&credential, kd(&credential, &robot_pub), None, TNOW).unwrap();
7677        assert!(
7678            ok_no_entries,
7679            "proof and issuer binding verify without entries"
7680        );
7681
7682        // Tampering one entry breaks the chain, so verification fails.
7683        let mut tampered = entries.clone();
7684        tampered[1]["ciphertext"] = json!("utampered_ciphertext_value_that_does_not_match_hash");
7685        let (ok_tampered, subj_tampered) = verify_safety_evidence(
7686            &credential,
7687            kd(&credential, &robot_pub),
7688            Some(&tampered),
7689            TNOW,
7690        )
7691        .unwrap();
7692        assert!(!ok_tampered, "a tampered entry must be rejected");
7693        assert!(subj_tampered.is_none());
7694
7695        // A wrong entry count (here a truncated log) is rejected against the seal.
7696        let truncated = entries[..2].to_vec();
7697        let (ok_truncated, _) = verify_safety_evidence(
7698            &credential,
7699            kd(&credential, &robot_pub),
7700            Some(&truncated),
7701            TNOW,
7702        )
7703        .unwrap();
7704        assert!(!ok_truncated, "a wrong entry count must be rejected");
7705    }
7706
7707    #[test]
7708    fn forged_hardware_root_fails() {
7709        let robot_seed = [3u8; 32];
7710        let root_seed = [7u8; 32];
7711        let attacker_seed = [9u8; 32];
7712        let robot_did = "did:web:robot.example.com";
7713        let robot_kp = Ed25519KeyPair::from_seed(&robot_seed);
7714        let root_kp = Ed25519KeyPair::from_seed(&root_seed);
7715        let attacker_kp = Ed25519KeyPair::from_seed(&attacker_seed);
7716
7717        let attestation = software_root_attest(&root_seed, robot_did, &robot_kp.public_multikey());
7718        let params = MintRobotIdentity {
7719            robot_did: robot_did.into(),
7720            make: "Acme".into(),
7721            model: "AR-7".into(),
7722            serial: "SN-1".into(),
7723            owner: None,
7724            root_kind: "TPM".into(),
7725            root_public_multibase: root_kp.public_multikey(),
7726            attestation,
7727            lifecycle: None,
7728            valid_from: "2026-01-01T00:00:00Z".into(),
7729            valid_until: None,
7730        };
7731        let mut cred = mint_robot_identity(&robot_seed, &params).unwrap();
7732
7733        // Point the hardware-root key at an attacker's and re-sign the credential
7734        // proof; the attestation over the binding no longer matches.
7735        cred["credentialSubject"]["hardwareRoot"]["publicKeyMultibase"] =
7736            json!(attacker_kp.public_multikey());
7737        let resigned = {
7738            let mut bare = cred.clone();
7739            bare.as_object_mut().unwrap().remove("proof");
7740            let opts = BuildProofOptions::new(format!("{robot_did}#key-1"), "2026-01-01T00:00:00Z");
7741            data_integrity::sign(&bare, &robot_seed, &opts).unwrap()
7742        };
7743        assert!(verify_robot_identity(
7744            &resigned,
7745            kd(&resigned, &robot_kp.public_key()),
7746            None,
7747            TNOW
7748        )
7749        .unwrap()
7750        .is_none());
7751    }
7752
7753    // Cross-language interop: Rust reproduces the exact configHash Python pinned.
7754    #[test]
7755    fn config_hash_matches_interop_vector() {
7756        let vector = load_vector();
7757        let got = config_hash(&vector["config"]);
7758        assert_eq!(got, vector["expected_config_hash"].as_str().unwrap());
7759        assert_eq!(got, "uMh9_H2Lk51-m9SpBhiEa1oqIwwwA7yT27e2QFS0YKUs");
7760    }
7761
7762    #[test]
7763    fn provenance_roundtrip_and_config_tamper() {
7764        let seed = [4u8; 32];
7765        let kp = Ed25519KeyPair::from_seed(&seed);
7766        let config = load_vector()["config"].clone();
7767        let params = BuildProvenance {
7768            issuer_did: "did:web:robot.example.com".into(),
7769            robot_did: "did:web:robot.example.com".into(),
7770            model_name: "openvla-7b".into(),
7771            weights_hash: "uABCDEF".into(),
7772            safety_policy: "did:web:authority.example.com#policy-v3".into(),
7773            config: Some(config.clone()),
7774            version: Some("2026.06".into()),
7775            supersedes: None,
7776            valid_from: "2026-01-01T00:00:00Z".into(),
7777            valid_until: None,
7778        };
7779        let att = build_provenance_attestation(&seed, &params).unwrap();
7780        assert!(verify_provenance_attestation(
7781            &att,
7782            kd(&att, &kp.public_key()),
7783            Some(&config),
7784            TNOW
7785        )
7786        .unwrap()
7787        .is_some());
7788        // A different config than the one signed must be rejected.
7789        let tampered = json!({"temperature": 1.0, "max_torque": 99.0});
7790        assert!(verify_provenance_attestation(
7791            &att,
7792            kd(&att, &kp.public_key()),
7793            Some(&tampered),
7794            TNOW
7795        )
7796        .unwrap()
7797        .is_none());
7798    }
7799
7800    #[test]
7801    fn capability_build_check_attenuate() {
7802        let seed = [6u8; 32];
7803        let kp = Ed25519KeyPair::from_seed(&seed);
7804        let params = BuildPhysicalScope {
7805            issuer_did: "did:web:fleet.example.com".into(),
7806            subject_did: "did:web:robot.example.com".into(),
7807            max_force_n: Some(80.0),
7808            max_speed_mps: Some(2.0),
7809            max_speed_near_humans_mps: Some(0.5),
7810            allowed_zones: Some(vec!["warehouse-a".into(), "dock-3".into()]),
7811            shift_windows: Some(vec![ShiftWindow {
7812                start: "08:00".into(),
7813                end: "18:00".into(),
7814            }]),
7815            valid_from: "2026-01-01T00:00:00Z".into(),
7816            valid_until: None,
7817        };
7818        let cred = build_physical_scope_credential(&seed, &params).unwrap();
7819        assert!(cred["type"]
7820            .as_array()
7821            .unwrap()
7822            .contains(&json!(PHYSICAL_SCOPE_TYPE)));
7823        assert!(data_integrity::verify_proof(&cred, &kp.public_key()).unwrap());
7824
7825        let scope = cred["credentialSubject"]["physicalScope"].clone();
7826        let within = check_physical_action(
7827            &scope,
7828            &PhysicalAction {
7829                force_n: Some(50.0),
7830                speed_mps: Some(1.5),
7831                zone: Some("warehouse-a".into()),
7832                time_hm: Some("09:30".into()),
7833                ..Default::default()
7834            },
7835        );
7836        assert!(within.ok, "within-scope action: {:?}", within.reasons);
7837        assert!(
7838            !check_physical_action(
7839                &scope,
7840                &PhysicalAction {
7841                    force_n: Some(120.0),
7842                    ..Default::default()
7843                }
7844            )
7845            .ok
7846        );
7847        // Near humans the 0.5 m/s cap applies; 1.5 is fine away from them.
7848        assert!(
7849            !check_physical_action(
7850                &scope,
7851                &PhysicalAction {
7852                    speed_mps: Some(1.5),
7853                    near_humans: true,
7854                    ..Default::default()
7855                }
7856            )
7857            .ok
7858        );
7859        assert!(
7860            check_physical_action(
7861                &scope,
7862                &PhysicalAction {
7863                    speed_mps: Some(1.5),
7864                    near_humans: false,
7865                    ..Default::default()
7866                }
7867            )
7868            .ok
7869        );
7870        assert!(
7871            !check_physical_action(
7872                &scope,
7873                &PhysicalAction {
7874                    zone: Some("loading-bay-9".into()),
7875                    ..Default::default()
7876                }
7877            )
7878            .ok
7879        );
7880        assert!(
7881            !check_physical_action(
7882                &scope,
7883                &PhysicalAction {
7884                    time_hm: Some("23:00".into()),
7885                    ..Default::default()
7886                }
7887            )
7888            .ok
7889        );
7890    }
7891
7892    #[test]
7893    fn attenuation_rules() {
7894        let parent = json!({
7895            "maxForceN": 80.0, "maxSpeedMps": 2.0, "maxSpeedNearHumansMps": 0.5,
7896            "allowedZones": ["warehouse-a", "dock-3"],
7897            "shiftWindows": [{"start": "08:00", "end": "18:00"}]
7898        });
7899        let narrower = json!({
7900            "maxForceN": 50.0, "maxSpeedMps": 1.0, "maxSpeedNearHumansMps": 0.3,
7901            "allowedZones": ["warehouse-a"],
7902            "shiftWindows": [{"start": "09:00", "end": "17:00"}]
7903        });
7904        assert!(attenuates(&parent, &narrower));
7905        assert!(!attenuates(
7906            &parent,
7907            &json!({"maxForceN": 100.0, "maxSpeedMps": 1.0, "maxSpeedNearHumansMps": 0.3, "allowedZones": ["warehouse-a"]})
7908        ));
7909        assert!(!attenuates(
7910            &parent,
7911            &json!({"maxForceN": 50.0, "allowedZones": ["warehouse-a"]})
7912        ));
7913        assert!(!attenuates(
7914            &parent,
7915            &json!({"maxForceN": 50.0, "maxSpeedMps": 1.0, "maxSpeedNearHumansMps": 0.3, "allowedZones": ["loading-bay-9"]})
7916        ));
7917        assert!(!attenuates(
7918            &parent,
7919            &json!({"maxForceN": 50.0, "maxSpeedMps": 1.0, "maxSpeedNearHumansMps": 0.3, "allowedZones": ["warehouse-a"], "shiftWindows": [{"start": "06:00", "end": "20:00"}]})
7920        ));
7921    }
7922
7923    #[test]
7924    fn handshake_full_flow() {
7925        let a_seed = [11u8; 32];
7926        let b_seed = [12u8; 32];
7927        let a = Ed25519KeyPair::from_seed(&a_seed);
7928        let b = Ed25519KeyPair::from_seed(&b_seed);
7929        let a_did = "did:web:robot-a.example.com";
7930        let b_did = "did:web:robot-b.example.com";
7931        let policy_b = TrustPolicy::new(["robot-a.example.com".to_string()], false);
7932
7933        let hello = build_hello(
7934            &a_seed,
7935            &BuildHello {
7936                from_did: a_did.into(),
7937                proposed_scope: vec!["lift".into(), "carry".into(), "scan".into()],
7938                nonce: "abc123".into(),
7939                peer_did: Some(b_did.into()),
7940                issued_at: "2026-01-01T00:00:00Z".into(),
7941            },
7942        )
7943        .unwrap();
7944
7945        let accept = build_accept(
7946            &b_seed,
7947            &hello,
7948            Keys::One(a_did, &a.public_key()),
7949            &policy_b,
7950            &BuildAccept {
7951                from_did: b_did.into(),
7952                offered_scope: vec!["carry".into(), "scan".into(), "weld".into()],
7953                session_id: "urn:uuid:sess-1".into(),
7954                valid_until: "2026-01-01T00:05:00Z".into(),
7955                created: "2026-01-01T00:00:01Z".into(),
7956            },
7957        )
7958        .unwrap();
7959
7960        let session = verify_accept(
7961            &accept,
7962            Keys::One(b_did, &b.public_key()),
7963            &hello,
7964            Some("abc123"),
7965            None,
7966            "2026-01-01T00:00:01Z",
7967        )
7968        .unwrap()
7969        .expect("accept verifies");
7970        // A bare key cannot vouch for a did:web peer, and a stale or expired
7971        // exchange is refused.
7972        assert!(verify_accept(
7973            &accept,
7974            Keys::Bare(&b.public_key()),
7975            &hello,
7976            None,
7977            None,
7978            "2026-01-01T00:00:01Z"
7979        )
7980        .unwrap()
7981        .is_none());
7982        assert!(verify_accept(
7983            &accept,
7984            Keys::One(b_did, &b.public_key()),
7985            &hello,
7986            None,
7987            None,
7988            "2026-01-01T00:06:00Z"
7989        )
7990        .unwrap()
7991        .is_none());
7992        // An ACCEPT replayed against another HELLO is refused.
7993        let other_hello = build_hello(
7994            &a_seed,
7995            &BuildHello {
7996                from_did: a_did.into(),
7997                proposed_scope: vec!["carry".into()],
7998                nonce: "zzz".into(),
7999                peer_did: Some(b_did.into()),
8000                issued_at: "2026-01-01T00:00:00Z".into(),
8001            },
8002        )
8003        .unwrap();
8004        assert!(verify_accept(
8005            &accept,
8006            Keys::One(b_did, &b.public_key()),
8007            &other_hello,
8008            None,
8009            None,
8010            "2026-01-01T00:00:01Z"
8011        )
8012        .unwrap()
8013        .is_none());
8014        assert_eq!(session.scope, vec!["carry".to_string(), "scan".to_string()]);
8015        assert_eq!(session.initiator, a_did);
8016        assert_eq!(session.responder, b_did);
8017
8018        let confirm = build_confirm(&a_seed, a_did, &session, "2026-01-01T00:00:02Z").unwrap();
8019        assert!(verify_confirm(
8020            &confirm,
8021            Keys::One(a_did, &a.public_key()),
8022            &accept,
8023            "2026-01-01T00:00:02Z"
8024        )
8025        .unwrap());
8026        assert!(!verify_confirm(
8027            &confirm,
8028            Keys::One(a_did, &a.public_key()),
8029            &accept,
8030            "2026-01-01T00:06:00Z"
8031        )
8032        .unwrap());
8033        // A stale HELLO is refused by the responder.
8034        assert!(build_accept(
8035            &b_seed,
8036            &hello,
8037            Keys::One(a_did, &a.public_key()),
8038            &policy_b,
8039            &BuildAccept {
8040                from_did: b_did.into(),
8041                offered_scope: vec!["carry".into()],
8042                session_id: "s2".into(),
8043                valid_until: "2026-01-01T01:00:00Z".into(),
8044                created: "2026-01-01T00:10:00Z".into(),
8045            }
8046        )
8047        .is_err());
8048    }
8049
8050    #[test]
8051    fn handshake_untrusted_tamper_and_nonce() {
8052        let a_seed = [11u8; 32];
8053        let b_seed = [12u8; 32];
8054        let a = Ed25519KeyPair::from_seed(&a_seed);
8055        let b = Ed25519KeyPair::from_seed(&b_seed);
8056        let a_did = "did:web:robot-a.example.com";
8057        let b_did = "did:web:robot-b.example.com";
8058
8059        let hello = build_hello(
8060            &a_seed,
8061            &BuildHello {
8062                from_did: a_did.into(),
8063                proposed_scope: vec!["lift".into()],
8064                nonce: "n1".into(),
8065                peer_did: None,
8066                issued_at: "2026-01-01T00:00:00Z".into(),
8067            },
8068        )
8069        .unwrap();
8070
8071        // Untrusted initiator.
8072        let strict = TrustPolicy::new(["someone-else.example.com".to_string()], false);
8073        assert!(build_accept(
8074            &b_seed,
8075            &hello,
8076            Keys::One(a_did, &a.public_key()),
8077            &strict,
8078            &BuildAccept {
8079                from_did: b_did.into(),
8080                offered_scope: vec!["lift".into()],
8081                session_id: "s".into(),
8082                valid_until: "2026-01-01T00:05:00Z".into(),
8083                created: "2026-01-01T00:00:01Z".into(),
8084            },
8085        )
8086        .is_err());
8087
8088        // Tampered HELLO (scope broadened after signing) fails signature check.
8089        let open = TrustPolicy::new(Vec::<String>::new(), true);
8090        let mut tampered = hello.clone();
8091        tampered["proposedScope"] = json!(["lift", "weld"]);
8092        assert!(build_accept(
8093            &b_seed,
8094            &tampered,
8095            Keys::One(a_did, &a.public_key()),
8096            &open,
8097            &BuildAccept {
8098                from_did: b_did.into(),
8099                offered_scope: vec!["lift".into(), "weld".into()],
8100                session_id: "s".into(),
8101                valid_until: "2026-01-01T00:05:00Z".into(),
8102                created: "2026-01-01T00:00:01Z".into(),
8103            },
8104        )
8105        .is_err());
8106
8107        // Nonce mismatch on a valid ACCEPT.
8108        let accept = build_accept(
8109            &b_seed,
8110            &hello,
8111            Keys::One(a_did, &a.public_key()),
8112            &open,
8113            &BuildAccept {
8114                from_did: b_did.into(),
8115                offered_scope: vec!["lift".into()],
8116                session_id: "s".into(),
8117                valid_until: "2026-01-01T00:05:00Z".into(),
8118                created: "2026-01-01T00:00:01Z".into(),
8119            },
8120        )
8121        .unwrap();
8122        assert!(verify_accept(
8123            &accept,
8124            Keys::One(b_did, &b.public_key()),
8125            &hello,
8126            Some("wrong-nonce"),
8127            Some(&open),
8128            "2026-01-01T00:00:01Z"
8129        )
8130        .unwrap()
8131        .is_none());
8132    }
8133
8134    #[test]
8135    fn did_web_domain_parsing() {
8136        let domain = |did: &str| did_web_domain(did);
8137        assert_eq!(
8138            domain("did:web:example.com").as_deref(),
8139            Some("example.com")
8140        );
8141        // A path is part of the name, so a bare-domain entry never covers it.
8142        assert_eq!(
8143            domain("did:web:robot.example.com:agent").as_deref(),
8144            Some("robot.example.com:agent")
8145        );
8146        assert_eq!(domain("did:web:robot.example.com:"), None);
8147        assert_eq!(domain("did:key:z6Mk"), None);
8148        // A did:webvh DID gives its parsed host, never read as did:web.
8149        let scid = "QmUy89VrfryQ254CeHZzQfmcKqByPoKNGqYykP3SeXuegQ";
8150        assert_eq!(
8151            domain(&format!("did:webvh:{scid}:Robot.Example.com%3A8443:agents")).as_deref(),
8152            Some("robot.example.com:agents")
8153        );
8154        // One that does not parse has no domain.
8155        assert_eq!(domain("did:webvh:{SCID}:robot.example.com"), None);
8156        assert_eq!(domain(&format!("did:webvh:{scid}:127.0.0.1")), None);
8157        assert_eq!(domain("did:webvhx:robot.example.com"), None);
8158        let policy = TrustPolicy::new(["robot.example.com".to_string()], false);
8159        assert!(policy.is_trusted(&format!("did:webvh:{scid}:robot.example.com")));
8160        assert!(!policy.is_trusted(&format!("did:webvh:{scid}:other.example.com")));
8161        assert!(!policy.is_trusted("did:webvh:{SCID}:robot.example.com"));
8162    }
8163
8164    #[test]
8165    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
8166    fn blackbox_append_open_and_chain() {
8167        let key = [0x11u8; 32];
8168        let mut log = BlackBoxLog::new(&key, None).unwrap();
8169        let e0 = log
8170            .append(
8171                "motion",
8172                &json!({"speed": 1.5, "joint": "elbow"}),
8173                "2026-01-01T00:00:00Z",
8174            )
8175            .unwrap();
8176        log.append("stop", &json!({"reason": "human"}), "2026-01-01T00:00:01Z")
8177            .unwrap();
8178
8179        // Round-trip decrypt.
8180        let opened = log.open(&e0).unwrap();
8181        assert_eq!(opened["joint"], json!("elbow"));
8182
8183        // Chain verifies, in memory and after a JSON round trip.
8184        assert!(verify_blackbox_chain(log.entries(), None).ok);
8185        let wire: Vec<Value> =
8186            serde_json::from_str(&serde_json::to_string(log.entries()).unwrap()).unwrap();
8187        assert!(verify_blackbox_chain(&wire, None).ok);
8188        assert_eq!(open_entry(&wire[0], &key).unwrap()["joint"], json!("elbow"));
8189
8190        // Tamper detection.
8191        let mut tampered = wire.clone();
8192        tampered[1]["event"] = json!("tampered");
8193        assert!(!verify_blackbox_chain(&tampered, None).ok);
8194
8195        // Wrong key fails decryption; bad key length rejected.
8196        assert!(open_entry(&e0, &[0x22u8; 32]).is_err());
8197        assert!(BlackBoxLog::new(&[0u8; 16], None).is_err());
8198
8199        // Genesis constant matches the multibase of 32 zero bytes.
8200        assert_eq!(genesis_prev_hash(), format!("u{}", "A".repeat(43)));
8201    }
8202
8203    #[test]
8204    fn killswitch_build_verify_and_trust() {
8205        let seed = [13u8; 32];
8206        let kp = Ed25519KeyPair::from_seed(&seed);
8207        let cred = build_killswitch_credential(
8208            &seed,
8209            &BuildKillswitch {
8210                issuer_did: "did:web:safety.example.com".into(),
8211                target: "did:web:robot.example.com".into(),
8212                reason: "human in path".into(),
8213                command: None,
8214                scope: Some(vec!["arm".into(), "drive".into()]),
8215                valid_from: "2026-01-01T00:00:00Z".into(),
8216                valid_until: None,
8217            },
8218        )
8219        .unwrap();
8220
8221        let mut trusted = HashSet::new();
8222        trusted.insert("did:web:safety.example.com".to_string());
8223        let subject =
8224            verify_killswitch_credential(&cred, kd(&cred, &kp.public_key()), Some(&trusted), TNOW)
8225                .unwrap()
8226                .expect("trusted authority verifies");
8227        assert_eq!(subject["command"], json!(EMERGENCY_STOP));
8228
8229        // Untrusted issuer rejected though the signature is valid.
8230        let mut other = HashSet::new();
8231        other.insert("did:web:someone-else.example.com".to_string());
8232        assert!(verify_killswitch_credential(
8233            &cred,
8234            kd(&cred, &kp.public_key()),
8235            Some(&other),
8236            TNOW
8237        )
8238        .unwrap()
8239        .is_none());
8240
8241        // Wrong type rejected.
8242        let mut wrong = cred.clone();
8243        wrong["type"] = json!(["VerifiableCredential"]);
8244        assert!(
8245            verify_killswitch_credential(&wrong, kd(&wrong, &kp.public_key()), None, TNOW)
8246                .unwrap()
8247                .is_none()
8248        );
8249    }
8250
8251    #[test]
8252    fn passport_build_encode_verify() {
8253        let seed = [14u8; 32];
8254        let kp = Ed25519KeyPair::from_seed(&seed);
8255        let did = "did:web:robot.example.com";
8256        let pass = build_passport(
8257            &seed,
8258            &BuildPassport {
8259                issuer_did: did.into(),
8260                robot_did: did.into(),
8261                make: "Acme Robotics".into(),
8262                model: "AR-7".into(),
8263                owner: "did:web:owner.example.com".into(),
8264                authorized_actions: vec!["lift".into(), "carry".into()],
8265                certification: Some("ISO-10218".into()),
8266                status: None,
8267                valid_from: "2026-01-01T00:00:00Z".into(),
8268                valid_until: None,
8269            },
8270        )
8271        .unwrap();
8272
8273        // Direct verify.
8274        let subject = verify_passport(
8275            &pass,
8276            kd(&pass, &kp.public_key()),
8277            None,
8278            "2026-06-01T00:00:00Z",
8279        )
8280        .unwrap()
8281        .expect("passport verifies");
8282        assert_eq!(subject["owner"], json!("did:web:owner.example.com"));
8283        assert_eq!(subject["status"], json!(STATUS_ACTIVE));
8284
8285        // Encode to a URI, decode, and verify the offline-scan path.
8286        let uri = encode_passport(&pass);
8287        assert!(uri.starts_with("vouch-passport:u"));
8288        let decoded = decode_passport(&uri).unwrap();
8289        assert!(verify_passport(
8290            &decoded,
8291            kd(&decoded, &kp.public_key()),
8292            None,
8293            "2026-06-01T00:00:00Z"
8294        )
8295        .unwrap()
8296        .is_some());
8297        assert!(verify_passport_uri(
8298            &uri,
8299            Keys::Resolver(&any_did(&kp.public_key())),
8300            None,
8301            "2026-06-01T00:00:00Z"
8302        )
8303        .unwrap()
8304        .is_some());
8305
8306        // Tamper and wrong type rejected.
8307        let mut tampered = pass.clone();
8308        tampered["credentialSubject"]["owner"] = json!("did:web:attacker.example.com");
8309        assert!(verify_passport(
8310            &tampered,
8311            kd(&tampered, &kp.public_key()),
8312            None,
8313            "2026-06-01T00:00:00Z"
8314        )
8315        .unwrap()
8316        .is_none());
8317
8318        // Malformed URI.
8319        assert!(decode_passport("https://example.com/x").is_err());
8320    }
8321
8322    #[test]
8323    fn passport_expiry_and_suspended() {
8324        let seed = [15u8; 32];
8325        let kp = Ed25519KeyPair::from_seed(&seed);
8326        let did = "did:web:robot.example.com";
8327
8328        // Expiry: valid inside the window, expired past validUntil.
8329        let timed = build_passport(
8330            &seed,
8331            &BuildPassport {
8332                issuer_did: did.into(),
8333                robot_did: did.into(),
8334                make: "Acme".into(),
8335                model: "AR-7".into(),
8336                owner: "did:web:owner.example.com".into(),
8337                authorized_actions: vec!["lift".into()],
8338                certification: None,
8339                status: None,
8340                valid_from: "2026-01-01T00:00:00Z".into(),
8341                valid_until: Some("2026-01-01T00:01:00Z".into()),
8342            },
8343        )
8344        .unwrap();
8345        assert!(verify_passport(
8346            &timed,
8347            kd(&timed, &kp.public_key()),
8348            None,
8349            "2026-01-01T00:00:30Z"
8350        )
8351        .unwrap()
8352        .is_some());
8353        assert!(verify_passport(
8354            &timed,
8355            kd(&timed, &kp.public_key()),
8356            None,
8357            "2026-01-01T00:02:00Z"
8358        )
8359        .unwrap()
8360        .is_none());
8361
8362        // Suspended still verifies but the status is surfaced.
8363        let suspended = build_passport(
8364            &seed,
8365            &BuildPassport {
8366                issuer_did: did.into(),
8367                robot_did: did.into(),
8368                make: "Acme".into(),
8369                model: "AR-7".into(),
8370                owner: "did:web:owner.example.com".into(),
8371                authorized_actions: vec!["lift".into()],
8372                certification: None,
8373                status: Some(STATUS_SUSPENDED.into()),
8374                valid_from: "2026-01-01T00:00:00Z".into(),
8375                valid_until: None,
8376            },
8377        )
8378        .unwrap();
8379        let subject = verify_passport(
8380            &suspended,
8381            kd(&suspended, &kp.public_key()),
8382            None,
8383            "2026-06-01T00:00:00Z",
8384        )
8385        .unwrap()
8386        .expect("a suspended passport still verifies");
8387        assert_eq!(subject["status"], json!(STATUS_SUSPENDED));
8388    }
8389
8390    // Cross-language interop: Rust reproduces the exact motion digest Python
8391    // pinned from the same fixed samples against the same physical scope.
8392    #[test]
8393    fn motion_digest_matches_interop_vector() {
8394        let vector = load_vector();
8395        let scope = vector["physical_scope"].clone();
8396        let mut collector = MotionCollector::new(Some(scope));
8397        collector
8398            .record(&MotionSample {
8399                force_n: Some(12.0),
8400                speed_mps: Some(0.4),
8401                near_humans: false,
8402                zone: Some("cell-3".into()),
8403                time_hm: None,
8404            })
8405            .unwrap();
8406        collector
8407            .record(&MotionSample {
8408                force_n: Some(20.0),
8409                speed_mps: Some(0.2),
8410                near_humans: true,
8411                zone: Some("cell-3".into()),
8412                time_hm: None,
8413            })
8414            .unwrap();
8415        assert_eq!(collector.digest(), vector["expected_motion_digest"]);
8416    }
8417
8418    #[test]
8419    fn heartbeat_build_verify_and_liveness() {
8420        let seed = [21u8; 32];
8421        let kp = Ed25519KeyPair::from_seed(&seed);
8422        let did = "did:web:robot.example.com";
8423        let digest = json!({
8424            "samples": 2, "maxForceN": 20.0, "maxSpeedMps": 0.4,
8425            "maxSpeedNearHumansMps": 0.2, "zoneBreaches": 0, "breachCount": 0,
8426            "withinEnvelope": true
8427        });
8428        let hb = build_robot_heartbeat(
8429            &seed,
8430            &BuildRobotHeartbeat {
8431                robot_did: did.into(),
8432                session_id: "urn:uuid:sess-1".into(),
8433                interval_index: 0,
8434                interval_seconds: 60,
8435                motion_digest: digest,
8436                valid_from: "2026-01-01T00:00:00Z".into(),
8437            },
8438        )
8439        .unwrap();
8440
8441        let subject = verify_robot_heartbeat(&hb, kd(&hb, &kp.public_key()), TNOW)
8442            .unwrap()
8443            .expect("heartbeat verifies");
8444        assert_eq!(subject["sessionId"], json!("urn:uuid:sess-1"));
8445
8446        // Fresh and in-envelope: live. Stale: not live.
8447        assert!(is_live(&hb, "2026-01-01T00:01:00Z", None, DEFAULT_GRACE_INTERVALS).unwrap());
8448        assert!(!is_live(&hb, "2026-01-01T01:00:00Z", None, DEFAULT_GRACE_INTERVALS).unwrap());
8449
8450        // Out-of-envelope heartbeat is never live, even when fresh.
8451        let breached = json!({
8452            "samples": 1, "maxForceN": 99.0, "maxSpeedMps": 0.4,
8453            "maxSpeedNearHumansMps": 0.2, "zoneBreaches": 0, "breachCount": 1,
8454            "withinEnvelope": false
8455        });
8456        let hb2 = build_robot_heartbeat(
8457            &seed,
8458            &BuildRobotHeartbeat {
8459                robot_did: did.into(),
8460                session_id: "s".into(),
8461                interval_index: 1,
8462                interval_seconds: 60,
8463                motion_digest: breached,
8464                valid_from: "2026-01-01T00:00:00Z".into(),
8465            },
8466        )
8467        .unwrap();
8468        assert!(!is_live(&hb2, "2026-01-01T00:00:30Z", None, DEFAULT_GRACE_INTERVALS).unwrap());
8469
8470        // Tamper and wrong type rejected.
8471        let mut tampered = hb.clone();
8472        tampered["credentialSubject"]["sessionId"] = json!("urn:uuid:other");
8473        assert!(
8474            verify_robot_heartbeat(&tampered, kd(&tampered, &kp.public_key()), TNOW)
8475                .unwrap()
8476                .is_none()
8477        );
8478    }
8479
8480    // Cross-language interop: Rust reproduces the exact hash-linked ledger and
8481    // the summary Python pinned from the same fixed events and timestamps.
8482    #[test]
8483    fn safety_log_matches_interop_vector() {
8484        let vector = load_vector();
8485        let mut log = SafetyEventLog::new(None);
8486        log.append(
8487            "near_miss",
8488            "low",
8489            Some(&json!({"zone": "cell-3"})),
8490            None,
8491            "2026-01-01T00:00:00Z",
8492        )
8493        .unwrap();
8494        log.append(
8495            "envelope_breach",
8496            "high",
8497            None,
8498            None,
8499            "2026-01-01T00:01:00Z",
8500        )
8501        .unwrap();
8502
8503        assert_eq!(
8504            Value::Array(log.entries().to_vec()),
8505            vector["safety_log_entries"]
8506        );
8507        assert_eq!(
8508            log.head(),
8509            vector["expected_safety_log_head"].as_str().unwrap()
8510        );
8511        assert_eq!(log.summarize(), vector["expected_safety_summary"]);
8512        assert!(verify_safety_log(log.entries(), None).ok);
8513    }
8514
8515    #[test]
8516    fn safety_record_build_verify_and_tamper() {
8517        let seed = [22u8; 32];
8518        let kp = Ed25519KeyPair::from_seed(&seed);
8519        let mut log = SafetyEventLog::new(None);
8520        log.append("near_miss", "low", None, None, "2026-01-01T00:00:00Z")
8521            .unwrap();
8522        let summary = log.summarize();
8523
8524        let record = build_safety_record(
8525            &seed,
8526            &BuildSafetyRecord {
8527                issuer_did: "did:web:owner.example.com".into(),
8528                robot_did: "did:web:robot.example.com".into(),
8529                summary,
8530                period_start: Some("2026-01-01T00:00:00Z".into()),
8531                period_end: Some("2026-01-31T00:00:00Z".into()),
8532                valid_from: "2026-02-01T00:00:00Z".into(),
8533                valid_until: None,
8534            },
8535        )
8536        .unwrap();
8537
8538        let subject = verify_safety_record(
8539            &record,
8540            kd(&record, &kp.public_key()),
8541            SafetyRecordCheck::default(),
8542            "2026-03-01T00:00:00Z",
8543        )
8544        .unwrap()
8545        .expect("safety record verifies");
8546        assert_eq!(subject["totalEvents"], json!(1));
8547        assert_eq!(subject["period"]["start"], json!("2026-01-01T00:00:00Z"));
8548
8549        let mut tampered = record.clone();
8550        tampered["credentialSubject"]["totalEvents"] = json!(99);
8551        assert!(verify_safety_record(
8552            &tampered,
8553            kd(&tampered, &kp.public_key()),
8554            SafetyRecordCheck::default(),
8555            "2026-03-01T00:00:00Z"
8556        )
8557        .unwrap()
8558        .is_none());
8559
8560        // Tamper detection in the ledger itself.
8561        let mut entries = log.entries().to_vec();
8562        entries[0]["severity"] = json!("critical");
8563        assert!(!verify_safety_log(&entries, None).ok);
8564    }
8565
8566    // Cross-language interop: Rust reproduces the exact credentialStatus entry.
8567    #[test]
8568    fn status_entry_matches_interop_vector() {
8569        let vector = load_vector();
8570        let entry = build_status_list_entry(
8571            "https://fleet.example.com/status/1",
8572            42,
8573            STATUS_PURPOSE_REVOCATION,
8574            None,
8575        )
8576        .unwrap();
8577        assert_eq!(entry, vector["expected_credential_status_entry"]);
8578    }
8579
8580    #[test]
8581    #[cfg_attr(not(feature = "std"), ignore = "needs gunzip (std)")]
8582    fn attach_and_check_credential_status() {
8583        let seed = [23u8; 32];
8584        let kp = Ed25519KeyPair::from_seed(&seed);
8585        let did = "did:web:robot.example.com";
8586
8587        // Mint a passport, then attach a revocation status and re-sign.
8588        let pass = build_passport(
8589            &seed,
8590            &BuildPassport {
8591                issuer_did: did.into(),
8592                robot_did: did.into(),
8593                make: "Acme".into(),
8594                model: "AR-7".into(),
8595                owner: "did:web:owner.example.com".into(),
8596                authorized_actions: vec!["lift".into()],
8597                certification: None,
8598                status: None,
8599                valid_from: "2026-01-01T00:00:00Z".into(),
8600                valid_until: None,
8601            },
8602        )
8603        .unwrap();
8604
8605        let with_status = attach_credential_status(
8606            &pass,
8607            &seed,
8608            &AttachCredentialStatus {
8609                status_list_credential: "https://fleet.example.com/status/1".into(),
8610                status_list_index: 42,
8611                status_purpose: STATUS_PURPOSE_REVOCATION.into(),
8612                entry_id: None,
8613                created: "2026-01-01T00:00:00Z".into(),
8614            },
8615        )
8616        .unwrap();
8617
8618        // The re-signed credential still verifies and now carries the entry.
8619        assert!(data_integrity::verify_proof(&with_status, &kp.public_key()).unwrap());
8620        assert_eq!(
8621            with_status["credentialStatus"]["statusListIndex"],
8622            json!("42")
8623        );
8624
8625        // Build a status list with bit 42 set, then check the entry resolves.
8626        let mut bits = vec![0u8; crate::status_list::DEFAULT_BITSTRING_LENGTH / 8];
8627        crate::status_list::set_status(&mut bits, 42, true).unwrap();
8628        let encoded = crate::status_list::encode_bitstring(&bits).unwrap();
8629        let status_list = json!({
8630            "id": "https://fleet.example.com/status/1",
8631            "issuer": did,
8632            "type": ["VerifiableCredential", "BitstringStatusListCredential"],
8633            "credentialSubject": {
8634                "type": "BitstringStatusList",
8635                "statusPurpose": "revocation",
8636                "encodedList": encoded,
8637            }
8638        });
8639        assert!(
8640            check_credential_status(&with_status, &status_list, STATUS_PURPOSE_REVOCATION).unwrap()
8641        );
8642
8643        // A credential with no status entry is not revoked.
8644        assert!(!check_credential_status(&pass, &status_list, STATUS_PURPOSE_REVOCATION).unwrap());
8645
8646        // A list with the bit clear reports not-revoked.
8647        let clear_bits = vec![0u8; crate::status_list::DEFAULT_BITSTRING_LENGTH / 8];
8648        let clear_encoded = crate::status_list::encode_bitstring(&clear_bits).unwrap();
8649        let mut clear_list = status_list.clone();
8650        clear_list["credentialSubject"]["encodedList"] = json!(clear_encoded);
8651        assert!(
8652            !check_credential_status(&with_status, &clear_list, STATUS_PURPOSE_REVOCATION).unwrap()
8653        );
8654
8655        // A list from another issuer, or a list the entry does not name, cannot
8656        // answer: an error, never "not revoked".
8657        let mut foreign = status_list.clone();
8658        foreign["issuer"] = json!("did:web:someone-else.example.com");
8659        assert!(
8660            check_credential_status(&with_status, &foreign, STATUS_PURPOSE_REVOCATION).is_err()
8661        );
8662        let mut other = status_list.clone();
8663        other["id"] = json!("https://fleet.example.com/status/2");
8664        assert!(check_credential_status(&with_status, &other, STATUS_PURPOSE_REVOCATION).is_err());
8665    }
8666
8667    // Cross-language interop: Rust reproduces the exact frame hash Python pinned.
8668    #[test]
8669    fn frame_hash_matches_interop_vector() {
8670        let vector = load_vector();
8671        let sample_frame: Vec<u8> = (0u8..64).collect();
8672        let got = hash_frame(&sample_frame);
8673        assert_eq!(got, vector["expected_frame_hash"].as_str().unwrap());
8674        assert_eq!(got, "u_eq5rPNxA2K9JljNyaKej5x1f8-YEWA6jER80dkVEQg");
8675    }
8676
8677    // Cross-language interop: Rust reproduces the exact hash-linked perception log
8678    // Python pinned from the same fixed frames and timestamps.
8679    #[test]
8680    fn perception_log_matches_interop_vector() {
8681        let vector = load_vector();
8682        let sample_frame: Vec<u8> = (0u8..64).collect();
8683        let mut log = PerceptionLog::new(None);
8684        log.record(
8685            "cam-front",
8686            "camera",
8687            Some(&sample_frame),
8688            None,
8689            "2026-01-01T00:00:00Z",
8690        )
8691        .unwrap();
8692        log.record(
8693            "lidar-top",
8694            "lidar",
8695            None,
8696            Some(&hash_frame(b"scan-0")),
8697            "2026-01-01T00:00:01Z",
8698        )
8699        .unwrap();
8700
8701        assert_eq!(
8702            Value::Array(log.entries().to_vec()),
8703            vector["perception_log_entries"]
8704        );
8705        assert_eq!(
8706            log.head(),
8707            vector["expected_perception_log_head"].as_str().unwrap()
8708        );
8709        assert!(verify_perception_log(log.entries(), None).ok);
8710    }
8711
8712    #[test]
8713    fn perception_record_validation_and_tamper() {
8714        let mut log = PerceptionLog::new(None);
8715        // Unknown modality rejected.
8716        assert!(log
8717            .record("cam", "sonar", Some(b"x"), None, "2026-01-01T00:00:00Z")
8718            .is_err());
8719        // Both frame and frame_hash rejected.
8720        assert!(log
8721            .record(
8722                "cam",
8723                "camera",
8724                Some(b"x"),
8725                Some("uABC"),
8726                "2026-01-01T00:00:00Z"
8727            )
8728            .is_err());
8729        // Neither frame nor frame_hash rejected.
8730        assert!(log
8731            .record("cam", "camera", None, None, "2026-01-01T00:00:00Z")
8732            .is_err());
8733        // Empty sensor id rejected.
8734        assert!(log
8735            .record("", "camera", Some(b"x"), None, "2026-01-01T00:00:00Z")
8736            .is_err());
8737
8738        log.record(
8739            "cam",
8740            "camera",
8741            Some(b"frame-0"),
8742            None,
8743            "2026-01-01T00:00:00Z",
8744        )
8745        .unwrap();
8746        log.record(
8747            "cam",
8748            "camera",
8749            Some(b"frame-1"),
8750            None,
8751            "2026-01-01T00:00:01Z",
8752        )
8753        .unwrap();
8754        assert!(verify_perception_log(log.entries(), None).ok);
8755
8756        // Tamper detection in the chain.
8757        let mut entries = log.entries().to_vec();
8758        entries[0]["frameHash"] = json!("uTAMPERED");
8759        assert!(!verify_perception_log(&entries, None).ok);
8760    }
8761
8762    #[test]
8763    fn perception_attestation_build_verify_and_tamper() {
8764        let seed = [24u8; 32];
8765        let kp = Ed25519KeyPair::from_seed(&seed);
8766        let did = "did:web:robot.example.com";
8767        let frame = b"sensor-frame-bytes";
8768        let frame_hash = hash_frame(frame);
8769
8770        let cred = build_perception_attestation(
8771            &seed,
8772            &BuildPerception {
8773                robot_did: did.into(),
8774                sensor_id: "cam-front".into(),
8775                modality: "camera".into(),
8776                frame_hash: frame_hash.clone(),
8777                captured_at: Some("2026-01-01T00:00:00Z".into()),
8778                log_head: Some("uHEAD".into()),
8779                log_count: None,
8780                valid_from: "2026-01-01T00:00:00Z".into(),
8781                valid_until: None,
8782            },
8783        )
8784        .unwrap();
8785
8786        // Verify the proof and the embedded provenance, and recompute the frame.
8787        let subject =
8788            verify_perception_attestation(&cred, kd(&cred, &kp.public_key()), Some(frame), TNOW)
8789                .unwrap()
8790                .expect("perception attestation verifies");
8791        assert_eq!(subject["sensorId"], json!("cam-front"));
8792        assert_eq!(subject["frameHash"], json!(frame_hash));
8793        assert_eq!(subject["logHead"], json!("uHEAD"));
8794
8795        // Verify without the raw frame still passes (proof only).
8796        assert!(
8797            verify_perception_attestation(&cred, kd(&cred, &kp.public_key()), None, TNOW)
8798                .unwrap()
8799                .is_some()
8800        );
8801
8802        // A different frame than the one attested is rejected.
8803        assert!(verify_perception_attestation(
8804            &cred,
8805            kd(&cred, &kp.public_key()),
8806            Some(b"other-frame"),
8807            TNOW
8808        )
8809        .unwrap()
8810        .is_none());
8811
8812        // Tampered subject fails the proof.
8813        let mut tampered = cred.clone();
8814        tampered["credentialSubject"]["sensorId"] = json!("cam-rear");
8815        assert!(verify_perception_attestation(
8816            &tampered,
8817            kd(&tampered, &kp.public_key()),
8818            None,
8819            TNOW
8820        )
8821        .unwrap()
8822        .is_none());
8823
8824        // Wrong type rejected.
8825        let mut wrong = cred.clone();
8826        wrong["type"] = json!(["VerifiableCredential"]);
8827        assert!(
8828            verify_perception_attestation(&wrong, kd(&wrong, &kp.public_key()), None, TNOW)
8829                .unwrap()
8830                .is_none()
8831        );
8832
8833        // Bad modality and missing frame_hash rejected at build time.
8834        assert!(build_perception_attestation(
8835            &seed,
8836            &BuildPerception {
8837                robot_did: did.into(),
8838                sensor_id: "s".into(),
8839                modality: "sonar".into(),
8840                frame_hash: frame_hash.clone(),
8841                captured_at: None,
8842                log_head: None,
8843                log_count: None,
8844                valid_from: "2026-01-01T00:00:00Z".into(),
8845                valid_until: None,
8846            },
8847        )
8848        .is_err());
8849        assert!(build_perception_attestation(
8850            &seed,
8851            &BuildPerception {
8852                robot_did: did.into(),
8853                sensor_id: "s".into(),
8854                modality: "camera".into(),
8855                frame_hash: String::new(),
8856                captured_at: None,
8857                log_head: None,
8858                log_count: None,
8859                valid_from: "2026-01-01T00:00:00Z".into(),
8860                valid_until: None,
8861            },
8862        )
8863        .is_err());
8864    }
8865
8866    fn jwk_pub(jwk: &Value) -> Vec<u8> {
8867        URL_SAFE_NO_PAD
8868            .decode(jwk["x"].as_str().unwrap())
8869            .expect("base64url JWK x")
8870    }
8871
8872    // Cross-language interop: Go and TypeScript verify this same Python-signed
8873    // delegation lease; the Rust core must too.
8874    #[test]
8875    fn verifies_python_lease_interop_vector() {
8876        let vector = load_vector();
8877        let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
8878        let lease = vector["delegation_lease_credential"].clone();
8879
8880        let subject = verify_delegation_lease(
8881            &lease,
8882            kd(&lease, &robot_pub),
8883            "did:web:robot.example.com",
8884            None,
8885            None,
8886            "2026-06-01T00:00:00Z",
8887        )
8888        .unwrap()
8889        .expect("the Python lease interop vector must verify in Rust");
8890        assert_eq!(subject["leaseId"], json!("lease-vector-1"));
8891    }
8892
8893    // Cross-language interop: Rust authorizes the Python-signed quorum with the
8894    // same two approver keys and a threshold of 2.
8895    #[test]
8896    fn verifies_python_quorum_interop_vector() {
8897        let vector = load_vector();
8898        let approvals = vector["quorum_approvals"].as_array().unwrap().clone();
8899        let action_id = vector["quorum_action_id"].as_str().unwrap();
8900        let keys: Vec<ApproverKey> = vector["quorum_approver_keys"]
8901            .as_object()
8902            .unwrap()
8903            .iter()
8904            .map(|(did, jwk)| ApproverKey {
8905                did: did.clone(),
8906                public_key: jwk_pub(jwk),
8907            })
8908            .collect();
8909
8910        let (ok, approvers) = verify_action_authorization(
8911            &approvals,
8912            action_id,
8913            "did:web:robot.example.com",
8914            &keys,
8915            2,
8916            None,
8917            vector["quorum_now"].as_str().unwrap(),
8918        )
8919        .unwrap();
8920        assert!(
8921            ok,
8922            "the Python quorum interop vector must authorize in Rust"
8923        );
8924        assert_eq!(approvers.len(), 2);
8925        assert_eq!(approvers[0], "did:web:approver-1.example.com");
8926        assert_eq!(approvers[1], "did:web:approver-2.example.com");
8927    }
8928
8929    #[test]
8930    fn lease_build_verify_permits_and_expiry() {
8931        let seed = [31u8; 32];
8932        let kp = Ed25519KeyPair::from_seed(&seed);
8933        let did = "did:web:robot.example.com";
8934        let scope = json!({
8935            "maxForceN": 80.0, "maxSpeedMps": 2.0, "maxSpeedNearHumansMps": 0.5,
8936            "allowedZones": ["warehouse-a", "dock-3"]
8937        });
8938        let lease = build_delegation_lease(
8939            &seed,
8940            &BuildDelegationLease {
8941                issuer_did: did.into(),
8942                robot_did: did.into(),
8943                lease_id: "lease-1".into(),
8944                scope: scope.clone(),
8945                parent_lease_id: None,
8946                valid_from: "2026-01-01T00:00:00Z".into(),
8947                valid_until: "2026-01-01T01:00:00Z".into(),
8948            },
8949        )
8950        .unwrap();
8951
8952        // Round-trip verify, in-window.
8953        let subject = verify_delegation_lease(
8954            &lease,
8955            kd(&lease, &kp.public_key()),
8956            "did:web:robot.example.com",
8957            None,
8958            None,
8959            "2026-01-01T00:30:00Z",
8960        )
8961        .unwrap()
8962        .expect("lease verifies in window");
8963        assert_eq!(subject["leaseId"], json!("lease-1"));
8964
8965        // Permits a within-scope action, denies an out-of-scope one.
8966        assert!(lease_permits(
8967            &subject,
8968            &PhysicalAction {
8969                force_n: Some(50.0),
8970                zone: Some("warehouse-a".into()),
8971                ..Default::default()
8972            },
8973            Some(&lease),
8974            kd(&lease, &kp.public_key()),
8975            None,
8976            "2026-01-01T00:30:00Z",
8977        )
8978        .unwrap());
8979        assert!(!lease_permits(
8980            &subject,
8981            &PhysicalAction {
8982                force_n: Some(120.0),
8983                ..Default::default()
8984            },
8985            Some(&lease),
8986            kd(&lease, &kp.public_key()),
8987            None,
8988            "2026-01-01T00:30:00Z",
8989        )
8990        .unwrap());
8991
8992        // Expired window: verify fails and the lease no longer permits.
8993        assert!(verify_delegation_lease(
8994            &lease,
8995            kd(&lease, &kp.public_key()),
8996            "did:web:robot.example.com",
8997            None,
8998            None,
8999            "2026-01-01T02:00:00Z"
9000        )
9001        .unwrap()
9002        .is_none());
9003        assert!(!lease_permits(
9004            &subject,
9005            &PhysicalAction {
9006                force_n: Some(50.0),
9007                ..Default::default()
9008            },
9009            Some(&lease),
9010            kd(&lease, &kp.public_key()),
9011            None,
9012            "2026-01-01T02:00:00Z",
9013        )
9014        .unwrap());
9015
9016        // Tamper and wrong type rejected.
9017        let mut tampered = lease.clone();
9018        tampered["credentialSubject"]["leaseId"] = json!("lease-other");
9019        assert!(verify_delegation_lease(
9020            &tampered,
9021            kd(&tampered, &kp.public_key()),
9022            "did:web:robot.example.com",
9023            None,
9024            None,
9025            "2026-01-01T00:30:00Z"
9026        )
9027        .unwrap()
9028        .is_none());
9029    }
9030
9031    #[test]
9032    fn lease_sub_grant_attenuation() {
9033        let parent_seed = [32u8; 32];
9034        let child_seed = [33u8; 32];
9035        let parent_kp = Ed25519KeyPair::from_seed(&parent_seed);
9036        let child_kp = Ed25519KeyPair::from_seed(&child_seed);
9037        let parent_scope = json!({
9038            "maxForceN": 80.0, "maxSpeedMps": 2.0,
9039            "allowedZones": ["warehouse-a", "dock-3"]
9040        });
9041
9042        // A narrower sub-lease attenuates the parent: accepted.
9043        let narrower = build_delegation_lease(
9044            &child_seed,
9045            &BuildDelegationLease {
9046                issuer_did: "did:web:integrator.example.com".into(),
9047                robot_did: "did:web:robot.example.com".into(),
9048                lease_id: "lease-2".into(),
9049                scope: json!({
9050                    "maxForceN": 50.0, "maxSpeedMps": 1.0,
9051                    "allowedZones": ["warehouse-a"]
9052                }),
9053                parent_lease_id: Some("lease-1".into()),
9054                valid_from: "2026-01-01T00:00:00Z".into(),
9055                valid_until: "2026-01-01T01:00:00Z".into(),
9056            },
9057        )
9058        .unwrap();
9059        assert!(verify_delegation_lease(
9060            &narrower,
9061            kd(&narrower, &child_kp.public_key()),
9062            "did:web:robot.example.com",
9063            Some(&parent_scope),
9064            None,
9065            "2026-01-01T00:30:00Z"
9066        )
9067        .unwrap()
9068        .is_some());
9069
9070        // A widening sub-lease (force above the parent) is rejected against the
9071        // parent scope.
9072        let wider = build_delegation_lease(
9073            &parent_seed,
9074            &BuildDelegationLease {
9075                issuer_did: "did:web:integrator.example.com".into(),
9076                robot_did: "did:web:robot.example.com".into(),
9077                lease_id: "lease-3".into(),
9078                scope: json!({
9079                    "maxForceN": 200.0, "maxSpeedMps": 1.0,
9080                    "allowedZones": ["warehouse-a"]
9081                }),
9082                parent_lease_id: Some("lease-1".into()),
9083                valid_from: "2026-01-01T00:00:00Z".into(),
9084                valid_until: "2026-01-01T01:00:00Z".into(),
9085            },
9086        )
9087        .unwrap();
9088        assert!(verify_delegation_lease(
9089            &wider,
9090            kd(&wider, &parent_kp.public_key()),
9091            "did:web:robot.example.com",
9092            Some(&parent_scope),
9093            None,
9094            "2026-01-01T00:30:00Z"
9095        )
9096        .unwrap()
9097        .is_none());
9098    }
9099
9100    #[test]
9101    fn quorum_threshold_and_distinct_counting() {
9102        let s1 = [41u8; 32];
9103        let s2 = [42u8; 32];
9104        let k1 = Ed25519KeyPair::from_seed(&s1);
9105        let k2 = Ed25519KeyPair::from_seed(&s2);
9106        let a1 = "did:web:approver-1.example.com";
9107        let a2 = "did:web:approver-2.example.com";
9108        let robot = "did:web:robot.example.com";
9109        let action = "action-x";
9110
9111        let build = |seed: &[u8], did: &str, decision: &str| {
9112            build_action_approval(
9113                seed,
9114                &BuildActionApproval {
9115                    approver_did: did.into(),
9116                    action_id: action.into(),
9117                    robot_did: robot.into(),
9118                    decision: decision.into(),
9119                    valid_from: "2026-01-01T00:00:00Z".into(),
9120                    valid_until: None,
9121                },
9122            )
9123            .unwrap()
9124        };
9125
9126        let ap1 = build(&s1, a1, APPROVE);
9127        let ap2 = build(&s2, a2, APPROVE);
9128        let keys = vec![
9129            ApproverKey {
9130                did: a1.into(),
9131                public_key: k1.public_key().to_vec(),
9132            },
9133            ApproverKey {
9134                did: a2.into(),
9135                public_key: k2.public_key().to_vec(),
9136            },
9137        ];
9138
9139        // Two distinct approvers meet a threshold of 2.
9140        let (ok, approvers) = verify_action_authorization(
9141            &[ap1.clone(), ap2],
9142            action,
9143            robot,
9144            &keys,
9145            2,
9146            None,
9147            "2026-01-01T00:01:00Z",
9148        )
9149        .unwrap();
9150        assert!(ok);
9151        assert_eq!(approvers, vec![a1.to_string(), a2.to_string()]);
9152
9153        // Duplicate approvals from one approver count once: threshold 2 not met.
9154        let dup = build(&s1, a1, APPROVE);
9155        let (ok2, approvers2) = verify_action_authorization(
9156            &[ap1.clone(), dup],
9157            action,
9158            robot,
9159            &keys,
9160            2,
9161            None,
9162            "2026-01-01T00:01:00Z",
9163        )
9164        .unwrap();
9165        assert!(!ok2);
9166        assert_eq!(approvers2, vec![a1.to_string()]);
9167
9168        // A single valid approver does not meet a threshold of 2.
9169        let (ok3, _) = verify_action_authorization(
9170            &[ap1],
9171            action,
9172            robot,
9173            &keys,
9174            2,
9175            None,
9176            "2026-01-01T00:01:00Z",
9177        )
9178        .unwrap();
9179        assert!(!ok3);
9180
9181        // A rejection vetoes the action (each approver's latest decision counts).
9182        let rej = build(&s1, a1, REJECT);
9183        let approve2 = build(&s2, a2, APPROVE);
9184        let (ok4, approvers4) = verify_action_authorization(
9185            &[rej, approve2],
9186            action,
9187            robot,
9188            &keys,
9189            2,
9190            None,
9191            "2026-01-01T00:01:00Z",
9192        )
9193        .unwrap();
9194        assert!(!ok4);
9195        assert!(approvers4.is_empty());
9196    }
9197
9198    // Cross-language interop: Rust verifies the Python-signed ownership transfer
9199    // under the owner's key from the vector.
9200    #[test]
9201    fn verifies_python_ownership_transfer_interop_vector() {
9202        let vector = load_vector();
9203        let owner_pub = jwk_pub(&vector["ownership_transfer_owner_key"]);
9204        let cred = vector["ownership_transfer_credential"].clone();
9205
9206        let subject = verify_ownership_transfer(&cred, kd(&cred, &owner_pub), None, TNOW)
9207            .unwrap()
9208            .expect("the Python ownership-transfer interop vector must verify in Rust");
9209        assert_eq!(subject["toOwner"], json!("did:web:owner-b.example.com"));
9210    }
9211
9212    // Cross-language interop: Rust verifies the Python-signed key rotation under
9213    // the robot key from robot_public_key_jwk.
9214    #[test]
9215    fn verifies_python_key_rotation_interop_vector() {
9216        let vector = load_vector();
9217        let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
9218        let cred = vector["key_rotation_credential"].clone();
9219
9220        let subject = verify_key_rotation(&cred, Keys::Bare(&robot_pub), None, TNOW)
9221            .unwrap()
9222            .expect("the Python key-rotation interop vector must verify in Rust");
9223        assert_eq!(
9224            subject["newKey"],
9225            json!("z6MkmtWtY63GQVBrpMyRJWEzsnxfsGkemu6CtMDwGTv4RYj2")
9226        );
9227    }
9228
9229    // Cross-language interop: Rust verifies the Python-signed decommission under
9230    // the authority key from the vector.
9231    #[test]
9232    fn verifies_python_decommission_interop_vector() {
9233        let vector = load_vector();
9234        let authority_pub = jwk_pub(&vector["decommission_authority_key"]);
9235        let cred = vector["decommission_credential"].clone();
9236
9237        let subject = verify_decommission(&cred, kd(&cred, &authority_pub), None, None, TNOW)
9238            .unwrap()
9239            .expect("the Python decommission interop vector must verify in Rust");
9240        assert_eq!(subject["reason"], json!("end of service life"));
9241        assert_eq!(subject["finalDisposition"], json!("recycled"));
9242    }
9243
9244    #[test]
9245    fn ownership_transfer_roundtrip_and_issuer_rule() {
9246        let owner_a_seed = [51u8; 32];
9247        let owner_b_seed = [52u8; 32];
9248        let a = Ed25519KeyPair::from_seed(&owner_a_seed);
9249        let b = Ed25519KeyPair::from_seed(&owner_b_seed);
9250        let owner_a = "did:web:owner-a.example.com";
9251        let owner_b = "did:web:owner-b.example.com";
9252        let robot = "did:web:robot.example.com";
9253
9254        let transfer = build_ownership_transfer(
9255            &owner_a_seed,
9256            &BuildOwnershipTransfer {
9257                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000101".into(),
9258                issuer_did: owner_a.into(),
9259                robot_did: robot.into(),
9260                to_owner: owner_b.into(),
9261                from_owner: None,
9262                prev_transfer_id: None,
9263                valid_from: "2026-01-01T00:00:00Z".into(),
9264            },
9265        )
9266        .unwrap();
9267
9268        let subject =
9269            verify_ownership_transfer(&transfer, kd(&transfer, &a.public_key()), None, TNOW)
9270                .unwrap()
9271                .expect("transfer verifies under the current owner key");
9272        assert_eq!(subject["fromOwner"], json!(owner_a));
9273        assert_eq!(subject["toOwner"], json!(owner_b));
9274
9275        // Wrong type rejected.
9276        let mut wrong = transfer.clone();
9277        wrong["type"] = json!(["VerifiableCredential"]);
9278        assert!(
9279            verify_ownership_transfer(&wrong, kd(&wrong, &a.public_key()), None, TNOW)
9280                .unwrap()
9281                .is_none()
9282        );
9283
9284        // The issuer must equal fromOwner: forge a transfer whose issuer is not the
9285        // declared seller and re-sign it. It must be rejected even with a valid
9286        // proof under the signing key.
9287        let forged = build_ownership_transfer(
9288            &owner_b_seed,
9289            &BuildOwnershipTransfer {
9290                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000102".into(),
9291                issuer_did: owner_b.into(),
9292                robot_did: robot.into(),
9293                to_owner: "did:web:owner-c.example.com".into(),
9294                // Claim the robot was sold by owner A while owner B signs.
9295                from_owner: Some(owner_a.into()),
9296                prev_transfer_id: None,
9297                valid_from: "2026-01-01T00:00:00Z".into(),
9298            },
9299        )
9300        .unwrap();
9301        assert!(
9302            verify_ownership_transfer(&forged, kd(&forged, &b.public_key()), None, TNOW)
9303                .unwrap()
9304                .is_none()
9305        );
9306    }
9307
9308    #[test]
9309    fn custody_chain_links_and_rejects() {
9310        let owner_a_seed = [51u8; 32];
9311        let owner_b_seed = [52u8; 32];
9312        let owner_c_seed = [53u8; 32];
9313        let a = Ed25519KeyPair::from_seed(&owner_a_seed);
9314        let b = Ed25519KeyPair::from_seed(&owner_b_seed);
9315        let c = Ed25519KeyPair::from_seed(&owner_c_seed);
9316        let owner_a = "did:web:owner-a.example.com";
9317        let owner_b = "did:web:owner-b.example.com";
9318        let owner_c = "did:web:owner-c.example.com";
9319        let robot = "did:web:robot.example.com";
9320
9321        let t1 = build_ownership_transfer(
9322            &owner_a_seed,
9323            &BuildOwnershipTransfer {
9324                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000103".into(),
9325                issuer_did: owner_a.into(),
9326                robot_did: robot.into(),
9327                to_owner: owner_b.into(),
9328                from_owner: None,
9329                prev_transfer_id: None,
9330                valid_from: "2026-01-01T00:00:00Z".into(),
9331            },
9332        )
9333        .unwrap();
9334        let t2 = build_ownership_transfer(
9335            &owner_b_seed,
9336            &BuildOwnershipTransfer {
9337                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000104".into(),
9338                issuer_did: owner_b.into(),
9339                robot_did: robot.into(),
9340                to_owner: owner_c.into(),
9341                from_owner: None,
9342                prev_transfer_id: Some("urn:uuid:00000000-0000-4000-8000-000000000103".into()),
9343                valid_from: "2026-02-01T00:00:00Z".into(),
9344            },
9345        )
9346        .unwrap();
9347
9348        let keys = vec![
9349            OwnerKey {
9350                did: owner_a.into(),
9351                public_key: a.public_key().to_vec(),
9352            },
9353            OwnerKey {
9354                did: owner_b.into(),
9355                public_key: b.public_key().to_vec(),
9356            },
9357            OwnerKey {
9358                did: owner_c.into(),
9359                public_key: c.public_key().to_vec(),
9360            },
9361        ];
9362
9363        // A clean two-link chain rooted at owner A ends at owner C.
9364        let (ok, current) = verify_custody_chain(
9365            &[t1.clone(), t2.clone()],
9366            &keys,
9367            "did:web:robot.example.com",
9368            Some(owner_a),
9369            "2026-03-01T00:00:00Z",
9370        )
9371        .unwrap();
9372        assert!(ok);
9373        assert_eq!(current.as_deref(), Some(owner_c));
9374
9375        // A wrong declared origin breaks the first link.
9376        let (bad_origin, _) = verify_custody_chain(
9377            &[t1.clone(), t2.clone()],
9378            &keys,
9379            "did:web:robot.example.com",
9380            Some(owner_c),
9381            "2026-03-01T00:00:00Z",
9382        )
9383        .unwrap();
9384        assert!(!bad_origin);
9385
9386        // A gap (link two without link one) breaks the toOwner -> fromOwner join.
9387        let (gap, _) = verify_custody_chain(
9388            core::slice::from_ref(&t2),
9389            &keys,
9390            "did:web:robot.example.com",
9391            Some(owner_a),
9392            "2026-03-01T00:00:00Z",
9393        )
9394        .unwrap();
9395        assert!(!gap);
9396
9397        // A missing key for an issuer fails the chain.
9398        let partial = vec![OwnerKey {
9399            did: owner_a.into(),
9400            public_key: a.public_key().to_vec(),
9401        }];
9402        let (no_key, _) = verify_custody_chain(
9403            &[t1, t2],
9404            &partial,
9405            "did:web:robot.example.com",
9406            Some(owner_a),
9407            "2026-03-01T00:00:00Z",
9408        )
9409        .unwrap();
9410        assert!(!no_key);
9411    }
9412
9413    #[test]
9414    fn key_rotation_roundtrip_and_history() {
9415        let k1_seed = [61u8; 32];
9416        let k2_seed = [62u8; 32];
9417        let k3_seed = [63u8; 32];
9418        let k1 = Ed25519KeyPair::from_seed(&k1_seed);
9419        let k2 = Ed25519KeyPair::from_seed(&k2_seed);
9420        let k3 = Ed25519KeyPair::from_seed(&k3_seed);
9421        let robot = "did:web:robot.example.com";
9422
9423        // Rotate k1 -> k2, signed by k1.
9424        let r1 = build_key_rotation(
9425            &k1_seed,
9426            &BuildKeyRotation {
9427                robot_did: robot.into(),
9428                new_key_multibase: k2.public_multikey(),
9429                reason: Some("scheduled rotation".into()),
9430                valid_from: "2026-01-01T00:00:00Z".into(),
9431            },
9432        )
9433        .unwrap();
9434
9435        let subject = verify_key_rotation(&r1, Keys::Bare(&k1.public_key()), None, TNOW)
9436            .unwrap()
9437            .expect("rotation verifies under the old key");
9438        assert_eq!(subject["previousKey"], json!(k1.public_multikey()));
9439        assert_eq!(subject["newKey"], json!(k2.public_multikey()));
9440
9441        // The new key cannot verify a rotation that the old key signed.
9442        assert!(
9443            verify_key_rotation(&r1, Keys::Bare(&k2.public_key()), None, TNOW)
9444                .unwrap()
9445                .is_none()
9446        );
9447
9448        // Wrong type rejected.
9449        let mut wrong = r1.clone();
9450        wrong["type"] = json!(["VerifiableCredential"]);
9451        assert!(
9452            verify_key_rotation(&wrong, Keys::Bare(&k1.public_key()), None, TNOW)
9453                .unwrap()
9454                .is_none()
9455        );
9456
9457        // Rotate k2 -> k3, signed by k2, forming a history.
9458        let r2 = build_key_rotation(
9459            &k2_seed,
9460            &BuildKeyRotation {
9461                robot_did: robot.into(),
9462                new_key_multibase: k3.public_multikey(),
9463                reason: None,
9464                valid_from: "2026-02-01T00:00:00Z".into(),
9465            },
9466        )
9467        .unwrap();
9468
9469        let (ok, current) = verify_key_history(
9470            &[r1.clone(), r2.clone()],
9471            &k1.public_multikey(),
9472            None,
9473            "2026-03-01T00:00:00Z",
9474        )
9475        .unwrap();
9476        assert!(ok);
9477        assert_eq!(current.as_deref(), Some(k3.public_multikey().as_str()));
9478
9479        // A wrong origin key breaks the first previousKey match.
9480        let (bad_origin, _) = verify_key_history(
9481            &[r1, r2],
9482            &k3.public_multikey(),
9483            None,
9484            "2026-03-01T00:00:00Z",
9485        )
9486        .unwrap();
9487        assert!(!bad_origin);
9488    }
9489
9490    #[test]
9491    fn decommission_roundtrip_and_trusted_authority() {
9492        let seed = [71u8; 32];
9493        let kp = Ed25519KeyPair::from_seed(&seed);
9494        let authority = "did:web:authority.example.com";
9495        let robot = "did:web:robot.example.com";
9496
9497        let cred = build_decommission(
9498            &seed,
9499            &BuildDecommission {
9500                issuer_did: authority.into(),
9501                robot_did: robot.into(),
9502                reason: "end of service life".into(),
9503                final_disposition: Some("recycled".into()),
9504                valid_from: "2026-01-01T00:00:00Z".into(),
9505                valid_until: None,
9506            },
9507        )
9508        .unwrap();
9509
9510        let mut trusted = HashSet::new();
9511        trusted.insert(authority.to_string());
9512        let subject = verify_decommission(
9513            &cred,
9514            kd(&cred, &kp.public_key()),
9515            Some(&trusted),
9516            None,
9517            TNOW,
9518        )
9519        .unwrap()
9520        .expect("a trusted authority decommission verifies");
9521        assert_eq!(subject["decommissionedBy"], json!(authority));
9522
9523        // An untrusted issuer is rejected even with a valid proof.
9524        let mut other = HashSet::new();
9525        other.insert("did:web:someone-else.example.com".to_string());
9526        assert!(
9527            verify_decommission(&cred, kd(&cred, &kp.public_key()), Some(&other), None, TNOW)
9528                .unwrap()
9529                .is_none()
9530        );
9531
9532        // No trusted-authority set: a valid proof verifies.
9533        assert!(
9534            verify_decommission(&cred, kd(&cred, &kp.public_key()), None, None, TNOW)
9535                .unwrap()
9536                .is_some()
9537        );
9538
9539        // Wrong type rejected.
9540        let mut wrong = cred.clone();
9541        wrong["type"] = json!(["VerifiableCredential"]);
9542        assert!(
9543            verify_decommission(&wrong, kd(&wrong, &kp.public_key()), None, None, TNOW)
9544                .unwrap()
9545                .is_none()
9546        );
9547
9548        // reason is required at build time.
9549        assert!(build_decommission(
9550            &seed,
9551            &BuildDecommission {
9552                issuer_did: authority.into(),
9553                robot_did: robot.into(),
9554                reason: String::new(),
9555                final_disposition: None,
9556                valid_from: "2026-01-01T00:00:00Z".into(),
9557                valid_until: None,
9558            },
9559        )
9560        .is_err());
9561    }
9562
9563    // Cross-language interop: Rust reproduces the exact conformance report and
9564    // digest Python pinned, from the same credential set and profile.
9565    #[test]
9566    fn conformance_matches_interop_vector() {
9567        let vector = load_vector();
9568        let credentials: Vec<Value> = vector["conformance_credentials"]
9569            .as_array()
9570            .expect("conformance_credentials present")
9571            .clone();
9572        let profile_id = vector["conformance_profile_id"].as_str().unwrap();
9573
9574        let report = check_conformance(&credentials, profile_id).unwrap();
9575        assert_eq!(report, vector["expected_conformance_report"]);
9576
9577        let digest = report_digest(&report);
9578        assert_eq!(
9579            digest,
9580            vector["expected_conformance_report_digest"]
9581                .as_str()
9582                .unwrap()
9583        );
9584    }
9585
9586    // Presence alone is not evidence. A heartbeat that reports an envelope
9587    // breach must not satisfy the continuous-monitoring requirement just by
9588    // carrying a motionDigest.
9589    #[test]
9590    fn a_breaching_heartbeat_does_not_evidence_monitoring() {
9591        let breaching = json!({
9592            "type": ["VerifiableCredential", "RobotHeartbeatCredential"],
9593            "credentialSubject": {
9594                "motionDigest": {"withinEnvelope": false, "samples": 120}
9595            }
9596        });
9597        let report = check_conformance(core::slice::from_ref(&breaching), "iso-ts-15066").unwrap();
9598        let monitoring = report["requirements"]
9599            .as_array()
9600            .unwrap()
9601            .iter()
9602            .find(|r| r["id"] == json!("iso15066-monitoring"))
9603            .expect("monitoring requirement present");
9604        assert_eq!(monitoring["satisfied"], json!(false));
9605
9606        // The same heartbeat reporting no breach does satisfy it.
9607        let mut clean = breaching;
9608        clean["credentialSubject"]["motionDigest"]["withinEnvelope"] = json!(true);
9609        let report = check_conformance(&[clean], "iso-ts-15066").unwrap();
9610        let monitoring = report["requirements"]
9611            .as_array()
9612            .unwrap()
9613            .iter()
9614            .find(|r| r["id"] == json!("iso15066-monitoring"))
9615            .unwrap();
9616        assert_eq!(monitoring["satisfied"], json!(true));
9617    }
9618
9619    // Every requirement declares where its clause number came from, and the
9620    // report totals them, so CONFORMS never reads as more authoritative about
9621    // the regulation than its sources are.
9622    #[test]
9623    fn conformance_report_carries_citation_provenance() {
9624        for profile_id in [
9625            "iso-10218",
9626            "iso-ts-15066",
9627            "eu-machinery-2023-1230",
9628            "eu-ai-act-high-risk",
9629            "ul-3300",
9630        ] {
9631            let report = check_conformance(&[], profile_id).unwrap();
9632            let citations = report["citations"].as_object().unwrap();
9633            assert_eq!(citations.len(), CITATION_STATUSES.len());
9634            let counted: i64 = citations.values().map(|v| v.as_i64().unwrap()).sum();
9635            assert_eq!(counted, report["totalCount"].as_i64().unwrap());
9636            for result in report["requirements"].as_array().unwrap() {
9637                let citation = result["citation"].as_str().unwrap();
9638                assert!(CITATION_STATUSES.contains(&citation));
9639            }
9640        }
9641
9642        // UL 3300 is paywalled with no clause numbering available, so none of
9643        // its "clauses" are citable.
9644        let ul = check_conformance(&[], "ul-3300").unwrap();
9645        assert_eq!(ul["citations"][CITATION_DESCRIPTIVE], ul["totalCount"]);
9646        assert_eq!(ul["citations"][CITATION_VERIFIED_PRIMARY], json!(0));
9647    }
9648
9649    #[test]
9650    fn conformance_unknown_profile_and_missing_field() {
9651        assert!(check_conformance(&[], "no-such-profile").is_err());
9652
9653        // An empty credential set satisfies nothing.
9654        let empty = check_conformance(&[], "eu-ai-act-high-risk").unwrap();
9655        assert_eq!(empty["conforms"], json!(false));
9656        assert_eq!(empty["satisfiedCount"], json!(0));
9657        assert_eq!(empty["totalCount"], json!(4));
9658
9659        // A safety record with no logHead does not satisfy the record-keeping
9660        // requirement (a missing field counts as unsatisfied).
9661        let creds = vec![json!({
9662            "type": ["VerifiableCredential", "RobotSafetyRecordCredential"],
9663            "credentialSubject": { "id": "did:web:robot.example.com", "totalEvents": 2 }
9664        })];
9665        let report = check_conformance(&creds, "eu-ai-act-high-risk").unwrap();
9666        let record_keeping = report["requirements"]
9667            .as_array()
9668            .unwrap()
9669            .iter()
9670            .find(|r| r["id"] == json!("eu-aia-record-keeping"))
9671            .unwrap();
9672        assert_eq!(record_keeping["satisfied"], json!(false));
9673
9674        // An empty allowedZones array is also unsatisfied.
9675        let zone_creds = vec![json!({
9676            "type": ["VerifiableCredential", "PhysicalCapabilityScope"],
9677            "credentialSubject": {
9678                "id": "did:web:robot.example.com",
9679                "physicalScope": { "maxSpeedMps": 1.5, "allowedZones": [] }
9680            }
9681        })];
9682        let ul = check_conformance(&zone_creds, "ul-3300").unwrap();
9683        let limits = ul["requirements"]
9684            .as_array()
9685            .unwrap()
9686            .iter()
9687            .find(|r| r["id"] == json!("ul3300-operating-limits"))
9688            .unwrap();
9689        assert_eq!(limits["satisfied"], json!(false));
9690    }
9691
9692    #[test]
9693    fn conformance_attestation_roundtrip_and_rejections() {
9694        let seed = [77u8; 32];
9695        let kp = Ed25519KeyPair::from_seed(&seed);
9696        let vector = load_vector();
9697        let credentials: Vec<Value> = vector["conformance_credentials"]
9698            .as_array()
9699            .unwrap()
9700            .clone();
9701        let report = check_conformance(&credentials, "eu-ai-act-high-risk").unwrap();
9702
9703        let att = build_conformance_attestation(
9704            &seed,
9705            &BuildConformanceAttestation {
9706                issuer_did: "did:web:authority.example.com".into(),
9707                robot_did: "did:web:robot.example.com".into(),
9708                report: report.clone(),
9709                valid_from: "2026-01-01T00:00:00Z".into(),
9710                valid_until: Some("2027-01-01T00:00:00Z".into()),
9711            },
9712        )
9713        .unwrap();
9714
9715        // Round-trip: a well-formed attestation verifies and surfaces the subject.
9716        let subject =
9717            verify_conformance_attestation(&att, kd(&att, &kp.public_key()), None, None, TNOW)
9718                .unwrap()
9719                .expect("a valid conformance attestation verifies");
9720        assert_eq!(subject["profileId"], json!("eu-ai-act-high-risk"));
9721        assert_eq!(subject["conforms"], json!(true));
9722        assert_eq!(
9723            subject["reportDigest"],
9724            vector["expected_conformance_report_digest"]
9725        );
9726
9727        // Wrong key is rejected.
9728        let wrong_kp = Ed25519KeyPair::from_seed(&[88u8; 32]);
9729        assert!(verify_conformance_attestation(
9730            &att,
9731            kd(&att, &wrong_kp.public_key()),
9732            None,
9733            None,
9734            TNOW
9735        )
9736        .unwrap()
9737        .is_none());
9738
9739        // A tampered embedded report no longer matches the bound digest.
9740        let mut tampered = att.clone();
9741        tampered["credentialSubject"]["report"]["conforms"] = json!(false);
9742        assert!(verify_conformance_attestation(
9743            &tampered,
9744            kd(&tampered, &kp.public_key()),
9745            None,
9746            None,
9747            TNOW
9748        )
9749        .unwrap()
9750        .is_none());
9751
9752        // Wrong type is rejected.
9753        let mut wrong_type = att.clone();
9754        wrong_type["type"] = json!(["VerifiableCredential"]);
9755        assert!(verify_conformance_attestation(
9756            &wrong_type,
9757            kd(&wrong_type, &kp.public_key()),
9758            None,
9759            None,
9760            TNOW
9761        )
9762        .unwrap()
9763        .is_none());
9764
9765        // robot_did is required at build time.
9766        assert!(build_conformance_attestation(
9767            &seed,
9768            &BuildConformanceAttestation {
9769                issuer_did: "did:web:authority.example.com".into(),
9770                robot_did: String::new(),
9771                report,
9772                valid_from: "2026-01-01T00:00:00Z".into(),
9773                valid_until: None,
9774            },
9775        )
9776        .is_err());
9777    }
9778
9779    // -- post-quantum robot credentials ------------------------------------
9780
9781    fn classical_robot_credential(issuer: &str, seed: &[u8]) -> Value {
9782        let cred = json!({
9783            "@context": [VC_CONTEXT_V2, VOUCH_CONTEXT_V1],
9784            "type": ["VerifiableCredential", ROBOT_IDENTITY_TYPE],
9785            "issuer": issuer,
9786            "validFrom": "2026-01-01T00:00:00Z",
9787            "credentialSubject": {
9788                "id": issuer,
9789                "make": "Acme Robotics",
9790                "model": "AR-7",
9791                "serial": "SN-000123"
9792            }
9793        });
9794        let opts = BuildProofOptions::new(format!("{issuer}#key-1"), "2026-01-01T00:00:00Z");
9795        data_integrity::sign(&cred, seed, &opts).unwrap()
9796    }
9797
9798    // Cross-language interop: Rust verifies the Python-signed hybrid PQ robot
9799    // identity under the Ed25519 key and the ML-DSA-44 multikey from the vector.
9800    #[test]
9801    fn verifies_python_pq_robot_identity_interop_vector() {
9802        let vector = load_vector();
9803        let ed_pub = jwk_pub(&vector["robot_public_key_jwk"]);
9804        let ml_multikey = vector["robot_mldsa44_public_multikey"].as_str().unwrap();
9805        let cred = vector["pq_robot_identity_credential"].clone();
9806
9807        // (b) the credential is detected as post-quantum.
9808        assert!(is_pq(&cred));
9809
9810        // (a) dual verify auto-detected from the proof, with the ML-DSA multikey.
9811        let ok = verify_robot_credential(
9812            &cred,
9813            kd(&cred, &ed_pub),
9814            Some(ml_multikey.as_bytes()),
9815            None,
9816            TNOW,
9817        )
9818        .expect("the Python hybrid PQ interop vector must verify in Rust");
9819        assert!(ok);
9820
9821        // verify_pq accepts the multikey string form directly.
9822        let resolved = mldsa44_public_from_multikey(ml_multikey).unwrap();
9823        assert!(verify_pq(&cred, &ed_pub, &resolved).unwrap());
9824    }
9825
9826    #[test]
9827    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
9828    fn pq_sign_verify_roundtrip_and_rejects() {
9829        let issuer = "did:web:robot.example.com";
9830        let seed = [21u8; 32];
9831        let kp = Ed25519KeyPair::from_seed(&seed);
9832        let ml = MlDsa44KeyPair::generate().unwrap();
9833
9834        let classical = classical_robot_credential(issuer, &seed);
9835        assert!(!is_pq(&classical));
9836
9837        // Sign post-quantum; any prior proof is replaced by a proof set holding
9838        // one classical and one ML-DSA-44 proof.
9839        let signed = sign_pq(&classical, &seed, &ml, "2026-02-01T00:00:00Z").unwrap();
9840        assert!(is_pq(&signed));
9841        let proofs = signed["proof"].as_array().expect("proof set");
9842        assert_eq!(proofs.len(), 2);
9843        assert_eq!(
9844            proofs[0]["cryptosuite"],
9845            json!(hybrid::EDDSA_CRYPTOSUITE_ID)
9846        );
9847        assert_eq!(
9848            proofs[1]["cryptosuite"],
9849            json!(hybrid::MLDSA44_CRYPTOSUITE_ID)
9850        );
9851        // Each proof carries the Multibase encoding its cryptosuite specifies.
9852        assert!(proofs[0]["proofValue"].as_str().unwrap().starts_with('z'));
9853        assert!(proofs[1]["proofValue"].as_str().unwrap().starts_with('u'));
9854
9855        // Round-trip: both signatures validate under the correct keys.
9856        assert!(verify_pq(&signed, &kp.public_key(), &ml.public_key()).unwrap());
9857        assert!(verify_robot_credential(
9858            &signed,
9859            kd(&signed, &kp.public_key()),
9860            Some(&ml.public_key()),
9861            None,
9862            TNOW
9863        )
9864        .unwrap());
9865
9866        // The multikey string form is accepted too (as UTF-8 bytes).
9867        let ml_mk = multikey::encode_mldsa44_public(&ml.public_key()).unwrap();
9868        assert!(verify_robot_credential(
9869            &signed,
9870            kd(&signed, &kp.public_key()),
9871            Some(ml_mk.as_bytes()),
9872            None,
9873            TNOW
9874        )
9875        .unwrap());
9876
9877        // Tampering the body breaks verification.
9878        let mut tampered = signed.clone();
9879        tampered["credentialSubject"]["model"] = json!("AR-9");
9880        assert!(!verify_pq(&tampered, &kp.public_key(), &ml.public_key()).unwrap());
9881
9882        // Wrong Ed25519 key is rejected.
9883        let other_ed = Ed25519KeyPair::from_seed(&[99u8; 32]);
9884        assert!(!verify_pq(&signed, &other_ed.public_key(), &ml.public_key()).unwrap());
9885
9886        // Wrong ML-DSA-44 key is rejected.
9887        let other_ml = MlDsa44KeyPair::generate().unwrap();
9888        assert!(!verify_pq(&signed, &kp.public_key(), &other_ml.public_key()).unwrap());
9889
9890        // A hybrid credential without the ML-DSA key returns false, not true.
9891        assert!(
9892            !verify_robot_credential(&signed, kd(&signed, &kp.public_key()), None, None, TNOW)
9893                .unwrap()
9894        );
9895
9896        // Downgrade by extraction: an attacker strips the proof set to the lone
9897        // standalone classical proof. A verifier that supplies the ML-DSA key
9898        // (so requires post-quantum) must reject it, not accept it as classical.
9899        let proofs = signed["proof"].as_array().unwrap();
9900        let classical_proof = proofs
9901            .iter()
9902            .find(|p| p["cryptosuite"] == json!(hybrid::EDDSA_CRYPTOSUITE_ID))
9903            .unwrap()
9904            .clone();
9905        let mut stripped = signed.clone();
9906        stripped["proof"] = classical_proof;
9907        assert!(!is_pq(&stripped));
9908        assert!(
9909            !verify_robot_credential(
9910                &stripped,
9911                kd(&stripped, &kp.public_key()),
9912                Some(&ml.public_key()),
9913                None,
9914                TNOW
9915            )
9916            .unwrap(),
9917            "a stripped proof set must not verify when the caller requires post-quantum"
9918        );
9919        // The extracted classical proof is genuine, so a caller that only does
9920        // classical verification (no ML-DSA key) still accepts it.
9921        assert!(verify_robot_credential(
9922            &stripped,
9923            kd(&stripped, &kp.public_key()),
9924            None,
9925            None,
9926            TNOW
9927        )
9928        .unwrap());
9929    }
9930
9931    #[test]
9932    fn classical_credential_passes_dual_verify_without_pq_key() {
9933        let issuer = "did:web:robot.example.com";
9934        let seed = [22u8; 32];
9935        let kp = Ed25519KeyPair::from_seed(&seed);
9936        let classical = classical_robot_credential(issuer, &seed);
9937
9938        assert!(!is_pq(&classical));
9939        // A classical credential verifies through the dual path with no ML-DSA key.
9940        assert!(verify_robot_credential(
9941            &classical,
9942            kd(&classical, &kp.public_key()),
9943            None,
9944            None,
9945            TNOW
9946        )
9947        .unwrap());
9948
9949        // A wrong key still fails.
9950        let other = Ed25519KeyPair::from_seed(&[7u8; 32]);
9951        assert!(!verify_robot_credential(
9952            &classical,
9953            kd(&classical, &other.public_key()),
9954            None,
9955            None,
9956            TNOW
9957        )
9958        .unwrap());
9959    }
9960
9961    #[test]
9962    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
9963    fn migrate_to_pq_resigns_classical_credential() {
9964        let issuer = "did:web:robot.example.com";
9965        let seed = [23u8; 32];
9966        let kp = Ed25519KeyPair::from_seed(&seed);
9967        let ml = MlDsa44KeyPair::generate().unwrap();
9968
9969        let classical = classical_robot_credential(issuer, &seed);
9970        assert!(verify_robot_credential(
9971            &classical,
9972            kd(&classical, &kp.public_key()),
9973            None,
9974            None,
9975            TNOW
9976        )
9977        .unwrap());
9978
9979        let migrated = migrate_to_pq(&classical, &seed, &ml, "2026-03-01T00:00:00Z").unwrap();
9980        assert!(is_pq(&migrated));
9981        // The body is preserved across migration.
9982        assert_eq!(
9983            migrated["credentialSubject"],
9984            classical["credentialSubject"]
9985        );
9986        assert!(verify_robot_credential(
9987            &migrated,
9988            kd(&migrated, &kp.public_key()),
9989            Some(&ml.public_key()),
9990            None,
9991            TNOW
9992        )
9993        .unwrap());
9994    }
9995
9996    // Cross-language interop: Rust verifies the Python-signed embodiment continuity
9997    // chain under the one agent key from the vector, ending on body-b, with no fork.
9998    #[test]
9999    fn verifies_python_embodiment_interop_vector() {
10000        let vector = load_vector();
10001        let agent_pub = jwk_pub(&vector["embodiment_agent_key"]);
10002        let chain: Vec<Value> = vector["embodiment_chain"]
10003            .as_array()
10004            .expect("embodiment_chain array")
10005            .clone();
10006
10007        let (ok, current) = verify_continuity_chain(
10008            &chain,
10009            Keys::Resolver(&any_did(&agent_pub)),
10010            None,
10011            None,
10012            "2026-06-01T00:00:00Z",
10013        )
10014        .unwrap();
10015        assert!(ok, "the Python embodiment chain must verify in Rust");
10016        assert_eq!(
10017            current.as_deref(),
10018            Some("did:web:body-b.example.com"),
10019            "the chain ends on body-b"
10020        );
10021
10022        let (no_fork, conflict) = check_no_fork(&chain).unwrap();
10023        assert!(no_fork, "the Python embodiment chain has no fork");
10024        assert!(conflict.is_none());
10025    }
10026
10027    #[test]
10028    fn embodiment_roundtrip_and_issuer_rule() {
10029        let agent_seed = [61u8; 32];
10030        let other_seed = [62u8; 32];
10031        let agent = Ed25519KeyPair::from_seed(&agent_seed);
10032        let other = Ed25519KeyPair::from_seed(&other_seed);
10033        let agent_did = "did:web:agent.example.com";
10034        let body_a = "did:web:body-a.example.com";
10035
10036        let cred = build_embodiment(
10037            &agent_seed,
10038            &BuildEmbodiment {
10039                agent_did: agent_did.into(),
10040                body_did: body_a.into(),
10041                body_hardware_root: "uROOTA".into(),
10042                from_body: None,
10043                embodied_at: "2026-01-01T00:00:00Z".into(),
10044                valid_until: None,
10045            },
10046        )
10047        .unwrap();
10048
10049        let subject = verify_embodiment(&cred, kd(&cred, &agent.public_key()), None, TNOW)
10050            .unwrap()
10051            .expect("embodiment verifies under the agent key");
10052        assert_eq!(subject["body"], json!(body_a));
10053        assert_eq!(subject["bodyHardwareRoot"], json!("uROOTA"));
10054
10055        // The issuer must equal the subject id: forge a credential issued by an
10056        // impostor over an unchanged subject (still the agent) and re-sign it. It
10057        // must be rejected even with a valid proof under the signing key, because a
10058        // mind only authorizes its own embodiment.
10059        let forged = {
10060            let mut bare = cred.clone();
10061            bare.as_object_mut().unwrap().remove("proof");
10062            bare["issuer"] = json!("did:web:impostor.example.com");
10063            let opts = BuildProofOptions::new(
10064                "did:web:impostor.example.com#key-1".to_string(),
10065                "2026-01-01T00:00:00Z",
10066            );
10067            data_integrity::sign(&bare, &other_seed, &opts).unwrap()
10068        };
10069        assert!(
10070            verify_embodiment(&forged, kd(&forged, &other.public_key()), None, TNOW)
10071                .unwrap()
10072                .is_none()
10073        );
10074    }
10075
10076    #[test]
10077    fn continuity_chain_links_and_rejects() {
10078        let agent_seed = [61u8; 32];
10079        let stranger_seed = [63u8; 32];
10080        let agent = Ed25519KeyPair::from_seed(&agent_seed);
10081        let stranger = Ed25519KeyPair::from_seed(&stranger_seed);
10082        let agent_did = "did:web:agent.example.com";
10083        let body_a = "did:web:body-a.example.com";
10084        let body_b = "did:web:body-b.example.com";
10085
10086        let e1 = build_embodiment(
10087            &agent_seed,
10088            &BuildEmbodiment {
10089                agent_did: agent_did.into(),
10090                body_did: body_a.into(),
10091                body_hardware_root: "uROOTA".into(),
10092                from_body: None,
10093                embodied_at: "2026-01-01T00:00:00Z".into(),
10094                valid_until: Some("2026-01-01T01:00:00Z".into()),
10095            },
10096        )
10097        .unwrap();
10098        let e2 = build_embodiment(
10099            &agent_seed,
10100            &BuildEmbodiment {
10101                agent_did: agent_did.into(),
10102                body_did: body_b.into(),
10103                body_hardware_root: "uROOTB".into(),
10104                from_body: Some(body_a.into()),
10105                embodied_at: "2026-01-01T01:00:00Z".into(),
10106                valid_until: None,
10107            },
10108        )
10109        .unwrap();
10110
10111        // A clean two-link chain ends at body-b: the first link opens on body-a
10112        // and the second link's fromBody re-binds to it.
10113        let (ok, current) = verify_continuity_chain(
10114            &[e1.clone(), e2.clone()],
10115            Keys::Resolver(&any_did(&agent.public_key())),
10116            None,
10117            None,
10118            "2026-06-01T00:00:00Z",
10119        )
10120        .unwrap();
10121        assert!(ok);
10122        assert_eq!(current.as_deref(), Some(body_b));
10123
10124        // Declaring the wrong origin body breaks the first link, since the first
10125        // link's fromBody must match the origin when given.
10126        let (bad_origin, _) = verify_continuity_chain(
10127            &[e1.clone(), e2.clone()],
10128            Keys::Resolver(&any_did(&agent.public_key())),
10129            Some(body_b),
10130            None,
10131            "2026-06-01T00:00:00Z",
10132        )
10133        .unwrap();
10134        assert!(!bad_origin);
10135
10136        // A broken link (second link's fromBody does not match the first's body)
10137        // fails the chain.
10138        let broken = build_embodiment(
10139            &agent_seed,
10140            &BuildEmbodiment {
10141                agent_did: agent_did.into(),
10142                body_did: body_b.into(),
10143                body_hardware_root: "uROOTB".into(),
10144                from_body: Some("did:web:body-x.example.com".into()),
10145                embodied_at: "2026-01-01T01:00:00Z".into(),
10146                valid_until: None,
10147            },
10148        )
10149        .unwrap();
10150        let (bad_link, _) = verify_continuity_chain(
10151            &[e1.clone(), broken],
10152            Keys::Resolver(&any_did(&agent.public_key())),
10153            None,
10154            None,
10155            "2026-06-01T00:00:00Z",
10156        )
10157        .unwrap();
10158        assert!(!bad_link);
10159
10160        // Every link must verify under the SAME agent key: a link signed by a
10161        // different key breaks the chain (a mind is one persistent identity).
10162        let e2_stranger = build_embodiment(
10163            &stranger_seed,
10164            &BuildEmbodiment {
10165                agent_did: agent_did.into(),
10166                body_did: body_b.into(),
10167                body_hardware_root: "uROOTB".into(),
10168                from_body: Some(body_a.into()),
10169                embodied_at: "2026-01-01T01:00:00Z".into(),
10170                valid_until: None,
10171            },
10172        )
10173        .unwrap();
10174        assert!(verify_embodiment(
10175            &e2_stranger,
10176            kd(&e2_stranger, &stranger.public_key()),
10177            None,
10178            "2026-06-01T00:00:00Z"
10179        )
10180        .unwrap()
10181        .is_some());
10182        let (mixed_keys, _) = verify_continuity_chain(
10183            &[e1, e2_stranger],
10184            Keys::Resolver(&any_did(&agent.public_key())),
10185            None,
10186            None,
10187            "2026-06-01T00:00:00Z",
10188        )
10189        .unwrap();
10190        assert!(!mixed_keys);
10191    }
10192
10193    #[test]
10194    fn fork_detection_flags_overlapping_bodies() {
10195        let agent_seed = [61u8; 32];
10196        let agent_did = "did:web:agent.example.com";
10197        let body_a = "did:web:body-a.example.com";
10198        let body_b = "did:web:body-b.example.com";
10199
10200        let build = |body: &str, root: &str, from: &str, until: &str| {
10201            build_embodiment(
10202                &agent_seed,
10203                &BuildEmbodiment {
10204                    agent_did: agent_did.into(),
10205                    body_did: body.into(),
10206                    body_hardware_root: root.into(),
10207                    from_body: None,
10208                    embodied_at: from.into(),
10209                    valid_until: Some(until.into()),
10210                },
10211            )
10212            .unwrap()
10213        };
10214
10215        // A clean handover: body-a's window ends exactly where body-b's begins.
10216        // Half-open intervals do not overlap, so this is not a fork.
10217        let clean_a = build(
10218            body_a,
10219            "uROOTA",
10220            "2026-01-01T00:00:00Z",
10221            "2026-01-01T01:00:00Z",
10222        );
10223        let clean_b = build(
10224            body_b,
10225            "uROOTB",
10226            "2026-01-01T01:00:00Z",
10227            "2026-01-01T02:00:00Z",
10228        );
10229        let (clean, conflict) = check_no_fork(&[clean_a, clean_b]).unwrap();
10230        assert!(clean);
10231        assert!(conflict.is_none());
10232
10233        // Overlapping windows on different bodies are a fork; the conflict names
10234        // both bodies.
10235        let fork_a = build(
10236            body_a,
10237            "uROOTA",
10238            "2026-01-01T00:00:00Z",
10239            "2026-01-01T02:00:00Z",
10240        );
10241        let fork_b = build(
10242            body_b,
10243            "uROOTB",
10244            "2026-01-01T01:00:00Z",
10245            "2026-01-01T03:00:00Z",
10246        );
10247        let (forked, conflict) = check_no_fork(&[fork_a, fork_b]).unwrap();
10248        assert!(!forked);
10249        let conflict = conflict.expect("a fork names the two conflicting bodies");
10250        assert_eq!(conflict.body_a, body_a);
10251        assert_eq!(conflict.body_b, body_b);
10252    }
10253
10254    // Custody handoff (Phase 5.16) -----------------------------------------
10255
10256    fn actor_keys_from_vector(map: &Value) -> Vec<ActorKey> {
10257        map.as_object()
10258            .expect("custody_actor_keys object")
10259            .iter()
10260            .map(|(did, jwk)| ActorKey {
10261                did: did.clone(),
10262                public_key: jwk_pub(jwk),
10263            })
10264            .collect()
10265    }
10266
10267    // Cross-language interop: Rust verifies the Python-signed custody chain under
10268    // the actor keys from the vector, ending on robot-b, and localizes the
10269    // condition change to the hop robot-a was responsible for.
10270    #[test]
10271    fn verifies_python_custody_interop_vector() {
10272        let vector = load_vector();
10273        let chain: Vec<Value> = vector["custody_chain"]
10274            .as_array()
10275            .expect("custody_chain array")
10276            .clone();
10277        let keys = actor_keys_from_vector(&vector["custody_actor_keys"]);
10278        let origin = vector["custody_origin_actor"].as_str().unwrap();
10279
10280        let (ok, current) =
10281            verify_handoff_chain(&chain, &keys, "tote-42", Some(origin), false, TNOW).unwrap();
10282        assert!(ok, "the Python custody chain must verify in Rust");
10283        assert_eq!(
10284            current.as_deref(),
10285            Some("did:web:robot-b.example.com"),
10286            "the chain ends holding at robot-b"
10287        );
10288
10289        let change = locate_condition_change(&chain).expect("the condition changed");
10290        assert_eq!(
10291            change.responsible_holder.as_deref(),
10292            Some("did:web:robot-a.example.com"),
10293            "robot-a held the task while its condition changed"
10294        );
10295        assert_eq!(change.from_condition, "intact");
10296        assert_eq!(change.to_condition, "damaged");
10297    }
10298
10299    #[test]
10300    fn handoff_roundtrip_and_receiver_rule() {
10301        let robot_seed = [71u8; 32];
10302        let other_seed = [72u8; 32];
10303        let robot = Ed25519KeyPair::from_seed(&robot_seed);
10304        let other = Ed25519KeyPair::from_seed(&other_seed);
10305        let worker = "did:web:worker-jane.example.com";
10306        let robot_a = "did:web:robot-a.example.com";
10307
10308        let cred = build_handoff(
10309            &robot_seed,
10310            &BuildHandoff {
10311                release: None,
10312                prev_handoff_id: None,
10313                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000105".into(),
10314                task_id: "tote-42".into(),
10315                from_actor: worker.into(),
10316                to_actor: robot_a.into(),
10317                condition: Some("intact".into()),
10318                handoff_at: "2026-01-01T00:00:00Z".into(),
10319                valid_until: None,
10320            },
10321        )
10322        .unwrap();
10323
10324        let subject = verify_handoff(
10325            &cred,
10326            kd(&cred, &robot.public_key()),
10327            HandoffCheck::default(),
10328            TNOW,
10329        )
10330        .unwrap()
10331        .expect("handoff verifies under the receiver key");
10332        assert_eq!(subject["fromActor"], json!(worker));
10333        assert_eq!(subject["toActor"], json!(robot_a));
10334
10335        // The issuer must be the receiver: forge a handoff issued by a different
10336        // party over the same subject and re-sign it. It must be rejected even with
10337        // a valid proof under the signing key, because a party attests its own
10338        // acceptance of custody.
10339        let forged = {
10340            let mut bare = cred.clone();
10341            bare.as_object_mut().unwrap().remove("proof");
10342            bare["issuer"] = json!("did:web:impostor.example.com");
10343            let opts = BuildProofOptions::new(
10344                "did:web:impostor.example.com#key-1".to_string(),
10345                "2026-01-01T00:00:00Z",
10346            );
10347            data_integrity::sign(&bare, &other_seed, &opts).unwrap()
10348        };
10349        assert!(verify_handoff(
10350            &forged,
10351            kd(&forged, &other.public_key()),
10352            HandoffCheck::default(),
10353            TNOW
10354        )
10355        .unwrap()
10356        .is_none());
10357    }
10358
10359    #[test]
10360    fn handoff_chain_links_and_rejects() {
10361        let a_seed = [73u8; 32];
10362        let b_seed = [74u8; 32];
10363        let a = Ed25519KeyPair::from_seed(&a_seed);
10364        let b = Ed25519KeyPair::from_seed(&b_seed);
10365        let worker = "did:web:worker-jane.example.com";
10366        let robot_a = "did:web:robot-a.example.com";
10367        let robot_b = "did:web:robot-b.example.com";
10368
10369        let h1 = build_handoff(
10370            &a_seed,
10371            &BuildHandoff {
10372                release: None,
10373                prev_handoff_id: None,
10374                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000106".into(),
10375                task_id: "tote-42".into(),
10376                from_actor: worker.into(),
10377                to_actor: robot_a.into(),
10378                condition: Some("intact".into()),
10379                handoff_at: "2026-01-01T00:00:00Z".into(),
10380                valid_until: None,
10381            },
10382        )
10383        .unwrap();
10384        let h2 = build_handoff(
10385            &b_seed,
10386            &BuildHandoff {
10387                release: None,
10388                prev_handoff_id: Some("urn:uuid:00000000-0000-4000-8000-000000000106".into()),
10389                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000107".into(),
10390                task_id: "tote-42".into(),
10391                from_actor: robot_a.into(),
10392                to_actor: robot_b.into(),
10393                condition: Some("damaged".into()),
10394                handoff_at: "2026-01-01T00:10:00Z".into(),
10395                valid_until: None,
10396            },
10397        )
10398        .unwrap();
10399
10400        let keys = vec![
10401            ActorKey {
10402                did: robot_a.into(),
10403                public_key: a.public_key().to_vec(),
10404            },
10405            ActorKey {
10406                did: robot_b.into(),
10407                public_key: b.public_key().to_vec(),
10408            },
10409        ];
10410
10411        // A clean two-link chain ends holding at robot-b: the first link's
10412        // fromActor is the origin worker and the second link re-binds to robot-a.
10413        let (ok, current) = verify_handoff_chain(
10414            &[h1.clone(), h2.clone()],
10415            &keys,
10416            "tote-42",
10417            Some(worker),
10418            false,
10419            TNOW,
10420        )
10421        .unwrap();
10422        assert!(ok);
10423        assert_eq!(current.as_deref(), Some(robot_b));
10424
10425        // Declaring the wrong origin actor breaks the first link.
10426        let (bad_origin, _) = verify_handoff_chain(
10427            &[h1.clone(), h2.clone()],
10428            &keys,
10429            "tote-42",
10430            Some(robot_b),
10431            false,
10432            TNOW,
10433        )
10434        .unwrap();
10435        assert!(!bad_origin);
10436
10437        // A broken link (second link's fromActor does not match the first's
10438        // toActor) fails the chain.
10439        let broken = build_handoff(
10440            &b_seed,
10441            &BuildHandoff {
10442                release: None,
10443                prev_handoff_id: Some("urn:uuid:00000000-0000-4000-8000-000000000106".into()),
10444                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000108".into(),
10445                task_id: "tote-42".into(),
10446                from_actor: "did:web:robot-x.example.com".into(),
10447                to_actor: robot_b.into(),
10448                condition: Some("damaged".into()),
10449                handoff_at: "2026-01-01T00:10:00Z".into(),
10450                valid_until: None,
10451            },
10452        )
10453        .unwrap();
10454        let (bad_link, _) = verify_handoff_chain(
10455            &[h1.clone(), broken],
10456            &keys,
10457            "tote-42",
10458            Some(worker),
10459            false,
10460            TNOW,
10461        )
10462        .unwrap();
10463        assert!(!bad_link);
10464
10465        // A missing receiver key for a link fails the chain.
10466        let partial = vec![ActorKey {
10467            did: robot_a.into(),
10468            public_key: a.public_key().to_vec(),
10469        }];
10470        let (no_key, _) = verify_handoff_chain(
10471            &[h1.clone(), h2.clone()],
10472            &partial,
10473            "tote-42",
10474            Some(worker),
10475            false,
10476            TNOW,
10477        )
10478        .unwrap();
10479        assert!(!no_key);
10480
10481        // holder_at reports who held the task at a moment: robot-a right after the
10482        // first handoff, robot-b right after the second.
10483        assert_eq!(
10484            holder_at(&[h1.clone(), h2.clone()], "2026-01-01T00:05:00Z").as_deref(),
10485            Some(robot_a)
10486        );
10487        assert_eq!(
10488            holder_at(&[h1.clone(), h2.clone()], "2026-01-01T00:15:00Z").as_deref(),
10489            Some(robot_b)
10490        );
10491
10492        // A chain whose condition never changes localizes nothing.
10493        let steady = build_handoff(
10494            &b_seed,
10495            &BuildHandoff {
10496                release: None,
10497                prev_handoff_id: None,
10498                credential_id: "urn:uuid:00000000-0000-4000-8000-000000000109".into(),
10499                task_id: "tote-42".into(),
10500                from_actor: robot_a.into(),
10501                to_actor: robot_b.into(),
10502                condition: Some("intact".into()),
10503                handoff_at: "2026-01-01T00:10:00Z".into(),
10504                valid_until: None,
10505            },
10506        )
10507        .unwrap();
10508        assert!(locate_condition_change(&[h1, steady]).is_none());
10509    }
10510
10511    // Robot-to-infrastructure bounded access (Phase 5.17) ------------------
10512
10513    // Cross-language interop: Rust authorizes the Python-signed grant and request
10514    // from the vector under the operator and robot keys, offline.
10515    #[test]
10516    fn authorizes_python_access_interop_vector() {
10517        let vector = load_vector();
10518        let grant = vector["access_grant_credential"].clone();
10519        let request = vector["access_request_credential"].clone();
10520        let operator_pub = jwk_pub(&vector["access_operator_key"]);
10521        let robot_pub = jwk_pub(&vector["access_robot_key"]);
10522
10523        // The request was made at VALID_FROM; a resource checks it within the
10524        // 60 s age limit and remembers its nonce.
10525        let mut seen = HashSet::new();
10526        let res = authorize_access(
10527            &grant,
10528            &request,
10529            kd(&grant, &operator_pub),
10530            kd(&request, &robot_pub),
10531            RequestReplay::new(&mut seen),
10532            "2026-01-01T00:00:30Z",
10533        )
10534        .unwrap();
10535        assert!(
10536            res.ok,
10537            "the Python grant and request must authorize in Rust: {:?}",
10538            res.reasons
10539        );
10540        assert!(res.reasons.is_empty());
10541        // A replay of the same request is refused, and so is a stale one.
10542        let again = authorize_access(
10543            &grant,
10544            &request,
10545            kd(&grant, &operator_pub),
10546            kd(&request, &robot_pub),
10547            RequestReplay::new(&mut seen),
10548            "2026-01-01T00:00:30Z",
10549        )
10550        .unwrap();
10551        assert!(!again.ok);
10552        let mut fresh = HashSet::new();
10553        let stale = authorize_access(
10554            &grant,
10555            &request,
10556            kd(&grant, &operator_pub),
10557            kd(&request, &robot_pub),
10558            RequestReplay::new(&mut fresh),
10559            "2026-01-01T00:05:00Z",
10560        )
10561        .unwrap();
10562        assert!(!stale.ok);
10563    }
10564
10565    // Fused-sensor provenance (Phase 5.18) ---------------------------------
10566
10567    // Cross-language interop: Rust reproduces the exact inputs digest and fused
10568    // output hash Python pinned, and verifies the Python-signed attestation.
10569    #[test]
10570    fn verifies_python_fused_interop_vector() {
10571        let vector = load_vector();
10572        let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
10573
10574        let inputs: Vec<String> = vector["fused_input_frame_hashes"]
10575            .as_array()
10576            .unwrap()
10577            .iter()
10578            .map(|v| v.as_str().unwrap().to_string())
10579            .collect();
10580        assert_eq!(
10581            fusion_inputs_digest_version(&inputs, INPUTS_DIGEST_V1).unwrap(),
10582            vector["expected_fusion_inputs_digest"].as_str().unwrap()
10583        );
10584        assert_eq!(
10585            fusion_inputs_digest(&inputs).unwrap(),
10586            vector["expected_fusion_inputs_digest_v2"].as_str().unwrap()
10587        );
10588
10589        assert_eq!(
10590            hash_fused_output(b"world-model-0"),
10591            vector["expected_fused_output_hash"].as_str().unwrap()
10592        );
10593
10594        let cred = vector["fused_perception_attestation"].clone();
10595        let subject = verify_fused_attestation(&cred, kd(&cred, &robot_pub), None, TNOW)
10596            .unwrap()
10597            .expect("fused attestation verifies");
10598        assert_eq!(subject["fusionMethod"], "occupancy-grid-v1");
10599        assert_eq!(
10600            subject["inputsDigest"].as_str().unwrap(),
10601            vector["expected_fusion_inputs_digest_v2"].as_str().unwrap()
10602        );
10603    }
10604
10605    // Wear and degradation attestation (Phase 5.19) ------------------------
10606
10607    // Cross-language interop: Rust verifies the Python-signed wear history and
10608    // reproduces the physical scope narrowed for the pinned wear level.
10609    #[test]
10610    fn verifies_python_wear_interop_vector() {
10611        let vector = load_vector();
10612        let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
10613
10614        let chain: Vec<Value> = vector["wear_chain"].as_array().unwrap().clone();
10615        let latest = verify_wear_chain(&chain, Keys::Resolver(&any_did(&robot_pub)), TNOW)
10616            .unwrap()
10617            .expect("wear chain verifies");
10618        assert_eq!(latest["wearLevel"].as_f64().unwrap(), 0.3);
10619
10620        let scope = vector["wear_input_scope"].clone();
10621        let level = vector["wear_attenuation_level"].as_f64().unwrap();
10622        let narrowed = attenuate_for_wear(&scope, level).unwrap();
10623        assert_eq!(narrowed, vector["expected_attenuated_scope"]);
10624        assert_eq!(narrowed["maxForceN"].as_f64().unwrap(), 60.0);
10625        assert_eq!(narrowed["maxSpeedMps"].as_f64().unwrap(), 1.125);
10626        assert_eq!(narrowed["maxSpeedNearHumansMps"].as_f64().unwrap(), 0.1875);
10627        assert!(attenuates(&scope, &narrowed));
10628    }
10629
10630    // Bystander-consent evidence (Phase 5.20) ------------------------------
10631
10632    // Cross-language interop: Rust reproduces the capture hash Python pinned,
10633    // verifies the bystander-signed token is bound to that capture, and verifies
10634    // the robot-signed evidence with the token and the bystander key.
10635    #[test]
10636    fn verifies_python_consent_interop_vector() {
10637        let vector = load_vector();
10638        let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
10639        let bystander_pub = jwk_pub(&vector["consent_bystander_key"]);
10640
10641        let capture = b"bystander-frame-0";
10642        let capture_hash = hash_capture(capture);
10643        assert_eq!(
10644            capture_hash,
10645            vector["expected_consent_capture_hash"].as_str().unwrap()
10646        );
10647
10648        let token = vector["consent_token_credential"].clone();
10649        let robot_did = token["credentialSubject"]["robotDid"].as_str().unwrap();
10650        let tok_subject = verify_consent_token(
10651            &token,
10652            kd(&token, &bystander_pub),
10653            &capture_hash,
10654            robot_did,
10655            "2026-01-01T00:05:00Z",
10656        )
10657        .unwrap()
10658        .expect("consent token verifies bound to the capture");
10659        assert_eq!(tok_subject["captureHash"].as_str().unwrap(), capture_hash);
10660
10661        let evidence = vector["consent_evidence_credential"].clone();
10662        let bystander_did = token["issuer"].as_str().unwrap();
10663        let keys = [BystanderKey {
10664            did: bystander_did.to_string(),
10665            public_key: bystander_pub.clone(),
10666        }];
10667        let ev_subject = verify_consent_evidence(
10668            &evidence,
10669            kd(&evidence, &robot_pub),
10670            Some(capture),
10671            Some(core::slice::from_ref(&token)),
10672            Some(&keys),
10673            "2026-01-01T00:05:00Z",
10674        )
10675        .unwrap()
10676        .expect("consent evidence verifies with token and bystander key");
10677        assert_eq!(ev_subject["basis"].as_str().unwrap(), "explicit-consent");
10678    }
10679}
10680
10681#[cfg(test)]
10682mod robot_root_identity_tests {
10683    use super::*;
10684    use crate::keys::Ed25519KeyPair;
10685    #[allow(unused_imports)]
10686    use crate::robotics_verify::test_keys::{any_did, kd, TNOW};
10687    #[allow(unused_imports)]
10688    use crate::robotics_verify::Keys;
10689    use std::path::PathBuf;
10690
10691    const NOW: &str = "2026-07-01T00:00:00Z";
10692    const VALID_FROM: &str = "2026-01-01T00:00:00Z";
10693    const CREATED: &str = "2026-01-01T00:00:00Z";
10694    const VALID_SECONDS: i64 = 100 * 365 * 24 * 3600;
10695    // Matches the manufacturer seed recorded in the interop vector (0x04 x32).
10696    const MANUFACTURER_SEED: [u8; 32] = [0x04; 32];
10697    const FORGED_ID: &str = "urn:uuid:66666666-6666-6666-6666-666666666666";
10698
10699    fn load_vector() -> Value {
10700        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
10701            .join("../../test-vectors/root-of-trust/vector.json");
10702        let text = std::fs::read_to_string(&path)
10703            .unwrap_or_else(|e| panic!("read vector {}: {e}", path.display()));
10704        serde_json::from_str(&text).expect("vector is valid JSON")
10705    }
10706
10707    fn robot_pub(vector: &Value) -> Vec<u8> {
10708        let x = vector["robotPublicKey"]["x"].as_str().unwrap();
10709        URL_SAFE_NO_PAD.decode(x).unwrap()
10710    }
10711
10712    fn stray_multikey(seed: &[u8]) -> String {
10713        let kp = Ed25519KeyPair::from_seed_slice(seed).unwrap();
10714        multikey::encode_ed25519_public(&kp.public_key()).unwrap()
10715    }
10716
10717    fn stray_did(seed: &[u8]) -> String {
10718        Ed25519KeyPair::from_seed_slice(seed).unwrap().did_key()
10719    }
10720
10721    fn robot_attributes() -> Value {
10722        json!({ "make": "Acme Robotics", "model": "AR-7", "serial": "SN-000123" })
10723    }
10724
10725    // The committed Python-minted robot chain must verify in Rust: recognized
10726    // manufacturer provenance plus hardware-rooting.
10727    #[test]
10728    fn verifies_python_robot_identity_interop_vector() {
10729        let v = load_vector();
10730        let root = v["trustedRoot"].as_str().unwrap();
10731        let r = verify_robot_identity_chain(
10732            &v["robotAuthorityIdentity"],
10733            &v["robotRecognizedIssuer"],
10734            &v["robotHardwareCredential"],
10735            root,
10736            &robot_pub(&v),
10737            Some(&v["rootOfTrust"]),
10738            NOW,
10739            30,
10740        );
10741        assert!(r.ok, "robot chain must verify: {:?}", r.reason);
10742        assert_eq!(
10743            Some(r.hardware_rooted),
10744            v["expected"]["hardwareRooted"].as_bool(),
10745            "the manufacturer pinned the hardware-root key"
10746        );
10747        assert_eq!(r.robot_did.as_deref(), v["expected"]["robotDid"].as_str());
10748        assert_eq!(
10749            r.issuer_did.as_deref(),
10750            v["expected"]["robotIssuerDid"].as_str()
10751        );
10752        assert_eq!(r.root_did.as_deref(), Some(root));
10753        assert_eq!(
10754            v["expected"]["verifyRobotIdentityChain"].as_bool(),
10755            Some(true)
10756        );
10757    }
10758
10759    // Adversarial: pinning a different root breaks the recognition anchor.
10760    #[test]
10761    fn wrong_pinned_root_rejected() {
10762        let v = load_vector();
10763        let other_root = stray_did(&[0x09; 32]);
10764        let r = verify_robot_identity_chain(
10765            &v["robotAuthorityIdentity"],
10766            &v["robotRecognizedIssuer"],
10767            &v["robotHardwareCredential"],
10768            &other_root,
10769            &robot_pub(&v),
10770            None,
10771            NOW,
10772            30,
10773        );
10774        assert!(!r.ok);
10775        assert_eq!(r.reason.as_deref(), Some("recognized_issuer_not_from_root"));
10776    }
10777
10778    // Adversarial: the manufacturer vouched a key that is not the robot's real
10779    // key. Provenance holds but the hardware key does not match.
10780    #[test]
10781    fn manufacturer_vouched_a_different_key() {
10782        let v = load_vector();
10783        let root = v["trustedRoot"].as_str().unwrap();
10784        let robot_did = v["expected"]["robotDid"].as_str().unwrap();
10785        let forged = build_robot_identity(
10786            &MANUFACTURER_SEED,
10787            robot_did,
10788            &stray_multikey(&[0x09; 32]),
10789            &robot_attributes(),
10790            VALID_SECONDS,
10791            VALID_FROM,
10792            CREATED,
10793            None,
10794            FORGED_ID,
10795            None,
10796        )
10797        .unwrap();
10798        let r = verify_robot_identity_chain(
10799            &forged,
10800            &v["robotRecognizedIssuer"],
10801            &v["robotHardwareCredential"],
10802            root,
10803            &robot_pub(&v),
10804            Some(&v["rootOfTrust"]),
10805            NOW,
10806            30,
10807        );
10808        assert!(!r.ok);
10809        assert_eq!(r.reason.as_deref(), Some("hardware_key_mismatch"));
10810    }
10811
10812    // Adversarial: an impostor key is presented for the hardware credential, so
10813    // the secure-element attestation no longer verifies.
10814    #[test]
10815    fn impostor_key_fails_hardware_root() {
10816        let v = load_vector();
10817        let root = v["trustedRoot"].as_str().unwrap();
10818        let impostor = Ed25519KeyPair::from_seed(&[0x09; 32]).public_key();
10819        let r = verify_robot_identity_chain(
10820            &v["robotAuthorityIdentity"],
10821            &v["robotRecognizedIssuer"],
10822            &v["robotHardwareCredential"],
10823            root,
10824            &impostor,
10825            Some(&v["rootOfTrust"]),
10826            NOW,
10827            30,
10828        );
10829        assert!(!r.ok);
10830        assert_eq!(r.reason.as_deref(), Some("hardware_root_invalid"));
10831    }
10832}
10833
10834#[cfg(test)]
10835mod port_hardening_tests {
10836    use super::*;
10837    use crate::keys::Ed25519KeyPair;
10838    #[allow(unused_imports)]
10839    use crate::robotics_verify::test_keys::{any_did, kd, TNOW};
10840    #[allow(unused_imports)]
10841    use crate::robotics_verify::Keys;
10842    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
10843    use base64::Engine;
10844
10845    // A missing or empty input list is malformed: the log check fails closed
10846    // instead of reporting "every input was logged".
10847    #[test]
10848    fn fusion_inputs_check_fails_closed_on_an_empty_list() {
10849        let empty = json!({"credentialSubject": {"inputFrameHashes": []}});
10850        assert!(!verify_fusion_inputs(&empty, &[]).ok);
10851        let missing = json!({"credentialSubject": {}});
10852        assert!(!verify_fusion_inputs(&missing, &[]).ok);
10853        let odd = json!({"credentialSubject": {"inputFrameHashes": ["ua", 5]}});
10854        let res = verify_fusion_inputs(&odd, &[json!({"frameHash": "ua"})]);
10855        assert!(!res.ok);
10856        assert_eq!(res.missing, vec!["5".to_string()]);
10857    }
10858
10859    fn load_vector() -> Value {
10860        let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
10861            .join("../../test-vectors/robotics/vector.json");
10862        serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
10863    }
10864
10865    fn jwk_pub(jwk: &Value) -> Vec<u8> {
10866        URL_SAFE_NO_PAD.decode(jwk["x"].as_str().unwrap()).unwrap()
10867    }
10868
10869    fn lease(valid_until: &str) -> (Value, Vec<u8>) {
10870        let seed = [51u8; 32];
10871        let kp = Ed25519KeyPair::from_seed(&seed);
10872        let cred = build_delegation_lease(
10873            &seed,
10874            &BuildDelegationLease {
10875                issuer_did: "did:web:robot.example.com".into(),
10876                robot_did: "did:web:robot.example.com".into(),
10877                lease_id: "lease-h".into(),
10878                scope: json!({"maxForceN": 80.0}),
10879                parent_lease_id: None,
10880                valid_from: "2026-01-01T00:00:00Z".into(),
10881                valid_until: valid_until.into(),
10882            },
10883        )
10884        .unwrap();
10885        (cred, kp.public_key().to_vec())
10886    }
10887
10888    // The core needs a clock: an empty or malformed `now` is an error, never a
10889    // skipped window check, in every verifier that checks a window.
10890    #[test]
10891    fn a_missing_or_malformed_clock_is_an_error() {
10892        let (cred, key) = lease("2026-01-01T01:00:00Z");
10893        for bad in ["", "null", "not-a-date", "2026-01-01"] {
10894            assert!(
10895                verify_delegation_lease(
10896                    &cred,
10897                    kd(&cred, &key),
10898                    "did:web:robot.example.com",
10899                    None,
10900                    None,
10901                    bad
10902                )
10903                .is_err(),
10904                "{bad:?}"
10905            );
10906            assert!(
10907                lease_permits(
10908                    &json!({}),
10909                    &PhysicalAction::default(),
10910                    Some(&cred),
10911                    kd(&cred, &key),
10912                    None,
10913                    bad
10914                )
10915                .is_err(),
10916                "{bad:?}"
10917            );
10918            assert!(verify_action_authorization(&[], "a", "r", &[], 1, None, bad).is_err());
10919            assert!(verify_access_grant(&cred, kd(&cred, &key), None, bad).is_err());
10920            assert!(authorize_access(
10921                &cred,
10922                &cred,
10923                kd(&cred, &key),
10924                kd(&cred, &key),
10925                RequestReplay::new(&mut HashSet::new()),
10926                bad
10927            )
10928            .is_err());
10929            assert!(verify_consent_token(&cred, kd(&cred, &key), "h", "r", bad).is_err());
10930            assert!(
10931                verify_consent_evidence(&cred, kd(&cred, &key), None, None, None, bad).is_err()
10932            );
10933        }
10934    }
10935
10936    // The shared vector's expired lease is refused at any time after its window,
10937    // and accepted inside it.
10938    #[test]
10939    fn expired_vector_lease_refused_after_its_window() {
10940        let v = load_vector();
10941        let key = jwk_pub(&v["robot_public_key_jwk"]);
10942        let cred = &v["delegation_lease_expired_credential"];
10943        assert!(verify_delegation_lease(
10944            cred,
10945            kd(cred, &key),
10946            "did:web:robot.example.com",
10947            None,
10948            None,
10949            "2026-01-01T00:30:00Z"
10950        )
10951        .unwrap()
10952        .is_some());
10953        assert!(verify_delegation_lease(
10954            cred,
10955            kd(cred, &key),
10956            "did:web:robot.example.com",
10957            None,
10958            None,
10959            "2026-06-01T00:00:00Z"
10960        )
10961        .unwrap()
10962        .is_none());
10963    }
10964
10965    // A validity bound that is present must be a string that parses.
10966    #[test]
10967    fn non_string_window_bounds_are_invalid() {
10968        for (key, bad) in [
10969            ("validFrom", json!(5)),
10970            ("validFrom", json!(null)),
10971            ("validUntil", json!(["2099-01-01T00:00:00Z"])),
10972            ("validUntil", json!(4102444800i64)),
10973            ("validUntil", json!("")),
10974        ] {
10975            let mut cred = json!({
10976                "validFrom": "2026-01-01T00:00:00Z",
10977                "validUntil": "2026-01-01T01:00:00Z"
10978            });
10979            cred[key] = bad.clone();
10980            assert!(
10981                rv::window_reason(&cred, Window::IfPresent, 1_767_225_660 * 1_000_000_000, 0)
10982                    .is_some(),
10983                "{key}={bad}"
10984            );
10985        }
10986    }
10987
10988    // One malformed approval from a listed approver is skipped; it does not fail
10989    // the whole authorization (shared vector).
10990    #[test]
10991    fn malformed_approvals_are_skipped_not_fatal() {
10992        let v = load_vector();
10993        let approvals = v["quorum_approvals_with_malformed"]
10994            .as_array()
10995            .unwrap()
10996            .clone();
10997        let keys: Vec<ApproverKey> = v["quorum_approver_keys"]
10998            .as_object()
10999            .unwrap()
11000            .iter()
11001            .map(|(did, jwk)| ApproverKey {
11002                did: did.clone(),
11003                public_key: jwk_pub(jwk),
11004            })
11005            .collect();
11006        let (ok, approvers) = verify_action_authorization(
11007            &approvals,
11008            v["quorum_action_id"].as_str().unwrap(),
11009            "did:web:robot.example.com",
11010            &keys,
11011            2,
11012            None,
11013            v["quorum_now"].as_str().unwrap(),
11014        )
11015        .unwrap();
11016        let expected = &v["expected_quorum_with_malformed"];
11017        assert_eq!(json!(ok), expected["authorized"]);
11018        assert_eq!(json!(approvers), expected["approvers"]);
11019    }
11020
11021    // A malformed scope field the action is checked against is a violation.
11022    #[test]
11023    fn malformed_scope_fields_are_violations() {
11024        let force = PhysicalAction {
11025            force_n: Some(5000.0),
11026            ..Default::default()
11027        };
11028        for cap in [json!("100"), json!(null), json!(true), json!([100])] {
11029            let r = check_physical_action(&json!({"maxForceN": cap}), &force);
11030            assert!(!r.ok, "maxForceN={cap}");
11031        }
11032        let speed = PhysicalAction {
11033            speed_mps: Some(9.0),
11034            near_humans: true,
11035            ..Default::default()
11036        };
11037        let r = check_physical_action(
11038            &json!({"maxSpeedMps": 1.0, "maxSpeedNearHumansMps": null}),
11039            &speed,
11040        );
11041        assert!(!r.ok);
11042        let zone = PhysicalAction {
11043            zone: Some("A".into()),
11044            ..Default::default()
11045        };
11046        for zones in [json!("A"), json!({"A": true}), json!(7)] {
11047            assert!(!check_physical_action(&json!({"allowedZones": zones}), &zone).ok);
11048        }
11049        let late = PhysicalAction {
11050            time_hm: Some("23:00".into()),
11051            ..Default::default()
11052        };
11053        for ws in [
11054            json!("08:00-18:00"),
11055            json!({"start": "08:00", "end": "18:00"}),
11056            json!(["08:00"]),
11057            json!([{"start": 800, "end": "18:00"}]),
11058        ] {
11059            assert!(
11060                !check_physical_action(&json!({"shiftWindows": ws}), &late).ok,
11061                "{ws}"
11062            );
11063        }
11064        // Native NaN in an action never passes a cap.
11065        let nan = PhysicalAction {
11066            force_n: Some(f64::NAN),
11067            ..Default::default()
11068        };
11069        assert!(!check_physical_action(&json!({"maxForceN": 10.0}), &nan).ok);
11070    }
11071
11072    #[test]
11073    fn malformed_child_fields_never_attenuate() {
11074        let parent = json!({
11075            "maxForceN": 80.0,
11076            "allowedZones": ["A", "B"],
11077            "shiftWindows": [{"start": "08:00", "end": "18:00"}]
11078        });
11079        let good = json!({
11080            "maxForceN": 50.0,
11081            "allowedZones": ["A"],
11082            "shiftWindows": [{"start": "09:00", "end": "17:00"}]
11083        });
11084        assert!(attenuates(&parent, &good));
11085        for (k, bad) in [
11086            ("shiftWindows", json!("00:00-23:59")),
11087            ("shiftWindows", json!({"start": "00:00"})),
11088            ("shiftWindows", json!([{"start": 0, "end": "23:59"}])),
11089            ("maxForceN", json!("50")),
11090            ("maxForceN", json!(null)),
11091            ("allowedZones", json!("A")),
11092            ("allowedZones", json!(["A", 7])),
11093            ("maxSpeedMps", json!("unlimited")),
11094        ] {
11095            let mut child = good.clone();
11096            child[k] = bad.clone();
11097            assert!(!attenuates(&parent, &child), "{k}={bad}");
11098        }
11099        // A malformed parent cap refuses rather than being skipped.
11100        assert!(!attenuates(&json!({"maxForceN": "80"}), &good));
11101    }
11102
11103    #[test]
11104    fn nan_wear_level_is_refused() {
11105        assert!(attenuate_for_wear(&json!({"maxForceN": 80.0}), f64::NAN).is_err());
11106        assert!(attenuate_for_wear(&json!({"maxForceN": 80.0}), 0.5).is_ok());
11107    }
11108}
11109
11110#[cfg(test)]
11111mod fork_check_tests {
11112    use super::*;
11113
11114    fn iso(offset: i64) -> String {
11115        // 2026-01-01T00:00:00Z plus offset seconds, offsets kept within one day.
11116        let s = offset.rem_euclid(86_400);
11117        let day = if offset < 0 { 31 } else { 1 };
11118        let month = if offset < 0 { "2025-12" } else { "2026-01" };
11119        format!(
11120            "{month}-{day:02}T{:02}:{:02}:{:02}Z",
11121            s / 3600,
11122            (s / 60) % 60,
11123            s % 60
11124        )
11125    }
11126
11127    fn emb(body: &str, start: i64, end: Option<i64>) -> Value {
11128        let mut e = json!({"credentialSubject": {"body": body}, "validFrom": iso(start)});
11129        if let Some(end) = end {
11130            e["validUntil"] = json!(iso(end));
11131        }
11132        e
11133    }
11134
11135    fn pairwise(windows: &[(String, i64, Option<i64>)]) -> (bool, Option<(String, String)>) {
11136        for (i, (bi, si, ei)) in windows.iter().enumerate() {
11137            for (bj, sj, ej) in &windows[i + 1..] {
11138                if bi == bj {
11139                    continue;
11140                }
11141                let a_before_b = ei.is_some_and(|e| e <= *sj);
11142                let b_before_a = ej.is_some_and(|e| e <= *si);
11143                if !(a_before_b || b_before_a) {
11144                    return (false, Some((bi.clone(), bj.clone())));
11145                }
11146            }
11147        }
11148        (true, None)
11149    }
11150
11151    fn run(list: &[Value]) -> (bool, Option<(String, String)>) {
11152        let (ok, conflict) = check_no_fork(list).unwrap();
11153        (ok, conflict.map(|c| (c.body_a, c.body_b)))
11154    }
11155
11156    #[test]
11157    fn fork_check_matches_the_shared_vector() {
11158        let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
11159            .join("../../test-vectors/robotics/fork_vector.json");
11160        let vector: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
11161        let cases = vector["cases"].as_array().unwrap();
11162        assert!(cases.len() > 40);
11163        for case in cases {
11164            let list = case["embodiments"].as_array().unwrap();
11165            let (ok, conflict) = check_no_fork(list).unwrap();
11166            let expected = &case["expected"];
11167            assert_eq!(ok, expected["ok"].as_bool().unwrap(), "{}", case["name"]);
11168            let got = conflict.map(|c| json!({"bodyA": c.body_a, "bodyB": c.body_b}));
11169            assert_eq!(got.as_ref(), expected.get("conflict"), "{}", case["name"]);
11170        }
11171    }
11172
11173    #[test]
11174    fn fork_check_matches_the_pairwise_scan_on_random_lists() {
11175        // A small fixed-seed generator keeps this free of extra dependencies.
11176        let mut state: u64 = 0x5eed_2026_1204;
11177        let mut next = |n: u64| {
11178            state = state
11179                .wrapping_mul(6364136223846793005)
11180                .wrapping_add(1442695040888963407);
11181            (state >> 33) % n
11182        };
11183        for _ in 0..3000 {
11184            let bodies = 1 + next(5);
11185            let len = next(15);
11186            let windows: Vec<(String, i64, Option<i64>)> = (0..len)
11187                .map(|_| {
11188                    let body = ((b'a' + next(bodies) as u8) as char).to_string();
11189                    let start = next(41) as i64;
11190                    let end = if next(100) < 15 {
11191                        None
11192                    } else {
11193                        Some(start + next(25) as i64 - 4)
11194                    };
11195                    (body, start, end)
11196                })
11197                .collect();
11198            let list: Vec<Value> = windows.iter().map(|(b, s, e)| emb(b, *s, *e)).collect();
11199            assert_eq!(run(&list), pairwise(&windows), "{windows:?}");
11200        }
11201    }
11202
11203    #[test]
11204    fn fork_check_handles_a_large_list_with_a_late_fork() {
11205        // Many overlapping windows on one body, then one other body overlapping
11206        // only the last of them: the pairwise scan needs about 2e8 steps here.
11207        let n = 20_000i64;
11208        let mut list: Vec<Value> = (0..n).map(|i| emb("body-a", i, Some(n + 5))).collect();
11209        list.push(emb("body-b", n + 4, Some(n + 6)));
11210        let began = std::time::Instant::now();
11211        assert_eq!(
11212            run(&list),
11213            (false, Some(("body-a".into(), "body-b".into())))
11214        );
11215        assert!(began.elapsed() < core::time::Duration::from_secs(10));
11216
11217        let clean: Vec<Value> = (0..n)
11218            .map(|i| {
11219                emb(
11220                    &format!("body-{i}"),
11221                    i,
11222                    if i + 1 < n { Some(i + 1) } else { None },
11223                )
11224            })
11225            .collect();
11226        let began = std::time::Instant::now();
11227        assert_eq!(run(&clean), (true, None));
11228        assert!(began.elapsed() < core::time::Duration::from_secs(10));
11229    }
11230
11231    #[test]
11232    fn fork_check_still_refuses_malformed_entries() {
11233        let good = emb("a", 0, Some(10));
11234        assert_eq!(
11235            run(&[good.clone(), json!({"validFrom": iso(0)})]),
11236            (false, None)
11237        );
11238        assert_eq!(
11239            run(&[good.clone(), json!({"credentialSubject": {"body": "b"}})]),
11240            (false, None)
11241        );
11242        let mut bad_end = emb("b", 0, None);
11243        bad_end["validUntil"] = json!("not a time");
11244        assert_eq!(run(&[good, bad_end]), (false, None));
11245    }
11246}