//! Robotics primitives (Phase 5), one byte-exact implementation in the core.
//!
//! Mirrors the Python `vouch.robotics` package and the TypeScript/Go SDKs so that
//! a robotics credential built in any language verifies in every other. Exposing
//! this module through the UniFFI and WASM wrappers gives Swift, Kotlin/JVM,
//! .NET, C/C++, and the browser the same robotics surface without re-deriving it.
//!
//! This file covers hardware-rooted robot identity (Phase 5.1). The remaining
//! capabilities (provenance, capability scope, handshake, black box, passport)
//! are added alongside it.
//!
//! Design: the core is hardware-agnostic and deterministic. A robot self-issues
//! its `RobotIdentityCredential` with its own Ed25519 key; the hardware root (a
//! TPM, secure element, or a software root in development) signs a binding over
//! the robot DID and key, supplied to [`mint_robot_identity`] as the attestation
//! bytes. Timestamps are caller-supplied, matching the rest of the core, so the
//! output is reproducible and the wrappers control the clock.
#[allow(unused_imports)]
use crate::prelude::*;
use serde_json::{json, Map, Value};
use crate::data_integrity::{self, BuildProofOptions};
use crate::error::{CoreError, Result};
use crate::keys;
use crate::pq::{MlDsa44KeyPair, MLDSA44_PUBLIC_LEN};
use crate::robotics_verify::{self as rv, Keys, VerifyOptions, Window};
use crate::root_of_trust::{self, ACTION_ISSUE_ROBOT_IDENTITY};
use crate::{hybrid, jcs, multikey};
use crate::collections::HashSet;
use aes_gcm::aead::{Aead, Payload};
use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine;
use sha2::{Digest, Sha256};
pub const VC_CONTEXT_V2: &str = "https://www.w3.org/ns/credentials/v2";
pub const VOUCH_CONTEXT_V1: &str = "https://vouch-protocol.com/contexts/v1";
pub const ROBOT_IDENTITY_TYPE: &str = "RobotIdentityCredential";
/// Multibase ('u') base64url-no-pad encoding, matching the Python/TS/Go `mb64`.
pub(crate) fn mb64(bytes: &[u8]) -> String {
format!("u{}", URL_SAFE_NO_PAD.encode(bytes))
}
/// Decode a multibase ('u') base64url-no-pad string.
pub(crate) fn unmb64(s: &str) -> Result<Vec<u8>> {
let body = s
.strip_prefix('u')
.ok_or_else(|| CoreError::Json("expected multibase 'u' prefix".into()))?;
URL_SAFE_NO_PAD
.decode(body)
.map_err(|e| CoreError::Json(format!("bad base64url: {e}")))
}
/// The canonical bytes a hardware root signs to bind a robot's identity key to
/// its hardware: JCS of `{"key": robot_key_multibase, "robotDid": robot_did}`.
pub fn robot_identity_binding(robot_did: &str, robot_key_multibase: &str) -> Vec<u8> {
jcs::canonicalize(&json!({
"key": robot_key_multibase,
"robotDid": robot_did,
}))
}
/// Parameters for [`mint_robot_identity`]. Timestamps are ISO-8601 strings the
/// caller supplies. `attestation` is the hardware root's signature over
/// [`robot_identity_binding`]; `root_public_multibase` is that root's public key.
#[derive(Debug, Clone)]
pub struct MintRobotIdentity {
pub robot_did: String,
pub make: String,
pub model: String,
pub serial: String,
pub owner: Option<String>,
pub root_kind: String,
pub root_public_multibase: String,
pub attestation: Vec<u8>,
/// Optional explicit lifecycle array; defaults to a single "commissioned" entry.
pub lifecycle: Option<Value>,
pub valid_from: String,
pub valid_until: Option<String>,
}
/// Mint a hardware-attested `RobotIdentityCredential`, signed by the robot's own
/// Ed25519 seed. The hardware-root attestation is embedded as
/// `credentialSubject.hardwareRoot.attestation`.
pub fn mint_robot_identity(robot_seed: &[u8], params: &MintRobotIdentity) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
let lifecycle = params
.lifecycle
.clone()
.unwrap_or_else(|| json!([{ "event": "commissioned", "timestamp": params.valid_from }]));
let mut subject = Map::new();
subject.insert("id".into(), json!(params.robot_did));
subject.insert("make".into(), json!(params.make));
subject.insert("model".into(), json!(params.model));
subject.insert("serial".into(), json!(params.serial));
subject.insert(
"hardwareRoot".into(),
json!({
"kind": params.root_kind,
"publicKeyMultibase": params.root_public_multibase,
"attestation": mb64(¶ms.attestation),
}),
);
subject.insert("lifecycle".into(), lifecycle);
if let Some(owner) = ¶ms.owner {
subject.insert("owner".into(), json!(owner));
}
let mut cred = Map::new();
cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
cred.insert(
"type".into(),
json!(["VerifiableCredential", ROBOT_IDENTITY_TYPE]),
);
cred.insert("issuer".into(), json!(params.robot_did));
cred.insert("validFrom".into(), json!(params.valid_from));
cred.insert("credentialSubject".into(), Value::Object(subject));
// After the subject, as the reference writes it (the shared vectors keep
// that member order; JCS signing does not depend on it).
if let Some(vu) = ¶ms.valid_until {
cred.insert("validUntil".into(), json!(vu));
}
let opts = BuildProofOptions::new(
format!("{}#key-1", params.robot_did),
params.valid_from.clone(),
);
data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
}
/// Verify a credential through the shared issuer-binding helper
/// ([`crate::robotics_verify`]) at `now_iso`. Errors only on a malformed
/// `now_iso`; any problem with the credential itself is `Ok(None)`.
pub(crate) fn bound(
credential: &Value,
keys: Keys<'_>,
expected_type: &str,
now_iso: &str,
window: Window,
) -> Result<Option<rv::Verified>> {
let now = rv::require_now(now_iso)?;
Ok(rv::verify_robotics_credential(
credential,
keys,
Some(expected_type),
now,
VerifyOptions::window(window),
)
.ok())
}
/// True when a self-attestation names its issuer as `credentialSubject.id`.
pub(crate) fn issuer_is_subject(v: &rv::Verified) -> bool {
v.subject.get("id").and_then(|x| x.as_str()) == Some(v.issuer.as_str())
}
/// Verify a `RobotIdentityCredential`: the credential proof bound to the robot
/// as issuer (which must also be `credentialSubject.id`), the validity window
/// at `now_iso` (validFrom required), AND the hardware-root attestation binding
/// the robot key to the hardware. `robot_keys` is a `{robot_did: key}` source
/// (or, for a did:key robot, the bare key). When `hardware_root_key` is given,
/// the credential's hardware-root key must be exactly that key. Returns the
/// credentialSubject on success, `None` if invalid.
pub fn verify_robot_identity(
credential: &Value,
robot_keys: Keys<'_>,
hardware_root_key: Option<&[u8]>,
now_iso: &str,
) -> Result<Option<Value>> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
let v = match bound(
credential,
robot_keys,
ROBOT_IDENTITY_TYPE,
now_iso,
Window::FromRequired,
)? {
Some(v) if issuer_is_subject(&v) => v,
_ => return Ok(None),
};
let robot_key =
match rv::resolve_issuer_key(&v.issuer, rv::pin_if_keyless(robot_keys, Some(&v.issuer))) {
Ok(k) => k,
Err(_) => return Ok(None),
};
let subject = match v.subject.as_object() {
Some(s) => s,
None => return Ok(None),
};
let hw = match subject.get("hardwareRoot").and_then(|h| h.as_object()) {
Some(h) => h,
None => return Ok(None),
};
let hw_mb = match hw.get("publicKeyMultibase").and_then(|v| v.as_str()) {
Some(s) => s,
None => return Ok(None),
};
let attestation_mb = match hw.get("attestation").and_then(|v| v.as_str()) {
Some(s) => s,
None => return Ok(None),
};
let decoded = match multikey::decode(hw_mb) {
Ok(d) if d.algorithm == "Ed25519" && d.raw_key.len() == 32 => d,
_ => return Ok(None),
};
if let Some(pin) = hardware_root_key {
if pin != decoded.raw_key.as_slice() {
return Ok(None);
}
}
let attestation = match unmb64(attestation_mb) {
Ok(a) => a,
Err(_) => return Ok(None),
};
let robot_key_mb = multikey::encode_ed25519_public(&robot_key)?;
let binding = robot_identity_binding(&v.issuer, &robot_key_mb);
if !matches!(
keys::verify(&decoded.raw_key, &binding, &attestation),
Ok(true)
) {
return Ok(None);
}
Ok(Some(v.subject))
}
// ---------------------------------------------------------------------------
// Root of Trust for robot identity (Phase 5.1, authority binding)
// ---------------------------------------------------------------------------
//
// Byte-exact port of the Python reference `vouch/robotics/root_identity.py`.
//
// The Root of Trust for Machine Identity lets one pinned Vouch root recognize
// issuers, and a recognized issuer bind a subject DID to attributes, verified
// offline against that one pinned root. This extends it to robots. A recognized
// manufacturer (an issuer the root granted the `issueRobotIdentity` action)
// issues an identity that binds a robot's DID and its hardware-rooted key to
// attributes such as make, model, serial, and owner. The robot separately holds
// a hardware-attested `RobotIdentityCredential` proving its key is bound to a
// secure element.
//
// [`verify_robot_identity_chain`] closes the loop: from one pinned root a
// verifier confirms both that the robot is a legitimate robot from a recognized
// manufacturer (the authority chain via [`root_of_trust::verify_identity_chain`])
// and that the key the manufacturer vouched for is genuinely hardware-rooted (the
// secure-element attestation via [`verify_robot_identity`]), and that the two
// name the same robot and the same key. It follows the anchor-once model and the
// reason-code style of the underlying root_of_trust.
/// Outcome of [`verify_robot_identity_chain`].
///
/// `ok` is true only if the authority chain verified against the pinned root AND
/// the robot's own credential names the same robot and the vouched key.
/// `hardware_rooted` is true only when the manufacturer also bound the
/// hardware-root key and the attestation was made by exactly that key. On failure `reason`
/// carries a structured code matching the Python reference exactly.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RobotIdentityChainResult {
pub ok: bool,
pub reason: Option<String>,
pub robot_did: Option<String>,
pub issuer_did: Option<String>,
pub root_did: Option<String>,
pub attributes: Option<Value>,
pub hardware_rooted: bool,
}
impl RobotIdentityChainResult {
/// A failure result carrying the reason code and the pinned root that was in
/// force when the check failed.
fn fail(reason: impl Into<String>, root_did: &str) -> Self {
Self {
ok: false,
reason: Some(reason.into()),
robot_did: None,
issuer_did: None,
root_did: Some(root_did.to_string()),
attributes: None,
hardware_rooted: false,
}
}
}
/// Issue an authority robot identity: a recognized manufacturer binds `robot_did`,
/// its hardware-rooted key (`hardware_key_multibase`, the robot's Ed25519 key as a
/// multikey), and identity `attributes` (make, model, serial, owner). The
/// manufacturer (derived from `issuer_seed`) must be a recognized issuer for the
/// `issueRobotIdentity` action.
///
/// The credential is an `AgentIdentityCredential` so the shared identity-chain
/// verification applies, with a `kind` of "robot" and the hardware key carried in
/// the bound identity attributes.
///
/// `hardware_root_key_multibase` is the public key of the robot's secure element
/// as the manufacturer recorded it. Bound as `hardwareRootKey`, it lets a
/// verifier tell the robot's hardware attestation comes from that exact
/// hardware; without it the chain verifies but is never hardware-rooted.
#[allow(clippy::too_many_arguments)]
pub fn build_robot_identity(
issuer_seed: &[u8],
robot_did: &str,
hardware_key_multibase: &str,
attributes: &Value,
valid_seconds: i64,
valid_from: &str,
created: &str,
credential_status: Option<Value>,
credential_id: &str,
hardware_root_key_multibase: Option<&str>,
) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); attributes; drop credential_status);
if robot_did.is_empty() {
return Err(CoreError::Json("robot_did is required".into()));
}
if hardware_key_multibase.is_empty() {
return Err(CoreError::Json("hardware_key_multibase is required".into()));
}
let bound = match attributes.as_object() {
Some(o) if !o.is_empty() => {
let mut m = o.clone();
m.insert("kind".into(), json!("robot"));
m.insert("hardwareKey".into(), json!(hardware_key_multibase));
if let Some(root) = hardware_root_key_multibase {
if root.is_empty() {
return Err(CoreError::Json(
"hardware_root_key_multibase must be a multikey string".into(),
));
}
m.insert("hardwareRootKey".into(), json!(root));
}
Value::Object(m)
}
_ => {
return Err(CoreError::Json(
"attributes must be a non-empty object".into(),
))
}
};
root_of_trust::build_agent_identity(
issuer_seed,
robot_did,
&bound,
valid_seconds,
valid_from,
created,
credential_status,
credential_id,
)
}
/// Verify a robot's identity against a single pinned Vouch root, confirming both
/// provenance and hardware-rooting.
///
/// From `trusted_root`, the pinned root DID:
///
/// 1. The authority chain: the recognized manufacturer must be recognized by
/// the pinned root for the `issueRobotIdentity` action, and the authority
/// identity must be signed by that manufacturer (shared identity-chain verify).
/// 2. The vouched key: the authority identity must carry a hardware key.
/// 3. The robot credential: the robot's own `RobotIdentityCredential` must
/// verify under the key the manufacturer vouched for, name the same robot,
/// and carry a valid secure-element attestation.
/// 4. The hardware root: when the manufacturer bound a `hardwareRootKey`, the
/// attestation's hardware key must be exactly that key (else
/// `hardware_root_mismatch`), and only then is `hardware_rooted` true.
///
/// `robot_public_key` is the robot's raw 32-byte Ed25519 public key. `now_iso` is
/// the current instant used for the temporal window; `clock_skew_seconds` is the
/// allowed drift. Reason codes on failure match the Python reference exactly.
#[allow(clippy::too_many_arguments)]
pub fn verify_robot_identity_chain(
authority_identity: &Value,
recognized_issuer_credential: &Value,
robot_hardware_credential: &Value,
trusted_root: &str,
robot_public_key: &[u8],
root_credential: Option<&Value>,
now_iso: &str,
clock_skew_seconds: i64,
) -> RobotIdentityChainResult {
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);
let chain = root_of_trust::verify_identity_chain(
authority_identity,
recognized_issuer_credential,
trusted_root,
root_credential,
None,
ACTION_ISSUE_ROBOT_IDENTITY,
now_iso,
clock_skew_seconds,
);
robot_identity_chain_tail(
chain,
robot_hardware_credential,
trusted_root,
robot_public_key,
now_iso,
)
}
/// The robot half of [`verify_robot_identity_chain`], after the authority
/// chain (`chain`, walked for `issueRobotIdentity`): the vouched hardware key,
/// the robot's own credential under `robot_public_key`, its subject and key,
/// and the hardware root.
pub fn robot_identity_chain_tail(
chain: root_of_trust::IdentityChainResult,
robot_hardware_credential: &Value,
trusted_root: &str,
robot_public_key: &[u8],
now_iso: &str,
) -> RobotIdentityChainResult {
// `chain` is the caller's and is dropped here: a deep `attributes` is
// taken apart without recursion before the refusal.
if crate::nesting::too_deep_here(robot_hardware_credential)
|| crate::nesting::too_deep_here(&chain.attributes)
{
if let Some(attributes) = chain.attributes {
crate::nesting::drop_flat(attributes);
}
return RobotIdentityChainResult::fail(crate::nesting::TOO_DEEP, trusted_root);
}
if !chain.ok {
return RobotIdentityChainResult {
ok: false,
reason: chain.reason,
robot_did: None,
issuer_did: None,
root_did: Some(trusted_root.to_string()),
attributes: None,
hardware_rooted: false,
};
}
let attributes = match &chain.attributes {
Some(v @ Value::Object(_)) => v.clone(),
_ => json!({}),
};
let hardware_key = match attributes.get("hardwareKey").and_then(|v| v.as_str()) {
Some(s) if !s.is_empty() => s.to_string(),
_ => return RobotIdentityChainResult::fail("identity_no_hardware_key", trusted_root),
};
// The robot's own credential must verify under the supplied key, accepted
// for whatever DID the credential names; the next two checks pin that DID
// to the manufacturer's subject and the key to the vouched key.
let any_did = |_: &str| Some(robot_public_key.to_vec());
let hw_subject = match verify_robot_identity(
robot_hardware_credential,
Keys::Resolver(&any_did),
None,
now_iso,
) {
Ok(Some(s)) => s,
_ => return RobotIdentityChainResult::fail("hardware_root_invalid", trusted_root),
};
if hw_subject.get("id").and_then(|v| v.as_str()) != chain.agent_did.as_deref() {
return RobotIdentityChainResult::fail("hardware_subject_mismatch", trusted_root);
}
let robot_key_mb = match multikey::encode_ed25519_public(robot_public_key) {
Ok(mb) => mb,
Err(_) => return RobotIdentityChainResult::fail("hardware_key_unresolvable", trusted_root),
};
if robot_key_mb != hardware_key {
return RobotIdentityChainResult::fail("hardware_key_mismatch", trusted_root);
}
// Hardware-rooted only when the manufacturer bound the hardware-root key and
// the robot's attestation was made by exactly that key.
let mut hardware_rooted = false;
if let Some(pinned) = attributes.get("hardwareRootKey") {
let claimed = hw_subject
.get("hardwareRoot")
.and_then(|h| h.get("publicKeyMultibase"))
.and_then(|v| v.as_str());
if pinned.as_str().is_none() || claimed != pinned.as_str() {
return RobotIdentityChainResult::fail("hardware_root_mismatch", trusted_root);
}
hardware_rooted = true;
}
RobotIdentityChainResult {
ok: true,
reason: None,
robot_did: chain.agent_did,
issuer_did: chain.issuer_did,
root_did: Some(trusted_root.to_string()),
attributes: Some(attributes),
hardware_rooted,
}
}
// ---------------------------------------------------------------------------
// Model and config provenance (Phase 5.2)
// ---------------------------------------------------------------------------
pub const MODEL_PROVENANCE_TYPE: &str = "ModelProvenanceAttestation";
/// Multibase SHA-256 of the JCS-canonical config object. Python, TypeScript, Go,
/// and Rust all canonicalize identically, so the digest is the same byte string
/// in every language.
pub fn config_hash(config: &Value) -> String {
let digest = Sha256::digest(jcs::canonicalize(config));
mb64(&digest)
}
/// Parameters for [`build_provenance_attestation`]. The issuer is the signer (the
/// robot itself or an authority); `robot_did` names the robot the attestation is
/// about.
#[derive(Debug, Clone)]
pub struct BuildProvenance {
pub issuer_did: String,
pub robot_did: String,
pub model_name: String,
pub weights_hash: String,
pub safety_policy: String,
pub config: Option<Value>,
pub version: Option<String>,
pub supersedes: Option<String>,
pub valid_from: String,
pub valid_until: Option<String>,
}
/// Build a signed `ModelProvenanceAttestation` for the software on a robot.
pub fn build_provenance_attestation(signer_seed: &[u8], params: &BuildProvenance) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
let mut vla = Map::new();
vla.insert("modelName".into(), json!(params.model_name));
vla.insert("weightsHash".into(), json!(params.weights_hash));
vla.insert("safetyPolicy".into(), json!(params.safety_policy));
if let Some(v) = ¶ms.version {
vla.insert("version".into(), json!(v));
}
if let Some(cfg) = ¶ms.config {
vla.insert("configHash".into(), json!(config_hash(cfg)));
}
let mut subject = Map::new();
subject.insert("id".into(), json!(params.robot_did));
subject.insert("vla".into(), Value::Object(vla));
if let Some(s) = ¶ms.supersedes {
subject.insert("supersedes".into(), json!(s));
}
let mut cred = Map::new();
cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
cred.insert(
"type".into(),
json!(["VerifiableCredential", MODEL_PROVENANCE_TYPE]),
);
cred.insert("issuer".into(), json!(params.issuer_did));
cred.insert("validFrom".into(), json!(params.valid_from));
if let Some(vu) = ¶ms.valid_until {
cred.insert("validUntil".into(), json!(vu));
}
cred.insert("credentialSubject".into(), Value::Object(subject));
let opts = BuildProofOptions::new(
format!("{}#key-1", params.issuer_did),
params.valid_from.clone(),
);
data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
}
/// Verify a `ModelProvenanceAttestation`. When `config` is supplied, also check
/// the recorded configHash reproduces. Returns the subject on success, `None`
/// otherwise.
pub fn verify_provenance_attestation(
attestation: &Value,
keys: Keys<'_>,
config: Option<&Value>,
now_iso: &str,
) -> Result<Option<Value>> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); attestation, config);
let v = match bound(
attestation,
keys,
MODEL_PROVENANCE_TYPE,
now_iso,
Window::FromRequired,
)? {
Some(v) => v,
None => return Ok(None),
};
if let Some(cfg) = config {
let want = config_hash(cfg);
let got = v
.subject
.get("vla")
.and_then(|v| v.as_object())
.and_then(|v| v.get("configHash"))
.and_then(|v| v.as_str());
if got != Some(want.as_str()) {
return Ok(None);
}
}
Ok(Some(v.subject))
}
/// The reference a superseding attestation uses: multibase SHA-256 of the JCS
/// form of the whole signed attestation (proof included).
pub fn provenance_attestation_id(attestation: &Value) -> String {
mb64(&Sha256::digest(jcs::canonicalize(attestation)))
}
/// Verify an ordered OTA history of provenance attestations for `robot_did`:
/// every attestation verifies and is about `robot_did`; each one after the
/// first names the previous by [`provenance_attestation_id`] as `supersedes`
/// and is dated no earlier. Each earlier attestation must still have been valid
/// when the next was made, and the last at `now_iso`. Returns the latest
/// subject on success.
pub fn verify_provenance_chain(
attestations: &[Value],
keys: Keys<'_>,
robot_did: &str,
now_iso: &str,
) -> Result<Option<Value>> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); attestations);
rv::require_now(now_iso)?;
if attestations.is_empty() || robot_did.is_empty() {
return Ok(None);
}
let mut prev: Option<&Value> = None;
let mut latest = None;
for (i, att) in attestations.iter().enumerate() {
let at: String = match attestations.get(i + 1) {
Some(next) => match next.get("validFrom").and_then(|v| v.as_str()) {
Some(t) if rv::time_ns(next.get("validFrom")).is_some() => t.to_string(),
_ => return Ok(None),
},
None => now_iso.to_string(),
};
let subject = match verify_provenance_attestation(att, keys, None, &at)? {
Some(s) if s.get("id").and_then(|v| v.as_str()) == Some(robot_did) => s,
_ => return Ok(None),
};
if let Some(p) = prev {
if subject.get("supersedes").and_then(|v| v.as_str())
!= Some(provenance_attestation_id(p).as_str())
{
return Ok(None);
}
if rv::time_ns(att.get("validFrom")) < rv::time_ns(p.get("validFrom")) {
return Ok(None);
}
}
prev = Some(att);
latest = Some(subject);
}
Ok(latest)
}
// ---------------------------------------------------------------------------
// Physical capability scope (Phase 5.3)
// ---------------------------------------------------------------------------
pub const PHYSICAL_SCOPE_TYPE: &str = "PhysicalCapabilityScope";
/// An allowed time-of-day window, "HH:MM" start and end.
#[derive(Debug, Clone)]
pub struct ShiftWindow {
pub start: String,
pub end: String,
}
/// A proposed actuation to check against a scope. `None` numerics mean "not
/// specified" (a meaningful zero is still `Some(0.0)`).
#[derive(Debug, Clone, Default)]
pub struct PhysicalAction {
pub force_n: Option<f64>,
pub speed_mps: Option<f64>,
pub near_humans: bool,
pub zone: Option<String>,
pub time_hm: Option<String>,
}
/// The outcome of [`check_physical_action`].
#[derive(Debug, Clone)]
pub struct CheckResult {
pub ok: bool,
pub reasons: Vec<String>,
}
/// Parameters for [`build_physical_scope_credential`]. The issuer is the signer
/// (a fleet authority); `subject_did` is the robot the scope is granted to.
#[derive(Debug, Clone, Default)]
pub struct BuildPhysicalScope {
pub issuer_did: String,
pub subject_did: String,
pub max_force_n: Option<f64>,
pub max_speed_mps: Option<f64>,
pub max_speed_near_humans_mps: Option<f64>,
pub allowed_zones: Option<Vec<String>>,
pub shift_windows: Option<Vec<ShiftWindow>>,
pub valid_from: String,
pub valid_until: Option<String>,
}
/// Build a signed `PhysicalCapabilityScope` credential.
pub fn build_physical_scope_credential(
signer_seed: &[u8],
params: &BuildPhysicalScope,
) -> Result<Value> {
let mut scope = Map::new();
if let Some(v) = params.max_force_n {
scope.insert("maxForceN".into(), json!(v));
}
if let Some(v) = params.max_speed_mps {
scope.insert("maxSpeedMps".into(), json!(v));
}
if let Some(v) = params.max_speed_near_humans_mps {
scope.insert("maxSpeedNearHumansMps".into(), json!(v));
}
if let Some(zones) = ¶ms.allowed_zones {
scope.insert("allowedZones".into(), json!(zones));
}
if let Some(ws) = ¶ms.shift_windows {
let arr: Vec<Value> = ws
.iter()
.map(|w| json!({"start": w.start, "end": w.end}))
.collect();
scope.insert("shiftWindows".into(), Value::Array(arr));
}
let mut subject = Map::new();
subject.insert("id".into(), json!(params.subject_did));
subject.insert("physicalScope".into(), Value::Object(scope));
let mut cred = Map::new();
cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
cred.insert(
"type".into(),
json!(["VerifiableCredential", PHYSICAL_SCOPE_TYPE]),
);
cred.insert("issuer".into(), json!(params.issuer_did));
cred.insert("validFrom".into(), json!(params.valid_from));
if let Some(vu) = ¶ms.valid_until {
cred.insert("validUntil".into(), json!(vu));
}
cred.insert("credentialSubject".into(), Value::Object(subject));
let opts = BuildProofOptions::new(
format!("{}#key-1", params.issuer_did),
params.valid_from.clone(),
);
data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
}
/// The numeric caps a physical scope may set.
pub const CAP_KEYS: [&str; 3] = ["maxForceN", "maxSpeedMps", "maxSpeedNearHumansMps"];
/// Every dimension a physical scope may set.
pub const SCOPE_KEYS: [&str; 5] = [
"maxForceN",
"maxSpeedMps",
"maxSpeedNearHumansMps",
"allowedZones",
"shiftWindows",
];
/// Minutes since midnight for a strict `HH:MM` string (00:00-23:59), else `None`.
pub fn parse_hm(value: &str) -> Option<u32> {
let b = value.as_bytes();
if b.len() != 5
|| b[2] != b':'
|| !b
.iter()
.enumerate()
.all(|(i, c)| i == 2 || c.is_ascii_digit())
{
return None;
}
let h = u32::from(b[0] - b'0') * 10 + u32::from(b[1] - b'0');
let m = u32::from(b[3] - b'0') * 10 + u32::from(b[4] - b'0');
if h > 23 || m > 59 {
return None;
}
Some(h * 60 + m)
}
/// A usable physical cap: a finite, non-negative JSON number (never a boolean).
pub fn valid_cap(v: &Value) -> bool {
v.is_number() && v.as_f64().is_some_and(|n| n.is_finite() && n >= 0.0)
}
/// `(start, end)` minutes of a `{"start", "end"}` window with start <= end.
pub fn parse_window(w: &Value) -> Option<(u32, u32)> {
let o = w.as_object()?;
let start = parse_hm(o.get("start")?.as_str()?)?;
let end = parse_hm(o.get("end")?.as_str()?)?;
(start <= end).then_some((start, end))
}
/// Every window of a list, or `None` if the list or any window is malformed.
pub fn parse_windows(v: &Value) -> Option<Vec<(u32, u32)>> {
v.as_array()?.iter().map(parse_window).collect()
}
/// The zone ids of a list of strings, or `None` if malformed.
pub fn parse_zones(v: &Value) -> Option<Vec<&str>> {
v.as_array()?.iter().map(|z| z.as_str()).collect()
}
/// Reasons the scope itself cannot be read; empty when every set dimension is
/// well-formed.
pub fn scope_problems(scope: &Value) -> Vec<String> {
crate::nesting::deep_guard!(vec![crate::nesting::TOO_DEEP.into()]; scope);
let o = match scope.as_object() {
Some(o) => o,
None => return vec!["scope_malformed: not an object".into()],
};
let mut problems = Vec::new();
for key in CAP_KEYS {
if o.get(key).is_some_and(|v| !valid_cap(v)) {
problems.push(format!(
"scope_malformed: {key} is not a finite non-negative number"
));
}
}
if o.get("allowedZones")
.is_some_and(|v| parse_zones(v).is_none())
{
problems.push("scope_malformed: allowedZones is not a list of strings".into());
}
if o.get("shiftWindows")
.is_some_and(|v| parse_windows(v).is_none())
{
problems.push("scope_malformed: shiftWindows is not a list of HH:MM windows".into());
}
problems
}
/// Verify a `PhysicalCapabilityScope` credential and return its physicalScope:
/// the proof bound to the issuer, the window at `now_iso` (validFrom
/// required), a well-formed scope with no unknown dimension (a misspelt cap
/// would otherwise limit nothing), and (when given) the subject `subject_did`.
pub fn verify_physical_scope_credential(
credential: &Value,
keys: Keys<'_>,
subject_did: Option<&str>,
now_iso: &str,
) -> Result<Option<Value>> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
let v = match bound(
credential,
keys,
PHYSICAL_SCOPE_TYPE,
now_iso,
Window::FromRequired,
)? {
Some(v) => v,
None => return Ok(None),
};
if subject_did.is_some_and(|d| v.subject.get("id").and_then(|x| x.as_str()) != Some(d)) {
return Ok(None);
}
let scope = match v.subject.get("physicalScope") {
Some(sc @ Value::Object(o)) if o.keys().all(|k| SCOPE_KEYS.contains(&k.as_str())) => sc,
_ => return Ok(None),
};
if !scope_problems(scope).is_empty() {
return Ok(None);
}
Ok(Some(scope.clone()))
}
/// Check a proposed physical action against a physical scope object, returning
/// ok plus a reason for each violation. A scope dimension that is set but
/// malformed, and an action value that is not a finite non-negative number or
/// not a strict `HH:MM`, are violations. An empty zone or shift-window list
/// allows nothing. Near humans, the speed cap is the lower of `maxSpeedMps`
/// and `maxSpeedNearHumansMps`.
pub fn check_physical_action(scope: &Value, action: &PhysicalAction) -> CheckResult {
crate::nesting::deep_guard!(CheckResult { ok: false, reasons: vec![crate::nesting::TOO_DEEP.into()] }; scope);
let mut reasons = scope_problems(scope);
if !reasons.is_empty() {
return CheckResult { ok: false, reasons };
}
let o = scope
.as_object()
.expect("scope_problems checked it is an object");
for (name, value) in [("force_n", action.force_n), ("speed_mps", action.speed_mps)] {
if let Some(v) = value {
if !v.is_finite() || v < 0.0 {
reasons.push(format!(
"action_malformed: {name} is not a finite non-negative number"
));
}
}
}
if !reasons.is_empty() {
return CheckResult { ok: false, reasons };
}
let cap = |k: &str| o.get(k).and_then(|v| v.as_f64());
if let (Some(force), Some(c)) = (action.force_n, cap("maxForceN")) {
if force > c {
reasons.push(format!("force_exceeded: {force}N > {c}N"));
}
}
if let Some(speed) = action.speed_mps {
let mut c = cap("maxSpeedMps");
if action.near_humans {
if let Some(near) = cap("maxSpeedNearHumansMps") {
c = Some(c.map_or(near, |g| g.min(near)));
}
}
if let Some(c) = c {
if speed > c {
let label = if action.near_humans {
"near_humans "
} else {
""
};
reasons.push(format!("{label}speed_exceeded: {speed} m/s > {c} m/s"));
}
}
}
if let (Some(zone), Some(zones)) = (&action.zone, o.get("allowedZones").and_then(parse_zones)) {
if !zones.contains(&zone.as_str()) {
reasons.push(format!("zone_not_allowed: {zone}"));
}
}
if let (Some(hm), Some(ws)) = (&action.time_hm, o.get("shiftWindows")) {
match parse_hm(hm) {
None => reasons.push(format!("action_malformed: time_hm {hm:?} is not HH:MM")),
Some(t) => {
let windows = parse_windows(ws).unwrap_or_default();
if !windows.iter().any(|(s, e)| *s <= t && t <= *e) {
reasons.push(format!("outside_shift_window: {hm}"));
}
}
}
}
CheckResult {
ok: reasons.is_empty(),
reasons,
}
}
/// Report whether `child` is a valid attenuation of `parent`: never broader on
/// any physical dimension. Both scopes must be well-formed; for every dimension
/// the parent sets, the child must set it too and be no broader (a cap no
/// higher, a NON-EMPTY subset of zones, a NON-EMPTY list of windows each inside
/// some parent window). Leaving a dimension out, or an empty list, is never an
/// attenuation of a parent that limits it.
pub fn attenuates(parent: &Value, child: &Value) -> bool {
crate::nesting::deep_guard!(false; parent, child);
if !scope_problems(parent).is_empty() || !scope_problems(child).is_empty() {
return false;
}
let (p, c) = match (parent.as_object(), child.as_object()) {
(Some(p), Some(c)) => (p, c),
_ => return false,
};
for key in CAP_KEYS {
if let Some(pv) = p.get(key).and_then(|v| v.as_f64()) {
match c.get(key).and_then(|v| v.as_f64()) {
Some(cv) if cv <= pv => {}
_ => return false,
}
}
}
if let Some(pz) = p.get("allowedZones").and_then(parse_zones) {
match c.get("allowedZones").and_then(parse_zones) {
Some(cz) if !cz.is_empty() && cz.iter().all(|z| pz.contains(z)) => {}
_ => return false,
}
}
if let Some(pw) = p.get("shiftWindows").and_then(parse_windows) {
match c.get("shiftWindows").and_then(parse_windows) {
Some(cw) if !cw.is_empty() => {
for (cs, ce) in cw {
if !pw.iter().any(|(ps, pe)| *ps <= cs && ce <= *pe) {
return false;
}
}
}
_ => return false,
}
}
true
}
// ---------------------------------------------------------------------------
// Robot-to-robot trust handshake (Phase 5.4)
// ---------------------------------------------------------------------------
pub const HELLO: &str = "handshake_hello";
pub const ACCEPT: &str = "handshake_accept";
pub const CONFIRM: &str = "handshake_confirm";
/// Decides whether a peer DID is trusted: its did:web or did:webvh name must
/// be allowed, or `accept_unknown` is set. The name is the domain plus any
/// path, colon-joined (`did:web:a.example:agents` is `a.example:agents`), so a
/// bare-domain entry trusts the bare domain only and a path is trusted only
/// when the policy names it.
#[derive(Debug, Clone, Default)]
pub struct TrustPolicy {
pub trusted_domains: HashSet<String>,
pub accept_unknown: bool,
}
impl TrustPolicy {
pub fn new(domains: impl IntoIterator<Item = String>, accept_unknown: bool) -> Self {
Self {
trusted_domains: domains.into_iter().collect(),
accept_unknown,
}
}
pub fn is_trusted(&self, did: &str) -> bool {
if self.accept_unknown {
return true;
}
match did_web_domain(did) {
Some(d) => self.trusted_domains.contains(&d),
None => false,
}
}
}
/// The agreed cooperation session after a successful handshake.
#[derive(Debug, Clone)]
pub struct BoundedSession {
pub session_id: String,
pub initiator: String,
pub responder: String,
pub scope: Vec<String>,
pub nonce: String,
pub valid_until: Option<String>,
}
/// The name a did:web or did:webvh DID is trusted under, or None: the domain,
/// then each path segment after a colon. Each prefix keeps its trailing colon,
/// so a did:webvh DID never reads as did:web. A did:webvh DID is parsed
/// strictly ([`crate::did_webvh::parse`]) and gives its host (percent-decoded
/// and lower-cased) and its percent-decoded path; one that does not parse has
/// no name. A did:web with an empty segment has no name.
fn did_web_domain(did: &str) -> Option<String> {
if crate::did_webvh::is_did_webvh(did) {
return crate::did_webvh::parse(did).ok().map(|parsed| {
core::iter::once(parsed.host)
.chain(parsed.path)
.collect::<Vec<_>>()
.join(":")
});
}
let rest = did.strip_prefix("did:web:")?;
if rest.split(':').any(str::is_empty) {
None
} else {
Some(rest.to_string())
}
}
/// Parameters for [`build_hello`]. `nonce` and `issued_at` are caller-supplied so
/// the core stays deterministic; the wrapper SDKs generate them.
#[derive(Debug, Clone, Default)]
pub struct BuildHello {
pub from_did: String,
pub proposed_scope: Vec<String>,
pub nonce: String,
pub peer_did: Option<String>,
pub issued_at: String,
}
/// Open the handshake (initiator A): a proposed scope and a fresh nonce, signed.
pub fn build_hello(signer_seed: &[u8], params: &BuildHello) -> Result<Value> {
let mut hello = Map::new();
hello.insert("type".into(), json!(HELLO));
hello.insert("from".into(), json!(params.from_did));
hello.insert(
"to".into(),
match ¶ms.peer_did {
Some(p) => json!(p),
None => Value::Null,
},
);
hello.insert("nonce".into(), json!(params.nonce));
hello.insert("proposedScope".into(), json!(params.proposed_scope));
hello.insert("issuedAt".into(), json!(params.issued_at));
let opts = BuildProofOptions::new(format!("{}#key-1", params.from_did), ¶ms.issued_at);
data_integrity::sign(&Value::Object(hello), signer_seed, &opts)
}
/// The default clock skew for handshake freshness checks (seconds).
pub const DEFAULT_HANDSHAKE_SKEW_SECONDS: i64 = 30;
/// The oldest HELLO a responder answers (seconds).
pub const DEFAULT_MAX_HELLO_AGE_SECONDS: i64 = 300;
/// The longest session an ACCEPT may grant (validUntil - issuedAt).
pub const DEFAULT_MAX_SESSION_SECONDS: i64 = 3600;
/// The message is `expected_type` and its proof is bound to the DID in `from`
/// (assertionMethod, verification method of that DID, key resolved from it).
fn handshake_message_ok(obj: &Value, keys: Keys<'_>, expected_type: &str) -> bool {
if obj.get("type").and_then(|v| v.as_str()) != Some(expected_type) {
return false;
}
if rv::input_too_large(obj, rv::MAX_CREDENTIAL_BYTES).is_some() {
return false;
}
let sender = match obj.get("from").and_then(|v| v.as_str()) {
Some(s) if s.starts_with("did:") => s,
_ => return false,
};
if rv::proof_unbound_reason(obj.get("proof").unwrap_or(&Value::Null), sender).is_some() {
return false;
}
// The handshake binds each message to the DID in `from`; whether that
// party is trusted is the policy's decision (or the caller's own HELLO or
// ACCEPT pins it), so `from` is the pinned issuer here.
let key = match rv::resolve_issuer_key(sender, rv::pin_if_keyless(keys, Some(sender))) {
Ok(k) => k,
Err(_) => return false,
};
matches!(data_integrity::verify_proof(obj, &key), Ok(true))
}
fn scope_list(v: Option<&Value>) -> Option<Vec<String>> {
v?.as_array()?
.iter()
.map(|x| x.as_str().map(String::from))
.collect()
}
fn issued_recently(v: Option<&Value>, now_ns: i128, skew: i64, max_age: i64) -> bool {
let issued = match rv::time_ns(v) {
Some(t) => t,
None => return false,
};
let second: i128 = 1_000_000_000;
now_ns - i128::from(max_age.saturating_add(skew)) * second <= issued
&& issued <= now_ns + i128::from(skew) * second
}
impl BoundedSession {
/// True while `now_iso` is at or before the session's validUntil (required).
pub fn is_current(&self, now_iso: &str) -> bool {
match (
self.valid_until
.as_deref()
.and_then(|u| crate::time::parse_protocol_time_ns(u).ok()),
crate::time::parse_protocol_time_ns(now_iso).ok(),
) {
(Some(u), Some(n)) => n <= u,
_ => false,
}
}
}
/// Parameters for [`build_accept`]. `issued_at` is the responder's clock (it
/// also judges the HELLO's age); `valid_until` bounds the session.
#[derive(Debug, Clone, Default)]
pub struct BuildAccept {
pub from_did: String,
pub offered_scope: Vec<String>,
pub session_id: String,
pub valid_until: String,
pub created: String,
}
/// Verify A's HELLO, check A's domain, intersect the scope, and sign an
/// acceptance (responder B). The HELLO's proof must be bound to its `from` DID
/// (`hello_keys` is a `{did: key}` source, or the bare key of a did:key
/// initiator); it must be addressed to this responder (`to` unset or this
/// responder's DID) and its `issuedAt` within [`DEFAULT_MAX_HELLO_AGE_SECONDS`]
/// (plus [`DEFAULT_HANDSHAKE_SKEW_SECONDS`]) of `params.created`. The trust
/// policy is applied to the verified `from`. The ACCEPT carries `issuedAt`.
pub fn build_accept(
signer_seed: &[u8],
hello: &Value,
hello_keys: Keys<'_>,
policy: &TrustPolicy,
params: &BuildAccept,
) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); hello);
build_accept_with(
signer_seed,
hello,
hello_keys,
policy,
params,
HandshakeLimits::default(),
)
}
/// The time limits of the handshake: the clock skew allowed either way, the
/// oldest HELLO (for [`build_accept_with`]) or ACCEPT (for
/// [`verify_accept_with`]) accepted, and the longest session an ACCEPT may
/// grant.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HandshakeLimits {
pub clock_skew_seconds: i64,
pub max_age_seconds: i64,
pub max_session_seconds: i64,
}
impl Default for HandshakeLimits {
fn default() -> Self {
Self {
clock_skew_seconds: DEFAULT_HANDSHAKE_SKEW_SECONDS,
max_age_seconds: DEFAULT_MAX_HELLO_AGE_SECONDS,
max_session_seconds: DEFAULT_MAX_SESSION_SECONDS,
}
}
}
impl HandshakeLimits {
fn check(&self) -> Result<()> {
if !(0..=120).contains(&self.clock_skew_seconds) {
return Err(CoreError::Json(
"clock skew must be between 0 and 120 seconds".into(),
));
}
if self.max_age_seconds < 0 || self.max_session_seconds < 1 {
return Err(CoreError::Json(
"handshake age and session limits must be positive".into(),
));
}
Ok(())
}
}
/// [`build_accept`] with the caller's [`HandshakeLimits`].
pub fn build_accept_with(
signer_seed: &[u8],
hello: &Value,
hello_keys: Keys<'_>,
policy: &TrustPolicy,
params: &BuildAccept,
limits: HandshakeLimits,
) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); hello);
limits.check()?;
let now = rv::require_now(¶ms.created)?;
if !handshake_message_ok(hello, hello_keys, HELLO) {
return Err(CoreError::Json(
"HELLO is not signed by the DID it is from".into(),
));
}
match hello.get("to") {
None | Some(Value::Null) => {}
Some(Value::String(t)) if *t == params.from_did => {}
_ => return Err(CoreError::Json("HELLO is addressed to another node".into())),
}
if !issued_recently(
hello.get("issuedAt"),
now,
limits.clock_skew_seconds,
limits.max_age_seconds,
) {
return Err(CoreError::Json(
"HELLO is stale, from the future, or has no valid issuedAt".into(),
));
}
let proposed = scope_list(hello.get("proposedScope"));
let nonce = hello
.get("nonce")
.and_then(|v| v.as_str())
.filter(|n| !n.is_empty());
let (proposed, nonce) = match (proposed, nonce) {
(Some(p), Some(n)) => (p, n),
_ => return Err(CoreError::Json("HELLO is malformed".into())),
};
let initiator = hello.get("from").and_then(|v| v.as_str()).unwrap_or("");
if !policy.is_trusted(initiator) {
return Err(CoreError::Json(format!(
"peer {initiator} is not in this trust domain's policy"
)));
}
if rv::time_ns(Some(&json!(params.valid_until))).is_none_or(|u| u <= now) {
return Err(CoreError::Json(
"valid_until must be a protocol time after created".into(),
));
}
let offered: HashSet<&str> = params.offered_scope.iter().map(|s| s.as_str()).collect();
let mut bounded: Vec<String> = proposed
.into_iter()
.filter(|s| offered.contains(s.as_str()))
.collect::<HashSet<_>>()
.into_iter()
.collect();
bounded.sort();
let mut accept = Map::new();
accept.insert("type".into(), json!(ACCEPT));
accept.insert("from".into(), json!(params.from_did));
accept.insert("to".into(), json!(initiator));
accept.insert("sessionId".into(), json!(params.session_id));
accept.insert("nonce".into(), json!(nonce));
accept.insert("boundedScope".into(), json!(bounded));
accept.insert("issuedAt".into(), json!(params.created));
accept.insert("validUntil".into(), json!(params.valid_until));
let opts = BuildProofOptions::new(format!("{}#key-1", params.from_did), ¶ms.created);
data_integrity::sign(&Value::Object(accept), signer_seed, &opts)
}
/// Verify B's ACCEPT against the HELLO that A sent (initiator A). The ACCEPT's
/// proof must be bound to its `from` DID; it must be addressed to A (`to` ==
/// the HELLO's `from`), come from the node the HELLO was addressed to (a HELLO
/// addressed to nobody needs a `policy` that trusts the responder), echo the
/// HELLO's nonce (and `expected_nonce` when given), carry a bounded scope that
/// is a subset of what A proposed, and not have expired at `now_iso`.
pub fn verify_accept(
accept: &Value,
accept_keys: Keys<'_>,
hello: &Value,
expected_nonce: Option<&str>,
policy: Option<&TrustPolicy>,
now_iso: &str,
) -> Result<Option<BoundedSession>> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); accept, hello);
verify_accept_with(
accept,
accept_keys,
hello,
expected_nonce,
policy,
HandshakeLimits::default(),
now_iso,
)
}
/// [`verify_accept`] with the caller's [`HandshakeLimits`].
pub fn verify_accept_with(
accept: &Value,
accept_keys: Keys<'_>,
hello: &Value,
expected_nonce: Option<&str>,
policy: Option<&TrustPolicy>,
limits: HandshakeLimits,
now_iso: &str,
) -> Result<Option<BoundedSession>> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); accept, hello);
limits.check()?;
let now = rv::require_now(now_iso)?;
if !hello.is_object() || !handshake_message_ok(accept, accept_keys, ACCEPT) {
return Ok(None);
}
let responder = accept
.get("from")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
if accept.get("to") != hello.get("from") {
return Ok(None);
}
match hello.get("to") {
Some(Value::String(t)) if *t != responder => return Ok(None),
Some(Value::String(_)) => {}
_ if policy.is_none() => return Ok(None),
_ => {}
}
if let Some(p) = policy {
if !p.is_trusted(&responder) {
return Ok(None);
}
}
let nonce = match accept.get("nonce").and_then(|v| v.as_str()) {
Some(n) if Some(n) == hello.get("nonce").and_then(|v| v.as_str()) => n.to_string(),
_ => return Ok(None),
};
if expected_nonce.is_some_and(|e| e != nonce) {
return Ok(None);
}
let (bounded, proposed) = match (
scope_list(accept.get("boundedScope")),
scope_list(hello.get("proposedScope")),
) {
(Some(b), Some(p)) if b.iter().all(|x| p.contains(x)) => (b, p),
_ => return Ok(None),
};
let _ = proposed;
let sid = match non_empty_str(accept, "sessionId") {
Some(s) => s.to_string(),
None => return Ok(None),
};
let session = BoundedSession {
session_id: sid,
initiator: accept
.get("to")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string(),
responder,
scope: bounded,
nonce,
valid_until: accept
.get("validUntil")
.and_then(|v| v.as_str())
.map(String::from),
};
if !session.is_current(now_iso) {
return Ok(None);
}
// issuedAt is required: no older than the HELLO age limit, not ahead of
// the clock beyond the skew, and the session it grants is bounded.
if !issued_recently(
accept.get("issuedAt"),
now,
limits.clock_skew_seconds,
limits.max_age_seconds,
) {
return Ok(None);
}
match (
rv::time_ns(accept.get("issuedAt")),
rv::time_ns(accept.get("validUntil")),
) {
(Some(i), Some(u))
if u > i && u - i <= i128::from(limits.max_session_seconds) * 1_000_000_000 => {}
_ => return Ok(None),
}
Ok(Some(session))
}
/// Sign A's confirmation of the bounded session to B. Refuses an expired
/// session (checked at `created`).
pub fn build_confirm(
signer_seed: &[u8],
from_did: &str,
session: &BoundedSession,
created: &str,
) -> Result<Value> {
rv::require_now(created)?;
if !session.is_current(created) {
return Err(CoreError::Json("the session has expired".into()));
}
let mut confirm = Map::new();
confirm.insert("type".into(), json!(CONFIRM));
confirm.insert("from".into(), json!(from_did));
confirm.insert("to".into(), json!(session.responder));
confirm.insert("sessionId".into(), json!(session.session_id));
confirm.insert("nonce".into(), json!(session.nonce));
confirm.insert("acceptedScope".into(), json!(session.scope));
let opts = BuildProofOptions::new(format!("{from_did}#key-1"), created);
data_integrity::sign(&Value::Object(confirm), signer_seed, &opts)
}
/// Verify A's CONFIRM closes the session B accepted (responder B). `accept` is
/// the ACCEPT B sent. The CONFIRM's proof must be bound to its `from` DID,
/// which must be the initiator (the ACCEPT's `to`); it must be addressed to
/// B, name the same session and nonce, accept a scope within the bounded
/// scope, and arrive while the session is still valid at `now_iso`.
pub fn verify_confirm(
confirm: &Value,
confirm_keys: Keys<'_>,
accept: &Value,
now_iso: &str,
) -> Result<bool> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); confirm, accept);
let now = rv::require_now(now_iso)?;
if !accept.is_object() || !handshake_message_ok(confirm, confirm_keys, CONFIRM) {
return Ok(false);
}
if confirm.get("from") != accept.get("to") || confirm.get("to") != accept.get("from") {
return Ok(false);
}
if confirm.get("sessionId") != accept.get("sessionId")
|| confirm.get("nonce") != accept.get("nonce")
{
return Ok(false);
}
match (
scope_list(confirm.get("acceptedScope")),
scope_list(accept.get("boundedScope")),
) {
(Some(a), Some(b)) if a.iter().all(|x| b.contains(x)) => {}
_ => return Ok(false),
}
Ok(rv::time_ns(accept.get("validUntil")).is_some_and(|u| now <= u))
}
// ---------------------------------------------------------------------------
// Black box and kill switch (Phase 5.5)
// ---------------------------------------------------------------------------
/// Version 1.1 entries bind their header (every field but the ciphertext and
/// the hash) into AES-GCM as associated data; 1.0 entries do not.
pub const BLACKBOX_VERSION: &str = "1.1";
/// The pre-1.1 entry version, still opened (without associated data).
pub const BLACKBOX_LEGACY_VERSION: &str = "1.0";
/// A signed black-box head: entry count plus last hash.
pub const BLACKBOX_HEAD_TYPE: &str = "BlackBoxHeadCredential";
/// Size cap for a log handed to a verifier (before canonicalization).
pub const MAX_LOG_BYTES: usize = 64 * 1024 * 1024;
pub const KILLSWITCH_TYPE: &str = "KillSwitchCredential";
pub const EMERGENCY_STOP: &str = "emergency_stop";
/// The prevHash of the first entry: multibase of 32 zero bytes.
pub fn genesis_prev_hash() -> String {
mb64(&[0u8; 32])
}
/// The entry header bound into AES-GCM: JCS of every field but the ciphertext
/// and the entry hash.
fn entry_aad(entry: &Map<String, Value>) -> Vec<u8> {
let mut header = entry.clone();
header.remove("ciphertext");
header.remove("entryHash");
jcs::canonicalize(&Value::Object(header))
}
fn entry_hash(body: &Map<String, Value>) -> Result<String> {
let mut clean = body.clone();
clean.remove("entryHash");
let canonical = jcs::canonicalize(&Value::Object(clean));
Ok(mb64(&Sha256::digest(canonical)))
}
/// Build one black-box entry statelessly: encrypt `payload` under `key`, link it
/// to `prev_hash` at `seq`, and return the entry with its `entryHash`. The
/// stateful [`BlackBoxLog`] and the FFI layer both build on this. The encrypted
/// blob is nonce(12) || ciphertext || tag(16).
pub fn blackbox_append_entry(
key: &[u8],
seq: u64,
event: &str,
payload: &Value,
timestamp: &str,
prev_hash: &str,
) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); payload);
blackbox_append_entry_with_nonce(key, seq, event, payload, timestamp, prev_hash, None)
}
/// [`blackbox_append_entry`] with the host's own 12-byte AES-GCM nonce (a
/// host with its own random source or a secure element). A nonce must never
/// be used twice under one key; without one the core draws a random nonce.
pub fn blackbox_append_entry_with_nonce(
key: &[u8],
seq: u64,
event: &str,
payload: &Value,
timestamp: &str,
prev_hash: &str,
host_nonce: Option<&[u8]>,
) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); payload);
if key.len() != 32 {
return Err(CoreError::Crypto(
"black box key must be 32 bytes (AES-256)".into(),
));
}
let mut nonce = [0u8; 12];
match host_nonce {
Some(n) if n.len() == 12 => nonce.copy_from_slice(n),
Some(_) => return Err(CoreError::Crypto("black box nonce must be 12 bytes".into())),
None => {
crate::random::fill(&mut nonce).map_err(|e| CoreError::Crypto(format!("rng: {e}")))?
}
}
let plaintext = jcs::canonicalize(payload);
let mut body = Map::new();
body.insert("version".into(), json!(BLACKBOX_VERSION));
body.insert("seq".into(), json!(seq));
body.insert("timestamp".into(), json!(timestamp));
body.insert("event".into(), json!(event));
body.insert("prevHash".into(), json!(prev_hash));
let aad = entry_aad(&body);
let cipher =
Aes256Gcm::new_from_slice(key).map_err(|e| CoreError::Crypto(format!("aes key: {e}")))?;
let ct = cipher
.encrypt(
Nonce::from_slice(&nonce),
Payload {
msg: plaintext.as_ref(),
aad: &aad,
},
)
.map_err(|e| CoreError::Crypto(format!("encrypt: {e}")))?;
let mut blob = Vec::with_capacity(nonce.len() + ct.len());
blob.extend_from_slice(&nonce);
blob.extend_from_slice(&ct);
body.insert("ciphertext".into(), json!(mb64(&blob)));
let h = entry_hash(&body)?;
body.insert("entryHash".into(), json!(h));
Ok(Value::Object(body))
}
/// An append-only, AES-256-GCM-encrypted, JCS hash-linked event log. The key is
/// 32 bytes. The encrypted blob is nonce(12) || ciphertext || tag(16), matching
/// Python, TypeScript, and Go.
pub struct BlackBoxLog {
key: Vec<u8>,
genesis: String,
entries: Vec<Value>,
head: String,
}
impl BlackBoxLog {
/// Build a log. A `None` genesis uses [`genesis_prev_hash`].
pub fn new(key: &[u8], genesis_prev_hash_override: Option<&str>) -> Result<Self> {
if key.len() != 32 {
return Err(CoreError::Crypto(
"black box key must be 32 bytes (AES-256)".into(),
));
}
let genesis = genesis_prev_hash_override
.map(String::from)
.unwrap_or_else(genesis_prev_hash);
Ok(Self {
key: key.to_vec(),
head: genesis.clone(),
genesis,
entries: Vec::new(),
})
}
/// Encrypt `payload`, link it to the chain head, and return the new entry.
pub fn append(&mut self, event: &str, payload: &Value, timestamp: &str) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); payload);
let entry = blackbox_append_entry(
&self.key,
self.entries.len() as u64,
event,
payload,
timestamp,
&self.head,
)?;
self.head = entry
.get("entryHash")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
self.entries.push(entry.clone());
Ok(entry)
}
pub fn head(&self) -> &str {
&self.head
}
pub fn genesis(&self) -> &str {
&self.genesis
}
pub fn entries(&self) -> &[Value] {
&self.entries
}
/// The number of entries, the count a signed head carries.
pub fn count(&self) -> usize {
self.entries.len()
}
pub fn open(&self, entry: &Value) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); entry);
open_entry(entry, &self.key)
}
}
/// Decrypt a black-box entry payload with the log key.
pub fn open_entry(entry: &Value, key: &[u8]) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); entry);
let obj = entry
.as_object()
.ok_or_else(|| CoreError::Json("entry has no ciphertext".into()))?;
let ct_mb = obj
.get("ciphertext")
.and_then(|v| v.as_str())
.ok_or_else(|| CoreError::Json("entry has no ciphertext".into()))?;
// 1.1 entries open with their header as associated data, so a changed
// label, time, sequence number or link fails to decrypt. 1.0 entries were
// written before the header was bound and open without it.
let aad = match obj.get("version").and_then(|v| v.as_str()) {
Some(BLACKBOX_VERSION) => entry_aad(obj),
Some(BLACKBOX_LEGACY_VERSION) => Vec::new(),
other => {
return Err(CoreError::Json(format!(
"unsupported black-box entry version {other:?}"
)))
}
};
let blob = unmb64(ct_mb)?;
if blob.len() < 12 + 16 {
return Err(CoreError::Crypto("ciphertext too short".into()));
}
let cipher =
Aes256Gcm::new_from_slice(key).map_err(|e| CoreError::Crypto(format!("aes key: {e}")))?;
let (nonce, rest) = blob.split_at(12);
let pt = cipher
.decrypt(
Nonce::from_slice(nonce),
Payload {
msg: rest,
aad: &aad,
},
)
.map_err(|_| CoreError::Crypto("decryption failed".into()))?;
crate::nesting::check_text(&pt)?;
serde_json::from_slice(&pt).map_err(|e| CoreError::Json(format!("payload decode: {e}")))
}
/// The outcome of [`verify_blackbox_chain`].
#[derive(Debug, Clone)]
pub struct ChainResult {
pub ok: bool,
pub reason: Option<String>,
}
/// Verify the hash chain over the (still-encrypted) entries. Tamper-evident
/// without the key. A `None` genesis uses [`genesis_prev_hash`].
pub fn verify_blackbox_chain(
entries: &[Value],
genesis_prev_hash_override: Option<&str>,
) -> ChainResult {
crate::nesting::deep_guard!(ChainResult { ok: false, reason: Some(crate::nesting::TOO_DEEP.into()) }; entries);
verify_blackbox_chain_capped(entries, genesis_prev_hash_override, MAX_LOG_BYTES)
}
/// [`verify_blackbox_chain`] with the host's size limit for the log.
pub fn verify_blackbox_chain_capped(
entries: &[Value],
genesis_prev_hash_override: Option<&str>,
max_bytes: usize,
) -> ChainResult {
crate::nesting::deep_guard!(ChainResult { ok: false, reason: Some(crate::nesting::TOO_DEEP.into()) }; entries);
let mut progress = ChainProgress::start(genesis_prev_hash_override);
verify_chain_segment(&mut progress, entries, max_bytes);
progress.result()
}
/// Where a hash-chain check stands after the first entries of a log: the
/// number the next entry must carry, the hash it must link to, and the first
/// failure. A long log is checked one segment at a time by passing this from
/// one [`verify_chain_segment`] call to the next, so memory stays bounded by
/// one segment however long the log is. The verdict is the one
/// [`verify_blackbox_chain`] gives for the whole log.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChainProgress {
/// The prevHash of entry 0.
pub genesis: String,
/// The number of entries checked so far (the next entry's seq).
pub next_seq: u64,
/// The entryHash of the last entry checked, or the genesis.
pub last_hash: String,
/// The first failure; once set, later segments are not read.
pub failure: Option<String>,
}
impl ChainProgress {
/// The start of a log. A `None` genesis uses [`genesis_prev_hash`].
pub fn start(genesis_prev_hash_override: Option<&str>) -> Self {
let genesis = genesis_prev_hash_override
.map(String::from)
.unwrap_or_else(genesis_prev_hash);
Self {
last_hash: genesis.clone(),
genesis,
next_seq: 0,
failure: None,
}
}
/// The verdict over every entry checked so far.
pub fn result(&self) -> ChainResult {
ChainResult {
ok: self.failure.is_none(),
reason: self.failure.clone(),
}
}
}
/// The reason a segment of log entries nests too deeply or is larger than
/// `max_bytes`, measured as [`rv::input_too_large`] measures the same entries
/// in one list, without copying them.
fn entries_too_large(entries: &[Value], max_bytes: usize) -> Option<String> {
use crate::attenuation::json_nesting_exceeds;
if entries
.iter()
.any(|e| json_nesting_exceeds(e, rv::MAX_NESTING - 1))
{
return Some(format!("input nests more than {} levels", rv::MAX_NESTING));
}
let mut total = 2 + entries.len();
for e in entries {
if total > max_bytes {
break;
}
total += rv::approx_size(e, max_bytes - total);
}
if total > max_bytes {
return Some(format!("input larger than {max_bytes} bytes"));
}
None
}
/// Check the next `entries` of a log (one segment) and move `progress` past
/// them. Every hash-linked log (black box, safety ledger, perception log)
/// verifies through here, whole or in segments.
pub fn verify_chain_segment(progress: &mut ChainProgress, entries: &[Value], max_bytes: usize) {
#[cfg(not(feature = "std"))]
if crate::nesting::Nested::nests_past(&entries, crate::nesting::NO_STD_MAX_NESTING) {
progress
.failure
.get_or_insert_with(|| crate::nesting::TOO_DEEP.into());
return;
}
#[cfg(not(feature = "std"))]
if crate::nesting::Nested::nests_past(&entries, crate::nesting::NO_STD_MAX_NESTING) {
progress
.failure
.get_or_insert_with(|| crate::nesting::TOO_DEEP.into());
return;
}
if progress.failure.is_some() {
return;
}
if let Some(big) = entries_too_large(entries, max_bytes) {
progress.failure = Some(big);
return;
}
for entry in entries {
let i = progress.next_seq;
let obj = match entry.as_object() {
Some(o) => o,
None => {
progress.failure = Some(format!("entry {i} is not an object"));
return;
}
};
if entry.get("seq").and_then(|v| v.as_u64()) != Some(i) {
progress.failure = Some(format!("entry {i} seq mismatch"));
return;
}
if entry.get("prevHash").and_then(|v| v.as_str()).unwrap_or("") != progress.last_hash {
progress.failure = Some(format!("entry {i} prevHash does not link"));
return;
}
let want = match entry_hash(obj) {
Ok(w) => w,
Err(_) => {
progress.failure = Some(format!("entry {i} hash error"));
return;
}
};
let eh = entry
.get("entryHash")
.and_then(|v| v.as_str())
.unwrap_or("");
if eh != want {
progress.failure = Some(format!("entry {i} entryHash mismatch (tampered)"));
return;
}
// A resumed state can carry any number; one past u64::MAX is no seq.
let Some(next) = progress.next_seq.checked_add(1) else {
progress.failure = Some(format!("entry {i} seq mismatch"));
return;
};
progress.last_hash = want;
progress.next_seq = next;
}
}
/// The end of a segmented check against a signed head: the same verdict
/// [`verify_chain_against_head`] gives for the whole log.
pub fn finish_chain_against_head(
progress: &ChainProgress,
head: Option<&Value>,
count: Option<&Value>,
) -> ChainResult {
crate::nesting::deep_guard!(ChainResult { ok: false, reason: Some(crate::nesting::TOO_DEEP.into()) }; head, count);
if progress.failure.is_some() {
return progress.result();
}
let fail = |r: String| ChainResult {
ok: false,
reason: Some(r),
};
let n = match count.and_then(|c| rv::strict_int(Some(c))) {
Some(n) if n >= 0 => n,
_ => return fail("anchored count is not a non-negative integer".into()),
};
if i128::from(progress.next_seq) != i128::from(n) {
return fail(format!(
"log has {} entries, the signed head says {n}",
progress.next_seq
));
}
if head.and_then(|h| h.as_str()) != Some(progress.last_hash.as_str()) {
return fail("log does not end at the signed head".into());
}
ChainResult {
ok: true,
reason: None,
}
}
/// Parameters for [`build_killswitch_credential`].
#[derive(Debug, Clone, Default)]
pub struct BuildKillswitch {
pub issuer_did: String,
pub target: String,
pub reason: String,
pub command: Option<String>,
pub scope: Option<Vec<String>>,
pub valid_from: String,
pub valid_until: Option<String>,
}
/// Build a signed `KillSwitchCredential` proving who issued an emergency stop.
pub fn build_killswitch_credential(
authority_seed: &[u8],
params: &BuildKillswitch,
) -> Result<Value> {
let command = params
.command
.clone()
.unwrap_or_else(|| EMERGENCY_STOP.to_string());
let mut subject = Map::new();
subject.insert("id".into(), json!(params.target));
subject.insert("command".into(), json!(command));
subject.insert("reason".into(), json!(params.reason));
subject.insert("issuedBy".into(), json!(params.issuer_did));
if let Some(scope) = ¶ms.scope {
subject.insert("scope".into(), json!(scope));
}
let mut cred = Map::new();
cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
cred.insert(
"type".into(),
json!(["VerifiableCredential", KILLSWITCH_TYPE]),
);
cred.insert("issuer".into(), json!(params.issuer_did));
cred.insert("validFrom".into(), json!(params.valid_from));
if let Some(vu) = ¶ms.valid_until {
cred.insert("validUntil".into(), json!(vu));
}
cred.insert("credentialSubject".into(), Value::Object(subject));
let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), ¶ms.valid_from);
data_integrity::sign(&Value::Object(cred), authority_seed, &opts)
}
/// Verify a `KillSwitchCredential`. When `trusted_authorities` is supplied, the
/// issuer DID MUST be in it. Returns the subject on success.
pub fn verify_killswitch_credential(
credential: &Value,
keys: Keys<'_>,
trusted_authorities: Option<&HashSet<String>>,
now_iso: &str,
) -> Result<Option<Value>> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
let now = rv::require_now(now_iso)?;
let opts = VerifyOptions {
trusted_issuers: trusted_authorities,
..VerifyOptions::window(Window::FromRequired)
};
let v = match rv::verify_robotics_credential(credential, keys, Some(KILLSWITCH_TYPE), now, opts)
{
Ok(v) => v,
Err(_) => return Ok(None),
};
// issuedBy, when present, must be the bound issuer.
if let Some(by) = v.subject.get("issuedBy") {
if by.as_str() != Some(v.issuer.as_str()) {
return Ok(None);
}
}
Ok(Some(v.subject))
}
/// Verify the hash links AND that the log ends at a known head: `head` and
/// `count` come from something signed (a head credential, a safety-record
/// summary, a perception attestation). A log cut short, extended or rebuilt
/// does not end at that head with that many entries.
pub fn verify_chain_against_head(
entries: &[Value],
head: Option<&Value>,
count: Option<&Value>,
genesis_prev_hash_override: Option<&str>,
) -> ChainResult {
crate::nesting::deep_guard!(ChainResult { ok: false, reason: Some(crate::nesting::TOO_DEEP.into()) }; entries, head, count);
verify_chain_against_head_capped(
entries,
head,
count,
genesis_prev_hash_override,
MAX_LOG_BYTES,
)
}
/// [`verify_chain_against_head`] with the host's size limit for the log.
pub fn verify_chain_against_head_capped(
entries: &[Value],
head: Option<&Value>,
count: Option<&Value>,
genesis_prev_hash_override: Option<&str>,
max_bytes: usize,
) -> ChainResult {
crate::nesting::deep_guard!(ChainResult { ok: false, reason: Some(crate::nesting::TOO_DEEP.into()) }; entries, head, count);
let mut progress = ChainProgress::start(genesis_prev_hash_override);
verify_chain_segment(&mut progress, entries, max_bytes);
finish_chain_against_head(&progress, head, count)
}
/// Sign the head of a black-box log (entry count plus last hash). The robot is
/// the issuer and the subject.
pub fn build_blackbox_head(
robot_seed: &[u8],
robot_did: &str,
head: &str,
entry_count: u64,
valid_from: &str,
valid_until: Option<&str>,
) -> Result<Value> {
let mut cred = Map::new();
cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
cred.insert(
"type".into(),
json!(["VerifiableCredential", BLACKBOX_HEAD_TYPE]),
);
cred.insert("issuer".into(), json!(robot_did));
cred.insert("validFrom".into(), json!(valid_from));
if let Some(vu) = valid_until {
cred.insert("validUntil".into(), json!(vu));
}
cred.insert(
"credentialSubject".into(),
json!({"id": robot_did, "logHead": head, "entryCount": entry_count}),
);
let opts = BuildProofOptions::new(format!("{robot_did}#key-1"), valid_from);
data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
}
/// Verify a log against the robot's signed head: the head credential must
/// verify bound to the robot as issuer and subject, and the log must link and
/// end at the signed head with exactly the signed number of entries.
pub fn verify_blackbox_head(
credential: &Value,
robot_keys: Keys<'_>,
entries: &[Value],
genesis_prev_hash_override: Option<&str>,
now_iso: &str,
) -> Result<ChainResult> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, entries);
let mut progress = ChainProgress::start(genesis_prev_hash_override);
verify_chain_segment(&mut progress, entries, MAX_LOG_BYTES);
finish_chain_against_head_credential(credential, robot_keys, &progress, now_iso)
}
/// The end of a segmented check against the robot's signed head credential:
/// the same verdict [`verify_blackbox_head`] gives for the whole log.
pub fn finish_chain_against_head_credential(
credential: &Value,
robot_keys: Keys<'_>,
progress: &ChainProgress,
now_iso: &str,
) -> Result<ChainResult> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
let now = rv::require_now(now_iso)?;
let v = match rv::verify_robotics_credential(
credential,
robot_keys,
Some(BLACKBOX_HEAD_TYPE),
now,
VerifyOptions::window(Window::FromRequired),
) {
Ok(v) => v,
Err(r) => {
return Ok(ChainResult {
ok: false,
reason: Some(r),
})
}
};
if !issuer_is_subject(&v) {
return Ok(ChainResult {
ok: false,
reason: Some("head is not issued by the robot it describes".into()),
});
}
Ok(finish_chain_against_head(
progress,
v.subject.get("logHead"),
v.subject.get("entryCount"),
))
}
// ---------------------------------------------------------------------------
// Halos safety-evidence recorder (NVIDIA Halos integration)
// ---------------------------------------------------------------------------
//
// Byte-exact port of the Python reference `vouch/robotics/halos.py`.
//
// Halos certifies that a robot's stack is functionally safe and secure by design.
// It does not, on its own, produce a verifiable record of what a specific robot
// did or bind that record to the robot's identity. This is the evidence layer
// under a Halos-certified stack: the robot seals its black-box chain head and
// entry count into a signed `HalosSafetyEvidenceCredential` that binds them to its
// identity, to the Halos stack elements it ran on, and to a time window. A
// verifier that holds the credential and the entries confirms, without the
// black-box key, that the record is unaltered, was not truncated or extended since
// it was sealed, and is attributable to that robot. This composes the existing
// black-box and credential primitives and adds no new cryptography.
pub const HALOS_SAFETY_EVIDENCE_TYPE: &str = "HalosSafetyEvidenceCredential";
/// Format Unix epoch seconds as "YYYY-MM-DDTHH:MM:SSZ" for a whole-second UTC
/// instant. Howard Hinnant's civil-from-days algorithm, matching the rest of the
/// core so a `valid_seconds` lifetime renders identically across languages.
fn halos_epoch_to_iso(epoch: i64) -> String {
let days = epoch.div_euclid(86400);
let secs = epoch.rem_euclid(86400);
let z = days + 719468;
let era = (if z >= 0 { z } else { z - 146096 }) / 146097;
let doe = z - era * 146097;
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let year = if m <= 2 { y + 1 } else { y };
let hh = secs / 3600;
let mm = (secs % 3600) / 60;
let ss = secs % 60;
format!("{year:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}Z")
}
/// Parameters for [`build_safety_evidence`]. The robot DID is derived from
/// `signer_seed` (a did:key), mirroring the Python signer. `blackbox_head` and
/// `entry_count` seal the robot's black-box chain; `halos_stack` names the
/// certified configuration; `window` covers the recorded events. Timestamps are
/// caller-supplied ISO-8601 strings.
#[derive(Debug, Clone)]
pub struct BuildSafetyEvidence {
pub halos_stack: Value,
pub window_from: String,
pub window_to: String,
pub blackbox_head: String,
pub entry_count: u64,
pub robot_identity: Option<String>,
pub valid_seconds: Option<i64>,
pub valid_from: String,
pub created: String,
/// The robot's DID, when it is not the did:key of the signing key (a
/// did:web robot); without it the issuer is that did:key.
pub robot_did: Option<String>,
}
/// Seal a robot's Halos safety-event record into a signed
/// `HalosSafetyEvidenceCredential`. The robot signs a credential binding the
/// black-box chain head and entry count to its identity, to the Halos stack
/// elements it ran on, and to the time window.
pub fn build_safety_evidence(signer_seed: &[u8], params: &BuildSafetyEvidence) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
match params.halos_stack.as_object() {
Some(o) if !o.is_empty() => {}
_ => return Err(CoreError::Json("halos_stack is required".into())),
}
if params.window_from.is_empty() || params.window_to.is_empty() {
return Err(CoreError::Json(
"window with 'from' and 'to' is required".into(),
));
}
let robot_did = match params.robot_did.as_deref().filter(|d| !d.is_empty()) {
Some(d) if d.starts_with("did:") => d.to_string(),
Some(_) => return Err(CoreError::Json("robot_did must be a DID".into())),
None => {
let kp = keys::Ed25519KeyPair::from_seed_slice(signer_seed)?;
keys::ed25519_to_did_key(&kp.public_key())?
}
};
let mut subject = Map::new();
subject.insert("id".into(), json!(robot_did));
subject.insert("blackboxHead".into(), json!(params.blackbox_head));
subject.insert("entryCount".into(), json!(params.entry_count));
subject.insert("halosStack".into(), params.halos_stack.clone());
subject.insert(
"window".into(),
json!({ "from": params.window_from, "to": params.window_to }),
);
if let Some(robot_identity) = ¶ms.robot_identity {
subject.insert("robotIdentity".into(), json!(robot_identity));
}
let mut cred = Map::new();
cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
cred.insert(
"type".into(),
json!(["VerifiableCredential", HALOS_SAFETY_EVIDENCE_TYPE]),
);
cred.insert("issuer".into(), json!(robot_did));
cred.insert("validFrom".into(), json!(params.valid_from));
if let Some(valid_seconds) = params.valid_seconds {
let from = crate::time::iso_to_epoch_seconds(¶ms.valid_from)?;
cred.insert(
"validUntil".into(),
json!(halos_epoch_to_iso(from + valid_seconds)),
);
}
cred.insert("credentialSubject".into(), Value::Object(subject));
let opts = BuildProofOptions::new(format!("{robot_did}#key-1"), ¶ms.created);
data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
}
/// Verify a `HalosSafetyEvidenceCredential`: the robot's proof and that the issuer
/// is the robot (`credentialSubject.id`). When `entries` is supplied, also checks
/// that the black-box chain is intact, that its length matches the sealed entry
/// count, and that its head matches the sealed head, so a truncated, extended,
/// reordered, or tampered record is rejected. Returns `(ok, credentialSubject)`.
pub fn verify_safety_evidence(
credential: &Value,
robot_keys: Keys<'_>,
entries: Option<&[Value]>,
now_iso: &str,
) -> Result<(bool, Option<Value>)> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, entries);
let v = match bound(
credential,
robot_keys,
HALOS_SAFETY_EVIDENCE_TYPE,
now_iso,
Window::FromRequired,
)? {
Some(v) if issuer_is_subject(&v) => v,
_ => return Ok((false, None)),
};
let subject = v.subject;
let count = match rv::strict_int(subject.get("entryCount")) {
Some(n) if n >= 0 => n,
_ => return Ok((false, None)),
};
if let Some(entries) = entries {
if !verify_blackbox_chain(entries, None).ok {
return Ok((false, None));
}
if count != entries.len() as i64 {
return Ok((false, None));
}
let head = match entries.last() {
Some(last) => last
.get("entryHash")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string(),
None => genesis_prev_hash(),
};
if Some(head.as_str()) != subject.get("blackboxHead").and_then(|v| v.as_str()) {
return Ok((false, None));
}
}
Ok((true, Some(subject)))
}
// ---------------------------------------------------------------------------
// Scannable robot passport (Phase 5.6)
// ---------------------------------------------------------------------------
pub const ROBOT_PASSPORT_TYPE: &str = "RobotPassport";
pub const PASSPORT_URI_SCHEME: &str = "vouch-passport:";
pub const STATUS_ACTIVE: &str = "active";
pub const STATUS_SUSPENDED: &str = "suspended";
pub const STATUS_DECOMMISSIONED: &str = "decommissioned";
/// Parameters for [`build_passport`]. The issuer is the signer (the robot or an
/// authority); `robot_did` is the robot the passport describes.
#[derive(Debug, Clone, Default)]
pub struct BuildPassport {
pub issuer_did: String,
pub robot_did: String,
pub make: String,
pub model: String,
pub owner: String,
pub authorized_actions: Vec<String>,
pub certification: Option<String>,
pub status: Option<String>,
pub valid_from: String,
pub valid_until: Option<String>,
}
/// Build a signed `RobotPassport` credential.
pub fn build_passport(signer_seed: &[u8], params: &BuildPassport) -> Result<Value> {
let status = params
.status
.clone()
.unwrap_or_else(|| STATUS_ACTIVE.to_string());
let mut subject = Map::new();
subject.insert("id".into(), json!(params.robot_did));
subject.insert("make".into(), json!(params.make));
subject.insert("model".into(), json!(params.model));
subject.insert("owner".into(), json!(params.owner));
subject.insert("authorizedActions".into(), json!(params.authorized_actions));
subject.insert("status".into(), json!(status));
if let Some(c) = ¶ms.certification {
subject.insert("certification".into(), json!(c));
}
let mut cred = Map::new();
cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
cred.insert(
"type".into(),
json!(["VerifiableCredential", ROBOT_PASSPORT_TYPE]),
);
cred.insert("issuer".into(), json!(params.issuer_did));
cred.insert("validFrom".into(), json!(params.valid_from));
if let Some(vu) = ¶ms.valid_until {
cred.insert("validUntil".into(), json!(vu));
}
cred.insert("credentialSubject".into(), Value::Object(subject));
let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), ¶ms.valid_from);
data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
}
/// Encode a passport into a compact `vouch-passport:` URI for a QR or NFC tag.
pub fn encode_passport(passport: &Value) -> String {
format!(
"{}{}",
PASSPORT_URI_SCHEME,
mb64(&jcs::canonicalize(passport))
)
}
/// Decode a `vouch-passport:` URI back into the passport credential.
pub fn decode_passport(uri: &str) -> Result<Value> {
let body = uri
.strip_prefix(PASSPORT_URI_SCHEME)
.ok_or_else(|| CoreError::Json(format!("not a {PASSPORT_URI_SCHEME} URI")))?;
if body.len() > 2 * rv::MAX_CREDENTIAL_BYTES {
return Err(CoreError::Json("passport URI too large".into()));
}
let raw = unmb64(body)?;
crate::nesting::check_text(&raw)?;
let decoded: Value = serde_json::from_slice(&raw)
.map_err(|e| CoreError::Json(format!("passport decode: {e}")))?;
if !decoded.is_object() {
return Err(CoreError::Json("passport payload is not an object".into()));
}
Ok(decoded)
}
/// Verify a passport: the proof bound to the issuer (`keys` is a `{did: key}`
/// source, or the bare key of a did:key issuer), the validity window at
/// `now_iso` (validFrom required, strict times), `authorizedActions` a list of
/// strings, and (when given) the issuer in `trusted_issuers`. A suspended or
/// decommissioned status still verifies; the caller reads it from the subject.
pub fn verify_passport(
passport: &Value,
keys: Keys<'_>,
trusted_issuers: Option<&HashSet<String>>,
now_iso: &str,
) -> Result<Option<Value>> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); passport);
let now = rv::require_now(now_iso)?;
let opts = VerifyOptions {
trusted_issuers,
..VerifyOptions::window(Window::FromRequired)
};
let v = match rv::verify_robotics_credential(
passport,
keys,
Some(ROBOT_PASSPORT_TYPE),
now,
opts,
) {
Ok(v) => v,
Err(_) => return Ok(None),
};
match v.subject.get("authorizedActions") {
None => {}
Some(Value::Array(a)) if a.iter().all(|x| x.is_string()) => {}
_ => return Ok(None),
}
Ok(Some(v.subject))
}
pub fn verify_passport_uri(
uri: &str,
keys: Keys<'_>,
trusted_issuers: Option<&HashSet<String>>,
now_iso: &str,
) -> Result<Option<Value>> {
rv::require_now(now_iso)?;
match decode_passport(uri) {
Ok(p) => verify_passport(&p, keys, trusted_issuers, now_iso),
Err(_) => Ok(None),
}
}
/// Verify a passport (a credential object or a `vouch-passport:` URI) as
/// [`verify_passport`] does and return the human-facing summary the Python
/// reference returns: robot, make, model, owner, authorizedActions,
/// certification, status, and the verified `issuer`.
pub fn verify_passport_summary(
passport: &Value,
keys: Keys<'_>,
trusted_issuers: Option<&HashSet<String>>,
now_iso: &str,
) -> Result<Option<Value>> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); passport);
let cred = match passport {
Value::String(uri) => match decode_passport(uri) {
Ok(p) => p,
Err(_) => return Ok(None),
},
other => other.clone(),
};
let subject = match verify_passport(&cred, keys, trusted_issuers, now_iso)? {
Some(s) => s,
None => return Ok(None),
};
let issuer = rv::issuer_id(cred.get("issuer")).unwrap_or("").to_string();
let g = |k: &str| subject.get(k).cloned().unwrap_or(Value::Null);
Ok(Some(json!({
"robot": g("id"),
"make": g("make"),
"model": g("model"),
"owner": g("owner"),
"authorizedActions": subject.get("authorizedActions").cloned().unwrap_or(json!([])),
"certification": g("certification"),
"status": g("status"),
"issuer": issuer,
})))
}
// ---------------------------------------------------------------------------
// Liveness heartbeat with safety-envelope conformance (Phase 5.7)
// ---------------------------------------------------------------------------
pub const ROBOT_HEARTBEAT_TYPE: &str = "RobotHeartbeatCredential";
/// Default number of missed intervals tolerated before trust is considered stale.
pub const DEFAULT_GRACE_INTERVALS: i64 = 2;
/// One observed motion sample. `None` numerics mean "not specified" (a meaningful
/// zero is still `Some(0.0)`), matching [`PhysicalAction`].
#[derive(Debug, Clone, Default)]
pub struct MotionSample {
pub force_n: Option<f64>,
pub speed_mps: Option<f64>,
pub near_humans: bool,
pub zone: Option<String>,
pub time_hm: Option<String>,
}
/// Collector for per-interval motion telemetry. It accumulates aggregates of what
/// the robot physically did over a heartbeat interval and, when given a physical
/// scope, counts how many samples fell outside the declared envelope. The
/// physical analogue of the agent behavioral digest.
///
/// With `scope` set to `None` the digest still reports observed maxima but cannot
/// judge conformance, so it reports `withinEnvelope` true with a zero breach
/// count, mirroring the Python `MotionCollector`.
#[derive(Debug, Clone, Default)]
pub struct MotionCollector {
scope: Option<Value>,
samples: u64,
max_force: f64,
max_speed: f64,
max_speed_near: f64,
zone_breaches: u64,
breaches: u64,
}
impl MotionCollector {
/// A collector that judges samples against `scope` (the
/// `credentialSubject.physicalScope` object). Pass `None` to only aggregate.
pub fn new(scope: Option<Value>) -> Self {
Self {
scope,
..Default::default()
}
}
/// Record a single observed motion sample, updating the running aggregates and
/// (when a scope is set) the breach counts.
pub fn record(&mut self, sample: &MotionSample) -> Result<()> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); self);
if let Some(f) = sample.force_n {
if !f.is_finite() || f < 0.0 {
return Err(CoreError::Json(format!(
"force_n must be a finite non-negative number, got {f}"
)));
}
}
if let Some(s) = sample.speed_mps {
if !s.is_finite() || s < 0.0 {
return Err(CoreError::Json(format!(
"speed_mps must be a finite non-negative number, got {s}"
)));
}
}
self.samples += 1;
if let Some(f) = sample.force_n {
self.max_force = self.max_force.max(f);
}
if let Some(s) = sample.speed_mps {
self.max_speed = self.max_speed.max(s);
if sample.near_humans {
self.max_speed_near = self.max_speed_near.max(s);
}
}
if let Some(scope) = &self.scope {
let action = PhysicalAction {
force_n: sample.force_n,
speed_mps: sample.speed_mps,
near_humans: sample.near_humans,
zone: sample.zone.clone(),
time_hm: sample.time_hm.clone(),
};
let result = check_physical_action(scope, &action);
if !result.ok {
self.breaches += 1;
if result
.reasons
.iter()
.any(|r| r.starts_with("zone_not_allowed"))
{
self.zone_breaches += 1;
}
}
}
Ok(())
}
/// Return the `motionDigest` object for embedding in a heartbeat credential.
pub fn digest(&self) -> Value {
crate::nesting::deep_guard!(Value::Null; self);
json!({
"samples": self.samples,
"maxForceN": self.max_force,
"maxSpeedMps": self.max_speed,
"maxSpeedNearHumansMps": self.max_speed_near,
"zoneBreaches": self.zone_breaches,
"breachCount": self.breaches,
"withinEnvelope": self.breaches == 0,
})
}
/// Clear all state. Call after submitting a heartbeat to start fresh.
pub fn reset(&mut self) {
self.samples = 0;
self.max_force = 0.0;
self.max_speed = 0.0;
self.max_speed_near = 0.0;
self.zone_breaches = 0;
self.breaches = 0;
}
}
fn digest_non_negative_int(digest: &Map<String, Value>, name: &str) -> Result<()> {
match digest.get(name) {
Some(v) if v.is_u64() => Ok(()),
Some(Value::Number(n)) if n.as_i64().map(|i| i >= 0).unwrap_or(false) => Ok(()),
Some(_) => Err(CoreError::Json(format!(
"motionDigest.{name} must be a non-negative integer"
))),
None => Err(CoreError::Json(format!("motionDigest.{name} is required"))),
}
}
/// Structural validation of a `motionDigest` object. Does not judge whether the
/// values are acceptable; that is policy, expressed through [`is_live`].
pub fn validate_motion_digest(digest: &Value) -> Result<()> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); digest);
let obj = digest
.as_object()
.ok_or_else(|| CoreError::Json("motionDigest must be an object".into()))?;
for name in ["samples", "zoneBreaches", "breachCount"] {
digest_non_negative_int(obj, name)?;
}
for name in ["maxForceN", "maxSpeedMps", "maxSpeedNearHumansMps"] {
match obj.get(name) {
Some(Value::Bool(_)) | None => {
return Err(CoreError::Json(format!("motionDigest.{name} is required")))
}
Some(v) => {
let n = rv::finite_number(Some(v)).ok_or_else(|| {
CoreError::Json(format!("motionDigest.{name} must be a finite number"))
})?;
if n < 0.0 {
return Err(CoreError::Json(format!(
"motionDigest.{name} must be non-negative"
)));
}
}
}
}
let within = match obj.get("withinEnvelope") {
Some(Value::Bool(b)) => *b,
Some(_) => {
return Err(CoreError::Json(
"motionDigest.withinEnvelope must be a boolean".into(),
))
}
None => {
return Err(CoreError::Json(
"motionDigest.withinEnvelope is required".into(),
))
}
};
let n = |k: &str| obj.get(k).and_then(|v| v.as_u64()).unwrap_or(0);
if within != (n("breachCount") == 0) {
return Err(CoreError::Json(
"motionDigest.withinEnvelope disagrees with breachCount".into(),
));
}
if n("zoneBreaches") > n("breachCount") {
return Err(CoreError::Json(
"motionDigest.zoneBreaches exceeds breachCount".into(),
));
}
Ok(())
}
/// The longest heartbeat cadence a verifier accepts from the heartbeat itself.
pub const MAX_INTERVAL_SECONDS: i64 = 3600;
/// Parameters for [`build_robot_heartbeat`]. The robot self-issues the credential
/// with its own Ed25519 seed; `motion_digest` is produced by a [`MotionCollector`]
/// over the interval and `interval_seconds` is the declared heartbeat cadence.
#[derive(Debug, Clone)]
pub struct BuildRobotHeartbeat {
pub robot_did: String,
pub session_id: String,
pub interval_index: i64,
pub interval_seconds: i64,
pub motion_digest: Value,
pub valid_from: String,
}
/// Build a signed `RobotHeartbeatCredential`.
pub fn build_robot_heartbeat(robot_seed: &[u8], params: &BuildRobotHeartbeat) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
if params.interval_index < 0 {
return Err(CoreError::Json(
"interval_index must be non-negative".into(),
));
}
if params.interval_seconds <= 0 {
return Err(CoreError::Json("interval_seconds must be positive".into()));
}
validate_motion_digest(¶ms.motion_digest)?;
let mut subject = Map::new();
subject.insert("id".into(), json!(params.robot_did));
subject.insert("sessionId".into(), json!(params.session_id));
subject.insert("intervalIndex".into(), json!(params.interval_index));
subject.insert("intervalSeconds".into(), json!(params.interval_seconds));
subject.insert("motionDigest".into(), params.motion_digest.clone());
let mut cred = Map::new();
cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
cred.insert(
"type".into(),
json!(["VerifiableCredential", ROBOT_HEARTBEAT_TYPE]),
);
cred.insert("issuer".into(), json!(params.robot_did));
cred.insert("validFrom".into(), json!(params.valid_from));
cred.insert("credentialSubject".into(), Value::Object(subject));
let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), ¶ms.valid_from);
data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
}
/// Verify a `RobotHeartbeatCredential`: the credential proof bound to the robot
/// as issuer (which must also be `credentialSubject.id`), a validFrom no later
/// than `now_iso`, and the structural validity of the embedded motion digest. Returns the subject on
/// success. Whether the robot is currently trusted is a separate, time-dependent
/// question answered by [`is_live`].
pub fn verify_robot_heartbeat(
credential: &Value,
robot_keys: Keys<'_>,
now_iso: &str,
) -> Result<Option<Value>> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
let v = match bound(
credential,
robot_keys,
ROBOT_HEARTBEAT_TYPE,
now_iso,
Window::FromRequired,
)? {
Some(v) if issuer_is_subject(&v) => v,
_ => return Ok(None),
};
let digest = v
.subject
.get("motionDigest")
.cloned()
.unwrap_or(Value::Null);
if validate_motion_digest(&digest).is_err() {
return Ok(None);
}
Ok(Some(v.subject))
}
/// Decide whether a robot is currently trusted, given its most recent heartbeat
/// (verify it with [`verify_robot_heartbeat`] first). Live only when: the
/// heartbeat was issued within `grace_intervals` cadence periods of `now_iso`
/// (the cadence is the verifier's `interval_seconds` when given, else the
/// heartbeat's declared interval capped at [`MAX_INTERVAL_SECONDS`]); the
/// motion digest covers at least one sample; and the digest is well-formed and
/// reports withinEnvelope true. Malformed input returns `false`.
pub fn is_live(
credential: &Value,
now_iso: &str,
interval_seconds: Option<i64>,
grace_intervals: i64,
) -> Result<bool> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
is_live_capped(
credential,
now_iso,
interval_seconds,
grace_intervals,
MAX_INTERVAL_SECONDS,
)
}
/// [`is_live`] with the caller's cap on a declared cadence instead of
/// [`MAX_INTERVAL_SECONDS`].
pub fn is_live_capped(
credential: &Value,
now_iso: &str,
interval_seconds: Option<i64>,
grace_intervals: i64,
max_interval_seconds: i64,
) -> Result<bool> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
if max_interval_seconds < 1 {
return Err(CoreError::Json(
"max_interval_seconds must be at least 1".into(),
));
}
if grace_intervals < 1 {
return Err(CoreError::Json("grace_intervals must be at least 1".into()));
}
let subject = match credential
.get("credentialSubject")
.and_then(|s| s.as_object())
{
Some(s) => s,
None => return Ok(false),
};
let digest = match subject.get("motionDigest") {
Some(d) if validate_motion_digest(d).is_ok() => d,
_ => return Ok(false),
};
if digest.get("samples").and_then(|v| v.as_u64()).unwrap_or(0) == 0
|| digest.get("withinEnvelope") != Some(&Value::Bool(true))
{
return Ok(false);
}
let cadence = match interval_seconds {
Some(c) => c,
None => match rv::strict_int(subject.get("intervalSeconds")) {
Some(d) if d > 0 => d.min(max_interval_seconds),
_ => return Ok(false),
},
};
if cadence <= 0 {
return Ok(false);
}
let issued = match rv::time_ns(credential.get("validFrom")) {
Some(t) => t,
None => return Ok(false),
};
let moment = match crate::time::parse_protocol_time_ns(now_iso) {
Ok(t) => t,
Err(_) => return Ok(false),
};
let cadence_ns = i128::from(cadence) * 1_000_000_000;
// A heartbeat from the future (clock skew beyond one cadence) is not trusted.
if moment + cadence_ns < issued {
return Ok(false);
}
Ok(moment <= issued + cadence_ns * i128::from(grace_intervals))
}
// ---------------------------------------------------------------------------
// Per-credential revocation (Phase 5.8)
// ---------------------------------------------------------------------------
pub use crate::status_list::{BITSTRING_STATUS_LIST_ENTRY_TYPE, STATUS_PURPOSE_REVOCATION};
/// Build a BitstringStatusList `credentialStatus` entry referencing a bit index in
/// a published status list credential. Mirrors the agent-side
/// `status_list.build_status_list_entry`. `entry_id`, when `None`, defaults to
/// `{status_list_credential}#{status_list_index}`.
pub fn build_status_list_entry(
status_list_credential: &str,
status_list_index: i64,
status_purpose: &str,
entry_id: Option<&str>,
) -> Result<Value> {
if !matches!(status_purpose, "revocation" | "suspension" | "message") {
return Err(CoreError::Json(format!(
"status_purpose must be one of revocation, suspension, message, got {status_purpose:?}"
)));
}
if status_list_index < 0 {
return Err(CoreError::Json(
"status_list_index must be non-negative".into(),
));
}
if status_list_credential.is_empty() {
return Err(CoreError::Json(
"status_list_credential URL is required".into(),
));
}
let id = entry_id
.map(String::from)
.unwrap_or_else(|| format!("{status_list_credential}#{status_list_index}"));
Ok(json!({
"id": id,
"type": BITSTRING_STATUS_LIST_ENTRY_TYPE,
"statusPurpose": status_purpose,
"statusListIndex": status_list_index.to_string(),
"statusListCredential": status_list_credential,
}))
}
/// Parameters for [`attach_credential_status`].
#[derive(Debug, Clone)]
pub struct AttachCredentialStatus {
pub status_list_credential: String,
pub status_list_index: i64,
pub status_purpose: String,
pub entry_id: Option<String>,
/// `validFrom`-style timestamp used as the proof `created` when re-signing.
pub created: String,
}
/// Add a BitstringStatusList `credentialStatus` entry to a robot credential and
/// re-sign it under `signer_seed`, so the proof covers the status binding. If the
/// credential already carries a `credentialStatus`, the new entry is appended (the
/// field becomes a list), matching the Verifiable Credentials data model. Any
/// pre-existing proof is replaced.
pub fn attach_credential_status(
credential: &Value,
signer_seed: &[u8],
params: &AttachCredentialStatus,
) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
let entry = build_status_list_entry(
¶ms.status_list_credential,
params.status_list_index,
¶ms.status_purpose,
params.entry_id.as_deref(),
)?;
let mut obj = credential
.as_object()
.ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
.clone();
match obj.get("credentialStatus").cloned() {
None => {
obj.insert("credentialStatus".into(), entry);
}
Some(Value::Array(mut existing)) => {
existing.push(entry);
obj.insert("credentialStatus".into(), Value::Array(existing));
}
Some(existing) => {
obj.insert("credentialStatus".into(), json!([existing, entry]));
}
}
// Re-sign: the proof must cover the credentialStatus we just added.
obj.remove("proof");
let issuer = obj.get("issuer").and_then(|v| v.as_str()).unwrap_or("");
let opts = BuildProofOptions::new(format!("{issuer}#key-1"), ¶ms.created);
data_integrity::sign(&Value::Object(obj), signer_seed, &opts)
}
fn status_entries(credential: &Value) -> Result<Vec<Value>> {
match credential.get("credentialStatus") {
None => Ok(Vec::new()),
Some(Value::Array(a)) => Ok(a.iter().filter(|e| e.is_object()).cloned().collect()),
Some(v) if v.is_object() => Ok(vec![v.clone()]),
Some(_) => Err(CoreError::Json(
"credentialStatus must be an object or a list of objects".into(),
)),
}
}
/// Return `true` if the robot credential's status bit for `status_purpose` is
/// set in the supplied status list. Returns `false` only when the credential
/// carries no status entry for that purpose, or every entry for that purpose
/// that references this list has its bit clear (every matching entry is
/// checked). Errors when the credential has an entry for this purpose but none
/// references the supplied list (the list cannot answer), or when the list's
/// issuer is not the credential's issuer. The caller verifies the list's proof
/// first.
pub fn check_credential_status(
credential: &Value,
status_list_credential: &Value,
status_purpose: &str,
) -> Result<bool> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, status_list_credential);
check_status_inner(credential, status_list_credential, status_purpose, None)
}
/// [`check_credential_status`], and the status list's own signature must
/// verify: issued by the issuer it names, under that issuer's key from `keys`
/// (see [`crate::robotics_dtn::verify_status_list_signature`]), checked at
/// `now_iso` with 30 s of skew. A list whose signature fails is an error.
pub fn check_credential_status_signed(
credential: &Value,
status_list_credential: &Value,
status_purpose: &str,
keys: Keys<'_>,
now_iso: &str,
) -> Result<bool> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, status_list_credential);
check_status_inner(
credential,
status_list_credential,
status_purpose,
Some((keys, now_iso)),
)
}
fn check_status_inner(
credential: &Value,
status_list_credential: &Value,
status_purpose: &str,
signed_by: Option<(Keys<'_>, &str)>,
) -> Result<bool> {
let entries: Vec<Value> = status_entries(credential)?
.into_iter()
.filter(|e| e.get("statusPurpose").and_then(|v| v.as_str()) == Some(status_purpose))
.collect();
if entries.is_empty() {
return Ok(false);
}
let referenced_id = status_list_credential.get("id");
let matching: Vec<&Value> = entries
.iter()
.filter(|e| e.get("statusListCredential") == referenced_id)
.collect();
if matching.is_empty() {
return Err(CoreError::Json(
"the credential has a status entry for this purpose, but none references this list"
.into(),
));
}
if rv::issuer_id(status_list_credential.get("issuer"))
!= rv::issuer_id(credential.get("issuer"))
{
return Err(CoreError::Json(
"the status list is not from the credential's issuer".into(),
));
}
if let Some((keys, now_iso)) = signed_by {
if !crate::robotics_dtn::verify_status_list_signature(
status_list_credential,
keys,
now_iso,
30,
)? {
return Err(CoreError::Json(
"the status list signature does not verify".into(),
));
}
}
for entry in matching {
if crate::status_list::verify_status(entry, status_list_credential)? {
return Ok(true);
}
}
Ok(false)
}
// ---------------------------------------------------------------------------
// Accountable safety record (Phase 5.9)
// ---------------------------------------------------------------------------
pub const SAFETY_RECORD_TYPE: &str = "RobotSafetyRecordCredential";
pub const SAFETY_LOG_VERSION: &str = "1.0";
/// Standard safety event types: the interoperable set a verifier and an insurer
/// can rely on. Implementers MAY use additional types.
pub const EVENT_TYPES: [&str; 6] = [
"incident",
"near_miss",
"manual_override",
"kill_switch",
"envelope_breach",
"maintenance",
];
/// Severity bands, ordered from least to most serious.
pub const SEVERITIES: [&str; 5] = ["info", "low", "medium", "high", "critical"];
/// Append-only, plaintext, hash-linked safety event ledger. Reuses the black-box
/// chain semantics ([`entry_hash`], [`genesis_prev_hash`]) so the two logs verify
/// the same way, but entries are plaintext: a safety record is meant to be read
/// and trusted by third parties.
pub struct SafetyEventLog {
genesis: String,
entries: Vec<Value>,
head: String,
seq_base: u64,
}
impl SafetyEventLog {
/// Build a log. A `None` genesis uses [`genesis_prev_hash`].
pub fn new(genesis_prev_hash_override: Option<&str>) -> Self {
let genesis = genesis_prev_hash_override
.map(String::from)
.unwrap_or_else(genesis_prev_hash);
Self {
head: genesis.clone(),
genesis,
entries: Vec::new(),
seq_base: 0,
}
}
/// Continue a log whose head is `prev_hash` and whose next entry is
/// number `next_seq` (a host that keeps the log itself appends one entry
/// at a time this way).
pub fn resume(prev_hash: &str, next_seq: u64) -> Self {
let mut log = Self::new(Some(prev_hash));
log.seq_base = next_seq;
log
}
/// Append one safety event, link it to the chain head, and return the entry.
pub fn append(
&mut self,
event_type: &str,
severity: &str,
details: Option<&Value>,
actor: Option<&str>,
timestamp: &str,
) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); details);
if !EVENT_TYPES.contains(&event_type) {
return Err(CoreError::Json(format!(
"event_type must be one of {EVENT_TYPES:?}, got {event_type:?}"
)));
}
if !SEVERITIES.contains(&severity) {
return Err(CoreError::Json(format!(
"severity must be one of {SEVERITIES:?}, got {severity:?}"
)));
}
let mut body = Map::new();
body.insert("version".into(), json!(SAFETY_LOG_VERSION));
body.insert(
"seq".into(),
json!(self.seq_base + self.entries.len() as u64),
);
body.insert("timestamp".into(), json!(timestamp));
body.insert("eventType".into(), json!(event_type));
body.insert("severity".into(), json!(severity));
body.insert("prevHash".into(), json!(self.head));
if let Some(d) = details {
body.insert("details".into(), d.clone());
}
if let Some(a) = actor {
body.insert("actor".into(), json!(a));
}
let h = entry_hash(&body)?;
body.insert("entryHash".into(), json!(h));
self.head = h;
let entry = Value::Object(body);
self.entries.push(entry.clone());
Ok(entry)
}
pub fn head(&self) -> &str {
&self.head
}
pub fn genesis(&self) -> &str {
&self.genesis
}
pub fn entries(&self) -> &[Value] {
&self.entries
}
/// Produce a summary object for embedding in a safety-record credential.
pub fn summarize(&self) -> Value {
summarize_entries(&self.entries, Some(&self.head))
}
}
/// Verify the hash chain over the ledger entries. Tamper-evident. Shares the
/// black-box chain verifier so the two logs verify identically.
pub fn verify_safety_log(
entries: &[Value],
genesis_prev_hash_override: Option<&str>,
) -> ChainResult {
crate::nesting::deep_guard!(ChainResult { ok: false, reason: Some(crate::nesting::TOO_DEEP.into()) }; entries);
verify_blackbox_chain(entries, genesis_prev_hash_override)
}
/// Summarize ledger entries into counts by event type (sorted) and by severity
/// (info..critical), the total event count, and (when supplied) the ledger head
/// hash that anchors the summary to a specific chain state.
pub fn summarize_entries(entries: &[Value], head: Option<&str>) -> Value {
crate::nesting::deep_guard!(Value::Null; entries);
let mut sorted_types: Vec<&str> = EVENT_TYPES.to_vec();
sorted_types.sort_unstable();
let mut event_counts = Map::new();
for t in &sorted_types {
event_counts.insert((*t).to_string(), json!(0));
}
let mut severity_counts = Map::new();
for s in SEVERITIES {
severity_counts.insert(s.to_string(), json!(0));
}
for e in entries {
if let Some(et) = e.get("eventType").and_then(|v| v.as_str()) {
if let Some(c) = event_counts.get_mut(et).and_then(|v| v.as_u64()) {
event_counts.insert(et.to_string(), json!(c + 1));
}
}
if let Some(sv) = e.get("severity").and_then(|v| v.as_str()) {
if let Some(c) = severity_counts.get_mut(sv).and_then(|v| v.as_u64()) {
severity_counts.insert(sv.to_string(), json!(c + 1));
}
}
}
let mut summary = Map::new();
summary.insert("eventCounts".into(), Value::Object(event_counts));
summary.insert("severityCounts".into(), Value::Object(severity_counts));
summary.insert("totalEvents".into(), json!(entries.len() as u64));
if let Some(h) = head {
summary.insert("logHead".into(), json!(h));
}
Value::Object(summary)
}
/// Structural validation of a safety summary.
pub fn validate_safety_summary(summary: &Value) -> Result<()> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); summary);
let obj = summary
.as_object()
.ok_or_else(|| CoreError::Json("summary must be an object".into()))?;
for name in ["eventCounts", "severityCounts"] {
let block = obj
.get(name)
.and_then(|v| v.as_object())
.ok_or_else(|| CoreError::Json(format!("summary.{name} must be an object")))?;
for (k, v) in block {
let ok = v.is_u64() || v.as_i64().map(|i| i >= 0).unwrap_or(false);
if v.is_boolean() || !ok {
return Err(CoreError::Json(format!(
"summary.{name}[{k:?}] must be a non-negative integer"
)));
}
}
}
let total_ok = obj
.get("totalEvents")
.map(|v| (v.is_u64() || v.as_i64().map(|i| i >= 0).unwrap_or(false)) && !v.is_boolean())
.unwrap_or(false);
if !total_ok {
return Err(CoreError::Json(
"summary.totalEvents must be a non-negative integer".into(),
));
}
Ok(())
}
/// Parameters for [`build_safety_record`]. The issuer (an owner, an auditor, or
/// the robot itself) attests `summary`, produced by [`SafetyEventLog::summarize`]
/// or [`summarize_entries`].
#[derive(Debug, Clone)]
pub struct BuildSafetyRecord {
pub issuer_did: String,
pub robot_did: String,
pub summary: Value,
pub period_start: Option<String>,
pub period_end: Option<String>,
pub valid_from: String,
pub valid_until: Option<String>,
}
/// Build a signed `RobotSafetyRecordCredential` summarizing a robot's safety
/// ledger.
pub fn build_safety_record(signer_seed: &[u8], params: &BuildSafetyRecord) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
validate_safety_summary(¶ms.summary)?;
let mut subject = Map::new();
subject.insert("id".into(), json!(params.robot_did));
if let Some(s) = params.summary.as_object() {
for (k, v) in s {
subject.insert(k.clone(), v.clone());
}
}
if params.period_start.is_some() || params.period_end.is_some() {
let mut period = Map::new();
if let Some(start) = ¶ms.period_start {
period.insert("start".into(), json!(start));
}
if let Some(end) = ¶ms.period_end {
period.insert("end".into(), json!(end));
}
subject.insert("period".into(), Value::Object(period));
}
let mut cred = Map::new();
cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
cred.insert(
"type".into(),
json!(["VerifiableCredential", SAFETY_RECORD_TYPE]),
);
cred.insert("issuer".into(), json!(params.issuer_did));
cred.insert("validFrom".into(), json!(params.valid_from));
if let Some(vu) = ¶ms.valid_until {
cred.insert("validUntil".into(), json!(vu));
}
cred.insert("credentialSubject".into(), Value::Object(subject));
let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), ¶ms.valid_from);
data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
}
/// Options for [`verify_safety_record`].
#[derive(Default, Clone, Copy)]
pub struct SafetyRecordCheck<'a> {
/// The ledger entries: they must link, end at the summary's `logHead` with
/// exactly `totalEvents` entries, and reproduce the summary's counts.
pub entries: Option<&'a [Value]>,
/// The record must be about this robot.
pub robot_did: Option<&'a str>,
/// The issuer must be in this set.
pub trusted_issuers: Option<&'a HashSet<String>>,
}
/// Verify a `RobotSafetyRecordCredential`: the issuer's proof bound to the
/// issuer, the validity window at `now_iso` (validFrom required), and the
/// structure of the embedded summary, plus the [`SafetyRecordCheck`] options.
/// Returns the credentialSubject on success.
pub fn verify_safety_record(
credential: &Value,
keys: Keys<'_>,
check: SafetyRecordCheck<'_>,
now_iso: &str,
) -> Result<Option<Value>> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, check);
let now = rv::require_now(now_iso)?;
let opts = VerifyOptions {
trusted_issuers: check.trusted_issuers,
..VerifyOptions::window(Window::FromRequired)
};
let v =
match rv::verify_robotics_credential(credential, keys, Some(SAFETY_RECORD_TYPE), now, opts)
{
Ok(v) => v,
Err(_) => return Ok(None),
};
let subject = v.subject;
if validate_safety_summary(&subject).is_err() {
return Ok(None);
}
if let Some(robot) = check.robot_did {
if subject.get("id").and_then(|x| x.as_str()) != Some(robot) {
return Ok(None);
}
}
if let Some(entries) = check.entries {
if !verify_chain_against_head(
entries,
subject.get("logHead"),
subject.get("totalEvents"),
None,
)
.ok
{
return Ok(None);
}
let recount = summarize_entries(entries, None);
if recount.get("eventCounts") != subject.get("eventCounts")
|| recount.get("severityCounts") != subject.get("severityCounts")
{
return Ok(None);
}
}
Ok(Some(subject))
}
// ---------------------------------------------------------------------------
// Perception provenance (Phase 5.10)
// ---------------------------------------------------------------------------
pub const PERCEPTION_TYPE: &str = "PerceptionProvenanceCredential";
pub const PERCEPTION_LOG_VERSION: &str = "1.0";
/// Standard sensor modalities: the interoperable set a verifier can rely on.
/// Implementers MAY use additional values.
pub const MODALITIES: [&str; 6] = ["camera", "lidar", "radar", "depth", "audio", "thermal"];
/// Multibase (base64url) SHA-256 of a raw sensor frame. Only the hash travels in
/// the log and the attestation; the frame stays wherever the deployment keeps it.
pub fn hash_frame(frame: &[u8]) -> String {
mb64(&Sha256::digest(frame))
}
/// Append-only, plaintext, hash-linked log of sensor-frame provenance records.
/// Reuses the black-box chain semantics ([`entry_hash`], [`genesis_prev_hash`]),
/// so a perception log verifies the same way as the safety ledger. Each entry
/// binds a sequence number, a timestamp, the sensor id, the modality, the frame
/// hash, and the hash of the previous entry; the frames are not stored.
pub struct PerceptionLog {
genesis: String,
entries: Vec<Value>,
head: String,
seq_base: u64,
}
impl PerceptionLog {
/// Build a log. A `None` genesis uses [`genesis_prev_hash`].
pub fn new(genesis_prev_hash_override: Option<&str>) -> Self {
let genesis = genesis_prev_hash_override
.map(String::from)
.unwrap_or_else(genesis_prev_hash);
Self {
head: genesis.clone(),
genesis,
entries: Vec::new(),
seq_base: 0,
}
}
/// Continue a log whose head is `prev_hash` and whose next entry is
/// number `next_seq`.
pub fn resume(prev_hash: &str, next_seq: u64) -> Self {
let mut log = Self::new(Some(prev_hash));
log.seq_base = next_seq;
log
}
/// Append one frame-provenance record, link it to the chain head, and return
/// the entry. Provide either the raw `frame` (it is hashed) or a precomputed
/// `frame_hash`, not both.
pub fn record(
&mut self,
sensor_id: &str,
modality: &str,
frame: Option<&[u8]>,
frame_hash: Option<&str>,
timestamp: &str,
) -> Result<Value> {
if !MODALITIES.contains(&modality) {
return Err(CoreError::Json(format!(
"modality must be one of {MODALITIES:?}, got {modality:?}"
)));
}
if sensor_id.is_empty() {
return Err(CoreError::Json("sensor_id is required".into()));
}
if frame.is_some() && frame_hash.is_some() {
return Err(CoreError::Json(
"provide either frame or frame_hash, not both".into(),
));
}
let resolved = match (frame, frame_hash) {
(Some(f), None) => hash_frame(f),
(None, Some(h)) if !h.is_empty() => h.to_string(),
_ => return Err(CoreError::Json("frame or frame_hash is required".into())),
};
let mut body = Map::new();
body.insert("version".into(), json!(PERCEPTION_LOG_VERSION));
body.insert(
"seq".into(),
json!(self.seq_base + self.entries.len() as u64),
);
body.insert("timestamp".into(), json!(timestamp));
body.insert("sensorId".into(), json!(sensor_id));
body.insert("modality".into(), json!(modality));
body.insert("frameHash".into(), json!(resolved));
body.insert("prevHash".into(), json!(self.head));
let h = entry_hash(&body)?;
body.insert("entryHash".into(), json!(h));
self.head = h;
let entry = Value::Object(body);
self.entries.push(entry.clone());
Ok(entry)
}
pub fn head(&self) -> &str {
&self.head
}
pub fn genesis(&self) -> &str {
&self.genesis
}
pub fn entries(&self) -> &[Value] {
&self.entries
}
/// The number of records, the count a perception attestation anchors.
pub fn count(&self) -> usize {
self.entries.len()
}
}
/// Verify the hash chain over the perception log entries. Tamper-evident. Shares
/// the black-box chain verifier so every hash-linked log verifies identically.
pub fn verify_perception_log(
entries: &[Value],
genesis_prev_hash_override: Option<&str>,
) -> ChainResult {
crate::nesting::deep_guard!(ChainResult { ok: false, reason: Some(crate::nesting::TOO_DEEP.into()) }; entries);
verify_blackbox_chain(entries, genesis_prev_hash_override)
}
/// Parameters for [`build_perception_attestation`]. The robot self-issues the
/// credential with its own Ed25519 seed. `captured_at`, when `None`, defaults to
/// `valid_from`. When `log_head` is supplied, the attestation also anchors the
/// segment of frames up to that chain head.
#[derive(Debug, Clone)]
pub struct BuildPerception {
pub robot_did: String,
pub sensor_id: String,
pub modality: String,
pub frame_hash: String,
pub captured_at: Option<String>,
pub log_head: Option<String>,
/// The number of log entries up to `log_head`, so a verifier can tell a
/// segment was not cut short.
pub log_count: Option<u64>,
pub valid_from: String,
pub valid_until: Option<String>,
}
/// Build a signed `PerceptionProvenanceCredential` attesting that a robot's sensor
/// captured a specific frame. Software frame-hash signing: the robot signs the
/// provenance of the captured frame with its own key.
pub fn build_perception_attestation(robot_seed: &[u8], params: &BuildPerception) -> Result<Value> {
if !MODALITIES.contains(¶ms.modality.as_str()) {
return Err(CoreError::Json(format!(
"modality must be one of {MODALITIES:?}, got {:?}",
params.modality
)));
}
if params.frame_hash.is_empty() {
return Err(CoreError::Json("frame_hash is required".into()));
}
let captured = params
.captured_at
.clone()
.unwrap_or_else(|| params.valid_from.clone());
let mut subject = Map::new();
subject.insert("id".into(), json!(params.robot_did));
subject.insert("sensorId".into(), json!(params.sensor_id));
subject.insert("modality".into(), json!(params.modality));
subject.insert("frameHash".into(), json!(params.frame_hash));
subject.insert("capturedAt".into(), json!(captured));
if let Some(head) = ¶ms.log_head {
subject.insert("logHead".into(), json!(head));
}
if let Some(n) = params.log_count {
subject.insert("logCount".into(), json!(n));
}
let mut cred = Map::new();
cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
cred.insert(
"type".into(),
json!(["VerifiableCredential", PERCEPTION_TYPE]),
);
cred.insert("issuer".into(), json!(params.robot_did));
cred.insert("validFrom".into(), json!(params.valid_from));
if let Some(vu) = ¶ms.valid_until {
cred.insert("validUntil".into(), json!(vu));
}
cred.insert("credentialSubject".into(), Value::Object(subject));
let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), ¶ms.valid_from);
data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
}
/// Verify a `PerceptionProvenanceCredential`: the robot's proof and, when the raw
/// `frame` is supplied, that its hash reproduces the attested `frameHash`. Returns
/// the credentialSubject on success, `None` if invalid.
pub fn verify_perception_attestation(
credential: &Value,
keys: Keys<'_>,
frame: Option<&[u8]>,
now_iso: &str,
) -> Result<Option<Value>> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
let v = match bound(
credential,
keys,
PERCEPTION_TYPE,
now_iso,
Window::FromRequired,
)? {
Some(v) if issuer_is_subject(&v) => v,
_ => return Ok(None),
};
let frame_hash = v.subject.get("frameHash").and_then(|v| v.as_str());
let modality = v.subject.get("modality").and_then(|v| v.as_str());
match (frame_hash, modality) {
(Some(fh), Some(m)) if !fh.is_empty() && MODALITIES.contains(&m) => {}
_ => return Ok(None),
}
if let Some(f) = frame {
if hash_frame(f) != frame_hash.unwrap_or("") {
return Ok(None);
}
}
Ok(Some(v.subject))
}
/// Verify a perception log against the robot's signed head: the attestation
/// must verify and carry `logHead` and `logCount`, and the log must link and
/// end at that head with exactly that many entries.
pub fn verify_perception_segment(
entries: &[Value],
attestation: &Value,
keys: Keys<'_>,
genesis_prev_hash_override: Option<&str>,
now_iso: &str,
) -> Result<ChainResult> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); entries, attestation);
let subject = match verify_perception_attestation(attestation, keys, None, now_iso)? {
Some(s) => s,
None => {
return Ok(ChainResult {
ok: false,
reason: Some("attestation does not verify".into()),
})
}
};
if subject.get("logHead").is_none() || subject.get("logCount").is_none() {
return Ok(ChainResult {
ok: false,
reason: Some("attestation does not anchor a log head and count".into()),
});
}
Ok(verify_chain_against_head(
entries,
subject.get("logHead"),
subject.get("logCount"),
genesis_prev_hash_override,
))
}
// ---------------------------------------------------------------------------
// Delegation lease (Phase 5.11)
// ---------------------------------------------------------------------------
pub const DELEGATION_LEASE_TYPE: &str = "DelegationLeaseCredential";
/// Parameters for [`build_delegation_lease`]. The issuer is the signer (an
/// authority or the holder of a parent lease); `robot_did` is the subject the
/// lease is granted to. `scope` is a physicalScope object (the same shape as a
/// `PhysicalCapabilityScope` credentialSubject.physicalScope). Leases are
/// short-lived by design, so the window is bounded by `valid_from`/`valid_until`.
/// Set `parent_lease_id` when sub-granting from another lease.
#[derive(Debug, Clone)]
pub struct BuildDelegationLease {
pub issuer_did: String,
pub robot_did: String,
pub lease_id: String,
pub scope: Value,
pub parent_lease_id: Option<String>,
pub valid_from: String,
pub valid_until: String,
}
/// Build a signed `DelegationLeaseCredential` granting `robot_did` a bounded
/// physical scope for a fixed window. The window is verifiable entirely offline.
pub fn build_delegation_lease(signer_seed: &[u8], params: &BuildDelegationLease) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
if params.lease_id.is_empty() {
return Err(CoreError::Json("lease_id is required".into()));
}
if !params.scope.is_object() {
return Err(CoreError::Json(
"scope must be a physicalScope object".into(),
));
}
let mut subject = Map::new();
subject.insert("id".into(), json!(params.robot_did));
subject.insert("leaseId".into(), json!(params.lease_id));
subject.insert("physicalScope".into(), params.scope.clone());
if let Some(parent) = ¶ms.parent_lease_id {
subject.insert("parentLeaseId".into(), json!(parent));
}
let mut cred = Map::new();
cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
cred.insert(
"type".into(),
json!(["VerifiableCredential", DELEGATION_LEASE_TYPE]),
);
cred.insert("issuer".into(), json!(params.issuer_did));
cred.insert("validFrom".into(), json!(params.valid_from));
cred.insert("validUntil".into(), json!(params.valid_until));
cred.insert("credentialSubject".into(), Value::Object(subject));
let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), ¶ms.valid_from);
data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
}
/// Verify a `DelegationLeaseCredential` offline: the issuer's proof bound to the
/// issuer (`keys` is a `{did: key}` source, or the bare key of a did:key
/// issuer), validFrom and validUntil both present with `now_iso` inside, the
/// lease is for `expected_robot` (required), it carries a `leaseId` and a
/// well-formed scope, the issuer is in `trusted_issuers` when given, and (when
/// `parent_scope` is supplied) the scope attenuates the parent. Returns the
/// credentialSubject on success, `None` if invalid.
pub fn verify_delegation_lease(
credential: &Value,
keys: Keys<'_>,
expected_robot: &str,
parent_scope: Option<&Value>,
trusted_issuers: Option<&HashSet<String>>,
now_iso: &str,
) -> Result<Option<Value>> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, parent_scope);
if expected_robot.is_empty() {
return Err(CoreError::Json("expected_robot is required".into()));
}
let now = rv::require_now(now_iso)?;
let opts = VerifyOptions {
trusted_issuers,
..VerifyOptions::window(Window::Required)
};
let v = match rv::verify_robotics_credential(
credential,
keys,
Some(DELEGATION_LEASE_TYPE),
now,
opts,
) {
Ok(v) => v,
Err(_) => return Ok(None),
};
if v.subject.get("id").and_then(|x| x.as_str()) != Some(expected_robot)
|| non_empty_str(&v.subject, "leaseId").is_none()
{
return Ok(None);
}
let scope = match v.subject.get("physicalScope") {
Some(sc) if sc.is_object() && scope_problems(sc).is_empty() => sc,
_ => return Ok(None),
};
if parent_scope.is_some_and(|p| !attenuates(p, scope)) {
return Ok(None);
}
Ok(Some(v.subject))
}
/// Verify a chain of leases from a trusted root down to `expected_robot`
/// (`leases` runs root to leaf). The root is issued by one of `root_issuers`
/// and has no `parentLeaseId`; each later lease names the previous `leaseId`
/// as its `parentLeaseId`, is issued by the party the previous lease was
/// granted to, has a window inside the previous window, and attenuates the
/// previous scope. Every lease is current at `now_iso`; the leaf is for
/// `expected_robot`. Returns the leaf subject on success.
pub fn verify_lease_chain(
leases: &[Value],
keys: Keys<'_>,
expected_robot: &str,
root_issuers: &HashSet<String>,
now_iso: &str,
) -> Result<Option<Value>> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); leases);
rv::require_now(now_iso)?;
if leases.is_empty() || root_issuers.is_empty() {
return Ok(None);
}
let mut prev: Option<(&Value, Value)> = None;
for (i, lease) in leases.iter().enumerate() {
let holder = lease
.get("credentialSubject")
.and_then(|s| s.get("id"))
.and_then(|v| v.as_str())
.unwrap_or("");
let target = if i + 1 == leases.len() {
expected_robot
} else {
holder
};
if target.is_empty() {
return Ok(None);
}
let parent_scope = prev.as_ref().and_then(|(_, ps)| ps.get("physicalScope"));
// The root must be one of `root_issuers`; each child must be issued by
// the holder the verified parent names. Both are named sets, so did:key
// parties verify under their own keys with no key source.
let holder_set: HashSet<String> = prev
.as_ref()
.and_then(|(_, ps)| ps.get("id"))
.and_then(|v| v.as_str())
.filter(|h| !h.is_empty())
.map(|h| [h.to_string()].into_iter().collect())
.unwrap_or_default();
let subject = match verify_delegation_lease(
lease,
keys,
target,
parent_scope,
Some(if prev.is_none() {
root_issuers
} else {
&holder_set
}),
now_iso,
)? {
Some(s) => s,
None => return Ok(None),
};
match &prev {
Some((p_lease, p_sub)) => {
if subject.get("parentLeaseId") != p_sub.get("leaseId") {
return Ok(None);
}
if rv::issuer_id(lease.get("issuer")) != p_sub.get("id").and_then(|v| v.as_str()) {
return Ok(None);
}
let t = |c: &Value, k: &str| rv::time_ns(c.get(k));
if t(lease, "validFrom") < t(p_lease, "validFrom")
|| t(lease, "validUntil") > t(p_lease, "validUntil")
{
return Ok(None);
}
}
None => {
if subject.get("parentLeaseId").is_some() {
return Ok(None);
}
}
}
prev = Some((lease, subject));
}
Ok(prev.map(|(_, s)| s))
}
/// Decide whether a verified lease permits a proposed physical action. The full
/// lease `credential` is required and is verified again here (`keys` and
/// `trusted_issuers` as in [`verify_delegation_lease`], with `subject.id` as the
/// expected robot), so its window is read from signed data: a copy with a
/// re-dated `validUntil` no longer verifies. Its subject must equal `subject`,
/// its window must contain `now_iso`, and the action must fit the scope.
pub fn lease_permits(
subject: &Value,
action: &PhysicalAction,
credential: Option<&Value>,
keys: Keys<'_>,
trusted_issuers: Option<&HashSet<String>>,
now_iso: &str,
) -> Result<bool> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); subject, credential);
let now = rv::require_now(now_iso)?;
let cred = match credential {
Some(c) if c.is_object() && subject.is_object() => c,
_ => return Ok(false),
};
let robot = match subject.get("id").and_then(|v| v.as_str()) {
Some(r) if !r.is_empty() => r,
_ => return Ok(false),
};
match verify_delegation_lease(cred, keys, robot, None, trusted_issuers, now_iso)? {
Some(v) if &v == subject => {}
_ => return Ok(false),
}
if rv::window_reason(cred, Window::Required, now, 0).is_some() {
return Ok(false);
}
match subject.get("physicalScope") {
Some(scope) if scope.is_object() => Ok(check_physical_action(scope, action).ok),
_ => Ok(false),
}
}
// ---------------------------------------------------------------------------
// Physical quorum (Phase 5.12)
// ---------------------------------------------------------------------------
pub const ACTION_APPROVAL_TYPE: &str = "PhysicalActionApprovalCredential";
pub const APPROVE: &str = "approve";
pub const REJECT: &str = "reject";
/// How long an approval lasts when its builder gives no end.
pub const DEFAULT_APPROVAL_SECONDS: i64 = 300;
/// The longest approval lifetime a verifier accepts.
pub const MAX_APPROVAL_SECONDS: i64 = 900;
/// Parameters for [`build_action_approval`]. The approver is the signer; the
/// approval is over a specific physical action `action_id` that `robot_did`
/// would perform. `decision` is "approve" or "reject".
#[derive(Debug, Clone)]
pub struct BuildActionApproval {
pub approver_did: String,
pub action_id: String,
pub robot_did: String,
pub decision: String,
pub valid_from: String,
pub valid_until: Option<String>,
}
/// Build a signed `PhysicalActionApprovalCredential` by one approver for a
/// specific physical action.
pub fn build_action_approval(approver_seed: &[u8], params: &BuildActionApproval) -> Result<Value> {
if params.decision != APPROVE && params.decision != REJECT {
return Err(CoreError::Json(format!(
"decision must be {APPROVE:?} or {REJECT:?}, got {:?}",
params.decision
)));
}
if params.action_id.is_empty() {
return Err(CoreError::Json("action_id is required".into()));
}
let mut subject = Map::new();
subject.insert("id".into(), json!(params.approver_did));
subject.insert("actionId".into(), json!(params.action_id));
subject.insert("robotDid".into(), json!(params.robot_did));
subject.insert("decision".into(), json!(params.decision));
let mut cred = Map::new();
cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
cred.insert(
"type".into(),
json!(["VerifiableCredential", ACTION_APPROVAL_TYPE]),
);
cred.insert("issuer".into(), json!(params.approver_did));
cred.insert("validFrom".into(), json!(params.valid_from));
// An approval is short-lived: without an explicit end it lasts
// DEFAULT_APPROVAL_SECONDS, and a verifier refuses one without validUntil.
let valid_until = match ¶ms.valid_until {
Some(vu) => vu.clone(),
None => crate::time::epoch_seconds_to_iso(
crate::time::iso_to_epoch_seconds(¶ms.valid_from)? + DEFAULT_APPROVAL_SECONDS,
),
};
cred.insert("validUntil".into(), json!(valid_until));
cred.insert("credentialSubject".into(), Value::Object(subject));
let opts = BuildProofOptions::new(format!("{}#key-1", params.approver_did), ¶ms.valid_from);
data_integrity::sign(&Value::Object(cred), approver_seed, &opts)
}
/// One approver's public key, looked up by issuer DID, for
/// [`verify_action_authorization`].
#[derive(Debug, Clone)]
pub struct ApproverKey {
pub did: String,
pub public_key: Vec<u8>,
}
/// Verify that a high-consequence physical action is authorized by a quorum.
///
/// Each approval must carry a proof bound to its issuer and verified with the
/// issuer's key from `approver_keys`, name the issuer as its subject, match
/// `action_id` and `robot_did`, and carry both validFrom and validUntil with
/// `now_iso` inside and a lifetime of at most [`MAX_APPROVAL_SECONDS`]. When
/// `approver_set` is supplied, the approver must be in it. Each approver's
/// latest decision counts (at the same instant a rejection wins); any latest
/// rejection vetoes the action. Otherwise it is authorized when at least
/// `threshold` approvers with DISTINCT signing keys approve: two DIDs mapped to
/// the same key count once. Returns `(authorized, sorted approving DIDs)`.
pub fn verify_action_authorization(
approvals: &[Value],
action_id: &str,
robot_did: &str,
approver_keys: &[ApproverKey],
threshold: i64,
approver_set: Option<&HashSet<String>>,
now_iso: &str,
) -> Result<(bool, Vec<String>)> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); approvals);
verify_action_authorization_with(
approvals,
action_id,
robot_did,
approver_keys,
threshold,
approver_set,
MAX_APPROVAL_SECONDS,
now_iso,
)
}
/// [`verify_action_authorization`] with the caller's longest approval
/// lifetime instead of [`MAX_APPROVAL_SECONDS`].
#[allow(clippy::too_many_arguments)]
pub fn verify_action_authorization_with(
approvals: &[Value],
action_id: &str,
robot_did: &str,
approver_keys: &[ApproverKey],
threshold: i64,
approver_set: Option<&HashSet<String>>,
max_approval_seconds: i64,
now_iso: &str,
) -> Result<(bool, Vec<String>)> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); approvals);
if max_approval_seconds < 1 {
return Err(CoreError::Json(
"max_approval_seconds must be at least 1".into(),
));
}
if threshold < 1 {
return Err(CoreError::Json("threshold must be at least 1".into()));
}
let now = rv::require_now(now_iso)?;
let map: alloc::collections::BTreeMap<String, Vec<u8>> =
Keys::map_of(approver_keys.iter().map(|k| (k.did.clone(), &k.public_key)));
let keys = Keys::Map(&map);
// The approver set is a named member set: with no key on file, its
// did:key members verify under their own keys. A freshly minted did:key
// is never an approver by itself.
let opts = VerifyOptions {
trusted_issuers: approver_set,
..VerifyOptions::window(Window::Required)
};
let mut latest: alloc::collections::BTreeMap<String, (i128, bool)> =
alloc::collections::BTreeMap::new();
for approval in approvals {
let mut early = false;
let v = match rv::verify_robotics_credential(
approval,
keys,
Some(ACTION_APPROVAL_TYPE),
now,
opts,
) {
Ok(v) if issuer_is_subject(&v) => v,
Err(why) if why == "credential window: not_yet_valid" => {
// A rejection dated slightly ahead of the verifier's clock
// still vetoes: re-check everything else at its own start. An
// early approval never counts.
let at = match rv::time_ns(approval.get("validFrom")) {
Some(t) => t,
None => continue,
};
match rv::verify_robotics_credential(
approval,
keys,
Some(ACTION_APPROVAL_TYPE),
at,
opts,
) {
Ok(v) if issuer_is_subject(&v) => {
early = true;
v
}
_ => continue,
}
}
_ => continue,
};
if v.subject.get("actionId").and_then(|x| x.as_str()) != Some(action_id)
|| v.subject.get("robotDid").and_then(|x| x.as_str()) != Some(robot_did)
{
continue;
}
let reject = match v.subject.get("decision").and_then(|x| x.as_str()) {
Some(APPROVE) => false,
Some(REJECT) => true,
_ => continue,
};
if early && !reject {
continue;
}
if let Some(set) = approver_set {
if !set.contains(&v.issuer) {
continue;
}
}
let (start, end) = match (
rv::time_ns(approval.get("validFrom")),
rv::time_ns(approval.get("validUntil")),
) {
(Some(a), Some(b)) => (a, b),
_ => continue,
};
if end - start > i128::from(max_approval_seconds) * 1_000_000_000 {
continue;
}
let newer = match latest.get(&v.issuer) {
None => true,
Some((t, _)) => start > *t || (start == *t && reject),
};
if newer {
latest.insert(v.issuer, (start, reject));
}
}
if latest.values().any(|(_, reject)| *reject) {
return Ok((false, Vec::new()));
}
let mut approvers: Vec<String> = Vec::new();
let mut seen: HashSet<Vec<u8>> = HashSet::new();
for issuer in latest.keys() {
let raw = match map.get(issuer) {
Some(k) => k.clone(),
None => match crate::keys::did_key_to_ed25519(issuer) {
Ok(k) if issuer.starts_with("did:key:") => k,
_ => continue,
},
};
if seen.insert(raw) {
approvers.push(issuer.clone());
}
}
approvers.sort();
Ok((approvers.len() as i64 >= threshold, approvers))
}
// ---------------------------------------------------------------------------
// Robot lifecycle: ownership transfer, key rotation, decommission (Phase 5.13)
// ---------------------------------------------------------------------------
pub const OWNERSHIP_TRANSFER_TYPE: &str = "RobotOwnershipTransferCredential";
pub const KEY_ROTATION_TYPE: &str = "RobotKeyRotationCredential";
pub const DECOMMISSION_TYPE: &str = "RobotDecommissionCredential";
/// Parameters for [`build_ownership_transfer`]. The signer is the current owner;
/// `from_owner` defaults to `issuer_did` (the current owner's DID). Setting
/// `prev_transfer_id` links this transfer to the previous one, forming a chain:
/// it must be the previous transfer's `id`. `credential_id` is this transfer's
/// own `id` (the caller supplies it; use a fresh `urn:uuid:`).
#[derive(Debug, Clone)]
pub struct BuildOwnershipTransfer {
pub issuer_did: String,
pub robot_did: String,
pub to_owner: String,
pub from_owner: Option<String>,
pub prev_transfer_id: Option<String>,
pub credential_id: String,
pub valid_from: String,
}
/// Build a signed transfer of `robot_did` from the current owner to `to_owner`.
/// The signer is the current owner; `from_owner` defaults to `issuer_did`.
pub fn build_ownership_transfer(
current_owner_seed: &[u8],
params: &BuildOwnershipTransfer,
) -> Result<Value> {
if params.robot_did.is_empty() || params.to_owner.is_empty() {
return Err(CoreError::Json(
"robot_did and to_owner are required".into(),
));
}
if params.credential_id.is_empty() {
return Err(CoreError::Json("credential_id is required".into()));
}
let seller = params
.from_owner
.clone()
.unwrap_or_else(|| params.issuer_did.clone());
let mut subject = Map::new();
subject.insert("id".into(), json!(params.robot_did));
subject.insert("fromOwner".into(), json!(seller));
subject.insert("toOwner".into(), json!(params.to_owner));
if let Some(prev) = ¶ms.prev_transfer_id {
subject.insert("prevTransferId".into(), json!(prev));
}
let mut cred = Map::new();
cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
cred.insert("id".into(), json!(params.credential_id));
cred.insert(
"type".into(),
json!(["VerifiableCredential", OWNERSHIP_TRANSFER_TYPE]),
);
cred.insert("issuer".into(), json!(params.issuer_did));
cred.insert("validFrom".into(), json!(params.valid_from));
cred.insert("credentialSubject".into(), Value::Object(subject));
let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), ¶ms.valid_from);
data_integrity::sign(&Value::Object(cred), current_owner_seed, &opts)
}
fn non_empty_str<'v>(v: &'v Value, key: &str) -> Option<&'v str> {
v.get(key)
.and_then(|x| x.as_str())
.filter(|s| !s.is_empty())
}
/// Verify a transfer: the current owner's proof bound to the issuer, the
/// issuer is the `fromOwner` (only the current owner can transfer the robot),
/// `toOwner` and the robot `id` are non-empty strings, validFrom no later than
/// `now_iso`, and (when given) the transfer is for `robot_did`. `owner_keys` is
/// a `{owner_did: key}` source (or the bare key of a did:key owner).
pub fn verify_ownership_transfer(
credential: &Value,
owner_keys: Keys<'_>,
robot_did: Option<&str>,
now_iso: &str,
) -> Result<Option<Value>> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
let v = match bound(
credential,
owner_keys,
OWNERSHIP_TRANSFER_TYPE,
now_iso,
Window::FromRequired,
)? {
Some(v) => v,
None => return Ok(None),
};
let ok = non_empty_str(&v.subject, "toOwner").is_some()
&& non_empty_str(&v.subject, "fromOwner") == Some(v.issuer.as_str())
&& non_empty_str(&v.subject, "id").is_some()
&& robot_did.is_none_or(|r| v.subject.get("id").and_then(|x| x.as_str()) == Some(r));
Ok(if ok { Some(v.subject) } else { None })
}
/// One owner's public key, looked up by owner DID, for [`verify_custody_chain`].
#[derive(Debug, Clone)]
pub struct OwnerKey {
pub did: String,
pub public_key: Vec<u8>,
}
/// Verify an ordered list of transfer credentials forms a valid chain of custody
/// for `robot_did`: every link verifies under the owner who signed it (keys
/// from `public_keys`), names the previous link's `id` as its
/// `prevTransferId`, is dated no earlier than the previous link, each
/// `toOwner` is the next link's `fromOwner`, and the first `fromOwner` is
/// `origin_owner`. Returns `(ok, current_owner)`.
///
/// `origin_owner` is required: with no known first owner, anyone could sign a
/// first transfer of any robot from themselves. Without it the chain is
/// refused. Each link's signer is pinned (the origin, then each `toOwner`), so
/// a did:key owner verifies under its own key even with no entry in
/// `public_keys`.
pub fn verify_custody_chain(
transfers: &[Value],
public_keys: &[OwnerKey],
robot_did: &str,
origin_owner: Option<&str>,
now_iso: &str,
) -> Result<(bool, Option<String>)> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); transfers);
rv::require_now(now_iso)?;
if robot_did.is_empty() || origin_owner.is_none_or(str::is_empty) {
return Ok((false, None));
}
let map = Keys::map_of(public_keys.iter().map(|k| (k.did.clone(), &k.public_key)));
let mut expected_from: Option<String> = origin_owner.map(String::from);
let mut current_owner: Option<String> = origin_owner.map(String::from);
let mut prev_id: Option<String> = None;
let mut prev_time: Option<i128> = None;
for (i, transfer) in transfers.iter().enumerate() {
let keys = rv::pin_if_keyless(Keys::Map(&map), expected_from.as_deref());
let subject = match verify_ownership_transfer(transfer, keys, Some(robot_did), now_iso)? {
Some(s) => s,
None => return Ok((false, None)),
};
if let Some(expected) = &expected_from {
if subject.get("fromOwner").and_then(|v| v.as_str()) != Some(expected.as_str()) {
return Ok((false, None));
}
}
let this_time = match rv::time_ns(transfer.get("validFrom")) {
Some(t) if prev_time.is_none_or(|p| t >= p) => t,
_ => return Ok((false, None)),
};
if i > 0 {
match &prev_id {
Some(p) if subject.get("prevTransferId").and_then(|v| v.as_str()) == Some(p) => {}
_ => return Ok((false, None)),
}
}
prev_id = non_empty_str(transfer, "id").map(String::from);
prev_time = Some(this_time);
current_owner = subject
.get("toOwner")
.and_then(|v| v.as_str())
.map(String::from);
expected_from = current_owner.clone();
}
Ok((true, current_owner))
}
/// Parameters for [`build_key_rotation`]. The credential is signed by the old key
/// (the `signer_seed`) and issued under `robot_did`; the old key's public multibase
/// is recorded as `previousKey` and `new_key_multibase` as the authorized successor.
#[derive(Debug, Clone)]
pub struct BuildKeyRotation {
pub robot_did: String,
pub new_key_multibase: String,
pub reason: Option<String>,
pub valid_from: String,
}
/// Build a key-rotation credential in which the robot's current (old) key
/// authorizes a new key. Signed by the old key, so anyone trusting the old key
/// can trust the new one. `old_key_seed` is the seed of the current key.
pub fn build_key_rotation(old_key_seed: &[u8], params: &BuildKeyRotation) -> Result<Value> {
if params.new_key_multibase.is_empty() {
return Err(CoreError::Json("new_key_multibase is required".into()));
}
let old_kp = keys::Ed25519KeyPair::from_seed_slice(old_key_seed)?;
let mut subject = Map::new();
subject.insert("id".into(), json!(params.robot_did));
subject.insert("previousKey".into(), json!(old_kp.public_multikey()));
subject.insert("newKey".into(), json!(params.new_key_multibase));
if let Some(reason) = ¶ms.reason {
subject.insert("reason".into(), json!(reason));
}
let mut cred = Map::new();
cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
cred.insert(
"type".into(),
json!(["VerifiableCredential", KEY_ROTATION_TYPE]),
);
cred.insert("issuer".into(), json!(params.robot_did));
cred.insert("validFrom".into(), json!(params.valid_from));
cred.insert("credentialSubject".into(), Value::Object(subject));
let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), ¶ms.valid_from);
data_integrity::sign(&Value::Object(cred), old_key_seed, &opts)
}
/// The raw Ed25519 key of a `z...` multikey, or `None`.
fn multikey_raw(v: Option<&Value>) -> Option<Vec<u8>> {
let s = v.and_then(|x| x.as_str()).filter(|s| s.starts_with('z'))?;
match multikey::decode(s) {
Ok(d) if d.algorithm == "Ed25519" && d.raw_key.len() == 32 => Some(d.raw_key),
_ => None,
}
}
/// Verify a key rotation: the robot's OLD key signed it, binding the new key.
///
/// The rotation is a self-attestation: the issuer must be the robot
/// (`credentialSubject.id`), `previousKey` must decode to exactly the key the
/// caller trusts as the robot's current key (`old_keys`: a bare key, or a
/// `{robot_did: key}` source), the proof is checked under that key, and
/// `newKey` must decode and differ. When given, the rotation must be for
/// `robot_did`. Returns the credentialSubject (with `newKey` the successor).
pub fn verify_key_rotation(
credential: &Value,
old_keys: Keys<'_>,
robot_did: Option<&str>,
now_iso: &str,
) -> Result<Option<Value>> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
let now = rv::require_now(now_iso)?;
let issuer = match rv::issuer_id(credential.get("issuer")) {
Some(i) => i.to_string(),
None => return Ok(None),
};
let trusted: Option<Vec<u8>> = match old_keys {
Keys::Embedded | Keys::Pinned(_) => None,
Keys::Bare(k) => Some(k.to_vec()),
Keys::One(did, k) => (did == issuer).then(|| k.to_vec()),
Keys::Map(m) => m.get(&issuer).cloned(),
Keys::Resolver(f) => f(&issuer),
};
let trusted = match trusted {
Some(t) if t.len() == 32 => t,
_ => return Ok(None),
};
let previous = credential
.get("credentialSubject")
.and_then(|s| s.get("previousKey"));
if multikey_raw(previous) != Some(trusted.clone()) {
return Ok(None);
}
let v = match rv::verify_robotics_credential(
credential,
Keys::One(&issuer, &trusted),
Some(KEY_ROTATION_TYPE),
now,
VerifyOptions::window(Window::FromRequired),
) {
Ok(v) if issuer_is_subject(&v) => v,
_ => return Ok(None),
};
if robot_did.is_some_and(|r| r != v.issuer) {
return Ok(None);
}
match multikey_raw(v.subject.get("newKey")) {
Some(n) if n != trusted => Ok(Some(v.subject)),
_ => Ok(None),
}
}
/// Verify an ordered list of key rotations forms one linear key history from
/// `origin_key_multibase`. Each rotation must be signed by the key it rotates
/// from, decoded from the multibase itself; every rotation is for the same
/// robot (`robot_did` when given, else the first rotation's robot) and dated no
/// earlier than the one before; a key that appears twice (a fork or a cycle)
/// is refused. Returns `(ok, current_key)`.
pub fn verify_key_history(
rotations: &[Value],
origin_key_multibase: &str,
robot_did: Option<&str>,
now_iso: &str,
) -> Result<(bool, Option<String>)> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); rotations);
rv::require_now(now_iso)?;
let origin = match multikey_raw(Some(&json!(origin_key_multibase))) {
Some(o) => o,
None => return Ok((false, None)),
};
let mut current_key = origin_key_multibase.to_string();
let mut current_raw = origin.clone();
let mut seen: HashSet<Vec<u8>> = HashSet::from([origin]);
let mut pinned: Option<String> = robot_did.map(String::from);
let mut prev_time: Option<i128> = None;
for rotation in rotations {
let subject = match verify_key_rotation(
rotation,
Keys::Bare(¤t_raw),
pinned.as_deref(),
now_iso,
)? {
Some(s) => s,
None => return Ok((false, None)),
};
if pinned.is_none() {
pinned = subject.get("id").and_then(|v| v.as_str()).map(String::from);
}
match rv::time_ns(rotation.get("validFrom")) {
Some(t) if prev_time.is_none_or(|p| t >= p) => prev_time = Some(t),
_ => return Ok((false, None)),
}
let new_raw = match multikey_raw(subject.get("newKey")) {
Some(n) if !seen.contains(&n) => n,
_ => return Ok((false, None)),
};
seen.insert(new_raw.clone());
current_raw = new_raw;
current_key = subject
.get("newKey")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
}
Ok((true, Some(current_key)))
}
/// Parameters for [`build_decommission`]. The signer is the owner or an authority;
/// `final_disposition` records the outcome (for example recycled, destroyed, or
/// transferred to parts). When `valid_until` is set it bounds the credential.
#[derive(Debug, Clone)]
pub struct BuildDecommission {
pub issuer_did: String,
pub robot_did: String,
pub reason: String,
pub final_disposition: Option<String>,
pub valid_from: String,
pub valid_until: Option<String>,
}
/// Build a signed decommission credential retiring `robot_did`. After
/// decommissioning, a verifier should refuse to trust the robot. `decommissionedBy`
/// is the issuer DID.
pub fn build_decommission(signer_seed: &[u8], params: &BuildDecommission) -> Result<Value> {
if params.reason.is_empty() {
return Err(CoreError::Json("reason is required".into()));
}
let mut subject = Map::new();
subject.insert("id".into(), json!(params.robot_did));
subject.insert("reason".into(), json!(params.reason));
subject.insert("decommissionedBy".into(), json!(params.issuer_did));
if let Some(disposition) = ¶ms.final_disposition {
subject.insert("finalDisposition".into(), json!(disposition));
}
let mut cred = Map::new();
cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
cred.insert(
"type".into(),
json!(["VerifiableCredential", DECOMMISSION_TYPE]),
);
cred.insert("issuer".into(), json!(params.issuer_did));
cred.insert("validFrom".into(), json!(params.valid_from));
if let Some(vu) = ¶ms.valid_until {
cred.insert("validUntil".into(), json!(vu));
}
cred.insert("credentialSubject".into(), Value::Object(subject));
let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), ¶ms.valid_from);
data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
}
/// Verify a decommission credential: the proof bound to the issuer, the
/// window at `now_iso` (validFrom required), `decommissionedBy` (when present)
/// equal to the issuer, the issuer in `trusted_authorities` when supplied, and
/// (when given) the credential is about `robot_did`.
pub fn verify_decommission(
credential: &Value,
keys: Keys<'_>,
trusted_authorities: Option<&HashSet<String>>,
robot_did: Option<&str>,
now_iso: &str,
) -> Result<Option<Value>> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
let now = rv::require_now(now_iso)?;
let opts = VerifyOptions {
trusted_issuers: trusted_authorities,
..VerifyOptions::window(Window::FromRequired)
};
let v = match rv::verify_robotics_credential(
credential,
keys,
Some(DECOMMISSION_TYPE),
now,
opts,
) {
Ok(v) => v,
Err(_) => return Ok(None),
};
if let Some(by) = v.subject.get("decommissionedBy") {
if by.as_str() != Some(v.issuer.as_str()) {
return Ok(None);
}
}
if robot_did.is_some_and(|r| v.subject.get("id").and_then(|x| x.as_str()) != Some(r)) {
return Ok(None);
}
Ok(Some(v.subject))
}
// ---------------------------------------------------------------------------
// Regulatory conformance profiles (Phase 5.14)
// ---------------------------------------------------------------------------
//
// A conformance profile is a machine-checkable mapping from Vouch robotics
// credentials to the clauses of a public safety or AI regulation. Given the
// credentials a robot presents, the checker reports which clauses are satisfied
// and cites each one, and an issuer can sign a point-in-time conformance
// attestation an auditor or notified body can consume. The profiles are plain
// data so every language reproduces them identically.
//
// This is the open layer: declarative profiles, a deterministic checker, and a
// signed point-in-time attestation over the full report. It is a reference
// crosswalk to make conformance verifiable in the open, not legal advice.
pub const CONFORMANCE_ATTESTATION_TYPE: &str = "RobotConformanceAttestation";
/// How well-sourced a requirement's clause citation is. A profile can be a
/// useful crosswalk while its citations are only as good as the sources that
/// were available, and a reader is entitled to know which. Every report and
/// every signed attestation carries these, so a conformance result never
/// implies more authority over the regulation than it has.
///
/// The clause text was read from the official published source.
pub const CITATION_VERIFIED_PRIMARY: &str = "verified-primary";
/// The mapping is believed sound, but the clause number comes from secondary
/// sources rather than the standard or official journal itself. The default,
/// because it is the honest default.
pub const CITATION_UNVERIFIED_SECONDARY: &str = "unverified-secondary";
/// Not a clause reference at all, only a description of the topic. An assessor
/// cannot look it up.
pub const CITATION_DESCRIPTIVE: &str = "descriptive";
/// Every citation provenance value, in report order.
pub const CITATION_STATUSES: &[&str] = &[
CITATION_VERIFIED_PRIMARY,
CITATION_UNVERIFIED_SECONDARY,
CITATION_DESCRIPTIVE,
];
// Citation notes shared by several requirements. Macros rather than consts so
// they can be `concat!`-ed into the longer per-requirement notes, byte-for-byte
// identical with the Python, TypeScript and Go profiles.
macro_rules! iso_paywall_note {
() => {
"Clause number taken from secondary sources; the standard is paywalled \
and the text has not been read."
};
}
macro_rules! iso_10218_note {
() => {
concat!(
iso_paywall_note!(),
" ISO 10218-1/-2:2011 were superseded by the 2025 editions (in \
force 1 April 2025); this mapping still cites the 2011 clause \
numbering and has not been migrated."
)
};
}
macro_rules! oj_note {
() => {
"Article number taken from a third-party reproduction of the Official \
Journal text, not from EUR-Lex itself."
};
}
macro_rules! ul_note {
() => {
"UL 3300 (now ANSI/CAN/UL 3300:2024) is paywalled and no clause \
numbering was available; this names the topic only and cannot be \
looked up."
};
}
/// One requirement in a profile: a clause of a regulation mapped to the
/// credential type and field paths that satisfy it.
struct ProfileRequirement {
id: &'static str,
clause: &'static str,
title: &'static str,
credential: &'static str,
fields: &'static [&'static str],
/// Subject paths that must hold boolean `true`, for requirements where mere
/// presence is not evidence: a heartbeat reporting an envelope breach is not
/// evidence of having stayed inside the envelope. This is the boolean subset
/// of the `expect` map the Python, TypeScript and Go profiles carry; the
/// built-in profiles use only boolean expectations.
expect_true: &'static [&'static str],
/// Provenance of the `clause` reference above, one of [`CITATION_STATUSES`].
citation: &'static str,
/// Anything a reader should know about the citation, such as a known
/// conflict between sources.
citation_note: Option<&'static str>,
}
/// A built-in conformance profile: a regime, a version, and its requirements.
struct ConformanceProfile {
regime: &'static str,
version: &'static str,
requirements: &'static [ProfileRequirement],
}
const ISO_10218_REQUIREMENTS: &[ProfileRequirement] = &[
ProfileRequirement {
id: "iso10218-identification",
clause: "ISO 10218-1:2011, 5.2",
title: "Robot identification bound to its hardware",
credential: "RobotIdentityCredential",
fields: &["hardwareRoot.kind", "hardwareRoot.attestation"],
expect_true: &[],
citation: CITATION_UNVERIFIED_SECONDARY,
citation_note: Some(iso_10218_note!()),
},
ProfileRequirement {
id: "iso10218-software-integrity",
clause: "ISO 10218-1:2011, 5.3",
title: "Control software and configuration integrity",
credential: "ModelProvenanceAttestation",
fields: &["vla.weightsHash"],
expect_true: &[],
citation: CITATION_UNVERIFIED_SECONDARY,
citation_note: Some(iso_10218_note!()),
},
ProfileRequirement {
id: "iso10218-limits",
clause: "ISO 10218-1:2011, 5.6",
title: "Limiting of speed, force, and workspace",
credential: "PhysicalCapabilityScope",
fields: &[
"physicalScope.maxForceN",
"physicalScope.maxSpeedMps",
"physicalScope.allowedZones",
],
expect_true: &[],
citation: CITATION_UNVERIFIED_SECONDARY,
citation_note: Some(iso_10218_note!()),
},
ProfileRequirement {
id: "iso10218-records",
clause: "ISO 10218-2:2011, 5.2",
title: "Records of safety-relevant events",
credential: "RobotSafetyRecordCredential",
fields: &["totalEvents", "logHead"],
expect_true: &[],
citation: CITATION_UNVERIFIED_SECONDARY,
citation_note: Some(iso_10218_note!()),
},
];
const ISO_TS_15066_REQUIREMENTS: &[ProfileRequirement] = &[
ProfileRequirement {
id: "iso15066-power-force-limiting",
clause: "ISO/TS 15066:2016, 5.5.4",
title: "Power and force limiting near humans",
credential: "PhysicalCapabilityScope",
fields: &[
"physicalScope.maxSpeedNearHumansMps",
"physicalScope.maxForceN",
],
expect_true: &[],
citation: CITATION_UNVERIFIED_SECONDARY,
citation_note: Some(concat!(
iso_paywall_note!(),
" Secondary sources disagree on whether power and force limiting \
is 5.5.4 or 5.5.2; confirm against the published table of \
contents before relying on the number."
)),
},
ProfileRequirement {
id: "iso15066-collaborative-workspace",
clause: "ISO/TS 15066:2016, 5.5.2",
title: "Defined collaborative workspace",
credential: "PhysicalCapabilityScope",
fields: &["physicalScope.allowedZones"],
expect_true: &[],
citation: CITATION_UNVERIFIED_SECONDARY,
citation_note: Some(concat!(
iso_paywall_note!(),
" Shares the unresolved 5.5.2/5.5.4 numbering conflict with \
iso15066-power-force-limiting."
)),
},
ProfileRequirement {
id: "iso15066-monitoring",
clause: "ISO/TS 15066:2016, 5.2",
title: "Continuous monitoring of the collaborative operation",
credential: "RobotHeartbeatCredential",
fields: &["motionDigest"],
expect_true: &["motionDigest.withinEnvelope"],
citation: CITATION_UNVERIFIED_SECONDARY,
citation_note: Some(iso_paywall_note!()),
},
];
const EU_MACHINERY_REQUIREMENTS: &[ProfileRequirement] = &[
ProfileRequirement {
id: "eu-mr-identification",
clause: "Reg (EU) 2023/1230, Annex III 1.7.4",
title: "Machinery identification and traceability",
credential: "RobotIdentityCredential",
fields: &["make", "model", "serial"],
expect_true: &[],
citation: CITATION_UNVERIFIED_SECONDARY,
citation_note: Some(oj_note!()),
},
ProfileRequirement {
id: "eu-mr-software-integrity",
clause: "Reg (EU) 2023/1230, Annex III 1.1.9",
title: "Protection against corruption of safety software",
credential: "ModelProvenanceAttestation",
fields: &["vla.weightsHash", "vla.safetyPolicy"],
expect_true: &[],
citation: CITATION_UNVERIFIED_SECONDARY,
citation_note: Some(concat!(
oj_note!(),
" The Annex III subclause for protection against corruption has \
not been confirmed and may need to be re-pointed."
)),
},
ProfileRequirement {
id: "eu-mr-safe-limits",
clause: "Reg (EU) 2023/1230, Annex III 1.2.1",
title: "Safety and reliability of control systems and limits",
credential: "PhysicalCapabilityScope",
fields: &["physicalScope.maxForceN"],
expect_true: &[],
citation: CITATION_UNVERIFIED_SECONDARY,
citation_note: Some(oj_note!()),
},
ProfileRequirement {
id: "eu-mr-records",
clause: "Reg (EU) 2023/1230, Annex III 1.2.1",
title: "Recording of safety-relevant data",
credential: "RobotSafetyRecordCredential",
fields: &["totalEvents", "logHead"],
expect_true: &[],
citation: CITATION_UNVERIFIED_SECONDARY,
citation_note: Some(oj_note!()),
},
];
const EU_AI_ACT_REQUIREMENTS: &[ProfileRequirement] = &[
ProfileRequirement {
id: "eu-aia-record-keeping",
clause: "Reg (EU) 2024/1689, Art. 12",
title: "Automatic recording of events (logging)",
credential: "RobotSafetyRecordCredential",
fields: &["logHead"],
expect_true: &[],
citation: CITATION_UNVERIFIED_SECONDARY,
citation_note: Some(oj_note!()),
},
ProfileRequirement {
id: "eu-aia-transparency",
clause: "Reg (EU) 2024/1689, Art. 13",
title: "Model and configuration transparency",
credential: "ModelProvenanceAttestation",
fields: &["vla.modelName", "vla.configHash"],
expect_true: &[],
citation: CITATION_UNVERIFIED_SECONDARY,
citation_note: Some(oj_note!()),
},
ProfileRequirement {
id: "eu-aia-human-oversight",
clause: "Reg (EU) 2024/1689, Art. 14",
title: "Human oversight through enforced operating limits",
credential: "PhysicalCapabilityScope",
fields: &["physicalScope.maxSpeedNearHumansMps"],
expect_true: &[],
citation: CITATION_UNVERIFIED_SECONDARY,
citation_note: Some(concat!(
oj_note!(),
" Art. 14 also requires a means for the overseer to intervene or \
stop the system, which an operating-limit scope alone does not \
evidence."
)),
},
ProfileRequirement {
id: "eu-aia-accuracy-robustness",
clause: "Reg (EU) 2024/1689, Art. 15",
title: "Accuracy and robustness traceable to a known build",
credential: "ModelProvenanceAttestation",
fields: &["vla.weightsHash"],
expect_true: &[],
citation: CITATION_UNVERIFIED_SECONDARY,
citation_note: Some(oj_note!()),
},
];
const UL_3300_REQUIREMENTS: &[ProfileRequirement] = &[
ProfileRequirement {
id: "ul3300-identity",
clause: "UL 3300, identification",
title: "Robot identity bound to its hardware",
credential: "RobotIdentityCredential",
fields: &["hardwareRoot.kind", "hardwareRoot.attestation"],
expect_true: &[],
citation: CITATION_DESCRIPTIVE,
citation_note: Some(ul_note!()),
},
ProfileRequirement {
id: "ul3300-operating-limits",
clause: "UL 3300, operating limits",
title: "Enforced speed and zone limits",
credential: "PhysicalCapabilityScope",
fields: &["physicalScope.maxSpeedMps", "physicalScope.allowedZones"],
expect_true: &[],
citation: CITATION_DESCRIPTIVE,
citation_note: Some(ul_note!()),
},
ProfileRequirement {
id: "ul3300-perception-integrity",
clause: "UL 3300, sensing integrity",
title: "Integrity of perception used for safe operation",
credential: "PerceptionProvenanceCredential",
fields: &["frameHash"],
expect_true: &[],
citation: CITATION_DESCRIPTIVE,
citation_note: Some(ul_note!()),
},
ProfileRequirement {
id: "ul3300-records",
clause: "UL 3300, incident records",
title: "Records of safety-relevant incidents",
credential: "RobotSafetyRecordCredential",
fields: &["totalEvents", "logHead"],
expect_true: &[],
citation: CITATION_DESCRIPTIVE,
citation_note: Some(ul_note!()),
},
];
/// Return a built-in profile by id, or `None` if it is unknown. The five profiles
/// cover ISO 10218-1/-2 (industrial), ISO/TS 15066 (collaborative), the EU
/// Machinery Regulation 2023/1230, the EU AI Act high-risk requirements, and
/// UL 3300 (service and mobile robots).
fn conformance_profile(profile_id: &str) -> Option<ConformanceProfile> {
match profile_id {
"iso-10218" => Some(ConformanceProfile {
regime: "ISO 10218-1/-2 industrial robots",
version: "2011 (superseded by the 2025 editions; mapping not yet migrated)",
requirements: ISO_10218_REQUIREMENTS,
}),
"iso-ts-15066" => Some(ConformanceProfile {
regime: "ISO/TS 15066 collaborative robots",
version: "2016",
requirements: ISO_TS_15066_REQUIREMENTS,
}),
"eu-machinery-2023-1230" => Some(ConformanceProfile {
regime: "EU Machinery Regulation 2023/1230",
version: "2023",
requirements: EU_MACHINERY_REQUIREMENTS,
}),
"eu-ai-act-high-risk" => Some(ConformanceProfile {
regime: "EU AI Act high-risk systems",
version: "2024",
requirements: EU_AI_ACT_REQUIREMENTS,
}),
"ul-3300" => Some(ConformanceProfile {
regime: "UL 3300 service, communication, and mobile robots",
version: "2022 (see ANSI/CAN/UL 3300:2024)",
requirements: UL_3300_REQUIREMENTS,
}),
_ => None,
}
}
/// A built-in conformance profile as JSON (`{regime, version, requirements:
/// [{id, clause, title, credential, fields, expect, citation,
/// citationNote?}]}`), or `null` for an unknown id.
pub fn conformance_profile_json(profile_id: &str) -> Value {
let Some(p) = conformance_profile(profile_id) else {
return Value::Null;
};
let requirements: Vec<Value> = p
.requirements
.iter()
.map(|r| {
let expect: Map<String, Value> = r
.expect_true
.iter()
.map(|f| (f.to_string(), Value::Bool(true)))
.collect();
let mut m = Map::new();
m.insert("id".into(), json!(r.id));
m.insert("clause".into(), json!(r.clause));
m.insert("title".into(), json!(r.title));
m.insert("credential".into(), json!(r.credential));
m.insert("fields".into(), json!(r.fields));
m.insert("expect".into(), Value::Object(expect));
m.insert("citation".into(), json!(r.citation));
if let Some(n) = r.citation_note {
m.insert("citationNote".into(), json!(n));
}
Value::Object(m)
})
.collect();
json!({"regime": p.regime, "version": p.version, "requirements": requirements})
}
/// The type array of a credential, accepting a JSON string or an array of strings.
fn credential_types(credential: &Value) -> Vec<&str> {
match credential.get("type") {
Some(Value::String(s)) => vec![s.as_str()],
Some(Value::Array(items)) => items.iter().filter_map(|v| v.as_str()).collect(),
_ => Vec::new(),
}
}
/// Follow a dot-separated path from the credentialSubject, returning the value at
/// the leaf or `None` if any segment is missing or not an object.
fn path_value<'a>(subject: &'a Value, path: &str) -> Option<&'a Value> {
let mut node = subject;
for part in path.split('.') {
match node {
Value::Object(map) => match map.get(part) {
Some(v) => node = v,
None => return None,
},
_ => return None,
}
}
Some(node)
}
/// True when a value is present and non-empty: not null, and not an empty array
/// or empty object. Any other value (including `false`, `0`, or `""`) counts.
fn value_present(value: &Value) -> bool {
match value {
Value::Null => false,
Value::Array(a) => !a.is_empty(),
Value::Object(o) => !o.is_empty(),
_ => true,
}
}
/// True when `credential` satisfies `requirement`: its type array includes the
/// requirement's credential type, its credentialSubject has a non-null,
/// non-empty value at every field path, and every `expect_true` path holds
/// boolean `true`. Presence alone is not evidence: a heartbeat that reports an
/// envelope breach does not evidence having stayed inside the envelope.
fn credential_satisfies(credential: &Value, requirement: &ProfileRequirement) -> bool {
if !credential_types(credential).contains(&requirement.credential) {
return false;
}
let empty = Value::Object(Map::new());
let subject = credential.get("credentialSubject").unwrap_or(&empty);
for path in requirement.fields {
match path_value(subject, path) {
Some(v) if value_present(v) => {}
_ => return false,
}
}
for path in requirement.expect_true {
if path_value(subject, path) != Some(&Value::Bool(true)) {
return false;
}
}
true
}
/// Check the presented `credentials` against the named profile and return a
/// deterministic report. Each requirement is satisfied when some presented
/// credential matches its type and has every required field. The caller is
/// expected to have verified the credentials' signatures first; this checks
/// structure and coverage, not proofs.
///
/// Every requirement carries the provenance of its clause citation, and the
/// report totals them, so a result never reads as more authoritative about the
/// regulation than its sources are.
///
/// The report has exactly `{profileId, regime, version, conforms,
/// satisfiedCount, totalCount, citations:{...},
/// requirements:[{id, clause, title, satisfied, citation, citationNote?}]}`.
pub fn check_conformance(credentials: &[Value], profile_id: &str) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credentials);
check_conformance_for(credentials, profile_id, None)
}
/// [`check_conformance`] bound to one robot: with `robot_did`, only credentials
/// whose `credentialSubject.id` is that robot count (so another robot's
/// credential mixed into the set cannot fill a gap), and the report carries
/// `robotDid`.
pub fn check_conformance_for(
credentials: &[Value],
profile_id: &str,
robot_did: Option<&str>,
) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credentials);
let prof = conformance_profile(profile_id)
.ok_or_else(|| CoreError::Json(format!("unknown conformance profile: {profile_id}")))?;
if robot_did.is_some_and(str::is_empty) {
return Err(CoreError::Json("robot_did must be a non-empty DID".into()));
}
let presented: Vec<&Value> = credentials
.iter()
.filter(|c| c.is_object())
.filter(|c| {
robot_did.is_none_or(|r| {
c.get("credentialSubject")
.and_then(|s| s.get("id"))
.and_then(|x| x.as_str())
== Some(r)
})
})
.collect();
let mut results: Vec<Value> = Vec::with_capacity(prof.requirements.len());
let mut satisfied = 0i64;
let mut citations = Map::new();
for status in CITATION_STATUSES {
citations.insert((*status).into(), json!(0i64));
}
for requirement in prof.requirements {
let ok = presented
.iter()
.any(|c| credential_satisfies(c, requirement));
if ok {
satisfied += 1;
}
let seen = citations
.get(requirement.citation)
.and_then(|v| v.as_i64())
.unwrap_or(0);
citations.insert(requirement.citation.into(), json!(seen + 1));
let mut result = Map::new();
result.insert("id".into(), json!(requirement.id));
result.insert("clause".into(), json!(requirement.clause));
result.insert("title".into(), json!(requirement.title));
result.insert("satisfied".into(), json!(ok));
result.insert("citation".into(), json!(requirement.citation));
if let Some(note) = requirement.citation_note {
result.insert("citationNote".into(), json!(note));
}
results.push(Value::Object(result));
}
let total = prof.requirements.len() as i64;
let mut report = Map::new();
report.insert("profileId".into(), json!(profile_id));
report.insert("regime".into(), json!(prof.regime));
report.insert("version".into(), json!(prof.version));
report.insert("conforms".into(), json!(satisfied == total));
report.insert("satisfiedCount".into(), json!(satisfied));
report.insert("totalCount".into(), json!(total));
report.insert("citations".into(), Value::Object(citations));
report.insert("requirements".into(), Value::Array(results));
if let Some(r) = robot_did {
report.insert("robotDid".into(), json!(r));
}
Ok(Value::Object(report))
}
/// Multibase SHA-256 of the JCS-canonical report, for binding into an
/// attestation. Every language canonicalizes identically, so the digest is the
/// same byte string everywhere.
pub fn report_digest(report: &Value) -> String {
mb64(&Sha256::digest(jcs::canonicalize(report)))
}
/// Parameters for [`build_conformance_attestation`]. The signer is the robot, its
/// owner, or an assessing authority; `robot_did` names the robot the attestation
/// is about. `report` is produced by [`check_conformance`] and is embedded and
/// bound by digest. When `valid_seconds` is set it bounds the attestation.
#[derive(Debug, Clone)]
pub struct BuildConformanceAttestation {
pub issuer_did: String,
pub robot_did: String,
pub report: Value,
pub valid_from: String,
pub valid_until: Option<String>,
}
/// Build a signed point-in-time `RobotConformanceAttestation` for `robot_did`
/// over a `report` produced by [`check_conformance`]. The report is embedded and
/// bound by digest.
pub fn build_conformance_attestation(
signer_seed: &[u8],
params: &BuildConformanceAttestation,
) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
if params.robot_did.is_empty() {
return Err(CoreError::Json("robot_did is required".into()));
}
let report = params
.report
.as_object()
.ok_or_else(|| CoreError::Json("report must come from check_conformance".into()))?;
if !report.contains_key("profileId") || !report.contains_key("conforms") {
return Err(CoreError::Json(
"report must come from check_conformance".into(),
));
}
let mut subject = Map::new();
subject.insert("id".into(), json!(params.robot_did));
subject.insert(
"profileId".into(),
report.get("profileId").cloned().unwrap_or(Value::Null),
);
subject.insert(
"regime".into(),
report.get("regime").cloned().unwrap_or(Value::Null),
);
subject.insert(
"conforms".into(),
report.get("conforms").cloned().unwrap_or(Value::Null),
);
subject.insert(
"satisfiedCount".into(),
report.get("satisfiedCount").cloned().unwrap_or(Value::Null),
);
subject.insert(
"totalCount".into(),
report.get("totalCount").cloned().unwrap_or(Value::Null),
);
subject.insert(
"citations".into(),
report
.get("citations")
.cloned()
.unwrap_or_else(|| Value::Object(Map::new())),
);
subject.insert("reportDigest".into(), json!(report_digest(¶ms.report)));
subject.insert("report".into(), params.report.clone());
let mut cred = Map::new();
cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
cred.insert(
"type".into(),
json!(["VerifiableCredential", CONFORMANCE_ATTESTATION_TYPE]),
);
cred.insert("issuer".into(), json!(params.issuer_did));
cred.insert("validFrom".into(), json!(params.valid_from));
if let Some(vu) = ¶ms.valid_until {
cred.insert("validUntil".into(), json!(vu));
}
cred.insert("credentialSubject".into(), Value::Object(subject));
let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), ¶ms.valid_from);
data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
}
/// Verify a conformance attestation: the issuer's proof bound to the issuer,
/// the window at `now_iso` (validFrom required), that the embedded report
/// matches its bound digest, that every summary field (profileId, regime,
/// conforms, satisfiedCount, totalCount) matches the report, and that
/// `conforms` is a boolean. When given, the attestation must be about
/// `robot_did` and its issuer must be in `trusted_issuers`. Returns the
/// credentialSubject on success, `None` if invalid.
pub fn verify_conformance_attestation(
credential: &Value,
keys: Keys<'_>,
robot_did: Option<&str>,
trusted_issuers: Option<&HashSet<String>>,
now_iso: &str,
) -> Result<Option<Value>> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
let now = rv::require_now(now_iso)?;
let opts = VerifyOptions {
trusted_issuers,
..VerifyOptions::window(Window::FromRequired)
};
let v = match rv::verify_robotics_credential(
credential,
keys,
Some(CONFORMANCE_ATTESTATION_TYPE),
now,
opts,
) {
Ok(v) => v,
Err(_) => return Ok(None),
};
let subject = v.subject;
let embedded = match subject.get("report") {
Some(r) if r.is_object() => r,
_ => return Ok(None),
};
if subject.get("reportDigest").and_then(|v| v.as_str())
!= Some(report_digest(embedded).as_str())
{
return Ok(None);
}
for name in [
"profileId",
"regime",
"conforms",
"satisfiedCount",
"totalCount",
] {
if subject.get(name) != embedded.get(name) {
return Ok(None);
}
}
if !subject.get("conforms").is_some_and(|c| c.is_boolean()) {
return Ok(None);
}
// A report bound to one robot cannot be attested as being about another.
if embedded.get("robotDid").is_some() && embedded.get("robotDid") != subject.get("id") {
return Ok(None);
}
if robot_did.is_some_and(|r| subject.get("id").and_then(|x| x.as_str()) != Some(r)) {
return Ok(None);
}
Ok(Some(subject))
}
// ---------------------------------------------------------------------------
// Post-quantum robot credentials (Phase 5.13)
// ---------------------------------------------------------------------------
//
// A robot fielded today lives for ten to twenty years, longer than classical
// Ed25519 is expected to stay safe, so a robot identity signed now could be
// forged once a quantum computer arrives. This section makes the hybrid
// post-quantum cryptosuite (`hybrid-eddsa-mldsa44-jcs-2026`, a classical
// Ed25519 signature alongside an ML-DSA-44 signature) available for robot
// credentials so they stay unforgeable across the robot's whole service life.
//
// - sign_pq: attach a hybrid proof to a robot credential.
// - verify_robot_credential: verify a robot credential whether it carries a
// classical or a hybrid proof, auto-detected from the proof, so a fleet can
// move to PQ gradually without breaking the classical credentials already in
// the field.
// - migrate_to_pq: re-sign a fielded robot's classical credential under PQ.
//
// This is the open layer: hybrid signing, backward-compatible verification, and
// a software re-signing migration path. It reuses the proof set of
// [`crate::hybrid`] and the ML-DSA-44 and multikey helpers rather than
// re-deriving any cryptography.
/// The classical (Ed25519-only) robot credential cryptosuite.
pub const CLASSICAL_CRYPTOSUITE: &str = data_integrity::CRYPTOSUITE_ID;
/// The ML-DSA-44 proof a post-quantum robot credential carries next to its
/// classical proof, in a proof set.
pub const POST_QUANTUM_CRYPTOSUITE: &str = hybrid::MLDSA44_CRYPTOSUITE_ID;
/// Coerce an ML-DSA-44 public key supplied either as raw 1312-byte bytes or as a
/// Multikey string into raw bytes. Errors on the wrong length or a non-ML-DSA
/// multikey.
pub fn coerce_mldsa44_public(mldsa44_public: &[u8]) -> Result<Vec<u8>> {
if mldsa44_public.len() != MLDSA44_PUBLIC_LEN {
return Err(CoreError::InvalidKeyLength {
expected: MLDSA44_PUBLIC_LEN,
got: mldsa44_public.len(),
});
}
Ok(mldsa44_public.to_vec())
}
/// Coerce an ML-DSA-44 Multikey string into raw public-key bytes. Errors if the
/// multikey does not carry an ML-DSA-44 key.
pub fn mldsa44_public_from_multikey(multikey_str: &str) -> Result<Vec<u8>> {
let decoded = multikey::decode(multikey_str)?;
if decoded.algorithm != "ML-DSA-44" {
return Err(CoreError::InvalidMultikey(format!(
"expected an ML-DSA-44 multikey, got {}",
decoded.algorithm
)));
}
coerce_mldsa44_public(&decoded.raw_key)
}
fn pq_verification_method(credential: &Value) -> String {
let issuer = credential
.as_object()
.and_then(|o| o.get("issuer"))
.and_then(|v| v.as_str())
.unwrap_or("");
format!("{issuer}#key-1")
}
/// The ML-DSA-44 verification method slot, matching the `#key-2` convention the
/// language SDKs derive for the post-quantum member of a proof set.
fn pq_mldsa_verification_method(credential: &Value) -> String {
let issuer = credential
.as_object()
.and_then(|o| o.get("issuer"))
.and_then(|v| v.as_str())
.unwrap_or("");
format!("{issuer}#key-2")
}
/// Attach a hybrid (classical Ed25519 plus post-quantum ML-DSA-44) Data Integrity
/// proof to a pre-built robot `credential`. Any existing proof is replaced. The
/// robot signs with its Ed25519 seed and its ML-DSA-44 key pair; `created` is the
/// caller-supplied ISO-8601 instant, keeping the core deterministic.
pub fn sign_pq(
credential: &Value,
ed25519_seed: &[u8],
mldsa: &MlDsa44KeyPair,
created: &str,
) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
let ed_vm = pq_verification_method(credential);
let ml_vm = pq_mldsa_verification_method(credential);
hybrid::sign_dual(credential, ed25519_seed, mldsa, &ed_vm, &ml_vm, created)
}
/// Return true if `credential` carries a post-quantum proof: a `proof` array
/// holding an ML-DSA-44 proof. One proof object is never post-quantum (the
/// earlier composite proof is refused by every verifier).
pub fn is_pq(credential: &Value) -> bool {
crate::nesting::deep_guard!(false; credential);
match credential.as_object().and_then(|o| o.get("proof")) {
Some(Value::Array(proofs)) => proofs
.iter()
.any(|p| hybrid::Suite::of_proof(p) == Some(hybrid::Suite::Mldsa44)),
_ => false,
}
}
/// Verify a post-quantum robot credential: a proof set whose Ed25519 and
/// ML-DSA-44 signatures both validate. One proof object is refused, the
/// earlier composite proof included.
fn verify_pq_proof_set(
credential: &Value,
ed25519_public_key: &[u8],
mldsa44_public_key: &[u8],
) -> Result<bool> {
match credential.as_object().and_then(|o| o.get("proof")) {
Some(Value::Array(_)) => {
hybrid::verify_dual(credential, ed25519_public_key, mldsa44_public_key)
}
_ => Ok(false),
}
}
/// Verify a hybrid robot credential. Both the Ed25519 and the ML-DSA-44 signature
/// MUST validate. `mldsa44_public_key` is raw 1312-byte bytes or an ML-DSA-44
/// Multikey string (pass `mldsa44_multikey` for the string form).
pub fn verify_pq(
credential: &Value,
ed25519_public_key: &[u8],
mldsa44_public_key: &[u8],
) -> Result<bool> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
let resolved_ml = coerce_mldsa44_public(mldsa44_public_key)?;
verify_pq_proof_set(credential, ed25519_public_key, &resolved_ml)
}
/// [`verify_robot_credential`] with the ML-DSA-44 key taken from a key source
/// like the Ed25519 key: a bare key, or a `{did: key}` map / resolver from which
/// the entry for the credential's issuer is used (no entry fails a
/// post-quantum credential). Map values are raw 1312-byte keys or ML-DSA-44
/// Multikey strings as UTF-8 bytes.
pub fn verify_robot_credential_keyed(
credential: &Value,
ed_keys: Keys<'_>,
mldsa44_keys: Option<Keys<'_>>,
expected_type: Option<&str>,
now_iso: &str,
) -> Result<bool> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
let ml = match mldsa44_keys {
None => return verify_robot_credential(credential, ed_keys, None, expected_type, now_iso),
Some(k) => k,
};
let issuer = rv::issuer_id(credential.get("issuer"))
.unwrap_or("")
.to_string();
let picked: Option<Vec<u8>> = match ml {
Keys::Embedded | Keys::Pinned(_) => None,
Keys::Bare(k) => Some(k.to_vec()),
Keys::One(d, k) => (d == issuer).then(|| k.to_vec()),
Keys::Map(m) => m.get(&issuer).cloned(),
Keys::Resolver(f) => f(&issuer),
};
match picked {
Some(k) => verify_robot_credential(credential, ed_keys, Some(&k), expected_type, now_iso),
// A post-quantum credential needs its issuer's ML-DSA key; a classical
// one given an ML-DSA source is refused by the same rule as a bare key.
None => Ok(false),
}
}
/// The backward-compatible robot credential verify a fleet uses while
/// migrating to post-quantum: auto-detects a hybrid proof set.
///
/// Every proof must be bound to the issuer (`proofPurpose` assertionMethod and
/// a verification method of the issuer DID), and the Ed25519 key must belong to
/// the issuer (the key inside a did:key, or `ed_keys` as a `{did: key}`
/// source for any other DID). Present validity bounds must be strict protocol
/// times with `now_iso` inside. When `expected_type` is given the credential
/// must carry it. A post-quantum credential requires `mldsa44_public_key`;
/// supplying one for a classical credential refuses it (so a stripped ML-DSA
/// proof cannot pass as classical). Malformed input returns `false`.
pub fn verify_robot_credential(
credential: &Value,
ed_keys: Keys<'_>,
mldsa44_public_key: Option<&[u8]>,
expected_type: Option<&str>,
now_iso: &str,
) -> Result<bool> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
let now = rv::require_now(now_iso)?;
if !credential.is_object() {
return Ok(false);
}
if is_pq(credential) {
let ml = match mldsa44_public_key {
Some(k) => k,
None => return Ok(false),
};
let issuer = match rv::issuer_id(credential.get("issuer")) {
Some(i) => i,
None => return Ok(false),
};
if rv::input_too_large(credential, rv::MAX_CREDENTIAL_BYTES).is_some() {
return Ok(false);
}
let types: Vec<&str> = match credential.get("type") {
Some(Value::String(t)) => vec![t.as_str()],
Some(Value::Array(a)) if a.iter().all(|t| t.is_string()) => {
a.iter().filter_map(|t| t.as_str()).collect()
}
_ => return Ok(false),
};
if expected_type.is_some_and(|e| !types.contains(&e)) {
return Ok(false);
}
let members: Vec<&Value> = match credential.get("proof") {
Some(Value::Array(a)) => a.iter().collect(),
Some(p) => vec![p],
None => return Ok(false),
};
if members.is_empty()
|| members
.iter()
.any(|m| rv::proof_unbound_reason(m, issuer).is_some())
{
return Ok(false);
}
if rv::window_reason(credential, Window::IfPresent, now, 0).is_some() {
return Ok(false);
}
let ed = match rv::resolve_issuer_key(issuer, ed_keys) {
Ok(k) => k,
Err(_) => return Ok(false),
};
let resolved_ml = match resolve_mldsa44_public(ml) {
Ok(m) => m,
Err(_) => return Ok(false),
};
return Ok(verify_pq_proof_set(credential, &ed, &resolved_ml).unwrap_or(false));
}
if mldsa44_public_key.is_some() {
return Ok(false);
}
Ok(rv::verify_robotics_credential(
credential,
ed_keys,
expected_type,
now,
VerifyOptions::window(Window::IfPresent),
)
.is_ok())
}
/// Resolve an ML-DSA-44 public key given either raw bytes or a Multikey string.
/// A 1312-byte input is the raw key; otherwise it is parsed as a UTF-8 Multikey.
pub fn resolve_mldsa44_public(mldsa44_public_key: &[u8]) -> Result<Vec<u8>> {
if mldsa44_public_key.len() == MLDSA44_PUBLIC_LEN {
return Ok(mldsa44_public_key.to_vec());
}
let s = core::str::from_utf8(mldsa44_public_key).map_err(|_| {
CoreError::InvalidMultikey("ML-DSA-44 key must be raw bytes or a Multikey string".into())
})?;
mldsa44_public_from_multikey(s)
}
/// Re-sign a fielded robot's classical `credential` under the hybrid PQ
/// cryptosuite, preserving its body. The robot holds its current Ed25519 seed and
/// an ML-DSA-44 key pair; `created` is the caller-supplied re-signing instant.
pub fn migrate_to_pq(
credential: &Value,
ed25519_seed: &[u8],
mldsa: &MlDsa44KeyPair,
created: &str,
) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
sign_pq(credential, ed25519_seed, mldsa, created)
}
// ---------------------------------------------------------------------------
// Cross-embodiment identity continuity (Phase 5.15)
// ---------------------------------------------------------------------------
//
// An AI agent (a policy with its own Vouch identity) can run on one robot body
// today and a different body tomorrow. An embodiment credential binds the agent
// identity to a specific body (a hardware-rooted robot identity) and that body's
// hardware root for a period, signed by the agent's own persistent key. Linking
// each embodiment to the previous forms a continuity chain a verifier walks to
// confirm the same accountable agent persisted across bodies, re-binding to each
// body's hardware root as it moved. A fork check confirms the agent was never
// actively embodied in two bodies at once.
//
// This is the inverse of the ownership custody chain: there one body passes
// between owners; here one mind passes between bodies, and the constant that
// signs every link is the agent identity itself.
//
// This is the open layer: plain signed embodiment credentials, continuity-chain
// verification, and software fork detection. It reuses the core proof path
// ([`data_integrity`]) rather than re-deriving any cryptography.
pub const EMBODIMENT_TYPE: &str = "AgentEmbodimentCredential";
/// Parameters for [`build_embodiment`]. The signer is the agent's own persistent
/// key; `agent_did` is both issuer and subject id, so the whole continuity chain
/// is signed by one accountable identity. `from_body`, when set, links this
/// embodiment to the body the agent left, forming the chain. `valid_until`, when
/// set, bounds the active window (used by [`check_no_fork`]).
#[derive(Debug, Clone)]
pub struct BuildEmbodiment {
pub agent_did: String,
pub body_did: String,
pub body_hardware_root: String,
pub from_body: Option<String>,
pub embodied_at: String,
pub valid_until: Option<String>,
}
/// Build a signed embodiment credential: the agent `agent_did` authorizes running
/// on `body_did`, re-binding to that body's hardware root `body_hardware_root`.
/// Signed by the agent's own persistent key. `from_body` links this embodiment to
/// the body the agent left.
pub fn build_embodiment(agent_seed: &[u8], params: &BuildEmbodiment) -> Result<Value> {
if params.agent_did.is_empty()
|| params.body_did.is_empty()
|| params.body_hardware_root.is_empty()
{
return Err(CoreError::Json(
"agent_did, body_did, and body_hardware_root are required".into(),
));
}
let mut subject = Map::new();
subject.insert("id".into(), json!(params.agent_did));
subject.insert("body".into(), json!(params.body_did));
subject.insert("bodyHardwareRoot".into(), json!(params.body_hardware_root));
if let Some(from_body) = ¶ms.from_body {
subject.insert("fromBody".into(), json!(from_body));
}
let mut cred = Map::new();
cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
cred.insert(
"type".into(),
json!(["VerifiableCredential", EMBODIMENT_TYPE]),
);
cred.insert("issuer".into(), json!(params.agent_did));
cred.insert("validFrom".into(), json!(params.embodied_at));
if let Some(vu) = ¶ms.valid_until {
cred.insert("validUntil".into(), json!(vu));
}
cred.insert("credentialSubject".into(), Value::Object(subject));
let opts = BuildProofOptions::new(format!("{}#key-1", params.agent_did), ¶ms.embodied_at);
data_integrity::sign(&Value::Object(cred), agent_seed, &opts)
}
/// Verify an embodiment credential: the agent's proof bound to the agent as
/// issuer (a mind authorizes its own embodiment, so the issuer must be
/// `credentialSubject.id`), the window at `now_iso` (validFrom required), and
/// that the subject carries a `body` and a `bodyHardwareRoot`. When
/// `body_hardware_roots` (body DID -> trusted hardware-root key) is given, the
/// credential's `bodyHardwareRoot` must match the entry for its body. Returns
/// the credentialSubject on success, `None` if invalid.
pub fn verify_embodiment(
credential: &Value,
agent_keys: Keys<'_>,
body_hardware_roots: Option<&alloc::collections::BTreeMap<String, String>>,
now_iso: &str,
) -> Result<Option<Value>> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
let v = match bound(
credential,
agent_keys,
EMBODIMENT_TYPE,
now_iso,
Window::FromRequired,
)? {
Some(v) if issuer_is_subject(&v) => v,
_ => return Ok(None),
};
let body = non_empty_str(&v.subject, "body");
let root = non_empty_str(&v.subject, "bodyHardwareRoot");
let (body, root) = match (body, root) {
(Some(b), Some(r)) => (b, r),
_ => return Ok(None),
};
if let Some(roots) = body_hardware_roots {
if roots.get(body).map(String::as_str) != Some(root) {
return Ok(None);
}
}
Ok(Some(v.subject))
}
/// Verify an ordered list of embodiment credentials forms a valid continuity
/// chain: every link verifies under the same agent (the persistent mind), each
/// link's `fromBody` matches the previous link's `body`, and (when given) the
/// first `fromBody` is `origin_body`. Links start in order; each earlier link
/// must still have been valid when the next one started, and the last link
/// must be valid at `now_iso`. The verified links are then checked for forks.
/// Returns `(ok, current_body)`.
pub fn verify_continuity_chain(
embodiments: &[Value],
agent_keys: Keys<'_>,
origin_body: Option<&str>,
body_hardware_roots: Option<&alloc::collections::BTreeMap<String, String>>,
now_iso: &str,
) -> Result<(bool, Option<String>)> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); embodiments);
rv::require_now(now_iso)?;
let mut expected_from: Option<String> = origin_body.map(String::from);
let mut current_body: Option<String> = origin_body.map(String::from);
let mut agent: Option<String> = None;
let mut prev_start: Option<i128> = None;
for (i, embodiment) in embodiments.iter().enumerate() {
let at: String = match embodiments.get(i + 1) {
Some(next) => match next.get("validFrom").and_then(|v| v.as_str()) {
Some(t) if rv::time_ns(next.get("validFrom")).is_some() => t.to_string(),
_ => return Ok((false, None)),
},
None => now_iso.to_string(),
};
let subject = match verify_embodiment(embodiment, agent_keys, body_hardware_roots, &at)? {
Some(s) => s,
None => return Ok((false, None)),
};
let id = subject.get("id").and_then(|v| v.as_str()).map(String::from);
match &agent {
None => agent = id,
Some(a) if id.as_deref() == Some(a.as_str()) => {}
_ => return Ok((false, None)),
}
match rv::time_ns(embodiment.get("validFrom")) {
Some(t) if prev_start.is_none_or(|p| t >= p) => prev_start = Some(t),
_ => return Ok((false, None)),
}
if let Some(expected) = &expected_from {
if subject.get("fromBody").and_then(|v| v.as_str()) != Some(expected.as_str()) {
return Ok((false, None));
}
}
current_body = subject
.get("body")
.and_then(|v| v.as_str())
.map(String::from);
expected_from = current_body.clone();
}
if !check_no_fork(embodiments)?.0 {
return Ok((false, None));
}
Ok((true, current_body))
}
/// Two conflicting bodies surfaced by [`check_no_fork`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ForkConflict {
pub body_a: String,
pub body_b: String,
}
/// Half-open intervals [start, end); a missing end is open-ended (+infinity). A
/// clean handover sets one window's end to the next window's start, which does not
/// overlap.
fn windows_overlap(start_a: i128, end_a: Option<i128>, start_b: i128, end_b: Option<i128>) -> bool {
let a_before_b = end_a.map(|e| e <= start_b).unwrap_or(false);
let b_before_a = end_b.map(|e| e <= start_a).unwrap_or(false);
!(a_before_b || b_before_a)
}
/// Confirm no two embodiments place the agent in different bodies with overlapping
/// active windows. Each embodiment is active from `validFrom` to `validUntil` (a
/// missing `validUntil` is treated as open-ended). Two embodiments on different
/// bodies whose windows overlap are a fork. Returns `(ok, conflict)` where
/// conflict, when present, names the two conflicting bodies.
pub fn check_no_fork(embodiments: &[Value]) -> Result<(bool, Option<ForkConflict>)> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); embodiments);
let mut windows: Vec<(String, i128, Option<i128>)> = Vec::with_capacity(embodiments.len());
for embodiment in embodiments {
let subject = embodiment
.get("credentialSubject")
.and_then(|s| s.as_object());
let body = subject
.and_then(|s| s.get("body"))
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty());
let start = rv::time_ns(embodiment.get("validFrom"));
let (body, start) = match (body, start) {
(Some(b), Some(s)) => (b.to_string(), s),
_ => return Ok((false, None)),
};
// A present end must be a strict time; only an absent end is open-ended.
let end = match embodiment.get("validUntil") {
None => None,
Some(v) => match rv::time_ns(Some(v)) {
Some(t) => Some(t),
None => return Ok((false, None)),
},
};
windows.push((body, start, end));
}
let Some(first) = first_forked_index(&windows) else {
return Ok((true, None));
};
let (body_i, start_i, end_i) = &windows[first];
for (body_j, start_j, end_j) in &windows[first + 1..] {
if body_i != body_j && windows_overlap(*start_i, *end_i, *start_j, *end_j) {
return Ok((
false,
Some(ForkConflict {
body_a: body_i.clone(),
body_b: body_j.clone(),
}),
));
}
}
unreachable!("the forked window has a partner")
}
/// The most windows on one body a segmented fork check keeps at once (the
/// windows whose ends still matter). A real history holds a handful; a
/// history that needs more is refused and must be checked whole.
pub const MAX_FORK_WINDOWS: usize = 4096;
/// Why a segmented fork check failed for a reason other than a fork.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ForkFailure {
/// An embodiment has no body, no valid `validFrom`, or a `validUntil`
/// that is not a protocol time. The whole check answers `(false, None)`.
Malformed(u64),
/// An embodiment starts before the one before it. The segmented check
/// reads a history in `validFrom` order.
OutOfOrder(u64),
/// More than [`MAX_FORK_WINDOWS`] windows on one body overlap at once.
TooManyWindows(u64),
}
/// Where a fork check stands after the first embodiments of a history, so a
/// long history is checked one segment at a time with bounded memory. The
/// history must be in `validFrom` order (the order a history is recorded
/// in); for such a history the verdict after the last segment is the one
/// [`check_no_fork`] gives for the whole list, conflict included.
///
/// The bookkeeping: while no fork has been seen, every window still open at
/// the latest start is on one body (two such windows on different bodies
/// would overlap). `windows` keeps, for that body, the points where the
/// latest end so far grows: `(start, latest end up to that start)`, with
/// `None` for an open end. A later window on another body forks exactly
/// when some kept window that starts before its end also ends after its
/// start.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ForkProgress {
/// Embodiments checked so far.
pub count: u64,
/// The latest `validFrom` seen, in nanoseconds.
pub last_start: Option<i128>,
/// The body every open window is on.
pub body: Option<String>,
/// `(start, latest end)` steps for `body`, oldest first.
pub windows: Vec<(i128, Option<i128>)>,
/// The first fork, as [`check_no_fork`] reports it.
pub conflict: Option<ForkConflict>,
/// A failure that is not a fork.
pub failure: Option<ForkFailure>,
}
impl Default for ForkProgress {
fn default() -> Self {
Self::start()
}
}
/// `a` ends after instant `t` (an open end is after everything).
fn ends_after(end: Option<i128>, t: i128) -> bool {
end.is_none_or(|e| e > t)
}
impl ForkProgress {
pub fn start() -> Self {
Self {
count: 0,
last_start: None,
body: None,
windows: Vec::new(),
conflict: None,
failure: None,
}
}
/// The verdict over every embodiment checked so far: `(ok, conflict)`
/// as [`check_no_fork`] gives it, plus a reason when not ok.
pub fn result(&self) -> (bool, Option<ForkConflict>, Option<String>) {
match &self.failure {
Some(ForkFailure::Malformed(i)) => (
false,
None,
Some(format!(
"embodiment {i} has no body, or a bad validFrom or validUntil"
)),
),
Some(ForkFailure::OutOfOrder(i)) => (
false,
None,
Some(format!(
"embodiment {i} starts before the one before it; a segmented check reads the history in validFrom order"
)),
),
Some(ForkFailure::TooManyWindows(i)) => (
false,
None,
Some(format!(
"at embodiment {i} more than {MAX_FORK_WINDOWS} windows on one body are open at once; check this history whole"
)),
),
None => match &self.conflict {
Some(c) => (
false,
Some(c.clone()),
Some("the agent is in two bodies at once".into()),
),
None => (true, None, None),
},
}
}
}
/// Check the next `embodiments` of a history (one segment) for forks and
/// move `progress` past them.
pub fn check_no_fork_segment(progress: &mut ForkProgress, embodiments: &[Value]) {
#[cfg(not(feature = "std"))]
if crate::nesting::Nested::nests_past(&embodiments, crate::nesting::NO_STD_MAX_NESTING) {
progress.failure = Some(ForkFailure::Malformed(progress.count));
return;
}
#[cfg(not(feature = "std"))]
if crate::nesting::Nested::nests_past(&embodiments, crate::nesting::NO_STD_MAX_NESTING) {
progress.failure = Some(ForkFailure::Malformed(progress.count));
return;
}
for embodiment in embodiments {
let i = progress.count;
progress.count = progress.count.saturating_add(1);
if matches!(
progress.failure,
Some(ForkFailure::Malformed(_)) | Some(ForkFailure::OutOfOrder(_))
) {
continue;
}
let body = embodiment
.get("credentialSubject")
.and_then(|s| s.as_object())
.and_then(|s| s.get("body"))
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty());
let start = rv::time_ns(embodiment.get("validFrom"));
let end = match embodiment.get("validUntil") {
None => Ok(None),
Some(v) => rv::time_ns(Some(v)).map(Some).ok_or(()),
};
let (body, start, end) = match (body, start, end) {
(Some(b), Some(s), Ok(e)) => (b, s, e),
_ => {
// The whole check answers (false, None) for a malformed
// entry anywhere in the list, a fork or not.
progress.failure = Some(ForkFailure::Malformed(i));
continue;
}
};
if progress.conflict.is_some() || progress.failure.is_some() {
// The verdict is set; only a malformed entry can still change it.
continue;
}
if progress.last_start.is_some_and(|p| start < p) {
progress.failure = Some(ForkFailure::OutOfOrder(i));
continue;
}
progress.last_start = Some(start);
// Steps whose latest end is not after this start can never overlap
// this or any later window (later windows start no earlier).
let live = progress
.windows
.iter()
.position(|(_, e)| ends_after(*e, start))
.unwrap_or(progress.windows.len());
progress.windows.drain(..live);
if progress.windows.is_empty() {
progress.body = None;
}
let same_body = progress.body.as_deref() == Some(body);
if !same_body && progress.body.is_some() {
// The latest end over the open windows on the other body that
// start before this window's end. A window that ends after it
// starts is past every kept start.
let latest = progress
.windows
.iter()
.take_while(|(s, _)| end.is_none_or(|e| *s < e))
.last()
.map(|(_, e)| *e);
if let Some(latest) = latest {
if ends_after(latest, start) {
progress.conflict = Some(ForkConflict {
body_a: progress.body.clone().unwrap_or_default(),
body_b: body.to_string(),
});
continue;
}
}
}
// A window that ends at or before its start never overlaps a later
// window, so it is not kept.
if !ends_after(end, start) {
continue;
}
if !same_body {
progress.body = Some(body.to_string());
progress.windows.clear();
}
let grows = match progress.windows.last() {
None => true,
Some((_, latest)) => match (latest, end) {
(None, _) => false,
(Some(_), None) => true,
(Some(l), Some(e)) => e > *l,
},
};
if grows {
if progress.windows.len() >= MAX_FORK_WINDOWS {
progress.failure = Some(ForkFailure::TooManyWindows(i));
continue;
}
progress.windows.push((start, end));
}
}
}
/// The smallest i whose window overlaps a later window on another body, or
/// None: the window a pairwise scan in list order reports first, found in
/// O(n log n).
///
/// Times become ranks. Walking the list from the end, a Fenwick tree indexed by
/// start rank holds the later windows; each node keeps the latest end for its
/// range plus the latest end on any other body. Window i overlaps a later
/// window j on another body exactly when some j with start_j < end_i, on
/// another body, has end_j > start_i.
fn first_forked_index(windows: &[(String, i128, Option<i128>)]) -> Option<usize> {
let mut times: Vec<i128> = windows
.iter()
.flat_map(|(_, s, e)| core::iter::once(*s).chain(*e))
.collect();
times.sort_unstable();
times.dedup();
let size = times.len();
let rank = |t: i128| times.binary_search(&t).expect("every time is ranked") as i64;
let mut body_ids: crate::collections::HashMap<&str, i64> = crate::collections::HashMap::new();
let ranked: Vec<(i64, i64, i64)> = windows
.iter()
.map(|(b, s, e)| {
let next = body_ids.len() as i64;
let id = *body_ids.entry(b.as_str()).or_insert(next);
(id, rank(*s), e.map_or(size as i64, rank))
})
.collect();
let mut tree = vec![TopTwo::EMPTY; size + 1];
let mut first = None;
for i in (0..ranked.len()).rev() {
let (body, start, end) = ranked[i];
let mut acc = TopTwo::EMPTY;
let mut k = (end as usize).min(size);
while k > 0 {
acc.add(tree[k].end, tree[k].body);
acc.add(tree[k].other_end, tree[k].other_body);
k &= k - 1;
}
let other_end = if acc.body != body {
acc.end
} else {
acc.other_end
};
if other_end > start {
first = Some(i);
}
let mut k = start as usize + 1;
while k <= size {
tree[k].add(end, body);
k += k & k.wrapping_neg();
}
}
first
}
/// The latest end in a range, and the latest end on a body other than its own.
#[derive(Clone, Copy)]
struct TopTwo {
end: i64,
body: i64,
other_end: i64,
other_body: i64,
}
impl TopTwo {
const EMPTY: TopTwo = TopTwo {
end: -1,
body: -1,
other_end: -1,
other_body: -1,
};
fn add(&mut self, end: i64, body: i64) {
if body < 0 {
return;
}
if body == self.body {
self.end = self.end.max(end);
} else if body == self.other_body {
if end > self.other_end {
self.other_end = end;
if self.other_end > self.end {
core::mem::swap(&mut self.end, &mut self.other_end);
core::mem::swap(&mut self.body, &mut self.other_body);
}
}
} else if end > self.end {
self.other_end = self.end;
self.other_body = self.body;
self.end = end;
self.body = body;
} else if end > self.other_end {
self.other_end = end;
self.other_body = body;
}
}
}
// ---------------------------------------------------------------------------
// Physical custody handoff (Phase 5.16)
// ---------------------------------------------------------------------------
//
// A physical task or object passes across a chain of actors, human and robot: a
// person picks an item, hands it to a robot, that robot hands it to another
// robot, which places it. Each handoff is a signed custody transition, so a
// physical-world event traces to the exact hop and the actor responsible.
//
// A custody handoff credential records that a receiving actor accepted custody
// of a task or object from a releasing actor, signed by the receiver. Linking
// each handoff to the previous forms a chain a verifier walks to establish who
// held the task at any time. A condition attested at each handoff lets a state
// change be localized to the specific hop whose holder was responsible.
//
// This is the open layer: signed handoff credentials, chain verification, a
// holder-at-time helper, and software condition localization. It reuses the core
// proof path ([`data_integrity`]) rather than re-deriving any cryptography.
pub const CUSTODY_HANDOFF_TYPE: &str = "CustodyHandoffCredential";
/// A signed custody release: the actor handing a task over states that it
/// releases custody to the receiver. The receiver embeds it in its handoff.
pub const CUSTODY_RELEASE_TYPE: &str = "CustodyReleaseCredential";
/// Build a signed custody release by `releaser_did` (the signer) for
/// `task_id` to `to_actor`, dated `released_at`.
pub fn build_release(
releaser_seed: &[u8],
releaser_did: &str,
task_id: &str,
to_actor: &str,
released_at: &str,
) -> Result<Value> {
if task_id.is_empty() || to_actor.is_empty() {
return Err(CoreError::Json("task_id and to_actor are required".into()));
}
let cred = json!({
"@context": [VC_CONTEXT_V2, VOUCH_CONTEXT_V1],
"type": ["VerifiableCredential", CUSTODY_RELEASE_TYPE],
"issuer": releaser_did,
"validFrom": released_at,
"credentialSubject": {"id": task_id, "fromActor": releaser_did, "toActor": to_actor},
});
let opts = BuildProofOptions::new(format!("{releaser_did}#key-1"), released_at);
data_integrity::sign(&cred, releaser_seed, &opts)
}
/// Parameters for [`build_handoff`]. The signer is the receiver (`to_actor`), the
/// party taking responsibility. `condition`, when set, attests the state of the
/// task or object as received, which lets a later state change be localized to
/// a hop. `release` is the releasing actor's signed [`build_release`]
/// credential (a chain verifier requires it). `prev_handoff_id` is the previous
/// handoff's `id`; `credential_id` is this handoff's own `id`. `valid_until`,
/// when set, bounds the handoff's active window.
#[derive(Debug, Clone)]
pub struct BuildHandoff {
pub task_id: String,
pub from_actor: String,
pub to_actor: String,
pub condition: Option<String>,
pub handoff_at: String,
pub valid_until: Option<String>,
pub release: Option<Value>,
pub prev_handoff_id: Option<String>,
pub credential_id: String,
}
/// Build a signed custody handoff: the receiving actor `to_actor` accepts custody
/// of `task_id` from `from_actor`, signed by the receiver. The issuer is the
/// receiver, so a party attests its own acceptance of custody.
pub fn build_handoff(receiver_seed: &[u8], params: &BuildHandoff) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
if params.task_id.is_empty() || params.from_actor.is_empty() || params.to_actor.is_empty() {
return Err(CoreError::Json(
"task_id, from_actor, and to_actor are required".into(),
));
}
if params.credential_id.is_empty() {
return Err(CoreError::Json("credential_id is required".into()));
}
let mut subject = Map::new();
subject.insert("id".into(), json!(params.task_id));
subject.insert("fromActor".into(), json!(params.from_actor));
subject.insert("toActor".into(), json!(params.to_actor));
if let Some(condition) = ¶ms.condition {
subject.insert("condition".into(), json!(condition));
}
if let Some(release) = ¶ms.release {
subject.insert("release".into(), release.clone());
}
if let Some(prev) = ¶ms.prev_handoff_id {
subject.insert("prevHandoffId".into(), json!(prev));
}
let mut cred = Map::new();
cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
cred.insert("id".into(), json!(params.credential_id));
cred.insert(
"type".into(),
json!(["VerifiableCredential", CUSTODY_HANDOFF_TYPE]),
);
cred.insert("issuer".into(), json!(params.to_actor));
cred.insert("validFrom".into(), json!(params.handoff_at));
if let Some(vu) = ¶ms.valid_until {
cred.insert("validUntil".into(), json!(vu));
}
cred.insert("credentialSubject".into(), Value::Object(subject));
let opts = BuildProofOptions::new(format!("{}#key-1", params.to_actor), ¶ms.handoff_at);
data_integrity::sign(&Value::Object(cred), receiver_seed, &opts)
}
/// True when the handoff `subject` embeds a release signed by its `fromActor`
/// that names the same task and receiver.
fn release_ok(subject: &Value, releaser_keys: Keys<'_>, now_ns: i128) -> bool {
let release = match subject.get("release") {
Some(r) => r,
None => return false,
};
let v = match rv::verify_robotics_credential(
release,
releaser_keys,
Some(CUSTODY_RELEASE_TYPE),
now_ns,
VerifyOptions::window(Window::FromRequired),
) {
Ok(v) => v,
Err(_) => return false,
};
let s = |x: &Value, k: &str| x.get(k).and_then(|y| y.as_str()).map(String::from);
Some(v.issuer.clone()) == s(subject, "fromActor")
&& s(&v.subject, "fromActor").as_deref() == Some(v.issuer.as_str())
&& s(&v.subject, "id") == s(subject, "id")
&& s(&v.subject, "toActor") == s(subject, "toActor")
}
/// Options for [`verify_handoff`].
#[derive(Clone, Copy, Default)]
pub struct HandoffCheck<'a> {
/// The handoff must be for this task.
pub task_id: Option<&'a str>,
/// Key source for the releasing actor; giving one requires the release.
pub releaser_keys: Option<Keys<'a>>,
/// Require the releasing actor's signed release (keys from the receiver
/// source when no `releaser_keys` is given).
pub require_release: bool,
/// The releasing actor the caller expects. The release must be signed by
/// it and name it as `fromActor`; with no releaser key a did:key releaser
/// verifies under its own key only when this names it, and the receiver
/// is then pinned to the toActor that verified release names.
pub from_actor: Option<&'a str>,
}
/// Verify a custody handoff: the receiver's proof bound to the issuer, the
/// issuer is the receiving actor (`toActor`), `id` / `fromActor` / `toActor`
/// are non-empty strings, and the window at `now_iso` (validFrom required).
/// With [`HandoffCheck`] options, the task is pinned and the embedded release
/// must be signed by the `fromActor` and name the same task and receiver.
pub fn verify_handoff(
credential: &Value,
receiver_keys: Keys<'_>,
check: HandoffCheck<'_>,
now_iso: &str,
) -> Result<Option<Value>> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
let now = rv::require_now(now_iso)?;
let releaser_keys = rv::pin_if_keyless(
check.releaser_keys.unwrap_or(receiver_keys),
check.from_actor,
);
// With no receiver key, the receiver is pinned to the toActor named by the
// release the pinned releaser signed.
let mut receiver_pin: Option<String> = None;
if check.from_actor.is_some() && rv::no_key_source(&receiver_keys) {
if let Some(rel) = credential
.get("credentialSubject")
.and_then(|s| s.get("release"))
{
if let Ok(r) = rv::verify_robotics_credential(
rel,
releaser_keys,
Some(CUSTODY_RELEASE_TYPE),
now,
VerifyOptions::window(Window::FromRequired),
) {
if r.subject.get("fromActor").and_then(|x| x.as_str()) == Some(r.issuer.as_str()) {
receiver_pin = non_empty_str(&r.subject, "toActor").map(String::from);
}
}
}
}
let v = match rv::verify_robotics_credential(
credential,
rv::pin_if_keyless(receiver_keys, receiver_pin.as_deref()),
Some(CUSTODY_HANDOFF_TYPE),
now,
VerifyOptions::window(Window::FromRequired),
) {
Ok(v) => v,
Err(_) => return Ok(None),
};
for f in ["id", "fromActor", "toActor"] {
if non_empty_str(&v.subject, f).is_none() {
return Ok(None);
}
}
if v.subject.get("toActor").and_then(|x| x.as_str()) != Some(v.issuer.as_str()) {
return Ok(None);
}
if check
.task_id
.is_some_and(|t| v.subject.get("id").and_then(|x| x.as_str()) != Some(t))
{
return Ok(None);
}
if check
.from_actor
.is_some_and(|f| v.subject.get("fromActor").and_then(|x| x.as_str()) != Some(f))
{
return Ok(None);
}
if (check.require_release || check.releaser_keys.is_some() || check.from_actor.is_some())
&& !release_ok(&v.subject, releaser_keys, now)
{
return Ok(None);
}
Ok(Some(v.subject))
}
/// One actor's public key, looked up by actor DID, for [`verify_handoff_chain`].
#[derive(Debug, Clone)]
pub struct ActorKey {
pub did: String,
pub public_key: Vec<u8>,
}
/// Verify an ordered list of handoff credentials forms a valid custody chain for
/// `task_id`: every handoff verifies under its receiver's key and (with
/// `require_release`) carries a release signed by its releasing actor (keys for
/// both from `public_keys`); each `toActor` matches the next link's
/// `fromActor`; each link after the first names the previous link's `id` as
/// `prevHandoffId`; links are in time order; and the first `fromActor` is
/// `origin_actor`. Each earlier link must still have been valid when the next
/// began, and the last at `now_iso`. Returns `(ok, current_holder)`.
///
/// `origin_actor` is required: with no known first holder, anyone could sign a
/// first link handing the task from themselves. Each link's releaser is pinned
/// (the origin, then each `toActor`), so did:key actors verify under their own
/// keys even with no entry in `public_keys`.
pub fn verify_handoff_chain(
handoffs: &[Value],
public_keys: &[ActorKey],
task_id: &str,
origin_actor: Option<&str>,
require_release: bool,
now_iso: &str,
) -> Result<(bool, Option<String>)> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); handoffs);
rv::require_now(now_iso)?;
if task_id.is_empty() || origin_actor.is_none_or(str::is_empty) {
return Ok((false, None));
}
let map = Keys::map_of(public_keys.iter().map(|k| (k.did.clone(), &k.public_key)));
let keys = Keys::Map(&map);
let mut expected_from: Option<String> = origin_actor.map(String::from);
let mut current_holder: Option<String> = origin_actor.map(String::from);
let mut prev_id: Option<String> = None;
let mut prev_time: Option<i128> = None;
for (i, handoff) in handoffs.iter().enumerate() {
let at: String = match handoffs.get(i + 1) {
Some(next) => match next.get("validFrom").and_then(|v| v.as_str()) {
Some(t) if rv::time_ns(next.get("validFrom")).is_some() => t.to_string(),
_ => return Ok((false, None)),
},
None => now_iso.to_string(),
};
let check = HandoffCheck {
task_id: Some(task_id),
releaser_keys: if require_release { Some(keys) } else { None },
require_release,
from_actor: if require_release {
expected_from.as_deref()
} else {
None
},
};
let subject = match verify_handoff(handoff, keys, check, &at)? {
Some(s) => s,
None => return Ok((false, None)),
};
if let Some(expected) = &expected_from {
if subject.get("fromActor").and_then(|v| v.as_str()) != Some(expected.as_str()) {
return Ok((false, None));
}
}
match rv::time_ns(handoff.get("validFrom")) {
Some(t) if prev_time.is_none_or(|p| t >= p) => prev_time = Some(t),
_ => return Ok((false, None)),
}
if i > 0 {
match &prev_id {
Some(p) if subject.get("prevHandoffId").and_then(|v| v.as_str()) == Some(p) => {}
_ => return Ok((false, None)),
}
}
prev_id = non_empty_str(handoff, "id").map(String::from);
current_holder = subject
.get("toActor")
.and_then(|v| v.as_str())
.map(String::from);
expected_from = current_holder.clone();
}
Ok((true, current_holder))
}
/// Return the actor holding the task at protocol time `at`: the receiver
/// (`toActor`) of the most recent handoff whose `validFrom` is at or before
/// `at`. Returns `None` if no handoff had occurred yet or `at` is not a strict
/// protocol time. `handoffs` is assumed in chain order.
pub fn holder_at(handoffs: &[Value], at: &str) -> Option<String> {
crate::nesting::deep_guard!(None; handoffs);
let when = crate::time::parse_protocol_time_ns(at).ok()?;
let mut holder: Option<String> = None;
for handoff in handoffs {
if let Some(start) = rv::time_ns(handoff.get("validFrom")) {
if start <= when {
holder = handoff
.get("credentialSubject")
.and_then(|s| s.get("toActor"))
.and_then(|v| v.as_str())
.map(String::from);
}
}
}
holder
}
/// A condition change localized to the hop responsible for it, surfaced by
/// [`locate_condition_change`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConditionChange {
pub responsible_holder: Option<String>,
pub from_condition: String,
pub to_condition: String,
}
/// Find the first hop where the attested condition differs from the previous
/// handoff. The holder responsible for the change is the actor who held the task
/// during it (the previous handoff's receiver). Returns the change, or `None` if
/// the condition never changed. Handoffs without a condition are skipped for the
/// comparison.
pub fn locate_condition_change(handoffs: &[Value]) -> Option<ConditionChange> {
crate::nesting::deep_guard!(None; handoffs);
let mut prev_condition: Option<String> = None;
let mut prev_holder: Option<String> = None;
for handoff in handoffs {
let subject = handoff.get("credentialSubject");
let condition = subject
.and_then(|s| s.get("condition"))
.and_then(|v| v.as_str());
let condition = match condition {
Some(c) => c,
None => continue,
};
if let Some(prev) = &prev_condition {
if condition != prev {
return Some(ConditionChange {
responsible_holder: prev_holder,
from_condition: prev.clone(),
to_condition: condition.to_string(),
});
}
}
prev_condition = Some(condition.to_string());
prev_holder = subject
.and_then(|s| s.get("toActor"))
.and_then(|v| v.as_str())
.map(String::from);
}
None
}
// ---------------------------------------------------------------------------
// Robot-to-infrastructure bounded access (Phase 5.17)
// ---------------------------------------------------------------------------
//
// A robot in a warehouse, hospital, or building needs to open doors, call
// elevators, dock at chargers, and operate machines. This gives it a bounded,
// revocable, auditable way to do so. The infrastructure operator issues an access
// grant naming a resource, the permitted operations, an optional zone, and a time
// window, signed by the operator. The robot presents a signed access request for a
// specific operation on a specific resource, and the resource authorizes it
// offline: the grant must be valid and operator-signed, the request valid and
// robot-signed, the operation permitted, and the moment inside the window. The
// grant plus the request is a tamper-evident, attributable record of the access.
//
// This is the open layer: signed grants and requests, an offline authorize
// decision, shrink-only attenuation, and the audit record. Hardware-enforced
// actuation in the resource and managed fleet access-policy orchestration are out
// of scope for the open layer.
pub const ACCESS_GRANT_TYPE: &str = "InfrastructureAccessGrant";
pub const ACCESS_REQUEST_TYPE: &str = "InfrastructureAccessRequest";
/// Parameters for [`build_access_grant`]. The signer is the operator; the grant
/// names the robot, the resource, the permitted operations, an optional zone, and
/// a validity window. `valid_until`, when set, bounds the window (the wrapper
/// derives it from a `valid_seconds` lifetime added to `granted_at`, keeping the
/// core's clock caller-supplied).
#[derive(Debug, Clone)]
pub struct BuildAccessGrant {
pub operator_did: String,
pub robot_did: String,
pub resource: String,
pub operations: Vec<String>,
pub zone: Option<String>,
pub granted_at: String,
pub valid_until: Option<String>,
}
/// Build a signed access grant: the operator grants `robot_did` permission to
/// perform `operations` on `resource` (optionally within `zone`) for the window.
/// Signed by the operator.
pub fn build_access_grant(operator_seed: &[u8], params: &BuildAccessGrant) -> Result<Value> {
if params.robot_did.is_empty() || params.resource.is_empty() {
return Err(CoreError::Json(
"robot_did and resource are required".into(),
));
}
if params.operations.is_empty() {
return Err(CoreError::Json(
"operations must be a non-empty list".into(),
));
}
let mut subject = Map::new();
subject.insert("id".into(), json!(params.robot_did));
subject.insert("resource".into(), json!(params.resource));
subject.insert("operations".into(), json!(params.operations));
if let Some(zone) = ¶ms.zone {
subject.insert("zone".into(), json!(zone));
}
let mut cred = Map::new();
cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
cred.insert(
"type".into(),
json!(["VerifiableCredential", ACCESS_GRANT_TYPE]),
);
cred.insert("issuer".into(), json!(params.operator_did));
cred.insert("validFrom".into(), json!(params.granted_at));
if let Some(vu) = ¶ms.valid_until {
cred.insert("validUntil".into(), json!(vu));
}
cred.insert("credentialSubject".into(), Value::Object(subject));
let opts = BuildProofOptions::new(format!("{}#key-1", params.operator_did), ¶ms.granted_at);
data_integrity::sign(&Value::Object(cred), operator_seed, &opts)
}
/// Verify an access grant: the operator's proof bound to the issuer
/// (`operator_keys` is a `{did: key}` source, or the bare key of a did:key
/// operator), validFrom and validUntil present strict protocol times with
/// `now_iso` inside, a non-empty string `resource`, a non-empty list of string
/// `operations`, and (when given) the operator in `trusted_operators`. Returns
/// the credentialSubject on success, `None` if invalid.
pub fn verify_access_grant(
credential: &Value,
operator_keys: Keys<'_>,
trusted_operators: Option<&HashSet<String>>,
now_iso: &str,
) -> Result<Option<Value>> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
let now = rv::require_now(now_iso)?;
let opts = VerifyOptions {
trusted_issuers: trusted_operators,
..VerifyOptions::window(Window::Required)
};
let v = match rv::verify_robotics_credential(
credential,
operator_keys,
Some(ACCESS_GRANT_TYPE),
now,
opts,
) {
Ok(v) => v,
Err(_) => return Ok(None),
};
if non_empty_str(&v.subject, "resource").is_none() {
return Ok(None);
}
match v.subject.get("operations") {
Some(Value::Array(ops)) if !ops.is_empty() && ops.iter().all(|o| o.is_string()) => {}
_ => return Ok(None),
}
Ok(Some(v.subject))
}
/// Parameters for [`build_access_request`]. The signer is the robot; the request
/// names the resource and the single operation the robot wants to perform.
#[derive(Debug, Clone)]
pub struct BuildAccessRequest {
pub robot_did: String,
pub resource: String,
pub operation: String,
pub requested_at: String,
/// A one-time value the resource remembers to refuse a replay.
pub nonce: String,
}
/// Build a signed access request: the robot requests to perform `operation` on
/// `resource`. Signed by the robot.
pub fn build_access_request(robot_seed: &[u8], params: &BuildAccessRequest) -> Result<Value> {
if params.robot_did.is_empty() || params.resource.is_empty() || params.operation.is_empty() {
return Err(CoreError::Json(
"robot_did, resource, and operation are required".into(),
));
}
if params.nonce.is_empty() {
return Err(CoreError::Json("nonce is required".into()));
}
let mut subject = Map::new();
subject.insert("id".into(), json!(params.robot_did));
subject.insert("resource".into(), json!(params.resource));
subject.insert("operation".into(), json!(params.operation));
subject.insert("nonce".into(), json!(params.nonce));
let mut cred = Map::new();
cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
cred.insert(
"type".into(),
json!(["VerifiableCredential", ACCESS_REQUEST_TYPE]),
);
cred.insert("issuer".into(), json!(params.robot_did));
cred.insert("validFrom".into(), json!(params.requested_at));
cred.insert("credentialSubject".into(), Value::Object(subject));
let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), ¶ms.requested_at);
data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
}
/// The outcome of an offline access authorization: `ok` plus any reasons it
/// failed. Surfaced by [`authorize_access`].
#[derive(Debug, Clone)]
pub struct AuthorizeResult {
pub ok: bool,
pub reasons: Vec<String>,
}
/// Decide, offline, whether to allow the requested access. The grant must verify
/// under the operator's key and be in window, the request must verify bound to
/// the robot as issuer (and name it as subject) with validFrom no later than
/// `now_iso` (keys are `{did: key}` sources, or bare keys of did:key parties), the grant and request must
/// name the same robot and resource, and the requested operation must be permitted
/// by the grant. Returns an [`AuthorizeResult`] with the reasons for any refusal.
/// How old an access request may be by default (seconds).
pub const DEFAULT_MAX_REQUEST_AGE_SECONDS: i64 = 60;
/// Replay limits for [`authorize_access`]: the request may be no older than
/// `max_age_seconds` and not from the future (both with `clock_skew_seconds`),
/// and its nonce must not be in `seen_nonces` (it is added when access is
/// allowed).
pub struct RequestReplay<'a> {
pub seen_nonces: &'a mut HashSet<String>,
pub max_age_seconds: i64,
pub clock_skew_seconds: i64,
/// With no operator key, the grant verifies only when its did:key
/// operator is in this non-empty set.
pub trusted_operators: Option<&'a HashSet<String>>,
}
impl<'a> RequestReplay<'a> {
/// The default limits (60 s age, 30 s skew) over `seen_nonces`.
pub fn new(seen_nonces: &'a mut HashSet<String>) -> Self {
Self {
seen_nonces,
max_age_seconds: DEFAULT_MAX_REQUEST_AGE_SECONDS,
clock_skew_seconds: 30,
trusted_operators: None,
}
}
}
pub fn authorize_access(
grant: &Value,
request: &Value,
operator_keys: Keys<'_>,
robot_keys: Keys<'_>,
replay: RequestReplay<'_>,
now_iso: &str,
) -> Result<AuthorizeResult> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); grant, request);
let current = rv::require_now(now_iso)?;
let mut reasons: Vec<String> = Vec::new();
let grant_subject =
match verify_access_grant(grant, operator_keys, replay.trusted_operators, now_iso)? {
Some(s) => s,
None => {
reasons.push("grant invalid or out of window".into());
return Ok(AuthorizeResult { ok: false, reasons });
}
};
// With no robot key, only the robot the verified grant names may sign.
let granted_robot = grant_subject
.get("id")
.and_then(|v| v.as_str())
.map(String::from);
let req_subject = match bound(
request,
rv::pin_if_keyless(robot_keys, granted_robot.as_deref()),
ACCESS_REQUEST_TYPE,
now_iso,
Window::FromRequired,
)? {
Some(v) if issuer_is_subject(&v) => v.subject,
_ => {
reasons.push("request invalid".into());
return Ok(AuthorizeResult { ok: false, reasons });
}
};
let second: i128 = 1_000_000_000;
let skew = i128::from(replay.clock_skew_seconds) * second;
match rv::time_ns(request.get("validFrom")) {
Some(issued) if issued > current + skew => {
reasons.push("request is dated in the future".into())
}
Some(issued) if current - issued > i128::from(replay.max_age_seconds) * second + skew => {
reasons.push("request is too old".into())
}
Some(_) => {}
None => reasons.push("request is dated in the future".into()),
}
let nonce = non_empty_str(&req_subject, "nonce").map(String::from);
match &nonce {
None => reasons.push("request carries no nonce".into()),
Some(n) if replay.seen_nonces.contains(n) => {
reasons.push("request was already used (replay)".into())
}
Some(_) => {}
}
if !reasons.is_empty() {
return Ok(AuthorizeResult { ok: false, reasons });
}
let req_id = req_subject.get("id").and_then(|v| v.as_str());
if grant_subject.get("id").and_then(|v| v.as_str()) != req_id {
reasons.push("grant and request name different robots".into());
}
if grant_subject.get("resource").and_then(|v| v.as_str())
!= req_subject.get("resource").and_then(|v| v.as_str())
{
reasons.push("grant and request name different resources".into());
}
let operation = req_subject.get("operation").and_then(|v| v.as_str());
let permitted = grant_subject
.get("operations")
.and_then(|v| v.as_array())
.map(|ops| operation.is_some() && ops.iter().any(|o| o.as_str() == operation))
.unwrap_or(false);
if !permitted {
reasons.push("operation not permitted by the grant".into());
}
if reasons.is_empty() {
if let Some(n) = nonce {
replay.seen_nonces.insert(n);
}
}
Ok(AuthorizeResult {
ok: reasons.is_empty(),
reasons,
})
}
/// Return true if `child` is a valid attenuation of `parent`: the same resource, a
/// subset of the operations, and the same zone (or the parent had no zone). A
/// sub-grant may only narrow, never widen, the access it inherits.
pub fn attenuates_grant(parent: &Value, child: &Value) -> bool {
crate::nesting::deep_guard!(false; parent, child);
let p = parent.get("credentialSubject");
let c = child.get("credentialSubject");
let p_resource = p.and_then(|s| s.get("resource")).and_then(|v| v.as_str());
let c_resource = c.and_then(|s| s.get("resource")).and_then(|v| v.as_str());
if p_resource != c_resource {
return false;
}
let p_ops: HashSet<&str> = p
.and_then(|s| s.get("operations"))
.and_then(|v| v.as_array())
.map(|a| a.iter().filter_map(|o| o.as_str()).collect())
.unwrap_or_default();
let c_ops: HashSet<&str> = c
.and_then(|s| s.get("operations"))
.and_then(|v| v.as_array())
.map(|a| a.iter().filter_map(|o| o.as_str()).collect())
.unwrap_or_default();
if !c_ops.is_subset(&p_ops) {
return false;
}
let p_zone = p.and_then(|s| s.get("zone")).and_then(|v| v.as_str());
let c_zone = c.and_then(|s| s.get("zone")).and_then(|v| v.as_str());
if p_zone.is_some() && c_zone != p_zone {
return false;
}
true
}
// ---------------------------------------------------------------------------
// Fused-sensor provenance (Phase 5.18)
// ---------------------------------------------------------------------------
//
// Perception provenance signs individual sensor frames. A robot rarely acts on
// one frame, though: it fuses many frames, from cameras, lidar, radar, and other
// sensors, into a single world model, an object set, an occupancy grid, or a
// pose estimate, and acts on that. This binds a fused output to the exact set of
// input frames that produced it and the fusion method that produced it, signed by
// the robot, so a manipulated fusion result or a silently dropped or substituted
// input is detectable at the provenance layer.
//
// A fused-perception attestation carries the hash of the fused output, an ordered
// list of the input frame hashes, a digest over those inputs, and a fusion method
// identifier, signed by the robot. A verifier reproduces the input digest from the
// listed inputs and, when it holds the raw fused output, reproduces its hash, so
// the attestation commits to exactly those inputs and that output. Checking each
// listed input against the robot's signed perception log confirms every fused
// input traces to a frame the robot actually recorded.
//
// This is the open layer: the robot signs the binding of a fused output to its
// inputs in software, reusing the perception frame hashes. Hardware sensor
// attestation and managed sensor-fusion orchestration are out of scope for the
// open layer.
pub const FUSED_PERCEPTION_TYPE: &str = "FusedPerceptionAttestation";
/// Multibase (base64url) SHA-256 of a raw fused output. Only the hash travels in
/// the attestation; the fused output stays wherever the deployment keeps it.
pub fn hash_fused_output(output: &[u8]) -> String {
mb64(&Sha256::digest(output))
}
/// Input-digest version 1: SHA-256 of the hashes joined by "\n" (the
/// original; assumed when an attestation names no version).
pub const INPUTS_DIGEST_V1: &str = "1";
/// Input-digest version 2: SHA-256 of the JCS JSON array of the hashes (the
/// default for new attestations).
pub const INPUTS_DIGEST_V2: &str = "2";
/// Deterministic multibase digest over an ordered list of input frame hashes
/// (version 2, the default). It commits to the exact inputs and their order.
pub fn fusion_inputs_digest(input_frame_hashes: &[String]) -> Result<String> {
fusion_inputs_digest_version(input_frame_hashes, INPUTS_DIGEST_V2)
}
/// [`fusion_inputs_digest`] under a named version. Version 1 refuses a hash
/// that contains "\n" (otherwise two different lists could share a digest).
pub fn fusion_inputs_digest_version(
input_frame_hashes: &[String],
version: &str,
) -> Result<String> {
if input_frame_hashes.is_empty() {
return Err(CoreError::Json(
"input_frame_hashes must be a non-empty list".into(),
));
}
for h in input_frame_hashes {
if h.is_empty() {
return Err(CoreError::Json(
"each input frame hash must be a non-empty string".into(),
));
}
}
match version {
INPUTS_DIGEST_V2 => Ok(mb64(&Sha256::digest(jcs::canonicalize(&json!(
input_frame_hashes
))))),
INPUTS_DIGEST_V1 => {
if input_frame_hashes.iter().any(|h| h.contains('\n')) {
return Err(CoreError::Json(
"a version 1 input digest cannot carry a hash containing a newline".into(),
));
}
Ok(mb64(&Sha256::digest(
input_frame_hashes.join("\n").as_bytes(),
)))
}
other => Err(CoreError::Json(format!(
"unknown inputs digest version {other:?}"
))),
}
}
/// Parameters for [`build_fused_attestation`]. The robot self-issues the
/// credential with its own Ed25519 seed. Provide either the raw `fused_output` (it
/// is hashed) or a precomputed `fused_output_hash`, not both. `captured_at`, when
/// `None`, defaults to `valid_from`.
#[derive(Debug, Clone)]
pub struct BuildFusedAttestation {
pub robot_did: String,
pub fusion_method: String,
pub input_frame_hashes: Vec<String>,
pub fused_output: Option<Vec<u8>>,
pub fused_output_hash: Option<String>,
pub captured_at: Option<String>,
pub valid_from: String,
pub valid_until: Option<String>,
}
/// Build a signed `FusedPerceptionAttestation`: the robot attests that a fused
/// output was produced by `fusion_method` from the frames named in
/// `input_frame_hashes`. The attestation carries a digest over the ordered inputs,
/// so the set of inputs is tamper-evident. Signed by the robot.
pub fn build_fused_attestation(robot_seed: &[u8], params: &BuildFusedAttestation) -> Result<Value> {
if params.robot_did.is_empty() {
return Err(CoreError::Json("robot_did is required".into()));
}
if params.fusion_method.is_empty() {
return Err(CoreError::Json("fusion_method is required".into()));
}
if params.input_frame_hashes.is_empty() {
return Err(CoreError::Json(
"input_frame_hashes must be a non-empty list".into(),
));
}
if params.fused_output.is_some() && params.fused_output_hash.is_some() {
return Err(CoreError::Json(
"provide either fused_output or fused_output_hash, not both".into(),
));
}
let fused_output_hash = match (¶ms.fused_output, ¶ms.fused_output_hash) {
(Some(o), None) => hash_fused_output(o),
(None, Some(h)) if !h.is_empty() => h.clone(),
_ => {
return Err(CoreError::Json(
"fused_output or fused_output_hash is required".into(),
))
}
};
let captured = params
.captured_at
.clone()
.unwrap_or_else(|| params.valid_from.clone());
let mut subject = Map::new();
subject.insert("id".into(), json!(params.robot_did));
subject.insert("fusionMethod".into(), json!(params.fusion_method));
subject.insert("fusedOutputHash".into(), json!(fused_output_hash));
subject.insert("inputFrameHashes".into(), json!(params.input_frame_hashes));
subject.insert(
"inputsDigest".into(),
json!(fusion_inputs_digest(¶ms.input_frame_hashes)?),
);
subject.insert("inputsDigestVersion".into(), json!(INPUTS_DIGEST_V2));
subject.insert("capturedAt".into(), json!(captured));
let mut cred = Map::new();
cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
cred.insert(
"type".into(),
json!(["VerifiableCredential", FUSED_PERCEPTION_TYPE]),
);
cred.insert("issuer".into(), json!(params.robot_did));
cred.insert("validFrom".into(), json!(params.valid_from));
if let Some(vu) = ¶ms.valid_until {
cred.insert("validUntil".into(), json!(vu));
}
cred.insert("credentialSubject".into(), Value::Object(subject));
let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), ¶ms.valid_from);
data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
}
/// Verify a `FusedPerceptionAttestation`: the robot's proof bound to the robot
/// as issuer (which must also be `credentialSubject.id`), the window at
/// `now_iso` (validFrom required), that the digest over
/// the listed inputs reproduces the attested `inputsDigest` (so the inputs are
/// internally consistent and tamper-evident), and, when the raw `fused_output` is
/// supplied, that its hash reproduces the attested `fusedOutputHash`. Returns the
/// credentialSubject on success, `None` if invalid.
pub fn verify_fused_attestation(
credential: &Value,
keys: Keys<'_>,
fused_output: Option<&[u8]>,
now_iso: &str,
) -> Result<Option<Value>> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
let v = match bound(
credential,
keys,
FUSED_PERCEPTION_TYPE,
now_iso,
Window::FromRequired,
)? {
Some(v) if issuer_is_subject(&v) => v,
_ => return Ok(None),
};
let subject = v.subject;
let fused_output_hash = non_empty_str(&subject, "fusedOutputHash");
let inputs: Vec<String> = match subject.get("inputFrameHashes") {
Some(Value::Array(a)) if !a.is_empty() && a.iter().all(|e| e.is_string()) => a
.iter()
.filter_map(|e| e.as_str().map(String::from))
.collect(),
_ => return Ok(None),
};
if fused_output_hash.is_none() {
return Ok(None);
}
let version = match subject.get("inputsDigestVersion") {
None => INPUTS_DIGEST_V1,
Some(Value::String(v)) if v == INPUTS_DIGEST_V1 || v == INPUTS_DIGEST_V2 => v.as_str(),
_ => return Ok(None),
};
match fusion_inputs_digest_version(&inputs, version) {
Ok(d) => {
if Some(d.as_str()) != subject.get("inputsDigest").and_then(|v| v.as_str()) {
return Ok(None);
}
}
Err(_) => return Ok(None),
}
if let Some(o) = fused_output {
if Some(hash_fused_output(o).as_str()) != fused_output_hash {
return Ok(None);
}
}
Ok(Some(subject))
}
/// The outcome of confirming an attestation's inputs against a perception log:
/// `ok` plus the input frame hashes not found. Surfaced by [`verify_fusion_inputs`].
#[derive(Debug, Clone)]
pub struct FusionInputsResult {
pub ok: bool,
pub missing: Vec<String>,
}
/// Confirm every input frame the attestation names was actually recorded in the
/// robot's perception log. Returns `ok` plus `missing`, the input frame hashes that
/// do not appear as a recorded frame, so a dropped or substituted fused input is
/// named rather than hidden.
pub fn verify_fusion_inputs(credential: &Value, log_entries: &[Value]) -> FusionInputsResult {
crate::nesting::deep_guard!(FusionInputsResult { ok: false, missing: Vec::new() }; credential, log_entries);
let recorded: HashSet<&str> = log_entries
.iter()
.filter_map(|e| e.get("frameHash").and_then(|v| v.as_str()))
.filter(|h| !h.is_empty())
.collect();
// A missing or empty input list is malformed: fail closed.
let inputs = match credential
.get("credentialSubject")
.and_then(|s| s.get("inputFrameHashes"))
.and_then(|v| v.as_array())
{
Some(a) if !a.is_empty() => a,
_ => {
return FusionInputsResult {
ok: false,
missing: Vec::new(),
}
}
};
let missing: Vec<String> = inputs
.iter()
.filter(|h| !h.as_str().is_some_and(|s| recorded.contains(s)))
.map(|h| match h.as_str() {
Some(s) => s.to_string(),
None => h.to_string(),
})
.collect();
FusionInputsResult {
ok: missing.is_empty(),
missing,
}
}
// ---------------------------------------------------------------------------
// Wear and degradation attestation (Phase 5.19)
// ---------------------------------------------------------------------------
//
// A robot does not stay as capable as it left the factory. Actuators wear, joints
// develop backlash, sensors drift out of calibration, and error rates creep up.
// This lets a robot sign its own degradation state, bound to its identity and
// hash-linked over time so the history is tamper-evident, and derives a narrowed
// physical capability scope from that state, so a worn robot operates inside a
// tighter, verifiable envelope instead of trusting the static limit it shipped
// with.
//
// A wear attestation carries a normalized wear level (0 for as-new, 1 for fully
// worn) and optional detailed metrics, signed by the robot. Linking each
// attestation to the previous one by its proof value forms a chain a verifier
// walks to see how the robot degraded over its life. `attenuate_for_wear` derives
// a physical scope whose numeric caps are scaled down by the wear level, and the
// result is a valid attenuation of the original scope, so the same attenuation
// rule the rest of Vouch uses carries the derating.
//
// This is the open layer: the robot signs its wear state and derives the narrowed
// scope credential in software. Firmware-level enforcement of the narrowed
// envelope and managed predictive-maintenance modeling are out of scope for the
// open layer.
pub const WEAR_ATTESTATION_TYPE: &str = "RobotWearAttestation";
/// Numeric caps that scale down with wear. Zones and shift windows are preserved
/// unchanged, so the derived scope stays a valid attenuation of the original.
const WEAR_DERATED_CAPS: [&str; 3] = ["maxForceN", "maxSpeedMps", "maxSpeedNearHumansMps"];
/// Parameters for [`build_wear_attestation`]. The robot self-issues the credential
/// with its own Ed25519 seed. `metrics`, when present, is carried through into the
/// subject unchanged. `prev_proof`, when present, links this attestation to the
/// previous one, forming a wear history. `attested_at`, when `None`, defaults to
/// `valid_from`.
#[derive(Debug, Clone)]
pub struct BuildWearAttestation {
pub robot_did: String,
pub wear_level: f64,
pub metrics: Option<Value>,
pub prev_proof: Option<String>,
pub attested_at: Option<String>,
pub valid_from: String,
pub valid_until: Option<String>,
}
/// Build a signed `RobotWearAttestation`: the robot attests its own degradation as
/// a normalized `wear_level` in `[0, 1]`, optionally with detailed `metrics`. When
/// `prev_proof` is the proof value of the previous attestation, the new one links
/// to it, forming a tamper-evident wear history. Signed by the robot.
pub fn build_wear_attestation(robot_seed: &[u8], params: &BuildWearAttestation) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
if params.robot_did.is_empty() {
return Err(CoreError::Json("robot_did is required".into()));
}
if params.wear_level < 0.0 || params.wear_level > 1.0 {
return Err(CoreError::Json(
"wear_level must be between 0.0 and 1.0".into(),
));
}
let attested = params
.attested_at
.clone()
.unwrap_or_else(|| params.valid_from.clone());
let mut subject = Map::new();
subject.insert("id".into(), json!(params.robot_did));
subject.insert("wearLevel".into(), json!(params.wear_level));
subject.insert("attestedAt".into(), json!(attested));
if let Some(m) = ¶ms.metrics {
subject.insert("metrics".into(), m.clone());
}
if let Some(prev) = ¶ms.prev_proof {
subject.insert("prevProof".into(), json!(prev));
}
let mut cred = Map::new();
cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
cred.insert(
"type".into(),
json!(["VerifiableCredential", WEAR_ATTESTATION_TYPE]),
);
cred.insert("issuer".into(), json!(params.robot_did));
cred.insert("validFrom".into(), json!(params.valid_from));
if let Some(vu) = ¶ms.valid_until {
cred.insert("validUntil".into(), json!(vu));
}
cred.insert("credentialSubject".into(), Value::Object(subject));
let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), ¶ms.valid_from);
data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
}
/// Verify a `RobotWearAttestation`: the robot's proof bound to the robot as
/// issuer (which must also be `credentialSubject.id`), the window at `now_iso`
/// (validFrom required), and that the wear level is a finite number in [0, 1]. Returns the credentialSubject on
/// success, `None` if invalid.
pub fn verify_wear_attestation(
credential: &Value,
keys: Keys<'_>,
now_iso: &str,
) -> Result<Option<Value>> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
let v = match bound(
credential,
keys,
WEAR_ATTESTATION_TYPE,
now_iso,
Window::FromRequired,
)? {
Some(v) if issuer_is_subject(&v) => v,
_ => return Ok(None),
};
match rv::finite_number(v.subject.get("wearLevel")) {
Some(level) if (0.0..=1.0).contains(&level) => Ok(Some(v.subject)),
_ => Ok(None),
}
}
/// Verify an ordered wear history: each attestation verifies under the same
/// robot, each one after the first links to the previous by its proof value,
/// and they are in time order. Each earlier attestation must still have been
/// valid when the next was made, and the last at `now_iso`. Returns the latest
/// credentialSubject on success, `None` if the chain is empty or invalid.
pub fn verify_wear_chain(
attestations: &[Value],
keys: Keys<'_>,
now_iso: &str,
) -> Result<Option<Value>> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); attestations);
rv::require_now(now_iso)?;
if attestations.is_empty() {
return Ok(None);
}
let mut prev_proof: Option<String> = None;
let mut prev_time: Option<i128> = None;
let mut robot: Option<String> = None;
let mut latest: Option<Value> = None;
for (i, att) in attestations.iter().enumerate() {
let at: String = match attestations.get(i + 1) {
Some(next) => match next.get("validFrom").and_then(|v| v.as_str()) {
Some(t) if rv::time_ns(next.get("validFrom")).is_some() => t.to_string(),
_ => return Ok(None),
},
None => now_iso.to_string(),
};
let subject = match verify_wear_attestation(att, keys, &at)? {
Some(s) => s,
None => return Ok(None),
};
let id = subject.get("id").and_then(|v| v.as_str()).map(String::from);
match &robot {
None => robot = id,
Some(r) if id.as_deref() == Some(r.as_str()) => {}
_ => return Ok(None),
}
if let Some(prev) = &prev_proof {
if subject.get("prevProof").and_then(|v| v.as_str()) != Some(prev.as_str()) {
return Ok(None);
}
}
match rv::time_ns(att.get("validFrom")) {
Some(t) if prev_time.is_none_or(|p| t >= p) => prev_time = Some(t),
_ => return Ok(None),
}
prev_proof = att
.get("proof")
.and_then(|p| p.get("proofValue"))
.and_then(|v| v.as_str())
.map(String::from);
latest = Some(subject);
}
Ok(latest)
}
/// Derive a physical scope narrowed for the given wear level: each numeric cap is
/// scaled by `(1 - wear_level)`, and the allowed zones and shift windows are
/// carried through unchanged. The result is a valid attenuation of `scope` (never
/// broader on any dimension), so the same attenuation check the rest of Vouch uses
/// accepts it. A wear level of 0 returns the caps unchanged.
pub fn attenuate_for_wear(scope: &Value, wear_level: f64) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); scope);
// `contains` is false for NaN, so a NaN wear level is refused here rather
// than turning every cap into NaN (which a NaN-unaware check would ignore).
if !(0.0..=1.0).contains(&wear_level) {
return Err(CoreError::Json(
"wear_level must be between 0.0 and 1.0".into(),
));
}
let problems = scope_problems(scope);
if !problems.is_empty() {
return Err(CoreError::Json(problems.join("; ")));
}
let factor = 1.0 - wear_level;
let empty = Map::new();
let src = scope.as_object().unwrap_or(&empty);
let mut narrowed = Map::new();
for (key, value) in src {
if WEAR_DERATED_CAPS.contains(&key.as_str()) {
if let Some(n) = value.as_f64() {
narrowed.insert(key.clone(), json!(n * factor));
continue;
}
}
narrowed.insert(key.clone(), value.clone());
}
Ok(Value::Object(narrowed))
}
// ---------------------------------------------------------------------------
// Bystander-consent evidence (Phase 5.20)
// ---------------------------------------------------------------------------
//
// A robot working in a shared or public space captures people incidentally
// through its cameras and microphones. This lets the robot record, at capture
// time, the basis on which a capture was permitted, bound to the specific capture
// and to the robot's identity, and lets a bystander (or their device) sign a
// consent token bound to that one capture. Only hashes and a consent basis are
// stored, never an image or a bystander's identifying data, so the evidence is
// verifiable without retaining anyone's biometrics.
//
// A bystander consent token is signed by the bystander over the hash of the
// capture and the robot's DID, so it verifies only against the capture it was
// given for and cannot be replayed to a different recording. A bystander-consent
// evidence credential is signed by the robot, binding the capture hash to a
// consent basis (an explicit token, posted notice, a legitimate interest, or a
// redaction that was applied) and, when the basis is explicit consent, to the
// tokens that cover it.
//
// This is the open layer: the cryptographic binding of a consent basis to a
// capture, and its verification, holding only hashes. On-device biometric
// detection and redaction, and managed consent-registry orchestration, are out of
// scope for the open layer.
pub const CONSENT_EVIDENCE_TYPE: &str = "BystanderConsentEvidence";
pub const CONSENT_TOKEN_TYPE: &str = "BystanderConsentToken";
/// Accepted consent bases: the interoperable set a verifier can rely on.
/// Implementers MAY use additional values.
pub const CONSENT_BASES: [&str; 4] = [
"explicit-consent",
"posted-notice",
"legitimate-interest",
"redacted",
];
/// Multibase (base64url) SHA-256 of a raw capture. Only the hash travels in the
/// token and the evidence; the capture stays wherever the deployment keeps it.
pub fn hash_capture(capture: &[u8]) -> String {
mb64(&Sha256::digest(capture))
}
/// Parameters for [`build_consent_token`]. The signer is the bystander; the token
/// binds their consent to one capture (named by `capture_hash`) by one robot
/// (`robot_did`). `valid_until`, when set, bounds the window (the wrapper derives
/// it from a `valid_seconds` lifetime added to `granted_at`, keeping the core's
/// clock caller-supplied). `scope`, when set, records what the consent covers.
#[derive(Debug, Clone)]
pub struct BuildConsentToken {
pub bystander_did: String,
pub capture_hash: String,
pub robot_did: String,
pub scope: Option<String>,
pub granted_at: String,
pub valid_until: Option<String>,
}
/// Build a signed `BystanderConsentToken`: a bystander grants consent for a
/// specific capture (named by `capture_hash`) by a specific robot (`robot_did`),
/// signed by the bystander. Binding the token to the capture hash means it cannot
/// be replayed to a different recording. Signed by the bystander.
pub fn build_consent_token(bystander_seed: &[u8], params: &BuildConsentToken) -> Result<Value> {
if params.bystander_did.is_empty()
|| params.capture_hash.is_empty()
|| params.robot_did.is_empty()
{
return Err(CoreError::Json(
"bystander_did, capture_hash, and robot_did are required".into(),
));
}
let mut subject = Map::new();
subject.insert("id".into(), json!(params.bystander_did));
subject.insert("captureHash".into(), json!(params.capture_hash));
subject.insert("robotDid".into(), json!(params.robot_did));
if let Some(scope) = ¶ms.scope {
subject.insert("scope".into(), json!(scope));
}
let mut cred = Map::new();
cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
cred.insert(
"type".into(),
json!(["VerifiableCredential", CONSENT_TOKEN_TYPE]),
);
cred.insert("issuer".into(), json!(params.bystander_did));
cred.insert("validFrom".into(), json!(params.granted_at));
if let Some(vu) = ¶ms.valid_until {
cred.insert("validUntil".into(), json!(vu));
}
cred.insert("credentialSubject".into(), Value::Object(subject));
let opts = BuildProofOptions::new(
format!("{}#key-1", params.bystander_did),
¶ms.granted_at,
);
data_integrity::sign(&Value::Object(cred), bystander_seed, &opts)
}
/// Verify a `BystanderConsentToken`: the bystander's proof bound to the issuer
/// (`bystander_keys` is a `{did: key}` source, or the bare key of a did:key
/// bystander), that the issuer is the bystander (`credentialSubject.id`), that
/// the token is bound to this capture and this robot, and that it is within its
/// window at `now_iso` (validFrom required, strict times). Returns the
/// credentialSubject on success, `None` if invalid.
pub fn verify_consent_token(
token: &Value,
bystander_keys: Keys<'_>,
capture_hash: &str,
robot_did: &str,
now_iso: &str,
) -> Result<Option<Value>> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); token);
let v = match bound(
token,
bystander_keys,
CONSENT_TOKEN_TYPE,
now_iso,
Window::FromRequired,
)? {
Some(v) if issuer_is_subject(&v) => v,
_ => return Ok(None),
};
if v.subject.get("captureHash").and_then(|v| v.as_str()) != Some(capture_hash)
|| v.subject.get("robotDid").and_then(|v| v.as_str()) != Some(robot_did)
{
return Ok(None);
}
Ok(Some(v.subject))
}
/// Parameters for [`build_consent_evidence`]. The signer is the robot; the
/// evidence records that a capture (named by `capture_hash`) was permitted on
/// `basis`, one of [`CONSENT_BASES`]. `consent_tokens`, when the basis is explicit
/// consent, are the bystander tokens that cover it, committed by their proof value.
/// `redaction_hash`, when set, records that a redacted output was produced.
/// `valid_until`, when set, bounds the window.
#[derive(Debug, Clone)]
pub struct BuildConsentEvidence {
pub robot_did: String,
pub capture_hash: String,
pub basis: String,
pub consent_tokens: Vec<Value>,
pub redaction_hash: Option<String>,
pub valid_from: String,
pub valid_until: Option<String>,
}
/// A privacy-preserving reference to a token: its proof value. Never embeds a
/// bystander's identifying data.
fn consent_token_ref(token: &Value) -> Result<String> {
token
.get("proof")
.and_then(|p| p.get("proofValue"))
.and_then(|v| v.as_str())
.map(String::from)
.ok_or_else(|| CoreError::Json("consent token is missing a proof value".into()))
}
/// Build a signed `BystanderConsentEvidence` credential: the robot records that a
/// capture (named by `capture_hash`) was permitted on `basis`, one of
/// [`CONSENT_BASES`]. When the basis is explicit consent, the `consent_tokens` are
/// the bystander tokens that cover it, and the evidence commits to them by their
/// proof value (never embedding a bystander's identifying data). Signed by the
/// robot.
pub fn build_consent_evidence(robot_seed: &[u8], params: &BuildConsentEvidence) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
if params.robot_did.is_empty() || params.capture_hash.is_empty() {
return Err(CoreError::Json(
"robot_did and capture_hash are required".into(),
));
}
if !CONSENT_BASES.contains(¶ms.basis.as_str()) {
return Err(CoreError::Json(format!(
"basis must be one of {:?}, got {:?}",
CONSENT_BASES, params.basis
)));
}
if params.basis == "explicit-consent" && params.consent_tokens.is_empty() {
return Err(CoreError::Json(
"explicit-consent basis requires at least one consent token".into(),
));
}
let mut subject = Map::new();
subject.insert("id".into(), json!(params.robot_did));
subject.insert("captureHash".into(), json!(params.capture_hash));
subject.insert("basis".into(), json!(params.basis));
if !params.consent_tokens.is_empty() {
let mut refs = Vec::with_capacity(params.consent_tokens.len());
for t in ¶ms.consent_tokens {
refs.push(consent_token_ref(t)?);
}
subject.insert("consentTokenRefs".into(), json!(refs));
}
if let Some(rh) = ¶ms.redaction_hash {
subject.insert("redactionHash".into(), json!(rh));
}
let mut cred = Map::new();
cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
cred.insert(
"type".into(),
json!(["VerifiableCredential", CONSENT_EVIDENCE_TYPE]),
);
cred.insert("issuer".into(), json!(params.robot_did));
cred.insert("validFrom".into(), json!(params.valid_from));
if let Some(vu) = ¶ms.valid_until {
cred.insert("validUntil".into(), json!(vu));
}
cred.insert("credentialSubject".into(), Value::Object(subject));
let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), ¶ms.valid_from);
data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
}
/// One bystander's public key, looked up by bystander DID, for
/// [`verify_consent_evidence`].
#[derive(Debug, Clone)]
pub struct BystanderKey {
pub did: String,
pub public_key: Vec<u8>,
}
/// Verify a `BystanderConsentEvidence` credential: the robot's proof bound to
/// the robot as issuer (which must also be `credentialSubject.id`), the window
/// at `now_iso` (validFrom required), and an accepted basis. When `capture` is
/// supplied, its hash must reproduce the attested capture hash.
///
/// An explicit-consent evidence is only as good as its tokens, so for that
/// basis `consent_tokens` and `bystander_keys` are required: every committed
/// reference must be matched by a token that verifies, is bound to this
/// capture and this robot, and is in its window. For other bases, tokens that
/// are supplied are checked the same way. Returns the credentialSubject on
/// success, `None` if invalid.
pub fn verify_consent_evidence(
evidence: &Value,
robot_keys: Keys<'_>,
capture: Option<&[u8]>,
consent_tokens: Option<&[Value]>,
bystander_keys: Option<&[BystanderKey]>,
now_iso: &str,
) -> Result<Option<Value>> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); evidence, consent_tokens);
let v = match bound(
evidence,
robot_keys,
CONSENT_EVIDENCE_TYPE,
now_iso,
Window::FromRequired,
)? {
Some(v) if issuer_is_subject(&v) => v,
_ => return Ok(None),
};
let subject = v.subject;
let basis = subject.get("basis").and_then(|v| v.as_str());
match basis {
Some(b) if CONSENT_BASES.contains(&b) => {}
_ => return Ok(None),
}
let capture_hash = match non_empty_str(&subject, "captureHash") {
Some(h) => h.to_string(),
None => return Ok(None),
};
if let Some(c) = capture {
if hash_capture(c) != capture_hash {
return Ok(None);
}
}
let refs: Vec<&str> = match subject.get("consentTokenRefs") {
None => Vec::new(),
Some(Value::Array(a)) if a.iter().all(|r| r.is_string()) => {
a.iter().filter_map(|r| r.as_str()).collect()
}
_ => return Ok(None),
};
let explicit = basis == Some("explicit-consent");
if explicit && refs.is_empty() {
return Ok(None);
}
if explicit && (consent_tokens.is_none() || bystander_keys.is_none()) {
return Ok(None);
}
if let (Some(tokens), Some(keys)) = (consent_tokens, bystander_keys) {
let map = Keys::map_of(keys.iter().map(|k| (k.did.clone(), &k.public_key)));
let mut matched: HashSet<String> = HashSet::new();
for token in tokens {
let tok_ok = !map.is_empty()
&& verify_consent_token(token, Keys::Map(&map), &capture_hash, &v.issuer, now_iso)?
.is_some();
if !tok_ok {
return Ok(None);
}
let r = match consent_token_ref(token) {
Ok(r) if refs.contains(&r.as_str()) => r,
_ => return Ok(None),
};
matched.insert(r);
}
if explicit {
let all: HashSet<String> = refs.iter().map(|r| r.to_string()).collect();
if matched != all {
return Ok(None);
}
}
}
Ok(Some(subject))
}
// What the no_std depth guard checks in the JSON these types carry.
crate::nesting::nested_fields!(MintRobotIdentity; lifecycle);
crate::nesting::nested_fields!(BuildProvenance; config);
crate::nesting::nested_fields!(BuildSafetyEvidence; halos_stack);
crate::nesting::nested_fields!(BuildRobotHeartbeat; motion_digest);
crate::nesting::nested_fields!(BuildSafetyRecord; summary);
crate::nesting::nested_fields!(BuildDelegationLease; scope);
crate::nesting::nested_fields!(BuildConformanceAttestation; report);
crate::nesting::nested_fields!(BuildHandoff; release);
crate::nesting::nested_fields!(BuildWearAttestation; metrics);
crate::nesting::nested_fields!(BuildConsentEvidence; consent_tokens);
crate::nesting::nested_fields!(SafetyRecordCheck<'_>; entries);
crate::nesting::nested_fields!(MotionCollector; scope);
#[cfg(test)]
mod tests {
use super::*;
use crate::keys::Ed25519KeyPair;
#[allow(unused_imports)]
use crate::robotics_verify::test_keys::{any_did, kd, TNOW};
#[allow(unused_imports)]
use crate::robotics_verify::Keys;
use std::fs;
fn load_vector() -> Value {
let raw = fs::read_to_string("../../test-vectors/robotics/vector.json")
.expect("interop vector present");
serde_json::from_str(&raw).unwrap()
}
fn software_root_attest(root_seed: &[u8], robot_did: &str, robot_key_mb: &str) -> Vec<u8> {
let kp = Ed25519KeyPair::from_seed_slice(root_seed).unwrap();
let binding = robot_identity_binding(robot_did, robot_key_mb);
kp.sign(&binding).to_vec()
}
// Cross-language interop: Go and TypeScript verify this same Python-minted
// credential; the Rust core must too.
#[test]
fn verifies_python_interop_vector() {
let raw = fs::read_to_string("../../test-vectors/robotics/vector.json")
.expect("interop vector present");
let vector: Value = serde_json::from_str(&raw).unwrap();
let jwk_x = vector["robot_public_key_jwk"]["x"].as_str().unwrap();
let robot_pub = URL_SAFE_NO_PAD.decode(jwk_x).unwrap();
let cred = vector["robot_identity_credential"].clone();
let subject = verify_robot_identity(&cred, kd(&cred, &robot_pub), None, TNOW).unwrap();
let subject = subject.expect("the Python interop vector must verify in Rust");
assert_eq!(subject["make"], json!("Acme Robotics"));
}
#[test]
fn mint_verify_roundtrip() {
let robot_seed = [3u8; 32];
let root_seed = [7u8; 32];
let robot_did = "did:web:robot.example.com";
let robot_kp = Ed25519KeyPair::from_seed(&robot_seed);
let root_kp = Ed25519KeyPair::from_seed(&root_seed);
let attestation = software_root_attest(&root_seed, robot_did, &robot_kp.public_multikey());
let params = MintRobotIdentity {
robot_did: robot_did.into(),
make: "Acme".into(),
model: "AR-7".into(),
serial: "SN-1".into(),
owner: Some("did:web:owner.example.com".into()),
root_kind: "TPM".into(),
root_public_multibase: root_kp.public_multikey(),
attestation,
lifecycle: None,
valid_from: "2026-01-01T00:00:00Z".into(),
valid_until: None,
};
let cred = mint_robot_identity(&robot_seed, ¶ms).unwrap();
let subject =
verify_robot_identity(&cred, kd(&cred, &robot_kp.public_key()), None, TNOW).unwrap();
assert!(subject.is_some(), "round-trip identity must verify");
}
// Cross-language interop: this HalosSafetyEvidenceCredential, its black-box
// entries, and the robot public key were produced by the Python reference
// (vouch/robotics/halos.py) from a fixed Ed25519 seed (0x05 x32), a fixed
// black-box key, and a fixed `created` timestamp. The Rust verify must accept
// it, and must reject a tampered entry or a wrong entry count.
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"}}"#;
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"}]"#;
// Robot public key (raw 32-byte Ed25519) as base64url-no-pad.
const PY_HALOS_ROBOT_PUB: &str = "bnoc3Smwt4_ROvTFWY_v9O8qlxZuPKby5Pv8zYBQW_E";
#[test]
#[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
fn build_verify_safety_evidence_roundtrip() {
let robot_seed = [5u8; 32];
let robot_kp = Ed25519KeyPair::from_seed(&robot_seed);
// A black-box chain the robot recorded.
let mut log = BlackBoxLog::new(&[9u8; 32], None).unwrap();
log.append(
"hazard_detected",
&json!({"zone": "cell-3"}),
"2026-01-01T00:00:01Z",
)
.unwrap();
log.append(
"slow_stop",
&json!({"reason": "human"}),
"2026-01-01T00:00:02Z",
)
.unwrap();
let entries: Vec<Value> = log.entries().to_vec();
let params = BuildSafetyEvidence {
halos_stack: json!({"igxSom": "IGX-Orin-64", "halosCore": "1.4.0"}),
window_from: "2026-01-01T00:00:00Z".into(),
window_to: "2026-01-01T00:00:10Z".into(),
blackbox_head: log.head().to_string(),
entry_count: entries.len() as u64,
robot_identity: Some("urn:uuid:robot-identity-1".into()),
valid_seconds: Some(3600),
valid_from: "2026-01-01T00:00:00Z".into(),
created: "2026-01-01T00:00:00Z".into(),
robot_did: None,
};
let cred = build_safety_evidence(&robot_seed, ¶ms).unwrap();
// The issuer is the did:key derived from the seed and the validUntil is
// rendered from the valid_seconds lifetime.
assert_eq!(
cred["issuer"],
json!("did:key:z6MkmtWtY63GQVBrpMyRJWEzsnxfsGkemu6CtMDwGTv4RYj2")
);
assert_eq!(cred["validUntil"], json!("2026-01-01T01:00:00Z"));
let (ok, subject) = verify_safety_evidence(
&cred,
kd(&cred, &robot_kp.public_key()),
Some(&entries),
TNOW,
)
.unwrap();
assert!(ok, "a Rust-built evidence credential must verify in Rust");
assert_eq!(subject.unwrap()["entryCount"], json!(2));
// A credential whose issuer is not the subject id is rejected.
let mut forged = cred.clone();
forged["issuer"] = json!("did:key:z6Mkother");
let (ok_forged, _) =
verify_safety_evidence(&forged, kd(&forged, &robot_kp.public_key()), None, TNOW)
.unwrap();
assert!(!ok_forged, "issuer must equal credentialSubject.id");
}
#[test]
fn verifies_python_halos_evidence() {
let credential: Value = serde_json::from_str(PY_HALOS_CREDENTIAL).unwrap();
let entries: Vec<Value> = serde_json::from_str(PY_HALOS_ENTRIES).unwrap();
let robot_pub = URL_SAFE_NO_PAD.decode(PY_HALOS_ROBOT_PUB).unwrap();
// The Python-produced credential and its entries verify in Rust.
let (ok, subject) = verify_safety_evidence(
&credential,
kd(&credential, &robot_pub),
Some(&entries),
TNOW,
)
.unwrap();
assert!(ok, "the Python Halos evidence must verify in Rust");
let subject = subject.expect("subject present on success");
assert_eq!(subject["entryCount"], json!(3));
assert_eq!(
subject["blackboxHead"],
json!("utfv4sSWc6TH-n0HrNqB35Hacy3lYVksU0QYz6gbHol8")
);
// The proof and issuer binding hold even without the entries.
let (ok_no_entries, _) =
verify_safety_evidence(&credential, kd(&credential, &robot_pub), None, TNOW).unwrap();
assert!(
ok_no_entries,
"proof and issuer binding verify without entries"
);
// Tampering one entry breaks the chain, so verification fails.
let mut tampered = entries.clone();
tampered[1]["ciphertext"] = json!("utampered_ciphertext_value_that_does_not_match_hash");
let (ok_tampered, subj_tampered) = verify_safety_evidence(
&credential,
kd(&credential, &robot_pub),
Some(&tampered),
TNOW,
)
.unwrap();
assert!(!ok_tampered, "a tampered entry must be rejected");
assert!(subj_tampered.is_none());
// A wrong entry count (here a truncated log) is rejected against the seal.
let truncated = entries[..2].to_vec();
let (ok_truncated, _) = verify_safety_evidence(
&credential,
kd(&credential, &robot_pub),
Some(&truncated),
TNOW,
)
.unwrap();
assert!(!ok_truncated, "a wrong entry count must be rejected");
}
#[test]
fn forged_hardware_root_fails() {
let robot_seed = [3u8; 32];
let root_seed = [7u8; 32];
let attacker_seed = [9u8; 32];
let robot_did = "did:web:robot.example.com";
let robot_kp = Ed25519KeyPair::from_seed(&robot_seed);
let root_kp = Ed25519KeyPair::from_seed(&root_seed);
let attacker_kp = Ed25519KeyPair::from_seed(&attacker_seed);
let attestation = software_root_attest(&root_seed, robot_did, &robot_kp.public_multikey());
let params = MintRobotIdentity {
robot_did: robot_did.into(),
make: "Acme".into(),
model: "AR-7".into(),
serial: "SN-1".into(),
owner: None,
root_kind: "TPM".into(),
root_public_multibase: root_kp.public_multikey(),
attestation,
lifecycle: None,
valid_from: "2026-01-01T00:00:00Z".into(),
valid_until: None,
};
let mut cred = mint_robot_identity(&robot_seed, ¶ms).unwrap();
// Point the hardware-root key at an attacker's and re-sign the credential
// proof; the attestation over the binding no longer matches.
cred["credentialSubject"]["hardwareRoot"]["publicKeyMultibase"] =
json!(attacker_kp.public_multikey());
let resigned = {
let mut bare = cred.clone();
bare.as_object_mut().unwrap().remove("proof");
let opts = BuildProofOptions::new(format!("{robot_did}#key-1"), "2026-01-01T00:00:00Z");
data_integrity::sign(&bare, &robot_seed, &opts).unwrap()
};
assert!(verify_robot_identity(
&resigned,
kd(&resigned, &robot_kp.public_key()),
None,
TNOW
)
.unwrap()
.is_none());
}
// Cross-language interop: Rust reproduces the exact configHash Python pinned.
#[test]
fn config_hash_matches_interop_vector() {
let vector = load_vector();
let got = config_hash(&vector["config"]);
assert_eq!(got, vector["expected_config_hash"].as_str().unwrap());
assert_eq!(got, "uMh9_H2Lk51-m9SpBhiEa1oqIwwwA7yT27e2QFS0YKUs");
}
#[test]
fn provenance_roundtrip_and_config_tamper() {
let seed = [4u8; 32];
let kp = Ed25519KeyPair::from_seed(&seed);
let config = load_vector()["config"].clone();
let params = BuildProvenance {
issuer_did: "did:web:robot.example.com".into(),
robot_did: "did:web:robot.example.com".into(),
model_name: "openvla-7b".into(),
weights_hash: "uABCDEF".into(),
safety_policy: "did:web:authority.example.com#policy-v3".into(),
config: Some(config.clone()),
version: Some("2026.06".into()),
supersedes: None,
valid_from: "2026-01-01T00:00:00Z".into(),
valid_until: None,
};
let att = build_provenance_attestation(&seed, ¶ms).unwrap();
assert!(verify_provenance_attestation(
&att,
kd(&att, &kp.public_key()),
Some(&config),
TNOW
)
.unwrap()
.is_some());
// A different config than the one signed must be rejected.
let tampered = json!({"temperature": 1.0, "max_torque": 99.0});
assert!(verify_provenance_attestation(
&att,
kd(&att, &kp.public_key()),
Some(&tampered),
TNOW
)
.unwrap()
.is_none());
}
#[test]
fn capability_build_check_attenuate() {
let seed = [6u8; 32];
let kp = Ed25519KeyPair::from_seed(&seed);
let params = BuildPhysicalScope {
issuer_did: "did:web:fleet.example.com".into(),
subject_did: "did:web:robot.example.com".into(),
max_force_n: Some(80.0),
max_speed_mps: Some(2.0),
max_speed_near_humans_mps: Some(0.5),
allowed_zones: Some(vec!["warehouse-a".into(), "dock-3".into()]),
shift_windows: Some(vec![ShiftWindow {
start: "08:00".into(),
end: "18:00".into(),
}]),
valid_from: "2026-01-01T00:00:00Z".into(),
valid_until: None,
};
let cred = build_physical_scope_credential(&seed, ¶ms).unwrap();
assert!(cred["type"]
.as_array()
.unwrap()
.contains(&json!(PHYSICAL_SCOPE_TYPE)));
assert!(data_integrity::verify_proof(&cred, &kp.public_key()).unwrap());
let scope = cred["credentialSubject"]["physicalScope"].clone();
let within = check_physical_action(
&scope,
&PhysicalAction {
force_n: Some(50.0),
speed_mps: Some(1.5),
zone: Some("warehouse-a".into()),
time_hm: Some("09:30".into()),
..Default::default()
},
);
assert!(within.ok, "within-scope action: {:?}", within.reasons);
assert!(
!check_physical_action(
&scope,
&PhysicalAction {
force_n: Some(120.0),
..Default::default()
}
)
.ok
);
// Near humans the 0.5 m/s cap applies; 1.5 is fine away from them.
assert!(
!check_physical_action(
&scope,
&PhysicalAction {
speed_mps: Some(1.5),
near_humans: true,
..Default::default()
}
)
.ok
);
assert!(
check_physical_action(
&scope,
&PhysicalAction {
speed_mps: Some(1.5),
near_humans: false,
..Default::default()
}
)
.ok
);
assert!(
!check_physical_action(
&scope,
&PhysicalAction {
zone: Some("loading-bay-9".into()),
..Default::default()
}
)
.ok
);
assert!(
!check_physical_action(
&scope,
&PhysicalAction {
time_hm: Some("23:00".into()),
..Default::default()
}
)
.ok
);
}
#[test]
fn attenuation_rules() {
let parent = json!({
"maxForceN": 80.0, "maxSpeedMps": 2.0, "maxSpeedNearHumansMps": 0.5,
"allowedZones": ["warehouse-a", "dock-3"],
"shiftWindows": [{"start": "08:00", "end": "18:00"}]
});
let narrower = json!({
"maxForceN": 50.0, "maxSpeedMps": 1.0, "maxSpeedNearHumansMps": 0.3,
"allowedZones": ["warehouse-a"],
"shiftWindows": [{"start": "09:00", "end": "17:00"}]
});
assert!(attenuates(&parent, &narrower));
assert!(!attenuates(
&parent,
&json!({"maxForceN": 100.0, "maxSpeedMps": 1.0, "maxSpeedNearHumansMps": 0.3, "allowedZones": ["warehouse-a"]})
));
assert!(!attenuates(
&parent,
&json!({"maxForceN": 50.0, "allowedZones": ["warehouse-a"]})
));
assert!(!attenuates(
&parent,
&json!({"maxForceN": 50.0, "maxSpeedMps": 1.0, "maxSpeedNearHumansMps": 0.3, "allowedZones": ["loading-bay-9"]})
));
assert!(!attenuates(
&parent,
&json!({"maxForceN": 50.0, "maxSpeedMps": 1.0, "maxSpeedNearHumansMps": 0.3, "allowedZones": ["warehouse-a"], "shiftWindows": [{"start": "06:00", "end": "20:00"}]})
));
}
#[test]
fn handshake_full_flow() {
let a_seed = [11u8; 32];
let b_seed = [12u8; 32];
let a = Ed25519KeyPair::from_seed(&a_seed);
let b = Ed25519KeyPair::from_seed(&b_seed);
let a_did = "did:web:robot-a.example.com";
let b_did = "did:web:robot-b.example.com";
let policy_b = TrustPolicy::new(["robot-a.example.com".to_string()], false);
let hello = build_hello(
&a_seed,
&BuildHello {
from_did: a_did.into(),
proposed_scope: vec!["lift".into(), "carry".into(), "scan".into()],
nonce: "abc123".into(),
peer_did: Some(b_did.into()),
issued_at: "2026-01-01T00:00:00Z".into(),
},
)
.unwrap();
let accept = build_accept(
&b_seed,
&hello,
Keys::One(a_did, &a.public_key()),
&policy_b,
&BuildAccept {
from_did: b_did.into(),
offered_scope: vec!["carry".into(), "scan".into(), "weld".into()],
session_id: "urn:uuid:sess-1".into(),
valid_until: "2026-01-01T00:05:00Z".into(),
created: "2026-01-01T00:00:01Z".into(),
},
)
.unwrap();
let session = verify_accept(
&accept,
Keys::One(b_did, &b.public_key()),
&hello,
Some("abc123"),
None,
"2026-01-01T00:00:01Z",
)
.unwrap()
.expect("accept verifies");
// A bare key cannot vouch for a did:web peer, and a stale or expired
// exchange is refused.
assert!(verify_accept(
&accept,
Keys::Bare(&b.public_key()),
&hello,
None,
None,
"2026-01-01T00:00:01Z"
)
.unwrap()
.is_none());
assert!(verify_accept(
&accept,
Keys::One(b_did, &b.public_key()),
&hello,
None,
None,
"2026-01-01T00:06:00Z"
)
.unwrap()
.is_none());
// An ACCEPT replayed against another HELLO is refused.
let other_hello = build_hello(
&a_seed,
&BuildHello {
from_did: a_did.into(),
proposed_scope: vec!["carry".into()],
nonce: "zzz".into(),
peer_did: Some(b_did.into()),
issued_at: "2026-01-01T00:00:00Z".into(),
},
)
.unwrap();
assert!(verify_accept(
&accept,
Keys::One(b_did, &b.public_key()),
&other_hello,
None,
None,
"2026-01-01T00:00:01Z"
)
.unwrap()
.is_none());
assert_eq!(session.scope, vec!["carry".to_string(), "scan".to_string()]);
assert_eq!(session.initiator, a_did);
assert_eq!(session.responder, b_did);
let confirm = build_confirm(&a_seed, a_did, &session, "2026-01-01T00:00:02Z").unwrap();
assert!(verify_confirm(
&confirm,
Keys::One(a_did, &a.public_key()),
&accept,
"2026-01-01T00:00:02Z"
)
.unwrap());
assert!(!verify_confirm(
&confirm,
Keys::One(a_did, &a.public_key()),
&accept,
"2026-01-01T00:06:00Z"
)
.unwrap());
// A stale HELLO is refused by the responder.
assert!(build_accept(
&b_seed,
&hello,
Keys::One(a_did, &a.public_key()),
&policy_b,
&BuildAccept {
from_did: b_did.into(),
offered_scope: vec!["carry".into()],
session_id: "s2".into(),
valid_until: "2026-01-01T01:00:00Z".into(),
created: "2026-01-01T00:10:00Z".into(),
}
)
.is_err());
}
#[test]
fn handshake_untrusted_tamper_and_nonce() {
let a_seed = [11u8; 32];
let b_seed = [12u8; 32];
let a = Ed25519KeyPair::from_seed(&a_seed);
let b = Ed25519KeyPair::from_seed(&b_seed);
let a_did = "did:web:robot-a.example.com";
let b_did = "did:web:robot-b.example.com";
let hello = build_hello(
&a_seed,
&BuildHello {
from_did: a_did.into(),
proposed_scope: vec!["lift".into()],
nonce: "n1".into(),
peer_did: None,
issued_at: "2026-01-01T00:00:00Z".into(),
},
)
.unwrap();
// Untrusted initiator.
let strict = TrustPolicy::new(["someone-else.example.com".to_string()], false);
assert!(build_accept(
&b_seed,
&hello,
Keys::One(a_did, &a.public_key()),
&strict,
&BuildAccept {
from_did: b_did.into(),
offered_scope: vec!["lift".into()],
session_id: "s".into(),
valid_until: "2026-01-01T00:05:00Z".into(),
created: "2026-01-01T00:00:01Z".into(),
},
)
.is_err());
// Tampered HELLO (scope broadened after signing) fails signature check.
let open = TrustPolicy::new(Vec::<String>::new(), true);
let mut tampered = hello.clone();
tampered["proposedScope"] = json!(["lift", "weld"]);
assert!(build_accept(
&b_seed,
&tampered,
Keys::One(a_did, &a.public_key()),
&open,
&BuildAccept {
from_did: b_did.into(),
offered_scope: vec!["lift".into(), "weld".into()],
session_id: "s".into(),
valid_until: "2026-01-01T00:05:00Z".into(),
created: "2026-01-01T00:00:01Z".into(),
},
)
.is_err());
// Nonce mismatch on a valid ACCEPT.
let accept = build_accept(
&b_seed,
&hello,
Keys::One(a_did, &a.public_key()),
&open,
&BuildAccept {
from_did: b_did.into(),
offered_scope: vec!["lift".into()],
session_id: "s".into(),
valid_until: "2026-01-01T00:05:00Z".into(),
created: "2026-01-01T00:00:01Z".into(),
},
)
.unwrap();
assert!(verify_accept(
&accept,
Keys::One(b_did, &b.public_key()),
&hello,
Some("wrong-nonce"),
Some(&open),
"2026-01-01T00:00:01Z"
)
.unwrap()
.is_none());
}
#[test]
fn did_web_domain_parsing() {
let domain = |did: &str| did_web_domain(did);
assert_eq!(
domain("did:web:example.com").as_deref(),
Some("example.com")
);
// A path is part of the name, so a bare-domain entry never covers it.
assert_eq!(
domain("did:web:robot.example.com:agent").as_deref(),
Some("robot.example.com:agent")
);
assert_eq!(domain("did:web:robot.example.com:"), None);
assert_eq!(domain("did:key:z6Mk"), None);
// A did:webvh DID gives its parsed host, never read as did:web.
let scid = "QmUy89VrfryQ254CeHZzQfmcKqByPoKNGqYykP3SeXuegQ";
assert_eq!(
domain(&format!("did:webvh:{scid}:Robot.Example.com%3A8443:agents")).as_deref(),
Some("robot.example.com:agents")
);
// One that does not parse has no domain.
assert_eq!(domain("did:webvh:{SCID}:robot.example.com"), None);
assert_eq!(domain(&format!("did:webvh:{scid}:127.0.0.1")), None);
assert_eq!(domain("did:webvhx:robot.example.com"), None);
let policy = TrustPolicy::new(["robot.example.com".to_string()], false);
assert!(policy.is_trusted(&format!("did:webvh:{scid}:robot.example.com")));
assert!(!policy.is_trusted(&format!("did:webvh:{scid}:other.example.com")));
assert!(!policy.is_trusted("did:webvh:{SCID}:robot.example.com"));
}
#[test]
#[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
fn blackbox_append_open_and_chain() {
let key = [0x11u8; 32];
let mut log = BlackBoxLog::new(&key, None).unwrap();
let e0 = log
.append(
"motion",
&json!({"speed": 1.5, "joint": "elbow"}),
"2026-01-01T00:00:00Z",
)
.unwrap();
log.append("stop", &json!({"reason": "human"}), "2026-01-01T00:00:01Z")
.unwrap();
// Round-trip decrypt.
let opened = log.open(&e0).unwrap();
assert_eq!(opened["joint"], json!("elbow"));
// Chain verifies, in memory and after a JSON round trip.
assert!(verify_blackbox_chain(log.entries(), None).ok);
let wire: Vec<Value> =
serde_json::from_str(&serde_json::to_string(log.entries()).unwrap()).unwrap();
assert!(verify_blackbox_chain(&wire, None).ok);
assert_eq!(open_entry(&wire[0], &key).unwrap()["joint"], json!("elbow"));
// Tamper detection.
let mut tampered = wire.clone();
tampered[1]["event"] = json!("tampered");
assert!(!verify_blackbox_chain(&tampered, None).ok);
// Wrong key fails decryption; bad key length rejected.
assert!(open_entry(&e0, &[0x22u8; 32]).is_err());
assert!(BlackBoxLog::new(&[0u8; 16], None).is_err());
// Genesis constant matches the multibase of 32 zero bytes.
assert_eq!(genesis_prev_hash(), format!("u{}", "A".repeat(43)));
}
#[test]
fn killswitch_build_verify_and_trust() {
let seed = [13u8; 32];
let kp = Ed25519KeyPair::from_seed(&seed);
let cred = build_killswitch_credential(
&seed,
&BuildKillswitch {
issuer_did: "did:web:safety.example.com".into(),
target: "did:web:robot.example.com".into(),
reason: "human in path".into(),
command: None,
scope: Some(vec!["arm".into(), "drive".into()]),
valid_from: "2026-01-01T00:00:00Z".into(),
valid_until: None,
},
)
.unwrap();
let mut trusted = HashSet::new();
trusted.insert("did:web:safety.example.com".to_string());
let subject =
verify_killswitch_credential(&cred, kd(&cred, &kp.public_key()), Some(&trusted), TNOW)
.unwrap()
.expect("trusted authority verifies");
assert_eq!(subject["command"], json!(EMERGENCY_STOP));
// Untrusted issuer rejected though the signature is valid.
let mut other = HashSet::new();
other.insert("did:web:someone-else.example.com".to_string());
assert!(verify_killswitch_credential(
&cred,
kd(&cred, &kp.public_key()),
Some(&other),
TNOW
)
.unwrap()
.is_none());
// Wrong type rejected.
let mut wrong = cred.clone();
wrong["type"] = json!(["VerifiableCredential"]);
assert!(
verify_killswitch_credential(&wrong, kd(&wrong, &kp.public_key()), None, TNOW)
.unwrap()
.is_none()
);
}
#[test]
fn passport_build_encode_verify() {
let seed = [14u8; 32];
let kp = Ed25519KeyPair::from_seed(&seed);
let did = "did:web:robot.example.com";
let pass = build_passport(
&seed,
&BuildPassport {
issuer_did: did.into(),
robot_did: did.into(),
make: "Acme Robotics".into(),
model: "AR-7".into(),
owner: "did:web:owner.example.com".into(),
authorized_actions: vec!["lift".into(), "carry".into()],
certification: Some("ISO-10218".into()),
status: None,
valid_from: "2026-01-01T00:00:00Z".into(),
valid_until: None,
},
)
.unwrap();
// Direct verify.
let subject = verify_passport(
&pass,
kd(&pass, &kp.public_key()),
None,
"2026-06-01T00:00:00Z",
)
.unwrap()
.expect("passport verifies");
assert_eq!(subject["owner"], json!("did:web:owner.example.com"));
assert_eq!(subject["status"], json!(STATUS_ACTIVE));
// Encode to a URI, decode, and verify the offline-scan path.
let uri = encode_passport(&pass);
assert!(uri.starts_with("vouch-passport:u"));
let decoded = decode_passport(&uri).unwrap();
assert!(verify_passport(
&decoded,
kd(&decoded, &kp.public_key()),
None,
"2026-06-01T00:00:00Z"
)
.unwrap()
.is_some());
assert!(verify_passport_uri(
&uri,
Keys::Resolver(&any_did(&kp.public_key())),
None,
"2026-06-01T00:00:00Z"
)
.unwrap()
.is_some());
// Tamper and wrong type rejected.
let mut tampered = pass.clone();
tampered["credentialSubject"]["owner"] = json!("did:web:attacker.example.com");
assert!(verify_passport(
&tampered,
kd(&tampered, &kp.public_key()),
None,
"2026-06-01T00:00:00Z"
)
.unwrap()
.is_none());
// Malformed URI.
assert!(decode_passport("https://example.com/x").is_err());
}
#[test]
fn passport_expiry_and_suspended() {
let seed = [15u8; 32];
let kp = Ed25519KeyPair::from_seed(&seed);
let did = "did:web:robot.example.com";
// Expiry: valid inside the window, expired past validUntil.
let timed = build_passport(
&seed,
&BuildPassport {
issuer_did: did.into(),
robot_did: did.into(),
make: "Acme".into(),
model: "AR-7".into(),
owner: "did:web:owner.example.com".into(),
authorized_actions: vec!["lift".into()],
certification: None,
status: None,
valid_from: "2026-01-01T00:00:00Z".into(),
valid_until: Some("2026-01-01T00:01:00Z".into()),
},
)
.unwrap();
assert!(verify_passport(
&timed,
kd(&timed, &kp.public_key()),
None,
"2026-01-01T00:00:30Z"
)
.unwrap()
.is_some());
assert!(verify_passport(
&timed,
kd(&timed, &kp.public_key()),
None,
"2026-01-01T00:02:00Z"
)
.unwrap()
.is_none());
// Suspended still verifies but the status is surfaced.
let suspended = build_passport(
&seed,
&BuildPassport {
issuer_did: did.into(),
robot_did: did.into(),
make: "Acme".into(),
model: "AR-7".into(),
owner: "did:web:owner.example.com".into(),
authorized_actions: vec!["lift".into()],
certification: None,
status: Some(STATUS_SUSPENDED.into()),
valid_from: "2026-01-01T00:00:00Z".into(),
valid_until: None,
},
)
.unwrap();
let subject = verify_passport(
&suspended,
kd(&suspended, &kp.public_key()),
None,
"2026-06-01T00:00:00Z",
)
.unwrap()
.expect("a suspended passport still verifies");
assert_eq!(subject["status"], json!(STATUS_SUSPENDED));
}
// Cross-language interop: Rust reproduces the exact motion digest Python
// pinned from the same fixed samples against the same physical scope.
#[test]
fn motion_digest_matches_interop_vector() {
let vector = load_vector();
let scope = vector["physical_scope"].clone();
let mut collector = MotionCollector::new(Some(scope));
collector
.record(&MotionSample {
force_n: Some(12.0),
speed_mps: Some(0.4),
near_humans: false,
zone: Some("cell-3".into()),
time_hm: None,
})
.unwrap();
collector
.record(&MotionSample {
force_n: Some(20.0),
speed_mps: Some(0.2),
near_humans: true,
zone: Some("cell-3".into()),
time_hm: None,
})
.unwrap();
assert_eq!(collector.digest(), vector["expected_motion_digest"]);
}
#[test]
fn heartbeat_build_verify_and_liveness() {
let seed = [21u8; 32];
let kp = Ed25519KeyPair::from_seed(&seed);
let did = "did:web:robot.example.com";
let digest = json!({
"samples": 2, "maxForceN": 20.0, "maxSpeedMps": 0.4,
"maxSpeedNearHumansMps": 0.2, "zoneBreaches": 0, "breachCount": 0,
"withinEnvelope": true
});
let hb = build_robot_heartbeat(
&seed,
&BuildRobotHeartbeat {
robot_did: did.into(),
session_id: "urn:uuid:sess-1".into(),
interval_index: 0,
interval_seconds: 60,
motion_digest: digest,
valid_from: "2026-01-01T00:00:00Z".into(),
},
)
.unwrap();
let subject = verify_robot_heartbeat(&hb, kd(&hb, &kp.public_key()), TNOW)
.unwrap()
.expect("heartbeat verifies");
assert_eq!(subject["sessionId"], json!("urn:uuid:sess-1"));
// Fresh and in-envelope: live. Stale: not live.
assert!(is_live(&hb, "2026-01-01T00:01:00Z", None, DEFAULT_GRACE_INTERVALS).unwrap());
assert!(!is_live(&hb, "2026-01-01T01:00:00Z", None, DEFAULT_GRACE_INTERVALS).unwrap());
// Out-of-envelope heartbeat is never live, even when fresh.
let breached = json!({
"samples": 1, "maxForceN": 99.0, "maxSpeedMps": 0.4,
"maxSpeedNearHumansMps": 0.2, "zoneBreaches": 0, "breachCount": 1,
"withinEnvelope": false
});
let hb2 = build_robot_heartbeat(
&seed,
&BuildRobotHeartbeat {
robot_did: did.into(),
session_id: "s".into(),
interval_index: 1,
interval_seconds: 60,
motion_digest: breached,
valid_from: "2026-01-01T00:00:00Z".into(),
},
)
.unwrap();
assert!(!is_live(&hb2, "2026-01-01T00:00:30Z", None, DEFAULT_GRACE_INTERVALS).unwrap());
// Tamper and wrong type rejected.
let mut tampered = hb.clone();
tampered["credentialSubject"]["sessionId"] = json!("urn:uuid:other");
assert!(
verify_robot_heartbeat(&tampered, kd(&tampered, &kp.public_key()), TNOW)
.unwrap()
.is_none()
);
}
// Cross-language interop: Rust reproduces the exact hash-linked ledger and
// the summary Python pinned from the same fixed events and timestamps.
#[test]
fn safety_log_matches_interop_vector() {
let vector = load_vector();
let mut log = SafetyEventLog::new(None);
log.append(
"near_miss",
"low",
Some(&json!({"zone": "cell-3"})),
None,
"2026-01-01T00:00:00Z",
)
.unwrap();
log.append(
"envelope_breach",
"high",
None,
None,
"2026-01-01T00:01:00Z",
)
.unwrap();
assert_eq!(
Value::Array(log.entries().to_vec()),
vector["safety_log_entries"]
);
assert_eq!(
log.head(),
vector["expected_safety_log_head"].as_str().unwrap()
);
assert_eq!(log.summarize(), vector["expected_safety_summary"]);
assert!(verify_safety_log(log.entries(), None).ok);
}
#[test]
fn safety_record_build_verify_and_tamper() {
let seed = [22u8; 32];
let kp = Ed25519KeyPair::from_seed(&seed);
let mut log = SafetyEventLog::new(None);
log.append("near_miss", "low", None, None, "2026-01-01T00:00:00Z")
.unwrap();
let summary = log.summarize();
let record = build_safety_record(
&seed,
&BuildSafetyRecord {
issuer_did: "did:web:owner.example.com".into(),
robot_did: "did:web:robot.example.com".into(),
summary,
period_start: Some("2026-01-01T00:00:00Z".into()),
period_end: Some("2026-01-31T00:00:00Z".into()),
valid_from: "2026-02-01T00:00:00Z".into(),
valid_until: None,
},
)
.unwrap();
let subject = verify_safety_record(
&record,
kd(&record, &kp.public_key()),
SafetyRecordCheck::default(),
"2026-03-01T00:00:00Z",
)
.unwrap()
.expect("safety record verifies");
assert_eq!(subject["totalEvents"], json!(1));
assert_eq!(subject["period"]["start"], json!("2026-01-01T00:00:00Z"));
let mut tampered = record.clone();
tampered["credentialSubject"]["totalEvents"] = json!(99);
assert!(verify_safety_record(
&tampered,
kd(&tampered, &kp.public_key()),
SafetyRecordCheck::default(),
"2026-03-01T00:00:00Z"
)
.unwrap()
.is_none());
// Tamper detection in the ledger itself.
let mut entries = log.entries().to_vec();
entries[0]["severity"] = json!("critical");
assert!(!verify_safety_log(&entries, None).ok);
}
// Cross-language interop: Rust reproduces the exact credentialStatus entry.
#[test]
fn status_entry_matches_interop_vector() {
let vector = load_vector();
let entry = build_status_list_entry(
"https://fleet.example.com/status/1",
42,
STATUS_PURPOSE_REVOCATION,
None,
)
.unwrap();
assert_eq!(entry, vector["expected_credential_status_entry"]);
}
#[test]
#[cfg_attr(not(feature = "std"), ignore = "needs gunzip (std)")]
fn attach_and_check_credential_status() {
let seed = [23u8; 32];
let kp = Ed25519KeyPair::from_seed(&seed);
let did = "did:web:robot.example.com";
// Mint a passport, then attach a revocation status and re-sign.
let pass = build_passport(
&seed,
&BuildPassport {
issuer_did: did.into(),
robot_did: did.into(),
make: "Acme".into(),
model: "AR-7".into(),
owner: "did:web:owner.example.com".into(),
authorized_actions: vec!["lift".into()],
certification: None,
status: None,
valid_from: "2026-01-01T00:00:00Z".into(),
valid_until: None,
},
)
.unwrap();
let with_status = attach_credential_status(
&pass,
&seed,
&AttachCredentialStatus {
status_list_credential: "https://fleet.example.com/status/1".into(),
status_list_index: 42,
status_purpose: STATUS_PURPOSE_REVOCATION.into(),
entry_id: None,
created: "2026-01-01T00:00:00Z".into(),
},
)
.unwrap();
// The re-signed credential still verifies and now carries the entry.
assert!(data_integrity::verify_proof(&with_status, &kp.public_key()).unwrap());
assert_eq!(
with_status["credentialStatus"]["statusListIndex"],
json!("42")
);
// Build a status list with bit 42 set, then check the entry resolves.
let mut bits = vec![0u8; crate::status_list::DEFAULT_BITSTRING_LENGTH / 8];
crate::status_list::set_status(&mut bits, 42, true).unwrap();
let encoded = crate::status_list::encode_bitstring(&bits).unwrap();
let status_list = json!({
"id": "https://fleet.example.com/status/1",
"issuer": did,
"type": ["VerifiableCredential", "BitstringStatusListCredential"],
"credentialSubject": {
"type": "BitstringStatusList",
"statusPurpose": "revocation",
"encodedList": encoded,
}
});
assert!(
check_credential_status(&with_status, &status_list, STATUS_PURPOSE_REVOCATION).unwrap()
);
// A credential with no status entry is not revoked.
assert!(!check_credential_status(&pass, &status_list, STATUS_PURPOSE_REVOCATION).unwrap());
// A list with the bit clear reports not-revoked.
let clear_bits = vec![0u8; crate::status_list::DEFAULT_BITSTRING_LENGTH / 8];
let clear_encoded = crate::status_list::encode_bitstring(&clear_bits).unwrap();
let mut clear_list = status_list.clone();
clear_list["credentialSubject"]["encodedList"] = json!(clear_encoded);
assert!(
!check_credential_status(&with_status, &clear_list, STATUS_PURPOSE_REVOCATION).unwrap()
);
// A list from another issuer, or a list the entry does not name, cannot
// answer: an error, never "not revoked".
let mut foreign = status_list.clone();
foreign["issuer"] = json!("did:web:someone-else.example.com");
assert!(
check_credential_status(&with_status, &foreign, STATUS_PURPOSE_REVOCATION).is_err()
);
let mut other = status_list.clone();
other["id"] = json!("https://fleet.example.com/status/2");
assert!(check_credential_status(&with_status, &other, STATUS_PURPOSE_REVOCATION).is_err());
}
// Cross-language interop: Rust reproduces the exact frame hash Python pinned.
#[test]
fn frame_hash_matches_interop_vector() {
let vector = load_vector();
let sample_frame: Vec<u8> = (0u8..64).collect();
let got = hash_frame(&sample_frame);
assert_eq!(got, vector["expected_frame_hash"].as_str().unwrap());
assert_eq!(got, "u_eq5rPNxA2K9JljNyaKej5x1f8-YEWA6jER80dkVEQg");
}
// Cross-language interop: Rust reproduces the exact hash-linked perception log
// Python pinned from the same fixed frames and timestamps.
#[test]
fn perception_log_matches_interop_vector() {
let vector = load_vector();
let sample_frame: Vec<u8> = (0u8..64).collect();
let mut log = PerceptionLog::new(None);
log.record(
"cam-front",
"camera",
Some(&sample_frame),
None,
"2026-01-01T00:00:00Z",
)
.unwrap();
log.record(
"lidar-top",
"lidar",
None,
Some(&hash_frame(b"scan-0")),
"2026-01-01T00:00:01Z",
)
.unwrap();
assert_eq!(
Value::Array(log.entries().to_vec()),
vector["perception_log_entries"]
);
assert_eq!(
log.head(),
vector["expected_perception_log_head"].as_str().unwrap()
);
assert!(verify_perception_log(log.entries(), None).ok);
}
#[test]
fn perception_record_validation_and_tamper() {
let mut log = PerceptionLog::new(None);
// Unknown modality rejected.
assert!(log
.record("cam", "sonar", Some(b"x"), None, "2026-01-01T00:00:00Z")
.is_err());
// Both frame and frame_hash rejected.
assert!(log
.record(
"cam",
"camera",
Some(b"x"),
Some("uABC"),
"2026-01-01T00:00:00Z"
)
.is_err());
// Neither frame nor frame_hash rejected.
assert!(log
.record("cam", "camera", None, None, "2026-01-01T00:00:00Z")
.is_err());
// Empty sensor id rejected.
assert!(log
.record("", "camera", Some(b"x"), None, "2026-01-01T00:00:00Z")
.is_err());
log.record(
"cam",
"camera",
Some(b"frame-0"),
None,
"2026-01-01T00:00:00Z",
)
.unwrap();
log.record(
"cam",
"camera",
Some(b"frame-1"),
None,
"2026-01-01T00:00:01Z",
)
.unwrap();
assert!(verify_perception_log(log.entries(), None).ok);
// Tamper detection in the chain.
let mut entries = log.entries().to_vec();
entries[0]["frameHash"] = json!("uTAMPERED");
assert!(!verify_perception_log(&entries, None).ok);
}
#[test]
fn perception_attestation_build_verify_and_tamper() {
let seed = [24u8; 32];
let kp = Ed25519KeyPair::from_seed(&seed);
let did = "did:web:robot.example.com";
let frame = b"sensor-frame-bytes";
let frame_hash = hash_frame(frame);
let cred = build_perception_attestation(
&seed,
&BuildPerception {
robot_did: did.into(),
sensor_id: "cam-front".into(),
modality: "camera".into(),
frame_hash: frame_hash.clone(),
captured_at: Some("2026-01-01T00:00:00Z".into()),
log_head: Some("uHEAD".into()),
log_count: None,
valid_from: "2026-01-01T00:00:00Z".into(),
valid_until: None,
},
)
.unwrap();
// Verify the proof and the embedded provenance, and recompute the frame.
let subject =
verify_perception_attestation(&cred, kd(&cred, &kp.public_key()), Some(frame), TNOW)
.unwrap()
.expect("perception attestation verifies");
assert_eq!(subject["sensorId"], json!("cam-front"));
assert_eq!(subject["frameHash"], json!(frame_hash));
assert_eq!(subject["logHead"], json!("uHEAD"));
// Verify without the raw frame still passes (proof only).
assert!(
verify_perception_attestation(&cred, kd(&cred, &kp.public_key()), None, TNOW)
.unwrap()
.is_some()
);
// A different frame than the one attested is rejected.
assert!(verify_perception_attestation(
&cred,
kd(&cred, &kp.public_key()),
Some(b"other-frame"),
TNOW
)
.unwrap()
.is_none());
// Tampered subject fails the proof.
let mut tampered = cred.clone();
tampered["credentialSubject"]["sensorId"] = json!("cam-rear");
assert!(verify_perception_attestation(
&tampered,
kd(&tampered, &kp.public_key()),
None,
TNOW
)
.unwrap()
.is_none());
// Wrong type rejected.
let mut wrong = cred.clone();
wrong["type"] = json!(["VerifiableCredential"]);
assert!(
verify_perception_attestation(&wrong, kd(&wrong, &kp.public_key()), None, TNOW)
.unwrap()
.is_none()
);
// Bad modality and missing frame_hash rejected at build time.
assert!(build_perception_attestation(
&seed,
&BuildPerception {
robot_did: did.into(),
sensor_id: "s".into(),
modality: "sonar".into(),
frame_hash: frame_hash.clone(),
captured_at: None,
log_head: None,
log_count: None,
valid_from: "2026-01-01T00:00:00Z".into(),
valid_until: None,
},
)
.is_err());
assert!(build_perception_attestation(
&seed,
&BuildPerception {
robot_did: did.into(),
sensor_id: "s".into(),
modality: "camera".into(),
frame_hash: String::new(),
captured_at: None,
log_head: None,
log_count: None,
valid_from: "2026-01-01T00:00:00Z".into(),
valid_until: None,
},
)
.is_err());
}
fn jwk_pub(jwk: &Value) -> Vec<u8> {
URL_SAFE_NO_PAD
.decode(jwk["x"].as_str().unwrap())
.expect("base64url JWK x")
}
// Cross-language interop: Go and TypeScript verify this same Python-signed
// delegation lease; the Rust core must too.
#[test]
fn verifies_python_lease_interop_vector() {
let vector = load_vector();
let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
let lease = vector["delegation_lease_credential"].clone();
let subject = verify_delegation_lease(
&lease,
kd(&lease, &robot_pub),
"did:web:robot.example.com",
None,
None,
"2026-06-01T00:00:00Z",
)
.unwrap()
.expect("the Python lease interop vector must verify in Rust");
assert_eq!(subject["leaseId"], json!("lease-vector-1"));
}
// Cross-language interop: Rust authorizes the Python-signed quorum with the
// same two approver keys and a threshold of 2.
#[test]
fn verifies_python_quorum_interop_vector() {
let vector = load_vector();
let approvals = vector["quorum_approvals"].as_array().unwrap().clone();
let action_id = vector["quorum_action_id"].as_str().unwrap();
let keys: Vec<ApproverKey> = vector["quorum_approver_keys"]
.as_object()
.unwrap()
.iter()
.map(|(did, jwk)| ApproverKey {
did: did.clone(),
public_key: jwk_pub(jwk),
})
.collect();
let (ok, approvers) = verify_action_authorization(
&approvals,
action_id,
"did:web:robot.example.com",
&keys,
2,
None,
vector["quorum_now"].as_str().unwrap(),
)
.unwrap();
assert!(
ok,
"the Python quorum interop vector must authorize in Rust"
);
assert_eq!(approvers.len(), 2);
assert_eq!(approvers[0], "did:web:approver-1.example.com");
assert_eq!(approvers[1], "did:web:approver-2.example.com");
}
#[test]
fn lease_build_verify_permits_and_expiry() {
let seed = [31u8; 32];
let kp = Ed25519KeyPair::from_seed(&seed);
let did = "did:web:robot.example.com";
let scope = json!({
"maxForceN": 80.0, "maxSpeedMps": 2.0, "maxSpeedNearHumansMps": 0.5,
"allowedZones": ["warehouse-a", "dock-3"]
});
let lease = build_delegation_lease(
&seed,
&BuildDelegationLease {
issuer_did: did.into(),
robot_did: did.into(),
lease_id: "lease-1".into(),
scope: scope.clone(),
parent_lease_id: None,
valid_from: "2026-01-01T00:00:00Z".into(),
valid_until: "2026-01-01T01:00:00Z".into(),
},
)
.unwrap();
// Round-trip verify, in-window.
let subject = verify_delegation_lease(
&lease,
kd(&lease, &kp.public_key()),
"did:web:robot.example.com",
None,
None,
"2026-01-01T00:30:00Z",
)
.unwrap()
.expect("lease verifies in window");
assert_eq!(subject["leaseId"], json!("lease-1"));
// Permits a within-scope action, denies an out-of-scope one.
assert!(lease_permits(
&subject,
&PhysicalAction {
force_n: Some(50.0),
zone: Some("warehouse-a".into()),
..Default::default()
},
Some(&lease),
kd(&lease, &kp.public_key()),
None,
"2026-01-01T00:30:00Z",
)
.unwrap());
assert!(!lease_permits(
&subject,
&PhysicalAction {
force_n: Some(120.0),
..Default::default()
},
Some(&lease),
kd(&lease, &kp.public_key()),
None,
"2026-01-01T00:30:00Z",
)
.unwrap());
// Expired window: verify fails and the lease no longer permits.
assert!(verify_delegation_lease(
&lease,
kd(&lease, &kp.public_key()),
"did:web:robot.example.com",
None,
None,
"2026-01-01T02:00:00Z"
)
.unwrap()
.is_none());
assert!(!lease_permits(
&subject,
&PhysicalAction {
force_n: Some(50.0),
..Default::default()
},
Some(&lease),
kd(&lease, &kp.public_key()),
None,
"2026-01-01T02:00:00Z",
)
.unwrap());
// Tamper and wrong type rejected.
let mut tampered = lease.clone();
tampered["credentialSubject"]["leaseId"] = json!("lease-other");
assert!(verify_delegation_lease(
&tampered,
kd(&tampered, &kp.public_key()),
"did:web:robot.example.com",
None,
None,
"2026-01-01T00:30:00Z"
)
.unwrap()
.is_none());
}
#[test]
fn lease_sub_grant_attenuation() {
let parent_seed = [32u8; 32];
let child_seed = [33u8; 32];
let parent_kp = Ed25519KeyPair::from_seed(&parent_seed);
let child_kp = Ed25519KeyPair::from_seed(&child_seed);
let parent_scope = json!({
"maxForceN": 80.0, "maxSpeedMps": 2.0,
"allowedZones": ["warehouse-a", "dock-3"]
});
// A narrower sub-lease attenuates the parent: accepted.
let narrower = build_delegation_lease(
&child_seed,
&BuildDelegationLease {
issuer_did: "did:web:integrator.example.com".into(),
robot_did: "did:web:robot.example.com".into(),
lease_id: "lease-2".into(),
scope: json!({
"maxForceN": 50.0, "maxSpeedMps": 1.0,
"allowedZones": ["warehouse-a"]
}),
parent_lease_id: Some("lease-1".into()),
valid_from: "2026-01-01T00:00:00Z".into(),
valid_until: "2026-01-01T01:00:00Z".into(),
},
)
.unwrap();
assert!(verify_delegation_lease(
&narrower,
kd(&narrower, &child_kp.public_key()),
"did:web:robot.example.com",
Some(&parent_scope),
None,
"2026-01-01T00:30:00Z"
)
.unwrap()
.is_some());
// A widening sub-lease (force above the parent) is rejected against the
// parent scope.
let wider = build_delegation_lease(
&parent_seed,
&BuildDelegationLease {
issuer_did: "did:web:integrator.example.com".into(),
robot_did: "did:web:robot.example.com".into(),
lease_id: "lease-3".into(),
scope: json!({
"maxForceN": 200.0, "maxSpeedMps": 1.0,
"allowedZones": ["warehouse-a"]
}),
parent_lease_id: Some("lease-1".into()),
valid_from: "2026-01-01T00:00:00Z".into(),
valid_until: "2026-01-01T01:00:00Z".into(),
},
)
.unwrap();
assert!(verify_delegation_lease(
&wider,
kd(&wider, &parent_kp.public_key()),
"did:web:robot.example.com",
Some(&parent_scope),
None,
"2026-01-01T00:30:00Z"
)
.unwrap()
.is_none());
}
#[test]
fn quorum_threshold_and_distinct_counting() {
let s1 = [41u8; 32];
let s2 = [42u8; 32];
let k1 = Ed25519KeyPair::from_seed(&s1);
let k2 = Ed25519KeyPair::from_seed(&s2);
let a1 = "did:web:approver-1.example.com";
let a2 = "did:web:approver-2.example.com";
let robot = "did:web:robot.example.com";
let action = "action-x";
let build = |seed: &[u8], did: &str, decision: &str| {
build_action_approval(
seed,
&BuildActionApproval {
approver_did: did.into(),
action_id: action.into(),
robot_did: robot.into(),
decision: decision.into(),
valid_from: "2026-01-01T00:00:00Z".into(),
valid_until: None,
},
)
.unwrap()
};
let ap1 = build(&s1, a1, APPROVE);
let ap2 = build(&s2, a2, APPROVE);
let keys = vec![
ApproverKey {
did: a1.into(),
public_key: k1.public_key().to_vec(),
},
ApproverKey {
did: a2.into(),
public_key: k2.public_key().to_vec(),
},
];
// Two distinct approvers meet a threshold of 2.
let (ok, approvers) = verify_action_authorization(
&[ap1.clone(), ap2],
action,
robot,
&keys,
2,
None,
"2026-01-01T00:01:00Z",
)
.unwrap();
assert!(ok);
assert_eq!(approvers, vec![a1.to_string(), a2.to_string()]);
// Duplicate approvals from one approver count once: threshold 2 not met.
let dup = build(&s1, a1, APPROVE);
let (ok2, approvers2) = verify_action_authorization(
&[ap1.clone(), dup],
action,
robot,
&keys,
2,
None,
"2026-01-01T00:01:00Z",
)
.unwrap();
assert!(!ok2);
assert_eq!(approvers2, vec![a1.to_string()]);
// A single valid approver does not meet a threshold of 2.
let (ok3, _) = verify_action_authorization(
&[ap1],
action,
robot,
&keys,
2,
None,
"2026-01-01T00:01:00Z",
)
.unwrap();
assert!(!ok3);
// A rejection vetoes the action (each approver's latest decision counts).
let rej = build(&s1, a1, REJECT);
let approve2 = build(&s2, a2, APPROVE);
let (ok4, approvers4) = verify_action_authorization(
&[rej, approve2],
action,
robot,
&keys,
2,
None,
"2026-01-01T00:01:00Z",
)
.unwrap();
assert!(!ok4);
assert!(approvers4.is_empty());
}
// Cross-language interop: Rust verifies the Python-signed ownership transfer
// under the owner's key from the vector.
#[test]
fn verifies_python_ownership_transfer_interop_vector() {
let vector = load_vector();
let owner_pub = jwk_pub(&vector["ownership_transfer_owner_key"]);
let cred = vector["ownership_transfer_credential"].clone();
let subject = verify_ownership_transfer(&cred, kd(&cred, &owner_pub), None, TNOW)
.unwrap()
.expect("the Python ownership-transfer interop vector must verify in Rust");
assert_eq!(subject["toOwner"], json!("did:web:owner-b.example.com"));
}
// Cross-language interop: Rust verifies the Python-signed key rotation under
// the robot key from robot_public_key_jwk.
#[test]
fn verifies_python_key_rotation_interop_vector() {
let vector = load_vector();
let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
let cred = vector["key_rotation_credential"].clone();
let subject = verify_key_rotation(&cred, Keys::Bare(&robot_pub), None, TNOW)
.unwrap()
.expect("the Python key-rotation interop vector must verify in Rust");
assert_eq!(
subject["newKey"],
json!("z6MkmtWtY63GQVBrpMyRJWEzsnxfsGkemu6CtMDwGTv4RYj2")
);
}
// Cross-language interop: Rust verifies the Python-signed decommission under
// the authority key from the vector.
#[test]
fn verifies_python_decommission_interop_vector() {
let vector = load_vector();
let authority_pub = jwk_pub(&vector["decommission_authority_key"]);
let cred = vector["decommission_credential"].clone();
let subject = verify_decommission(&cred, kd(&cred, &authority_pub), None, None, TNOW)
.unwrap()
.expect("the Python decommission interop vector must verify in Rust");
assert_eq!(subject["reason"], json!("end of service life"));
assert_eq!(subject["finalDisposition"], json!("recycled"));
}
#[test]
fn ownership_transfer_roundtrip_and_issuer_rule() {
let owner_a_seed = [51u8; 32];
let owner_b_seed = [52u8; 32];
let a = Ed25519KeyPair::from_seed(&owner_a_seed);
let b = Ed25519KeyPair::from_seed(&owner_b_seed);
let owner_a = "did:web:owner-a.example.com";
let owner_b = "did:web:owner-b.example.com";
let robot = "did:web:robot.example.com";
let transfer = build_ownership_transfer(
&owner_a_seed,
&BuildOwnershipTransfer {
credential_id: "urn:uuid:00000000-0000-4000-8000-000000000101".into(),
issuer_did: owner_a.into(),
robot_did: robot.into(),
to_owner: owner_b.into(),
from_owner: None,
prev_transfer_id: None,
valid_from: "2026-01-01T00:00:00Z".into(),
},
)
.unwrap();
let subject =
verify_ownership_transfer(&transfer, kd(&transfer, &a.public_key()), None, TNOW)
.unwrap()
.expect("transfer verifies under the current owner key");
assert_eq!(subject["fromOwner"], json!(owner_a));
assert_eq!(subject["toOwner"], json!(owner_b));
// Wrong type rejected.
let mut wrong = transfer.clone();
wrong["type"] = json!(["VerifiableCredential"]);
assert!(
verify_ownership_transfer(&wrong, kd(&wrong, &a.public_key()), None, TNOW)
.unwrap()
.is_none()
);
// The issuer must equal fromOwner: forge a transfer whose issuer is not the
// declared seller and re-sign it. It must be rejected even with a valid
// proof under the signing key.
let forged = build_ownership_transfer(
&owner_b_seed,
&BuildOwnershipTransfer {
credential_id: "urn:uuid:00000000-0000-4000-8000-000000000102".into(),
issuer_did: owner_b.into(),
robot_did: robot.into(),
to_owner: "did:web:owner-c.example.com".into(),
// Claim the robot was sold by owner A while owner B signs.
from_owner: Some(owner_a.into()),
prev_transfer_id: None,
valid_from: "2026-01-01T00:00:00Z".into(),
},
)
.unwrap();
assert!(
verify_ownership_transfer(&forged, kd(&forged, &b.public_key()), None, TNOW)
.unwrap()
.is_none()
);
}
#[test]
fn custody_chain_links_and_rejects() {
let owner_a_seed = [51u8; 32];
let owner_b_seed = [52u8; 32];
let owner_c_seed = [53u8; 32];
let a = Ed25519KeyPair::from_seed(&owner_a_seed);
let b = Ed25519KeyPair::from_seed(&owner_b_seed);
let c = Ed25519KeyPair::from_seed(&owner_c_seed);
let owner_a = "did:web:owner-a.example.com";
let owner_b = "did:web:owner-b.example.com";
let owner_c = "did:web:owner-c.example.com";
let robot = "did:web:robot.example.com";
let t1 = build_ownership_transfer(
&owner_a_seed,
&BuildOwnershipTransfer {
credential_id: "urn:uuid:00000000-0000-4000-8000-000000000103".into(),
issuer_did: owner_a.into(),
robot_did: robot.into(),
to_owner: owner_b.into(),
from_owner: None,
prev_transfer_id: None,
valid_from: "2026-01-01T00:00:00Z".into(),
},
)
.unwrap();
let t2 = build_ownership_transfer(
&owner_b_seed,
&BuildOwnershipTransfer {
credential_id: "urn:uuid:00000000-0000-4000-8000-000000000104".into(),
issuer_did: owner_b.into(),
robot_did: robot.into(),
to_owner: owner_c.into(),
from_owner: None,
prev_transfer_id: Some("urn:uuid:00000000-0000-4000-8000-000000000103".into()),
valid_from: "2026-02-01T00:00:00Z".into(),
},
)
.unwrap();
let keys = vec![
OwnerKey {
did: owner_a.into(),
public_key: a.public_key().to_vec(),
},
OwnerKey {
did: owner_b.into(),
public_key: b.public_key().to_vec(),
},
OwnerKey {
did: owner_c.into(),
public_key: c.public_key().to_vec(),
},
];
// A clean two-link chain rooted at owner A ends at owner C.
let (ok, current) = verify_custody_chain(
&[t1.clone(), t2.clone()],
&keys,
"did:web:robot.example.com",
Some(owner_a),
"2026-03-01T00:00:00Z",
)
.unwrap();
assert!(ok);
assert_eq!(current.as_deref(), Some(owner_c));
// A wrong declared origin breaks the first link.
let (bad_origin, _) = verify_custody_chain(
&[t1.clone(), t2.clone()],
&keys,
"did:web:robot.example.com",
Some(owner_c),
"2026-03-01T00:00:00Z",
)
.unwrap();
assert!(!bad_origin);
// A gap (link two without link one) breaks the toOwner -> fromOwner join.
let (gap, _) = verify_custody_chain(
core::slice::from_ref(&t2),
&keys,
"did:web:robot.example.com",
Some(owner_a),
"2026-03-01T00:00:00Z",
)
.unwrap();
assert!(!gap);
// A missing key for an issuer fails the chain.
let partial = vec![OwnerKey {
did: owner_a.into(),
public_key: a.public_key().to_vec(),
}];
let (no_key, _) = verify_custody_chain(
&[t1, t2],
&partial,
"did:web:robot.example.com",
Some(owner_a),
"2026-03-01T00:00:00Z",
)
.unwrap();
assert!(!no_key);
}
#[test]
fn key_rotation_roundtrip_and_history() {
let k1_seed = [61u8; 32];
let k2_seed = [62u8; 32];
let k3_seed = [63u8; 32];
let k1 = Ed25519KeyPair::from_seed(&k1_seed);
let k2 = Ed25519KeyPair::from_seed(&k2_seed);
let k3 = Ed25519KeyPair::from_seed(&k3_seed);
let robot = "did:web:robot.example.com";
// Rotate k1 -> k2, signed by k1.
let r1 = build_key_rotation(
&k1_seed,
&BuildKeyRotation {
robot_did: robot.into(),
new_key_multibase: k2.public_multikey(),
reason: Some("scheduled rotation".into()),
valid_from: "2026-01-01T00:00:00Z".into(),
},
)
.unwrap();
let subject = verify_key_rotation(&r1, Keys::Bare(&k1.public_key()), None, TNOW)
.unwrap()
.expect("rotation verifies under the old key");
assert_eq!(subject["previousKey"], json!(k1.public_multikey()));
assert_eq!(subject["newKey"], json!(k2.public_multikey()));
// The new key cannot verify a rotation that the old key signed.
assert!(
verify_key_rotation(&r1, Keys::Bare(&k2.public_key()), None, TNOW)
.unwrap()
.is_none()
);
// Wrong type rejected.
let mut wrong = r1.clone();
wrong["type"] = json!(["VerifiableCredential"]);
assert!(
verify_key_rotation(&wrong, Keys::Bare(&k1.public_key()), None, TNOW)
.unwrap()
.is_none()
);
// Rotate k2 -> k3, signed by k2, forming a history.
let r2 = build_key_rotation(
&k2_seed,
&BuildKeyRotation {
robot_did: robot.into(),
new_key_multibase: k3.public_multikey(),
reason: None,
valid_from: "2026-02-01T00:00:00Z".into(),
},
)
.unwrap();
let (ok, current) = verify_key_history(
&[r1.clone(), r2.clone()],
&k1.public_multikey(),
None,
"2026-03-01T00:00:00Z",
)
.unwrap();
assert!(ok);
assert_eq!(current.as_deref(), Some(k3.public_multikey().as_str()));
// A wrong origin key breaks the first previousKey match.
let (bad_origin, _) = verify_key_history(
&[r1, r2],
&k3.public_multikey(),
None,
"2026-03-01T00:00:00Z",
)
.unwrap();
assert!(!bad_origin);
}
#[test]
fn decommission_roundtrip_and_trusted_authority() {
let seed = [71u8; 32];
let kp = Ed25519KeyPair::from_seed(&seed);
let authority = "did:web:authority.example.com";
let robot = "did:web:robot.example.com";
let cred = build_decommission(
&seed,
&BuildDecommission {
issuer_did: authority.into(),
robot_did: robot.into(),
reason: "end of service life".into(),
final_disposition: Some("recycled".into()),
valid_from: "2026-01-01T00:00:00Z".into(),
valid_until: None,
},
)
.unwrap();
let mut trusted = HashSet::new();
trusted.insert(authority.to_string());
let subject = verify_decommission(
&cred,
kd(&cred, &kp.public_key()),
Some(&trusted),
None,
TNOW,
)
.unwrap()
.expect("a trusted authority decommission verifies");
assert_eq!(subject["decommissionedBy"], json!(authority));
// An untrusted issuer is rejected even with a valid proof.
let mut other = HashSet::new();
other.insert("did:web:someone-else.example.com".to_string());
assert!(
verify_decommission(&cred, kd(&cred, &kp.public_key()), Some(&other), None, TNOW)
.unwrap()
.is_none()
);
// No trusted-authority set: a valid proof verifies.
assert!(
verify_decommission(&cred, kd(&cred, &kp.public_key()), None, None, TNOW)
.unwrap()
.is_some()
);
// Wrong type rejected.
let mut wrong = cred.clone();
wrong["type"] = json!(["VerifiableCredential"]);
assert!(
verify_decommission(&wrong, kd(&wrong, &kp.public_key()), None, None, TNOW)
.unwrap()
.is_none()
);
// reason is required at build time.
assert!(build_decommission(
&seed,
&BuildDecommission {
issuer_did: authority.into(),
robot_did: robot.into(),
reason: String::new(),
final_disposition: None,
valid_from: "2026-01-01T00:00:00Z".into(),
valid_until: None,
},
)
.is_err());
}
// Cross-language interop: Rust reproduces the exact conformance report and
// digest Python pinned, from the same credential set and profile.
#[test]
fn conformance_matches_interop_vector() {
let vector = load_vector();
let credentials: Vec<Value> = vector["conformance_credentials"]
.as_array()
.expect("conformance_credentials present")
.clone();
let profile_id = vector["conformance_profile_id"].as_str().unwrap();
let report = check_conformance(&credentials, profile_id).unwrap();
assert_eq!(report, vector["expected_conformance_report"]);
let digest = report_digest(&report);
assert_eq!(
digest,
vector["expected_conformance_report_digest"]
.as_str()
.unwrap()
);
}
// Presence alone is not evidence. A heartbeat that reports an envelope
// breach must not satisfy the continuous-monitoring requirement just by
// carrying a motionDigest.
#[test]
fn a_breaching_heartbeat_does_not_evidence_monitoring() {
let breaching = json!({
"type": ["VerifiableCredential", "RobotHeartbeatCredential"],
"credentialSubject": {
"motionDigest": {"withinEnvelope": false, "samples": 120}
}
});
let report = check_conformance(core::slice::from_ref(&breaching), "iso-ts-15066").unwrap();
let monitoring = report["requirements"]
.as_array()
.unwrap()
.iter()
.find(|r| r["id"] == json!("iso15066-monitoring"))
.expect("monitoring requirement present");
assert_eq!(monitoring["satisfied"], json!(false));
// The same heartbeat reporting no breach does satisfy it.
let mut clean = breaching;
clean["credentialSubject"]["motionDigest"]["withinEnvelope"] = json!(true);
let report = check_conformance(&[clean], "iso-ts-15066").unwrap();
let monitoring = report["requirements"]
.as_array()
.unwrap()
.iter()
.find(|r| r["id"] == json!("iso15066-monitoring"))
.unwrap();
assert_eq!(monitoring["satisfied"], json!(true));
}
// Every requirement declares where its clause number came from, and the
// report totals them, so CONFORMS never reads as more authoritative about
// the regulation than its sources are.
#[test]
fn conformance_report_carries_citation_provenance() {
for profile_id in [
"iso-10218",
"iso-ts-15066",
"eu-machinery-2023-1230",
"eu-ai-act-high-risk",
"ul-3300",
] {
let report = check_conformance(&[], profile_id).unwrap();
let citations = report["citations"].as_object().unwrap();
assert_eq!(citations.len(), CITATION_STATUSES.len());
let counted: i64 = citations.values().map(|v| v.as_i64().unwrap()).sum();
assert_eq!(counted, report["totalCount"].as_i64().unwrap());
for result in report["requirements"].as_array().unwrap() {
let citation = result["citation"].as_str().unwrap();
assert!(CITATION_STATUSES.contains(&citation));
}
}
// UL 3300 is paywalled with no clause numbering available, so none of
// its "clauses" are citable.
let ul = check_conformance(&[], "ul-3300").unwrap();
assert_eq!(ul["citations"][CITATION_DESCRIPTIVE], ul["totalCount"]);
assert_eq!(ul["citations"][CITATION_VERIFIED_PRIMARY], json!(0));
}
#[test]
fn conformance_unknown_profile_and_missing_field() {
assert!(check_conformance(&[], "no-such-profile").is_err());
// An empty credential set satisfies nothing.
let empty = check_conformance(&[], "eu-ai-act-high-risk").unwrap();
assert_eq!(empty["conforms"], json!(false));
assert_eq!(empty["satisfiedCount"], json!(0));
assert_eq!(empty["totalCount"], json!(4));
// A safety record with no logHead does not satisfy the record-keeping
// requirement (a missing field counts as unsatisfied).
let creds = vec![json!({
"type": ["VerifiableCredential", "RobotSafetyRecordCredential"],
"credentialSubject": { "id": "did:web:robot.example.com", "totalEvents": 2 }
})];
let report = check_conformance(&creds, "eu-ai-act-high-risk").unwrap();
let record_keeping = report["requirements"]
.as_array()
.unwrap()
.iter()
.find(|r| r["id"] == json!("eu-aia-record-keeping"))
.unwrap();
assert_eq!(record_keeping["satisfied"], json!(false));
// An empty allowedZones array is also unsatisfied.
let zone_creds = vec![json!({
"type": ["VerifiableCredential", "PhysicalCapabilityScope"],
"credentialSubject": {
"id": "did:web:robot.example.com",
"physicalScope": { "maxSpeedMps": 1.5, "allowedZones": [] }
}
})];
let ul = check_conformance(&zone_creds, "ul-3300").unwrap();
let limits = ul["requirements"]
.as_array()
.unwrap()
.iter()
.find(|r| r["id"] == json!("ul3300-operating-limits"))
.unwrap();
assert_eq!(limits["satisfied"], json!(false));
}
#[test]
fn conformance_attestation_roundtrip_and_rejections() {
let seed = [77u8; 32];
let kp = Ed25519KeyPair::from_seed(&seed);
let vector = load_vector();
let credentials: Vec<Value> = vector["conformance_credentials"]
.as_array()
.unwrap()
.clone();
let report = check_conformance(&credentials, "eu-ai-act-high-risk").unwrap();
let att = build_conformance_attestation(
&seed,
&BuildConformanceAttestation {
issuer_did: "did:web:authority.example.com".into(),
robot_did: "did:web:robot.example.com".into(),
report: report.clone(),
valid_from: "2026-01-01T00:00:00Z".into(),
valid_until: Some("2027-01-01T00:00:00Z".into()),
},
)
.unwrap();
// Round-trip: a well-formed attestation verifies and surfaces the subject.
let subject =
verify_conformance_attestation(&att, kd(&att, &kp.public_key()), None, None, TNOW)
.unwrap()
.expect("a valid conformance attestation verifies");
assert_eq!(subject["profileId"], json!("eu-ai-act-high-risk"));
assert_eq!(subject["conforms"], json!(true));
assert_eq!(
subject["reportDigest"],
vector["expected_conformance_report_digest"]
);
// Wrong key is rejected.
let wrong_kp = Ed25519KeyPair::from_seed(&[88u8; 32]);
assert!(verify_conformance_attestation(
&att,
kd(&att, &wrong_kp.public_key()),
None,
None,
TNOW
)
.unwrap()
.is_none());
// A tampered embedded report no longer matches the bound digest.
let mut tampered = att.clone();
tampered["credentialSubject"]["report"]["conforms"] = json!(false);
assert!(verify_conformance_attestation(
&tampered,
kd(&tampered, &kp.public_key()),
None,
None,
TNOW
)
.unwrap()
.is_none());
// Wrong type is rejected.
let mut wrong_type = att.clone();
wrong_type["type"] = json!(["VerifiableCredential"]);
assert!(verify_conformance_attestation(
&wrong_type,
kd(&wrong_type, &kp.public_key()),
None,
None,
TNOW
)
.unwrap()
.is_none());
// robot_did is required at build time.
assert!(build_conformance_attestation(
&seed,
&BuildConformanceAttestation {
issuer_did: "did:web:authority.example.com".into(),
robot_did: String::new(),
report,
valid_from: "2026-01-01T00:00:00Z".into(),
valid_until: None,
},
)
.is_err());
}
// -- post-quantum robot credentials ------------------------------------
fn classical_robot_credential(issuer: &str, seed: &[u8]) -> Value {
let cred = json!({
"@context": [VC_CONTEXT_V2, VOUCH_CONTEXT_V1],
"type": ["VerifiableCredential", ROBOT_IDENTITY_TYPE],
"issuer": issuer,
"validFrom": "2026-01-01T00:00:00Z",
"credentialSubject": {
"id": issuer,
"make": "Acme Robotics",
"model": "AR-7",
"serial": "SN-000123"
}
});
let opts = BuildProofOptions::new(format!("{issuer}#key-1"), "2026-01-01T00:00:00Z");
data_integrity::sign(&cred, seed, &opts).unwrap()
}
// Cross-language interop: Rust verifies the Python-signed hybrid PQ robot
// identity under the Ed25519 key and the ML-DSA-44 multikey from the vector.
#[test]
fn verifies_python_pq_robot_identity_interop_vector() {
let vector = load_vector();
let ed_pub = jwk_pub(&vector["robot_public_key_jwk"]);
let ml_multikey = vector["robot_mldsa44_public_multikey"].as_str().unwrap();
let cred = vector["pq_robot_identity_credential"].clone();
// (b) the credential is detected as post-quantum.
assert!(is_pq(&cred));
// (a) dual verify auto-detected from the proof, with the ML-DSA multikey.
let ok = verify_robot_credential(
&cred,
kd(&cred, &ed_pub),
Some(ml_multikey.as_bytes()),
None,
TNOW,
)
.expect("the Python hybrid PQ interop vector must verify in Rust");
assert!(ok);
// verify_pq accepts the multikey string form directly.
let resolved = mldsa44_public_from_multikey(ml_multikey).unwrap();
assert!(verify_pq(&cred, &ed_pub, &resolved).unwrap());
}
#[test]
#[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
fn pq_sign_verify_roundtrip_and_rejects() {
let issuer = "did:web:robot.example.com";
let seed = [21u8; 32];
let kp = Ed25519KeyPair::from_seed(&seed);
let ml = MlDsa44KeyPair::generate().unwrap();
let classical = classical_robot_credential(issuer, &seed);
assert!(!is_pq(&classical));
// Sign post-quantum; any prior proof is replaced by a proof set holding
// one classical and one ML-DSA-44 proof.
let signed = sign_pq(&classical, &seed, &ml, "2026-02-01T00:00:00Z").unwrap();
assert!(is_pq(&signed));
let proofs = signed["proof"].as_array().expect("proof set");
assert_eq!(proofs.len(), 2);
assert_eq!(
proofs[0]["cryptosuite"],
json!(hybrid::EDDSA_CRYPTOSUITE_ID)
);
assert_eq!(
proofs[1]["cryptosuite"],
json!(hybrid::MLDSA44_CRYPTOSUITE_ID)
);
// Each proof carries the Multibase encoding its cryptosuite specifies.
assert!(proofs[0]["proofValue"].as_str().unwrap().starts_with('z'));
assert!(proofs[1]["proofValue"].as_str().unwrap().starts_with('u'));
// Round-trip: both signatures validate under the correct keys.
assert!(verify_pq(&signed, &kp.public_key(), &ml.public_key()).unwrap());
assert!(verify_robot_credential(
&signed,
kd(&signed, &kp.public_key()),
Some(&ml.public_key()),
None,
TNOW
)
.unwrap());
// The multikey string form is accepted too (as UTF-8 bytes).
let ml_mk = multikey::encode_mldsa44_public(&ml.public_key()).unwrap();
assert!(verify_robot_credential(
&signed,
kd(&signed, &kp.public_key()),
Some(ml_mk.as_bytes()),
None,
TNOW
)
.unwrap());
// Tampering the body breaks verification.
let mut tampered = signed.clone();
tampered["credentialSubject"]["model"] = json!("AR-9");
assert!(!verify_pq(&tampered, &kp.public_key(), &ml.public_key()).unwrap());
// Wrong Ed25519 key is rejected.
let other_ed = Ed25519KeyPair::from_seed(&[99u8; 32]);
assert!(!verify_pq(&signed, &other_ed.public_key(), &ml.public_key()).unwrap());
// Wrong ML-DSA-44 key is rejected.
let other_ml = MlDsa44KeyPair::generate().unwrap();
assert!(!verify_pq(&signed, &kp.public_key(), &other_ml.public_key()).unwrap());
// A hybrid credential without the ML-DSA key returns false, not true.
assert!(
!verify_robot_credential(&signed, kd(&signed, &kp.public_key()), None, None, TNOW)
.unwrap()
);
// Downgrade by extraction: an attacker strips the proof set to the lone
// standalone classical proof. A verifier that supplies the ML-DSA key
// (so requires post-quantum) must reject it, not accept it as classical.
let proofs = signed["proof"].as_array().unwrap();
let classical_proof = proofs
.iter()
.find(|p| p["cryptosuite"] == json!(hybrid::EDDSA_CRYPTOSUITE_ID))
.unwrap()
.clone();
let mut stripped = signed.clone();
stripped["proof"] = classical_proof;
assert!(!is_pq(&stripped));
assert!(
!verify_robot_credential(
&stripped,
kd(&stripped, &kp.public_key()),
Some(&ml.public_key()),
None,
TNOW
)
.unwrap(),
"a stripped proof set must not verify when the caller requires post-quantum"
);
// The extracted classical proof is genuine, so a caller that only does
// classical verification (no ML-DSA key) still accepts it.
assert!(verify_robot_credential(
&stripped,
kd(&stripped, &kp.public_key()),
None,
None,
TNOW
)
.unwrap());
}
#[test]
fn classical_credential_passes_dual_verify_without_pq_key() {
let issuer = "did:web:robot.example.com";
let seed = [22u8; 32];
let kp = Ed25519KeyPair::from_seed(&seed);
let classical = classical_robot_credential(issuer, &seed);
assert!(!is_pq(&classical));
// A classical credential verifies through the dual path with no ML-DSA key.
assert!(verify_robot_credential(
&classical,
kd(&classical, &kp.public_key()),
None,
None,
TNOW
)
.unwrap());
// A wrong key still fails.
let other = Ed25519KeyPair::from_seed(&[7u8; 32]);
assert!(!verify_robot_credential(
&classical,
kd(&classical, &other.public_key()),
None,
None,
TNOW
)
.unwrap());
}
#[test]
#[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
fn migrate_to_pq_resigns_classical_credential() {
let issuer = "did:web:robot.example.com";
let seed = [23u8; 32];
let kp = Ed25519KeyPair::from_seed(&seed);
let ml = MlDsa44KeyPair::generate().unwrap();
let classical = classical_robot_credential(issuer, &seed);
assert!(verify_robot_credential(
&classical,
kd(&classical, &kp.public_key()),
None,
None,
TNOW
)
.unwrap());
let migrated = migrate_to_pq(&classical, &seed, &ml, "2026-03-01T00:00:00Z").unwrap();
assert!(is_pq(&migrated));
// The body is preserved across migration.
assert_eq!(
migrated["credentialSubject"],
classical["credentialSubject"]
);
assert!(verify_robot_credential(
&migrated,
kd(&migrated, &kp.public_key()),
Some(&ml.public_key()),
None,
TNOW
)
.unwrap());
}
// Cross-language interop: Rust verifies the Python-signed embodiment continuity
// chain under the one agent key from the vector, ending on body-b, with no fork.
#[test]
fn verifies_python_embodiment_interop_vector() {
let vector = load_vector();
let agent_pub = jwk_pub(&vector["embodiment_agent_key"]);
let chain: Vec<Value> = vector["embodiment_chain"]
.as_array()
.expect("embodiment_chain array")
.clone();
let (ok, current) = verify_continuity_chain(
&chain,
Keys::Resolver(&any_did(&agent_pub)),
None,
None,
"2026-06-01T00:00:00Z",
)
.unwrap();
assert!(ok, "the Python embodiment chain must verify in Rust");
assert_eq!(
current.as_deref(),
Some("did:web:body-b.example.com"),
"the chain ends on body-b"
);
let (no_fork, conflict) = check_no_fork(&chain).unwrap();
assert!(no_fork, "the Python embodiment chain has no fork");
assert!(conflict.is_none());
}
#[test]
fn embodiment_roundtrip_and_issuer_rule() {
let agent_seed = [61u8; 32];
let other_seed = [62u8; 32];
let agent = Ed25519KeyPair::from_seed(&agent_seed);
let other = Ed25519KeyPair::from_seed(&other_seed);
let agent_did = "did:web:agent.example.com";
let body_a = "did:web:body-a.example.com";
let cred = build_embodiment(
&agent_seed,
&BuildEmbodiment {
agent_did: agent_did.into(),
body_did: body_a.into(),
body_hardware_root: "uROOTA".into(),
from_body: None,
embodied_at: "2026-01-01T00:00:00Z".into(),
valid_until: None,
},
)
.unwrap();
let subject = verify_embodiment(&cred, kd(&cred, &agent.public_key()), None, TNOW)
.unwrap()
.expect("embodiment verifies under the agent key");
assert_eq!(subject["body"], json!(body_a));
assert_eq!(subject["bodyHardwareRoot"], json!("uROOTA"));
// The issuer must equal the subject id: forge a credential issued by an
// impostor over an unchanged subject (still the agent) and re-sign it. It
// must be rejected even with a valid proof under the signing key, because a
// mind only authorizes its own embodiment.
let forged = {
let mut bare = cred.clone();
bare.as_object_mut().unwrap().remove("proof");
bare["issuer"] = json!("did:web:impostor.example.com");
let opts = BuildProofOptions::new(
"did:web:impostor.example.com#key-1".to_string(),
"2026-01-01T00:00:00Z",
);
data_integrity::sign(&bare, &other_seed, &opts).unwrap()
};
assert!(
verify_embodiment(&forged, kd(&forged, &other.public_key()), None, TNOW)
.unwrap()
.is_none()
);
}
#[test]
fn continuity_chain_links_and_rejects() {
let agent_seed = [61u8; 32];
let stranger_seed = [63u8; 32];
let agent = Ed25519KeyPair::from_seed(&agent_seed);
let stranger = Ed25519KeyPair::from_seed(&stranger_seed);
let agent_did = "did:web:agent.example.com";
let body_a = "did:web:body-a.example.com";
let body_b = "did:web:body-b.example.com";
let e1 = build_embodiment(
&agent_seed,
&BuildEmbodiment {
agent_did: agent_did.into(),
body_did: body_a.into(),
body_hardware_root: "uROOTA".into(),
from_body: None,
embodied_at: "2026-01-01T00:00:00Z".into(),
valid_until: Some("2026-01-01T01:00:00Z".into()),
},
)
.unwrap();
let e2 = build_embodiment(
&agent_seed,
&BuildEmbodiment {
agent_did: agent_did.into(),
body_did: body_b.into(),
body_hardware_root: "uROOTB".into(),
from_body: Some(body_a.into()),
embodied_at: "2026-01-01T01:00:00Z".into(),
valid_until: None,
},
)
.unwrap();
// A clean two-link chain ends at body-b: the first link opens on body-a
// and the second link's fromBody re-binds to it.
let (ok, current) = verify_continuity_chain(
&[e1.clone(), e2.clone()],
Keys::Resolver(&any_did(&agent.public_key())),
None,
None,
"2026-06-01T00:00:00Z",
)
.unwrap();
assert!(ok);
assert_eq!(current.as_deref(), Some(body_b));
// Declaring the wrong origin body breaks the first link, since the first
// link's fromBody must match the origin when given.
let (bad_origin, _) = verify_continuity_chain(
&[e1.clone(), e2.clone()],
Keys::Resolver(&any_did(&agent.public_key())),
Some(body_b),
None,
"2026-06-01T00:00:00Z",
)
.unwrap();
assert!(!bad_origin);
// A broken link (second link's fromBody does not match the first's body)
// fails the chain.
let broken = build_embodiment(
&agent_seed,
&BuildEmbodiment {
agent_did: agent_did.into(),
body_did: body_b.into(),
body_hardware_root: "uROOTB".into(),
from_body: Some("did:web:body-x.example.com".into()),
embodied_at: "2026-01-01T01:00:00Z".into(),
valid_until: None,
},
)
.unwrap();
let (bad_link, _) = verify_continuity_chain(
&[e1.clone(), broken],
Keys::Resolver(&any_did(&agent.public_key())),
None,
None,
"2026-06-01T00:00:00Z",
)
.unwrap();
assert!(!bad_link);
// Every link must verify under the SAME agent key: a link signed by a
// different key breaks the chain (a mind is one persistent identity).
let e2_stranger = build_embodiment(
&stranger_seed,
&BuildEmbodiment {
agent_did: agent_did.into(),
body_did: body_b.into(),
body_hardware_root: "uROOTB".into(),
from_body: Some(body_a.into()),
embodied_at: "2026-01-01T01:00:00Z".into(),
valid_until: None,
},
)
.unwrap();
assert!(verify_embodiment(
&e2_stranger,
kd(&e2_stranger, &stranger.public_key()),
None,
"2026-06-01T00:00:00Z"
)
.unwrap()
.is_some());
let (mixed_keys, _) = verify_continuity_chain(
&[e1, e2_stranger],
Keys::Resolver(&any_did(&agent.public_key())),
None,
None,
"2026-06-01T00:00:00Z",
)
.unwrap();
assert!(!mixed_keys);
}
#[test]
fn fork_detection_flags_overlapping_bodies() {
let agent_seed = [61u8; 32];
let agent_did = "did:web:agent.example.com";
let body_a = "did:web:body-a.example.com";
let body_b = "did:web:body-b.example.com";
let build = |body: &str, root: &str, from: &str, until: &str| {
build_embodiment(
&agent_seed,
&BuildEmbodiment {
agent_did: agent_did.into(),
body_did: body.into(),
body_hardware_root: root.into(),
from_body: None,
embodied_at: from.into(),
valid_until: Some(until.into()),
},
)
.unwrap()
};
// A clean handover: body-a's window ends exactly where body-b's begins.
// Half-open intervals do not overlap, so this is not a fork.
let clean_a = build(
body_a,
"uROOTA",
"2026-01-01T00:00:00Z",
"2026-01-01T01:00:00Z",
);
let clean_b = build(
body_b,
"uROOTB",
"2026-01-01T01:00:00Z",
"2026-01-01T02:00:00Z",
);
let (clean, conflict) = check_no_fork(&[clean_a, clean_b]).unwrap();
assert!(clean);
assert!(conflict.is_none());
// Overlapping windows on different bodies are a fork; the conflict names
// both bodies.
let fork_a = build(
body_a,
"uROOTA",
"2026-01-01T00:00:00Z",
"2026-01-01T02:00:00Z",
);
let fork_b = build(
body_b,
"uROOTB",
"2026-01-01T01:00:00Z",
"2026-01-01T03:00:00Z",
);
let (forked, conflict) = check_no_fork(&[fork_a, fork_b]).unwrap();
assert!(!forked);
let conflict = conflict.expect("a fork names the two conflicting bodies");
assert_eq!(conflict.body_a, body_a);
assert_eq!(conflict.body_b, body_b);
}
// Custody handoff (Phase 5.16) -----------------------------------------
fn actor_keys_from_vector(map: &Value) -> Vec<ActorKey> {
map.as_object()
.expect("custody_actor_keys object")
.iter()
.map(|(did, jwk)| ActorKey {
did: did.clone(),
public_key: jwk_pub(jwk),
})
.collect()
}
// Cross-language interop: Rust verifies the Python-signed custody chain under
// the actor keys from the vector, ending on robot-b, and localizes the
// condition change to the hop robot-a was responsible for.
#[test]
fn verifies_python_custody_interop_vector() {
let vector = load_vector();
let chain: Vec<Value> = vector["custody_chain"]
.as_array()
.expect("custody_chain array")
.clone();
let keys = actor_keys_from_vector(&vector["custody_actor_keys"]);
let origin = vector["custody_origin_actor"].as_str().unwrap();
let (ok, current) =
verify_handoff_chain(&chain, &keys, "tote-42", Some(origin), false, TNOW).unwrap();
assert!(ok, "the Python custody chain must verify in Rust");
assert_eq!(
current.as_deref(),
Some("did:web:robot-b.example.com"),
"the chain ends holding at robot-b"
);
let change = locate_condition_change(&chain).expect("the condition changed");
assert_eq!(
change.responsible_holder.as_deref(),
Some("did:web:robot-a.example.com"),
"robot-a held the task while its condition changed"
);
assert_eq!(change.from_condition, "intact");
assert_eq!(change.to_condition, "damaged");
}
#[test]
fn handoff_roundtrip_and_receiver_rule() {
let robot_seed = [71u8; 32];
let other_seed = [72u8; 32];
let robot = Ed25519KeyPair::from_seed(&robot_seed);
let other = Ed25519KeyPair::from_seed(&other_seed);
let worker = "did:web:worker-jane.example.com";
let robot_a = "did:web:robot-a.example.com";
let cred = build_handoff(
&robot_seed,
&BuildHandoff {
release: None,
prev_handoff_id: None,
credential_id: "urn:uuid:00000000-0000-4000-8000-000000000105".into(),
task_id: "tote-42".into(),
from_actor: worker.into(),
to_actor: robot_a.into(),
condition: Some("intact".into()),
handoff_at: "2026-01-01T00:00:00Z".into(),
valid_until: None,
},
)
.unwrap();
let subject = verify_handoff(
&cred,
kd(&cred, &robot.public_key()),
HandoffCheck::default(),
TNOW,
)
.unwrap()
.expect("handoff verifies under the receiver key");
assert_eq!(subject["fromActor"], json!(worker));
assert_eq!(subject["toActor"], json!(robot_a));
// The issuer must be the receiver: forge a handoff issued by a different
// party over the same subject and re-sign it. It must be rejected even with
// a valid proof under the signing key, because a party attests its own
// acceptance of custody.
let forged = {
let mut bare = cred.clone();
bare.as_object_mut().unwrap().remove("proof");
bare["issuer"] = json!("did:web:impostor.example.com");
let opts = BuildProofOptions::new(
"did:web:impostor.example.com#key-1".to_string(),
"2026-01-01T00:00:00Z",
);
data_integrity::sign(&bare, &other_seed, &opts).unwrap()
};
assert!(verify_handoff(
&forged,
kd(&forged, &other.public_key()),
HandoffCheck::default(),
TNOW
)
.unwrap()
.is_none());
}
#[test]
fn handoff_chain_links_and_rejects() {
let a_seed = [73u8; 32];
let b_seed = [74u8; 32];
let a = Ed25519KeyPair::from_seed(&a_seed);
let b = Ed25519KeyPair::from_seed(&b_seed);
let worker = "did:web:worker-jane.example.com";
let robot_a = "did:web:robot-a.example.com";
let robot_b = "did:web:robot-b.example.com";
let h1 = build_handoff(
&a_seed,
&BuildHandoff {
release: None,
prev_handoff_id: None,
credential_id: "urn:uuid:00000000-0000-4000-8000-000000000106".into(),
task_id: "tote-42".into(),
from_actor: worker.into(),
to_actor: robot_a.into(),
condition: Some("intact".into()),
handoff_at: "2026-01-01T00:00:00Z".into(),
valid_until: None,
},
)
.unwrap();
let h2 = build_handoff(
&b_seed,
&BuildHandoff {
release: None,
prev_handoff_id: Some("urn:uuid:00000000-0000-4000-8000-000000000106".into()),
credential_id: "urn:uuid:00000000-0000-4000-8000-000000000107".into(),
task_id: "tote-42".into(),
from_actor: robot_a.into(),
to_actor: robot_b.into(),
condition: Some("damaged".into()),
handoff_at: "2026-01-01T00:10:00Z".into(),
valid_until: None,
},
)
.unwrap();
let keys = vec![
ActorKey {
did: robot_a.into(),
public_key: a.public_key().to_vec(),
},
ActorKey {
did: robot_b.into(),
public_key: b.public_key().to_vec(),
},
];
// A clean two-link chain ends holding at robot-b: the first link's
// fromActor is the origin worker and the second link re-binds to robot-a.
let (ok, current) = verify_handoff_chain(
&[h1.clone(), h2.clone()],
&keys,
"tote-42",
Some(worker),
false,
TNOW,
)
.unwrap();
assert!(ok);
assert_eq!(current.as_deref(), Some(robot_b));
// Declaring the wrong origin actor breaks the first link.
let (bad_origin, _) = verify_handoff_chain(
&[h1.clone(), h2.clone()],
&keys,
"tote-42",
Some(robot_b),
false,
TNOW,
)
.unwrap();
assert!(!bad_origin);
// A broken link (second link's fromActor does not match the first's
// toActor) fails the chain.
let broken = build_handoff(
&b_seed,
&BuildHandoff {
release: None,
prev_handoff_id: Some("urn:uuid:00000000-0000-4000-8000-000000000106".into()),
credential_id: "urn:uuid:00000000-0000-4000-8000-000000000108".into(),
task_id: "tote-42".into(),
from_actor: "did:web:robot-x.example.com".into(),
to_actor: robot_b.into(),
condition: Some("damaged".into()),
handoff_at: "2026-01-01T00:10:00Z".into(),
valid_until: None,
},
)
.unwrap();
let (bad_link, _) = verify_handoff_chain(
&[h1.clone(), broken],
&keys,
"tote-42",
Some(worker),
false,
TNOW,
)
.unwrap();
assert!(!bad_link);
// A missing receiver key for a link fails the chain.
let partial = vec![ActorKey {
did: robot_a.into(),
public_key: a.public_key().to_vec(),
}];
let (no_key, _) = verify_handoff_chain(
&[h1.clone(), h2.clone()],
&partial,
"tote-42",
Some(worker),
false,
TNOW,
)
.unwrap();
assert!(!no_key);
// holder_at reports who held the task at a moment: robot-a right after the
// first handoff, robot-b right after the second.
assert_eq!(
holder_at(&[h1.clone(), h2.clone()], "2026-01-01T00:05:00Z").as_deref(),
Some(robot_a)
);
assert_eq!(
holder_at(&[h1.clone(), h2.clone()], "2026-01-01T00:15:00Z").as_deref(),
Some(robot_b)
);
// A chain whose condition never changes localizes nothing.
let steady = build_handoff(
&b_seed,
&BuildHandoff {
release: None,
prev_handoff_id: None,
credential_id: "urn:uuid:00000000-0000-4000-8000-000000000109".into(),
task_id: "tote-42".into(),
from_actor: robot_a.into(),
to_actor: robot_b.into(),
condition: Some("intact".into()),
handoff_at: "2026-01-01T00:10:00Z".into(),
valid_until: None,
},
)
.unwrap();
assert!(locate_condition_change(&[h1, steady]).is_none());
}
// Robot-to-infrastructure bounded access (Phase 5.17) ------------------
// Cross-language interop: Rust authorizes the Python-signed grant and request
// from the vector under the operator and robot keys, offline.
#[test]
fn authorizes_python_access_interop_vector() {
let vector = load_vector();
let grant = vector["access_grant_credential"].clone();
let request = vector["access_request_credential"].clone();
let operator_pub = jwk_pub(&vector["access_operator_key"]);
let robot_pub = jwk_pub(&vector["access_robot_key"]);
// The request was made at VALID_FROM; a resource checks it within the
// 60 s age limit and remembers its nonce.
let mut seen = HashSet::new();
let res = authorize_access(
&grant,
&request,
kd(&grant, &operator_pub),
kd(&request, &robot_pub),
RequestReplay::new(&mut seen),
"2026-01-01T00:00:30Z",
)
.unwrap();
assert!(
res.ok,
"the Python grant and request must authorize in Rust: {:?}",
res.reasons
);
assert!(res.reasons.is_empty());
// A replay of the same request is refused, and so is a stale one.
let again = authorize_access(
&grant,
&request,
kd(&grant, &operator_pub),
kd(&request, &robot_pub),
RequestReplay::new(&mut seen),
"2026-01-01T00:00:30Z",
)
.unwrap();
assert!(!again.ok);
let mut fresh = HashSet::new();
let stale = authorize_access(
&grant,
&request,
kd(&grant, &operator_pub),
kd(&request, &robot_pub),
RequestReplay::new(&mut fresh),
"2026-01-01T00:05:00Z",
)
.unwrap();
assert!(!stale.ok);
}
// Fused-sensor provenance (Phase 5.18) ---------------------------------
// Cross-language interop: Rust reproduces the exact inputs digest and fused
// output hash Python pinned, and verifies the Python-signed attestation.
#[test]
fn verifies_python_fused_interop_vector() {
let vector = load_vector();
let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
let inputs: Vec<String> = vector["fused_input_frame_hashes"]
.as_array()
.unwrap()
.iter()
.map(|v| v.as_str().unwrap().to_string())
.collect();
assert_eq!(
fusion_inputs_digest_version(&inputs, INPUTS_DIGEST_V1).unwrap(),
vector["expected_fusion_inputs_digest"].as_str().unwrap()
);
assert_eq!(
fusion_inputs_digest(&inputs).unwrap(),
vector["expected_fusion_inputs_digest_v2"].as_str().unwrap()
);
assert_eq!(
hash_fused_output(b"world-model-0"),
vector["expected_fused_output_hash"].as_str().unwrap()
);
let cred = vector["fused_perception_attestation"].clone();
let subject = verify_fused_attestation(&cred, kd(&cred, &robot_pub), None, TNOW)
.unwrap()
.expect("fused attestation verifies");
assert_eq!(subject["fusionMethod"], "occupancy-grid-v1");
assert_eq!(
subject["inputsDigest"].as_str().unwrap(),
vector["expected_fusion_inputs_digest_v2"].as_str().unwrap()
);
}
// Wear and degradation attestation (Phase 5.19) ------------------------
// Cross-language interop: Rust verifies the Python-signed wear history and
// reproduces the physical scope narrowed for the pinned wear level.
#[test]
fn verifies_python_wear_interop_vector() {
let vector = load_vector();
let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
let chain: Vec<Value> = vector["wear_chain"].as_array().unwrap().clone();
let latest = verify_wear_chain(&chain, Keys::Resolver(&any_did(&robot_pub)), TNOW)
.unwrap()
.expect("wear chain verifies");
assert_eq!(latest["wearLevel"].as_f64().unwrap(), 0.3);
let scope = vector["wear_input_scope"].clone();
let level = vector["wear_attenuation_level"].as_f64().unwrap();
let narrowed = attenuate_for_wear(&scope, level).unwrap();
assert_eq!(narrowed, vector["expected_attenuated_scope"]);
assert_eq!(narrowed["maxForceN"].as_f64().unwrap(), 60.0);
assert_eq!(narrowed["maxSpeedMps"].as_f64().unwrap(), 1.125);
assert_eq!(narrowed["maxSpeedNearHumansMps"].as_f64().unwrap(), 0.1875);
assert!(attenuates(&scope, &narrowed));
}
// Bystander-consent evidence (Phase 5.20) ------------------------------
// Cross-language interop: Rust reproduces the capture hash Python pinned,
// verifies the bystander-signed token is bound to that capture, and verifies
// the robot-signed evidence with the token and the bystander key.
#[test]
fn verifies_python_consent_interop_vector() {
let vector = load_vector();
let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
let bystander_pub = jwk_pub(&vector["consent_bystander_key"]);
let capture = b"bystander-frame-0";
let capture_hash = hash_capture(capture);
assert_eq!(
capture_hash,
vector["expected_consent_capture_hash"].as_str().unwrap()
);
let token = vector["consent_token_credential"].clone();
let robot_did = token["credentialSubject"]["robotDid"].as_str().unwrap();
let tok_subject = verify_consent_token(
&token,
kd(&token, &bystander_pub),
&capture_hash,
robot_did,
"2026-01-01T00:05:00Z",
)
.unwrap()
.expect("consent token verifies bound to the capture");
assert_eq!(tok_subject["captureHash"].as_str().unwrap(), capture_hash);
let evidence = vector["consent_evidence_credential"].clone();
let bystander_did = token["issuer"].as_str().unwrap();
let keys = [BystanderKey {
did: bystander_did.to_string(),
public_key: bystander_pub.clone(),
}];
let ev_subject = verify_consent_evidence(
&evidence,
kd(&evidence, &robot_pub),
Some(capture),
Some(core::slice::from_ref(&token)),
Some(&keys),
"2026-01-01T00:05:00Z",
)
.unwrap()
.expect("consent evidence verifies with token and bystander key");
assert_eq!(ev_subject["basis"].as_str().unwrap(), "explicit-consent");
}
}
#[cfg(test)]
mod robot_root_identity_tests {
use super::*;
use crate::keys::Ed25519KeyPair;
#[allow(unused_imports)]
use crate::robotics_verify::test_keys::{any_did, kd, TNOW};
#[allow(unused_imports)]
use crate::robotics_verify::Keys;
use std::path::PathBuf;
const NOW: &str = "2026-07-01T00:00:00Z";
const VALID_FROM: &str = "2026-01-01T00:00:00Z";
const CREATED: &str = "2026-01-01T00:00:00Z";
const VALID_SECONDS: i64 = 100 * 365 * 24 * 3600;
// Matches the manufacturer seed recorded in the interop vector (0x04 x32).
const MANUFACTURER_SEED: [u8; 32] = [0x04; 32];
const FORGED_ID: &str = "urn:uuid:66666666-6666-6666-6666-666666666666";
fn load_vector() -> Value {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../test-vectors/root-of-trust/vector.json");
let text = std::fs::read_to_string(&path)
.unwrap_or_else(|e| panic!("read vector {}: {e}", path.display()));
serde_json::from_str(&text).expect("vector is valid JSON")
}
fn robot_pub(vector: &Value) -> Vec<u8> {
let x = vector["robotPublicKey"]["x"].as_str().unwrap();
URL_SAFE_NO_PAD.decode(x).unwrap()
}
fn stray_multikey(seed: &[u8]) -> String {
let kp = Ed25519KeyPair::from_seed_slice(seed).unwrap();
multikey::encode_ed25519_public(&kp.public_key()).unwrap()
}
fn stray_did(seed: &[u8]) -> String {
Ed25519KeyPair::from_seed_slice(seed).unwrap().did_key()
}
fn robot_attributes() -> Value {
json!({ "make": "Acme Robotics", "model": "AR-7", "serial": "SN-000123" })
}
// The committed Python-minted robot chain must verify in Rust: recognized
// manufacturer provenance plus hardware-rooting.
#[test]
fn verifies_python_robot_identity_interop_vector() {
let v = load_vector();
let root = v["trustedRoot"].as_str().unwrap();
let r = verify_robot_identity_chain(
&v["robotAuthorityIdentity"],
&v["robotRecognizedIssuer"],
&v["robotHardwareCredential"],
root,
&robot_pub(&v),
Some(&v["rootOfTrust"]),
NOW,
30,
);
assert!(r.ok, "robot chain must verify: {:?}", r.reason);
assert_eq!(
Some(r.hardware_rooted),
v["expected"]["hardwareRooted"].as_bool(),
"the manufacturer pinned the hardware-root key"
);
assert_eq!(r.robot_did.as_deref(), v["expected"]["robotDid"].as_str());
assert_eq!(
r.issuer_did.as_deref(),
v["expected"]["robotIssuerDid"].as_str()
);
assert_eq!(r.root_did.as_deref(), Some(root));
assert_eq!(
v["expected"]["verifyRobotIdentityChain"].as_bool(),
Some(true)
);
}
// Adversarial: pinning a different root breaks the recognition anchor.
#[test]
fn wrong_pinned_root_rejected() {
let v = load_vector();
let other_root = stray_did(&[0x09; 32]);
let r = verify_robot_identity_chain(
&v["robotAuthorityIdentity"],
&v["robotRecognizedIssuer"],
&v["robotHardwareCredential"],
&other_root,
&robot_pub(&v),
None,
NOW,
30,
);
assert!(!r.ok);
assert_eq!(r.reason.as_deref(), Some("recognized_issuer_not_from_root"));
}
// Adversarial: the manufacturer vouched a key that is not the robot's real
// key. Provenance holds but the hardware key does not match.
#[test]
fn manufacturer_vouched_a_different_key() {
let v = load_vector();
let root = v["trustedRoot"].as_str().unwrap();
let robot_did = v["expected"]["robotDid"].as_str().unwrap();
let forged = build_robot_identity(
&MANUFACTURER_SEED,
robot_did,
&stray_multikey(&[0x09; 32]),
&robot_attributes(),
VALID_SECONDS,
VALID_FROM,
CREATED,
None,
FORGED_ID,
None,
)
.unwrap();
let r = verify_robot_identity_chain(
&forged,
&v["robotRecognizedIssuer"],
&v["robotHardwareCredential"],
root,
&robot_pub(&v),
Some(&v["rootOfTrust"]),
NOW,
30,
);
assert!(!r.ok);
assert_eq!(r.reason.as_deref(), Some("hardware_key_mismatch"));
}
// Adversarial: an impostor key is presented for the hardware credential, so
// the secure-element attestation no longer verifies.
#[test]
fn impostor_key_fails_hardware_root() {
let v = load_vector();
let root = v["trustedRoot"].as_str().unwrap();
let impostor = Ed25519KeyPair::from_seed(&[0x09; 32]).public_key();
let r = verify_robot_identity_chain(
&v["robotAuthorityIdentity"],
&v["robotRecognizedIssuer"],
&v["robotHardwareCredential"],
root,
&impostor,
Some(&v["rootOfTrust"]),
NOW,
30,
);
assert!(!r.ok);
assert_eq!(r.reason.as_deref(), Some("hardware_root_invalid"));
}
}
#[cfg(test)]
mod port_hardening_tests {
use super::*;
use crate::keys::Ed25519KeyPair;
#[allow(unused_imports)]
use crate::robotics_verify::test_keys::{any_did, kd, TNOW};
#[allow(unused_imports)]
use crate::robotics_verify::Keys;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine;
// A missing or empty input list is malformed: the log check fails closed
// instead of reporting "every input was logged".
#[test]
fn fusion_inputs_check_fails_closed_on_an_empty_list() {
let empty = json!({"credentialSubject": {"inputFrameHashes": []}});
assert!(!verify_fusion_inputs(&empty, &[]).ok);
let missing = json!({"credentialSubject": {}});
assert!(!verify_fusion_inputs(&missing, &[]).ok);
let odd = json!({"credentialSubject": {"inputFrameHashes": ["ua", 5]}});
let res = verify_fusion_inputs(&odd, &[json!({"frameHash": "ua"})]);
assert!(!res.ok);
assert_eq!(res.missing, vec!["5".to_string()]);
}
fn load_vector() -> Value {
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../test-vectors/robotics/vector.json");
serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
}
fn jwk_pub(jwk: &Value) -> Vec<u8> {
URL_SAFE_NO_PAD.decode(jwk["x"].as_str().unwrap()).unwrap()
}
fn lease(valid_until: &str) -> (Value, Vec<u8>) {
let seed = [51u8; 32];
let kp = Ed25519KeyPair::from_seed(&seed);
let cred = build_delegation_lease(
&seed,
&BuildDelegationLease {
issuer_did: "did:web:robot.example.com".into(),
robot_did: "did:web:robot.example.com".into(),
lease_id: "lease-h".into(),
scope: json!({"maxForceN": 80.0}),
parent_lease_id: None,
valid_from: "2026-01-01T00:00:00Z".into(),
valid_until: valid_until.into(),
},
)
.unwrap();
(cred, kp.public_key().to_vec())
}
// The core needs a clock: an empty or malformed `now` is an error, never a
// skipped window check, in every verifier that checks a window.
#[test]
fn a_missing_or_malformed_clock_is_an_error() {
let (cred, key) = lease("2026-01-01T01:00:00Z");
for bad in ["", "null", "not-a-date", "2026-01-01"] {
assert!(
verify_delegation_lease(
&cred,
kd(&cred, &key),
"did:web:robot.example.com",
None,
None,
bad
)
.is_err(),
"{bad:?}"
);
assert!(
lease_permits(
&json!({}),
&PhysicalAction::default(),
Some(&cred),
kd(&cred, &key),
None,
bad
)
.is_err(),
"{bad:?}"
);
assert!(verify_action_authorization(&[], "a", "r", &[], 1, None, bad).is_err());
assert!(verify_access_grant(&cred, kd(&cred, &key), None, bad).is_err());
assert!(authorize_access(
&cred,
&cred,
kd(&cred, &key),
kd(&cred, &key),
RequestReplay::new(&mut HashSet::new()),
bad
)
.is_err());
assert!(verify_consent_token(&cred, kd(&cred, &key), "h", "r", bad).is_err());
assert!(
verify_consent_evidence(&cred, kd(&cred, &key), None, None, None, bad).is_err()
);
}
}
// The shared vector's expired lease is refused at any time after its window,
// and accepted inside it.
#[test]
fn expired_vector_lease_refused_after_its_window() {
let v = load_vector();
let key = jwk_pub(&v["robot_public_key_jwk"]);
let cred = &v["delegation_lease_expired_credential"];
assert!(verify_delegation_lease(
cred,
kd(cred, &key),
"did:web:robot.example.com",
None,
None,
"2026-01-01T00:30:00Z"
)
.unwrap()
.is_some());
assert!(verify_delegation_lease(
cred,
kd(cred, &key),
"did:web:robot.example.com",
None,
None,
"2026-06-01T00:00:00Z"
)
.unwrap()
.is_none());
}
// A validity bound that is present must be a string that parses.
#[test]
fn non_string_window_bounds_are_invalid() {
for (key, bad) in [
("validFrom", json!(5)),
("validFrom", json!(null)),
("validUntil", json!(["2099-01-01T00:00:00Z"])),
("validUntil", json!(4102444800i64)),
("validUntil", json!("")),
] {
let mut cred = json!({
"validFrom": "2026-01-01T00:00:00Z",
"validUntil": "2026-01-01T01:00:00Z"
});
cred[key] = bad.clone();
assert!(
rv::window_reason(&cred, Window::IfPresent, 1_767_225_660 * 1_000_000_000, 0)
.is_some(),
"{key}={bad}"
);
}
}
// One malformed approval from a listed approver is skipped; it does not fail
// the whole authorization (shared vector).
#[test]
fn malformed_approvals_are_skipped_not_fatal() {
let v = load_vector();
let approvals = v["quorum_approvals_with_malformed"]
.as_array()
.unwrap()
.clone();
let keys: Vec<ApproverKey> = v["quorum_approver_keys"]
.as_object()
.unwrap()
.iter()
.map(|(did, jwk)| ApproverKey {
did: did.clone(),
public_key: jwk_pub(jwk),
})
.collect();
let (ok, approvers) = verify_action_authorization(
&approvals,
v["quorum_action_id"].as_str().unwrap(),
"did:web:robot.example.com",
&keys,
2,
None,
v["quorum_now"].as_str().unwrap(),
)
.unwrap();
let expected = &v["expected_quorum_with_malformed"];
assert_eq!(json!(ok), expected["authorized"]);
assert_eq!(json!(approvers), expected["approvers"]);
}
// A malformed scope field the action is checked against is a violation.
#[test]
fn malformed_scope_fields_are_violations() {
let force = PhysicalAction {
force_n: Some(5000.0),
..Default::default()
};
for cap in [json!("100"), json!(null), json!(true), json!([100])] {
let r = check_physical_action(&json!({"maxForceN": cap}), &force);
assert!(!r.ok, "maxForceN={cap}");
}
let speed = PhysicalAction {
speed_mps: Some(9.0),
near_humans: true,
..Default::default()
};
let r = check_physical_action(
&json!({"maxSpeedMps": 1.0, "maxSpeedNearHumansMps": null}),
&speed,
);
assert!(!r.ok);
let zone = PhysicalAction {
zone: Some("A".into()),
..Default::default()
};
for zones in [json!("A"), json!({"A": true}), json!(7)] {
assert!(!check_physical_action(&json!({"allowedZones": zones}), &zone).ok);
}
let late = PhysicalAction {
time_hm: Some("23:00".into()),
..Default::default()
};
for ws in [
json!("08:00-18:00"),
json!({"start": "08:00", "end": "18:00"}),
json!(["08:00"]),
json!([{"start": 800, "end": "18:00"}]),
] {
assert!(
!check_physical_action(&json!({"shiftWindows": ws}), &late).ok,
"{ws}"
);
}
// Native NaN in an action never passes a cap.
let nan = PhysicalAction {
force_n: Some(f64::NAN),
..Default::default()
};
assert!(!check_physical_action(&json!({"maxForceN": 10.0}), &nan).ok);
}
#[test]
fn malformed_child_fields_never_attenuate() {
let parent = json!({
"maxForceN": 80.0,
"allowedZones": ["A", "B"],
"shiftWindows": [{"start": "08:00", "end": "18:00"}]
});
let good = json!({
"maxForceN": 50.0,
"allowedZones": ["A"],
"shiftWindows": [{"start": "09:00", "end": "17:00"}]
});
assert!(attenuates(&parent, &good));
for (k, bad) in [
("shiftWindows", json!("00:00-23:59")),
("shiftWindows", json!({"start": "00:00"})),
("shiftWindows", json!([{"start": 0, "end": "23:59"}])),
("maxForceN", json!("50")),
("maxForceN", json!(null)),
("allowedZones", json!("A")),
("allowedZones", json!(["A", 7])),
("maxSpeedMps", json!("unlimited")),
] {
let mut child = good.clone();
child[k] = bad.clone();
assert!(!attenuates(&parent, &child), "{k}={bad}");
}
// A malformed parent cap refuses rather than being skipped.
assert!(!attenuates(&json!({"maxForceN": "80"}), &good));
}
#[test]
fn nan_wear_level_is_refused() {
assert!(attenuate_for_wear(&json!({"maxForceN": 80.0}), f64::NAN).is_err());
assert!(attenuate_for_wear(&json!({"maxForceN": 80.0}), 0.5).is_ok());
}
}
#[cfg(test)]
mod fork_check_tests {
use super::*;
fn iso(offset: i64) -> String {
// 2026-01-01T00:00:00Z plus offset seconds, offsets kept within one day.
let s = offset.rem_euclid(86_400);
let day = if offset < 0 { 31 } else { 1 };
let month = if offset < 0 { "2025-12" } else { "2026-01" };
format!(
"{month}-{day:02}T{:02}:{:02}:{:02}Z",
s / 3600,
(s / 60) % 60,
s % 60
)
}
fn emb(body: &str, start: i64, end: Option<i64>) -> Value {
let mut e = json!({"credentialSubject": {"body": body}, "validFrom": iso(start)});
if let Some(end) = end {
e["validUntil"] = json!(iso(end));
}
e
}
fn pairwise(windows: &[(String, i64, Option<i64>)]) -> (bool, Option<(String, String)>) {
for (i, (bi, si, ei)) in windows.iter().enumerate() {
for (bj, sj, ej) in &windows[i + 1..] {
if bi == bj {
continue;
}
let a_before_b = ei.is_some_and(|e| e <= *sj);
let b_before_a = ej.is_some_and(|e| e <= *si);
if !(a_before_b || b_before_a) {
return (false, Some((bi.clone(), bj.clone())));
}
}
}
(true, None)
}
fn run(list: &[Value]) -> (bool, Option<(String, String)>) {
let (ok, conflict) = check_no_fork(list).unwrap();
(ok, conflict.map(|c| (c.body_a, c.body_b)))
}
#[test]
fn fork_check_matches_the_shared_vector() {
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../test-vectors/robotics/fork_vector.json");
let vector: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
let cases = vector["cases"].as_array().unwrap();
assert!(cases.len() > 40);
for case in cases {
let list = case["embodiments"].as_array().unwrap();
let (ok, conflict) = check_no_fork(list).unwrap();
let expected = &case["expected"];
assert_eq!(ok, expected["ok"].as_bool().unwrap(), "{}", case["name"]);
let got = conflict.map(|c| json!({"bodyA": c.body_a, "bodyB": c.body_b}));
assert_eq!(got.as_ref(), expected.get("conflict"), "{}", case["name"]);
}
}
#[test]
fn fork_check_matches_the_pairwise_scan_on_random_lists() {
// A small fixed-seed generator keeps this free of extra dependencies.
let mut state: u64 = 0x5eed_2026_1204;
let mut next = |n: u64| {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
(state >> 33) % n
};
for _ in 0..3000 {
let bodies = 1 + next(5);
let len = next(15);
let windows: Vec<(String, i64, Option<i64>)> = (0..len)
.map(|_| {
let body = ((b'a' + next(bodies) as u8) as char).to_string();
let start = next(41) as i64;
let end = if next(100) < 15 {
None
} else {
Some(start + next(25) as i64 - 4)
};
(body, start, end)
})
.collect();
let list: Vec<Value> = windows.iter().map(|(b, s, e)| emb(b, *s, *e)).collect();
assert_eq!(run(&list), pairwise(&windows), "{windows:?}");
}
}
#[test]
fn fork_check_handles_a_large_list_with_a_late_fork() {
// Many overlapping windows on one body, then one other body overlapping
// only the last of them: the pairwise scan needs about 2e8 steps here.
let n = 20_000i64;
let mut list: Vec<Value> = (0..n).map(|i| emb("body-a", i, Some(n + 5))).collect();
list.push(emb("body-b", n + 4, Some(n + 6)));
let began = std::time::Instant::now();
assert_eq!(
run(&list),
(false, Some(("body-a".into(), "body-b".into())))
);
assert!(began.elapsed() < core::time::Duration::from_secs(10));
let clean: Vec<Value> = (0..n)
.map(|i| {
emb(
&format!("body-{i}"),
i,
if i + 1 < n { Some(i + 1) } else { None },
)
})
.collect();
let began = std::time::Instant::now();
assert_eq!(run(&clean), (true, None));
assert!(began.elapsed() < core::time::Duration::from_secs(10));
}
#[test]
fn fork_check_still_refuses_malformed_entries() {
let good = emb("a", 0, Some(10));
assert_eq!(
run(&[good.clone(), json!({"validFrom": iso(0)})]),
(false, None)
);
assert_eq!(
run(&[good.clone(), json!({"credentialSubject": {"body": "b"}})]),
(false, None)
);
let mut bad_end = emb("b", 0, None);
bad_end["validUntil"] = json!("not a time");
assert_eq!(run(&[good, bad_end]), (false, None));
}
}