1use serde_json::{json, Map, Value};
20
21use crate::data_integrity::{self, BuildProofOptions};
22use crate::error::{CoreError, Result};
23use crate::keys;
24use crate::pq::{MlDsa44KeyPair, MLDSA44_PUBLIC_LEN};
25use crate::{hybrid, jcs, multikey};
26
27use aes_gcm::aead::Aead;
28use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
29use base64::engine::general_purpose::URL_SAFE_NO_PAD;
30use base64::Engine;
31use sha2::{Digest, Sha256};
32use std::collections::HashSet;
33
34pub const VC_CONTEXT_V2: &str = "https://www.w3.org/ns/credentials/v2";
35pub const VOUCH_CONTEXT_V1: &str = "https://vouch-protocol.com/contexts/v1";
36pub const ROBOT_IDENTITY_TYPE: &str = "RobotIdentityCredential";
37
38pub(crate) fn mb64(bytes: &[u8]) -> String {
40 format!("u{}", URL_SAFE_NO_PAD.encode(bytes))
41}
42
43pub(crate) fn unmb64(s: &str) -> Result<Vec<u8>> {
45 let body = s
46 .strip_prefix('u')
47 .ok_or_else(|| CoreError::Json("expected multibase 'u' prefix".into()))?;
48 URL_SAFE_NO_PAD
49 .decode(body)
50 .map_err(|e| CoreError::Json(format!("bad base64url: {e}")))
51}
52
53pub(crate) fn has_type(type_field: Option<&Value>, want: &str) -> bool {
55 match type_field {
56 Some(Value::String(s)) => s == want,
57 Some(Value::Array(items)) => items.iter().any(|v| v.as_str() == Some(want)),
58 _ => false,
59 }
60}
61
62pub fn robot_identity_binding(robot_did: &str, robot_key_multibase: &str) -> Vec<u8> {
65 jcs::canonicalize(&json!({
66 "key": robot_key_multibase,
67 "robotDid": robot_did,
68 }))
69}
70
71#[derive(Debug, Clone)]
75pub struct MintRobotIdentity {
76 pub robot_did: String,
77 pub make: String,
78 pub model: String,
79 pub serial: String,
80 pub owner: Option<String>,
81 pub root_kind: String,
82 pub root_public_multibase: String,
83 pub attestation: Vec<u8>,
84 pub lifecycle: Option<Value>,
86 pub valid_from: String,
87 pub valid_until: Option<String>,
88}
89
90pub fn mint_robot_identity(robot_seed: &[u8], params: &MintRobotIdentity) -> Result<Value> {
94 let lifecycle = params
95 .lifecycle
96 .clone()
97 .unwrap_or_else(|| json!([{ "event": "commissioned", "timestamp": params.valid_from }]));
98
99 let mut subject = Map::new();
100 subject.insert("id".into(), json!(params.robot_did));
101 subject.insert("make".into(), json!(params.make));
102 subject.insert("model".into(), json!(params.model));
103 subject.insert("serial".into(), json!(params.serial));
104 subject.insert(
105 "hardwareRoot".into(),
106 json!({
107 "kind": params.root_kind,
108 "publicKeyMultibase": params.root_public_multibase,
109 "attestation": mb64(¶ms.attestation),
110 }),
111 );
112 subject.insert("lifecycle".into(), lifecycle);
113 if let Some(owner) = ¶ms.owner {
114 subject.insert("owner".into(), json!(owner));
115 }
116
117 let mut cred = Map::new();
118 cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
119 cred.insert(
120 "type".into(),
121 json!(["VerifiableCredential", ROBOT_IDENTITY_TYPE]),
122 );
123 cred.insert("issuer".into(), json!(params.robot_did));
124 cred.insert("validFrom".into(), json!(params.valid_from));
125 if let Some(vu) = ¶ms.valid_until {
126 cred.insert("validUntil".into(), json!(vu));
127 }
128 cred.insert("credentialSubject".into(), Value::Object(subject));
129
130 let opts = BuildProofOptions::new(
131 format!("{}#key-1", params.robot_did),
132 params.valid_from.clone(),
133 );
134 data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
135}
136
137pub fn verify_robot_identity(credential: &Value, robot_public_key: &[u8]) -> Result<Option<Value>> {
141 let obj = credential
142 .as_object()
143 .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?;
144 if !has_type(obj.get("type"), ROBOT_IDENTITY_TYPE) {
145 return Ok(None);
146 }
147 if !data_integrity::verify_proof(credential, robot_public_key)? {
148 return Ok(None);
149 }
150
151 let subject = match obj.get("credentialSubject").and_then(|s| s.as_object()) {
152 Some(s) => s,
153 None => return Ok(None),
154 };
155 let hw = match subject.get("hardwareRoot").and_then(|h| h.as_object()) {
156 Some(h) => h,
157 None => return Ok(None),
158 };
159 let hw_mb = match hw.get("publicKeyMultibase").and_then(|v| v.as_str()) {
160 Some(s) => s,
161 None => return Ok(None),
162 };
163 let attestation_mb = match hw.get("attestation").and_then(|v| v.as_str()) {
164 Some(s) => s,
165 None => return Ok(None),
166 };
167
168 let decoded = match multikey::decode(hw_mb) {
169 Ok(d) if d.algorithm == "Ed25519" && d.raw_key.len() == 32 => d,
170 _ => return Ok(None),
171 };
172 let attestation = match unmb64(attestation_mb) {
173 Ok(a) => a,
174 Err(_) => return Ok(None),
175 };
176
177 let robot_key_mb = multikey::encode_ed25519_public(robot_public_key)?;
178 let robot_did = subject.get("id").and_then(|v| v.as_str()).unwrap_or("");
179 let binding = robot_identity_binding(robot_did, &robot_key_mb);
180
181 if !keys::verify(&decoded.raw_key, &binding, &attestation)? {
182 return Ok(None);
183 }
184 Ok(Some(Value::Object(subject.clone())))
185}
186
187pub const MODEL_PROVENANCE_TYPE: &str = "ModelProvenanceAttestation";
192
193pub fn config_hash(config: &Value) -> String {
197 let digest = Sha256::digest(jcs::canonicalize(config));
198 mb64(&digest)
199}
200
201#[derive(Debug, Clone)]
205pub struct BuildProvenance {
206 pub issuer_did: String,
207 pub robot_did: String,
208 pub model_name: String,
209 pub weights_hash: String,
210 pub safety_policy: String,
211 pub config: Option<Value>,
212 pub version: Option<String>,
213 pub supersedes: Option<String>,
214 pub valid_from: String,
215 pub valid_until: Option<String>,
216}
217
218pub fn build_provenance_attestation(signer_seed: &[u8], params: &BuildProvenance) -> Result<Value> {
220 let mut vla = Map::new();
221 vla.insert("modelName".into(), json!(params.model_name));
222 vla.insert("weightsHash".into(), json!(params.weights_hash));
223 vla.insert("safetyPolicy".into(), json!(params.safety_policy));
224 if let Some(v) = ¶ms.version {
225 vla.insert("version".into(), json!(v));
226 }
227 if let Some(cfg) = ¶ms.config {
228 vla.insert("configHash".into(), json!(config_hash(cfg)));
229 }
230
231 let mut subject = Map::new();
232 subject.insert("id".into(), json!(params.robot_did));
233 subject.insert("vla".into(), Value::Object(vla));
234 if let Some(s) = ¶ms.supersedes {
235 subject.insert("supersedes".into(), json!(s));
236 }
237
238 let mut cred = Map::new();
239 cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
240 cred.insert(
241 "type".into(),
242 json!(["VerifiableCredential", MODEL_PROVENANCE_TYPE]),
243 );
244 cred.insert("issuer".into(), json!(params.issuer_did));
245 cred.insert("validFrom".into(), json!(params.valid_from));
246 if let Some(vu) = ¶ms.valid_until {
247 cred.insert("validUntil".into(), json!(vu));
248 }
249 cred.insert("credentialSubject".into(), Value::Object(subject));
250
251 let opts = BuildProofOptions::new(
252 format!("{}#key-1", params.issuer_did),
253 params.valid_from.clone(),
254 );
255 data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
256}
257
258pub fn verify_provenance_attestation(
262 attestation: &Value,
263 public_key: &[u8],
264 config: Option<&Value>,
265) -> Result<Option<Value>> {
266 let obj = attestation
267 .as_object()
268 .ok_or_else(|| CoreError::Json("attestation must be a JSON object".into()))?;
269 if !has_type(obj.get("type"), MODEL_PROVENANCE_TYPE) {
270 return Ok(None);
271 }
272 if !data_integrity::verify_proof(attestation, public_key)? {
273 return Ok(None);
274 }
275 let subject = match obj.get("credentialSubject").and_then(|s| s.as_object()) {
276 Some(s) => s,
277 None => return Ok(None),
278 };
279 if let Some(cfg) = config {
280 let want = config_hash(cfg);
281 let got = subject
282 .get("vla")
283 .and_then(|v| v.as_object())
284 .and_then(|v| v.get("configHash"))
285 .and_then(|v| v.as_str())
286 .unwrap_or("");
287 if got != want {
288 return Ok(None);
289 }
290 }
291 Ok(Some(Value::Object(subject.clone())))
292}
293
294pub const PHYSICAL_SCOPE_TYPE: &str = "PhysicalCapabilityScope";
299
300#[derive(Debug, Clone)]
302pub struct ShiftWindow {
303 pub start: String,
304 pub end: String,
305}
306
307#[derive(Debug, Clone, Default)]
310pub struct PhysicalAction {
311 pub force_n: Option<f64>,
312 pub speed_mps: Option<f64>,
313 pub near_humans: bool,
314 pub zone: Option<String>,
315 pub time_hm: Option<String>,
316}
317
318#[derive(Debug, Clone)]
320pub struct CheckResult {
321 pub ok: bool,
322 pub reasons: Vec<String>,
323}
324
325#[derive(Debug, Clone, Default)]
328pub struct BuildPhysicalScope {
329 pub issuer_did: String,
330 pub subject_did: String,
331 pub max_force_n: Option<f64>,
332 pub max_speed_mps: Option<f64>,
333 pub max_speed_near_humans_mps: Option<f64>,
334 pub allowed_zones: Option<Vec<String>>,
335 pub shift_windows: Option<Vec<ShiftWindow>>,
336 pub valid_from: String,
337 pub valid_until: Option<String>,
338}
339
340pub fn build_physical_scope_credential(
342 signer_seed: &[u8],
343 params: &BuildPhysicalScope,
344) -> Result<Value> {
345 let mut scope = Map::new();
346 if let Some(v) = params.max_force_n {
347 scope.insert("maxForceN".into(), json!(v));
348 }
349 if let Some(v) = params.max_speed_mps {
350 scope.insert("maxSpeedMps".into(), json!(v));
351 }
352 if let Some(v) = params.max_speed_near_humans_mps {
353 scope.insert("maxSpeedNearHumansMps".into(), json!(v));
354 }
355 if let Some(zones) = ¶ms.allowed_zones {
356 scope.insert("allowedZones".into(), json!(zones));
357 }
358 if let Some(ws) = ¶ms.shift_windows {
359 let arr: Vec<Value> = ws
360 .iter()
361 .map(|w| json!({"start": w.start, "end": w.end}))
362 .collect();
363 scope.insert("shiftWindows".into(), Value::Array(arr));
364 }
365
366 let mut subject = Map::new();
367 subject.insert("id".into(), json!(params.subject_did));
368 subject.insert("physicalScope".into(), Value::Object(scope));
369
370 let mut cred = Map::new();
371 cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
372 cred.insert(
373 "type".into(),
374 json!(["VerifiableCredential", PHYSICAL_SCOPE_TYPE]),
375 );
376 cred.insert("issuer".into(), json!(params.issuer_did));
377 cred.insert("validFrom".into(), json!(params.valid_from));
378 if let Some(vu) = ¶ms.valid_until {
379 cred.insert("validUntil".into(), json!(vu));
380 }
381 cred.insert("credentialSubject".into(), Value::Object(subject));
382
383 let opts = BuildProofOptions::new(
384 format!("{}#key-1", params.issuer_did),
385 params.valid_from.clone(),
386 );
387 data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
388}
389
390fn scope_num(scope: &Map<String, Value>, key: &str) -> Option<f64> {
391 scope.get(key).and_then(|v| v.as_f64())
392}
393
394fn window_bounds(w: &Value) -> (String, String) {
395 let start = w
396 .get("start")
397 .and_then(|v| v.as_str())
398 .filter(|s| !s.is_empty())
399 .unwrap_or("00:00")
400 .to_string();
401 let end = w
402 .get("end")
403 .and_then(|v| v.as_str())
404 .filter(|s| !s.is_empty())
405 .unwrap_or("23:59")
406 .to_string();
407 (start, end)
408}
409
410fn in_window(hm: &str, w: &Value) -> bool {
411 let (start, end) = window_bounds(w);
412 start.as_str() <= hm && hm <= end.as_str()
413}
414
415pub fn check_physical_action(scope: &Value, action: &PhysicalAction) -> CheckResult {
419 let empty = Map::new();
420 let scope = scope.as_object().unwrap_or(&empty);
421 let mut reasons = Vec::new();
422
423 if let Some(force) = action.force_n {
424 if let Some(cap) = scope_num(scope, "maxForceN") {
425 if force > cap {
426 reasons.push(format!("force_exceeded: {force}N > {cap}N"));
427 }
428 }
429 }
430
431 if let Some(speed) = action.speed_mps {
432 let mut cap = scope_num(scope, "maxSpeedMps");
433 if action.near_humans {
434 if let Some(nh) = scope_num(scope, "maxSpeedNearHumansMps") {
435 cap = Some(nh);
436 }
437 }
438 if let Some(c) = cap {
439 if speed > c {
440 let label = if action.near_humans {
441 "near_humans "
442 } else {
443 ""
444 };
445 reasons.push(format!("{label}speed_exceeded: {speed} m/s > {c} m/s"));
446 }
447 }
448 }
449
450 if let Some(zone) = &action.zone {
451 if let Some(zones) = scope.get("allowedZones").and_then(|v| v.as_array()) {
452 if !zones.iter().any(|z| z.as_str() == Some(zone.as_str())) {
453 reasons.push(format!("zone_not_allowed: {zone}"));
454 }
455 }
456 }
457
458 if let Some(time_hm) = &action.time_hm {
459 if let Some(windows) = scope.get("shiftWindows").and_then(|v| v.as_array()) {
460 if !windows.is_empty() && !windows.iter().any(|w| in_window(time_hm, w)) {
461 reasons.push(format!("outside_shift_window: {time_hm}"));
462 }
463 }
464 }
465
466 CheckResult {
467 ok: reasons.is_empty(),
468 reasons,
469 }
470}
471
472pub fn attenuates(parent: &Value, child: &Value) -> bool {
475 let empty = Map::new();
476 let p = parent.as_object().unwrap_or(&empty);
477 let c = child.as_object().unwrap_or(&empty);
478
479 for key in ["maxForceN", "maxSpeedMps", "maxSpeedNearHumansMps"] {
480 if let Some(pv) = scope_num(p, key) {
481 match scope_num(c, key) {
482 Some(cv) if cv <= pv => {}
483 _ => return false,
484 }
485 }
486 }
487
488 if let Some(pz) = p.get("allowedZones").and_then(|v| v.as_array()) {
489 let pset: Vec<&str> = pz.iter().filter_map(|z| z.as_str()).collect();
490 let cz: Vec<&str> = c
491 .get("allowedZones")
492 .and_then(|v| v.as_array())
493 .map(|a| a.iter().filter_map(|z| z.as_str()).collect())
494 .unwrap_or_default();
495 if cz.is_empty() || !cz.iter().all(|z| pset.contains(z)) {
496 return false;
497 }
498 }
499
500 if let Some(pw) = p.get("shiftWindows").and_then(|v| v.as_array()) {
501 let empty_arr = Vec::new();
502 let cw = c
503 .get("shiftWindows")
504 .and_then(|v| v.as_array())
505 .unwrap_or(&empty_arr);
506 for cwin in cw {
507 let (cs, ce) = window_bounds(cwin);
508 let fits = pw.iter().any(|pwin| {
509 let (ps, pe) = window_bounds(pwin);
510 ps.as_str() <= cs.as_str() && ce.as_str() <= pe.as_str()
511 });
512 if !fits {
513 return false;
514 }
515 }
516 }
517
518 true
519}
520
521pub const HELLO: &str = "handshake_hello";
526pub const ACCEPT: &str = "handshake_accept";
527pub const CONFIRM: &str = "handshake_confirm";
528
529#[derive(Debug, Clone, Default)]
532pub struct TrustPolicy {
533 pub trusted_domains: HashSet<String>,
534 pub accept_unknown: bool,
535}
536
537impl TrustPolicy {
538 pub fn new(domains: impl IntoIterator<Item = String>, accept_unknown: bool) -> Self {
539 Self {
540 trusted_domains: domains.into_iter().collect(),
541 accept_unknown,
542 }
543 }
544
545 pub fn is_trusted(&self, did: &str) -> bool {
546 if self.accept_unknown {
547 return true;
548 }
549 match did_web_domain(did) {
550 Some(d) => self.trusted_domains.contains(d),
551 None => false,
552 }
553 }
554}
555
556#[derive(Debug, Clone)]
558pub struct BoundedSession {
559 pub session_id: String,
560 pub initiator: String,
561 pub responder: String,
562 pub scope: Vec<String>,
563 pub nonce: String,
564 pub valid_until: Option<String>,
565}
566
567fn did_web_domain(did: &str) -> Option<&str> {
568 let rest = did.strip_prefix("did:web:")?;
569 let domain = rest.split(':').next().unwrap_or("");
570 if domain.is_empty() {
571 None
572 } else {
573 Some(domain)
574 }
575}
576
577#[derive(Debug, Clone, Default)]
580pub struct BuildHello {
581 pub from_did: String,
582 pub proposed_scope: Vec<String>,
583 pub nonce: String,
584 pub peer_did: Option<String>,
585 pub issued_at: String,
586}
587
588pub fn build_hello(signer_seed: &[u8], params: &BuildHello) -> Result<Value> {
590 let mut hello = Map::new();
591 hello.insert("type".into(), json!(HELLO));
592 hello.insert("from".into(), json!(params.from_did));
593 hello.insert(
594 "to".into(),
595 match ¶ms.peer_did {
596 Some(p) => json!(p),
597 None => Value::Null,
598 },
599 );
600 hello.insert("nonce".into(), json!(params.nonce));
601 hello.insert("proposedScope".into(), json!(params.proposed_scope));
602 hello.insert("issuedAt".into(), json!(params.issued_at));
603 let opts = BuildProofOptions::new(format!("{}#key-1", params.from_did), ¶ms.issued_at);
604 data_integrity::sign(&Value::Object(hello), signer_seed, &opts)
605}
606
607#[derive(Debug, Clone, Default)]
609pub struct BuildAccept {
610 pub from_did: String,
611 pub offered_scope: Vec<String>,
612 pub session_id: String,
613 pub valid_until: String,
614 pub created: String,
615}
616
617pub fn build_accept(
620 signer_seed: &[u8],
621 hello: &Value,
622 hello_public_key: &[u8],
623 policy: &TrustPolicy,
624 params: &BuildAccept,
625) -> Result<Value> {
626 if hello.get("type").and_then(|v| v.as_str()) != Some(HELLO) {
627 return Err(CoreError::Json("not a HELLO message".into()));
628 }
629 if !data_integrity::verify_proof(hello, hello_public_key)? {
630 return Err(CoreError::Json("HELLO signature invalid".into()));
631 }
632 let initiator = hello.get("from").and_then(|v| v.as_str()).unwrap_or("");
633 if !policy.is_trusted(initiator) {
634 return Err(CoreError::Json(format!(
635 "peer {initiator} is not in this trust domain's policy"
636 )));
637 }
638
639 let offered: HashSet<&str> = params.offered_scope.iter().map(|s| s.as_str()).collect();
640 let empty = Vec::new();
641 let proposed = hello
642 .get("proposedScope")
643 .and_then(|v| v.as_array())
644 .unwrap_or(&empty);
645 let mut seen: HashSet<String> = HashSet::new();
646 let mut bounded: Vec<String> = Vec::new();
647 for item in proposed {
648 if let Some(s) = item.as_str() {
649 if offered.contains(s) && seen.insert(s.to_string()) {
650 bounded.push(s.to_string());
651 }
652 }
653 }
654 bounded.sort();
655
656 let mut accept = Map::new();
657 accept.insert("type".into(), json!(ACCEPT));
658 accept.insert("from".into(), json!(params.from_did));
659 accept.insert("to".into(), json!(initiator));
660 accept.insert("sessionId".into(), json!(params.session_id));
661 accept.insert(
662 "nonce".into(),
663 hello.get("nonce").cloned().unwrap_or(Value::Null),
664 );
665 accept.insert("boundedScope".into(), json!(bounded));
666 accept.insert("validUntil".into(), json!(params.valid_until));
667 let opts = BuildProofOptions::new(format!("{}#key-1", params.from_did), ¶ms.created);
668 data_integrity::sign(&Value::Object(accept), signer_seed, &opts)
669}
670
671pub fn verify_accept(
674 accept: &Value,
675 accept_public_key: &[u8],
676 expected_nonce: &str,
677 policy: Option<&TrustPolicy>,
678) -> Result<Option<BoundedSession>> {
679 if accept.get("type").and_then(|v| v.as_str()) != Some(ACCEPT) {
680 return Ok(None);
681 }
682 if !data_integrity::verify_proof(accept, accept_public_key)? {
683 return Ok(None);
684 }
685 if accept.get("nonce").and_then(|v| v.as_str()) != Some(expected_nonce) {
686 return Ok(None);
687 }
688 let responder = accept.get("from").and_then(|v| v.as_str()).unwrap_or("");
689 if let Some(p) = policy {
690 if !p.is_trusted(responder) {
691 return Ok(None);
692 }
693 }
694 let scope = accept
695 .get("boundedScope")
696 .and_then(|v| v.as_array())
697 .map(|a| {
698 a.iter()
699 .filter_map(|s| s.as_str().map(String::from))
700 .collect()
701 })
702 .unwrap_or_default();
703 Ok(Some(BoundedSession {
704 session_id: accept
705 .get("sessionId")
706 .and_then(|v| v.as_str())
707 .unwrap_or("")
708 .to_string(),
709 initiator: accept
710 .get("to")
711 .and_then(|v| v.as_str())
712 .unwrap_or("")
713 .to_string(),
714 responder: responder.to_string(),
715 scope,
716 nonce: expected_nonce.to_string(),
717 valid_until: accept
718 .get("validUntil")
719 .and_then(|v| v.as_str())
720 .map(String::from),
721 }))
722}
723
724pub fn build_confirm(
726 signer_seed: &[u8],
727 from_did: &str,
728 session: &BoundedSession,
729 created: &str,
730) -> Result<Value> {
731 let mut confirm = Map::new();
732 confirm.insert("type".into(), json!(CONFIRM));
733 confirm.insert("from".into(), json!(from_did));
734 confirm.insert("to".into(), json!(session.responder));
735 confirm.insert("sessionId".into(), json!(session.session_id));
736 confirm.insert("nonce".into(), json!(session.nonce));
737 confirm.insert("acceptedScope".into(), json!(session.scope));
738 let opts = BuildProofOptions::new(format!("{from_did}#key-1"), created);
739 data_integrity::sign(&Value::Object(confirm), signer_seed, &opts)
740}
741
742pub fn verify_confirm(
745 confirm: &Value,
746 confirm_public_key: &[u8],
747 session_id: &str,
748 expected_nonce: &str,
749) -> Result<bool> {
750 if confirm.get("type").and_then(|v| v.as_str()) != Some(CONFIRM) {
751 return Ok(false);
752 }
753 if !data_integrity::verify_proof(confirm, confirm_public_key)? {
754 return Ok(false);
755 }
756 let sid = confirm
757 .get("sessionId")
758 .and_then(|v| v.as_str())
759 .unwrap_or("");
760 let nonce = confirm.get("nonce").and_then(|v| v.as_str()).unwrap_or("");
761 Ok(sid == session_id && nonce == expected_nonce)
762}
763
764pub const BLACKBOX_VERSION: &str = "1.0";
769pub const KILLSWITCH_TYPE: &str = "KillSwitchCredential";
770pub const EMERGENCY_STOP: &str = "emergency_stop";
771
772pub fn genesis_prev_hash() -> String {
774 mb64(&[0u8; 32])
775}
776
777fn entry_hash(body: &Map<String, Value>) -> Result<String> {
778 let mut clean = body.clone();
779 clean.remove("entryHash");
780 let canonical = jcs::canonicalize(&Value::Object(clean));
781 Ok(mb64(&Sha256::digest(canonical)))
782}
783
784pub fn blackbox_append_entry(
789 key: &[u8],
790 seq: u64,
791 event: &str,
792 payload: &Value,
793 timestamp: &str,
794 prev_hash: &str,
795) -> Result<Value> {
796 if key.len() != 32 {
797 return Err(CoreError::Crypto(
798 "black box key must be 32 bytes (AES-256)".into(),
799 ));
800 }
801 let mut nonce = [0u8; 12];
802 getrandom::getrandom(&mut nonce).map_err(|e| CoreError::Crypto(format!("rng: {e}")))?;
803 let plaintext = jcs::canonicalize(payload);
804 let cipher =
805 Aes256Gcm::new_from_slice(key).map_err(|e| CoreError::Crypto(format!("aes key: {e}")))?;
806 let ct = cipher
807 .encrypt(Nonce::from_slice(&nonce), plaintext.as_ref())
808 .map_err(|e| CoreError::Crypto(format!("encrypt: {e}")))?;
809 let mut blob = Vec::with_capacity(nonce.len() + ct.len());
810 blob.extend_from_slice(&nonce);
811 blob.extend_from_slice(&ct);
812
813 let mut body = Map::new();
814 body.insert("version".into(), json!(BLACKBOX_VERSION));
815 body.insert("seq".into(), json!(seq));
816 body.insert("timestamp".into(), json!(timestamp));
817 body.insert("event".into(), json!(event));
818 body.insert("ciphertext".into(), json!(mb64(&blob)));
819 body.insert("prevHash".into(), json!(prev_hash));
820 let h = entry_hash(&body)?;
821 body.insert("entryHash".into(), json!(h));
822 Ok(Value::Object(body))
823}
824
825pub struct BlackBoxLog {
829 key: Vec<u8>,
830 genesis: String,
831 entries: Vec<Value>,
832 head: String,
833}
834
835impl BlackBoxLog {
836 pub fn new(key: &[u8], genesis_prev_hash_override: Option<&str>) -> Result<Self> {
838 if key.len() != 32 {
839 return Err(CoreError::Crypto(
840 "black box key must be 32 bytes (AES-256)".into(),
841 ));
842 }
843 let genesis = genesis_prev_hash_override
844 .map(String::from)
845 .unwrap_or_else(genesis_prev_hash);
846 Ok(Self {
847 key: key.to_vec(),
848 head: genesis.clone(),
849 genesis,
850 entries: Vec::new(),
851 })
852 }
853
854 pub fn append(&mut self, event: &str, payload: &Value, timestamp: &str) -> Result<Value> {
856 let entry = blackbox_append_entry(
857 &self.key,
858 self.entries.len() as u64,
859 event,
860 payload,
861 timestamp,
862 &self.head,
863 )?;
864 self.head = entry
865 .get("entryHash")
866 .and_then(|v| v.as_str())
867 .unwrap_or("")
868 .to_string();
869 self.entries.push(entry.clone());
870 Ok(entry)
871 }
872
873 pub fn head(&self) -> &str {
874 &self.head
875 }
876
877 pub fn genesis(&self) -> &str {
878 &self.genesis
879 }
880
881 pub fn entries(&self) -> &[Value] {
882 &self.entries
883 }
884
885 pub fn open(&self, entry: &Value) -> Result<Value> {
886 open_entry(entry, &self.key)
887 }
888}
889
890pub fn open_entry(entry: &Value, key: &[u8]) -> Result<Value> {
892 let ct_mb = entry
893 .get("ciphertext")
894 .and_then(|v| v.as_str())
895 .ok_or_else(|| CoreError::Json("entry has no ciphertext".into()))?;
896 let blob = unmb64(ct_mb)?;
897 if blob.len() < 12 + 16 {
898 return Err(CoreError::Crypto("ciphertext too short".into()));
899 }
900 let cipher =
901 Aes256Gcm::new_from_slice(key).map_err(|e| CoreError::Crypto(format!("aes key: {e}")))?;
902 let (nonce, rest) = blob.split_at(12);
903 let pt = cipher
904 .decrypt(Nonce::from_slice(nonce), rest)
905 .map_err(|_| CoreError::Crypto("decryption failed".into()))?;
906 serde_json::from_slice(&pt).map_err(|e| CoreError::Json(format!("payload decode: {e}")))
907}
908
909#[derive(Debug, Clone)]
911pub struct ChainResult {
912 pub ok: bool,
913 pub reason: Option<String>,
914}
915
916pub fn verify_blackbox_chain(
919 entries: &[Value],
920 genesis_prev_hash_override: Option<&str>,
921) -> ChainResult {
922 let mut prev = genesis_prev_hash_override
923 .map(String::from)
924 .unwrap_or_else(genesis_prev_hash);
925 for (i, entry) in entries.iter().enumerate() {
926 if entry.get("seq").and_then(|v| v.as_u64()) != Some(i as u64) {
927 return ChainResult {
928 ok: false,
929 reason: Some(format!("entry {i} seq mismatch")),
930 };
931 }
932 if entry.get("prevHash").and_then(|v| v.as_str()).unwrap_or("") != prev {
933 return ChainResult {
934 ok: false,
935 reason: Some(format!("entry {i} prevHash does not link")),
936 };
937 }
938 let obj = match entry.as_object() {
939 Some(o) => o,
940 None => {
941 return ChainResult {
942 ok: false,
943 reason: Some(format!("entry {i} is not an object")),
944 }
945 }
946 };
947 let want = match entry_hash(obj) {
948 Ok(w) => w,
949 Err(_) => {
950 return ChainResult {
951 ok: false,
952 reason: Some(format!("entry {i} hash error")),
953 }
954 }
955 };
956 let eh = entry
957 .get("entryHash")
958 .and_then(|v| v.as_str())
959 .unwrap_or("");
960 if eh != want {
961 return ChainResult {
962 ok: false,
963 reason: Some(format!("entry {i} entryHash mismatch (tampered)")),
964 };
965 }
966 prev = eh.to_string();
967 }
968 ChainResult {
969 ok: true,
970 reason: None,
971 }
972}
973
974#[derive(Debug, Clone, Default)]
976pub struct BuildKillswitch {
977 pub issuer_did: String,
978 pub target: String,
979 pub reason: String,
980 pub command: Option<String>,
981 pub scope: Option<Vec<String>>,
982 pub valid_from: String,
983 pub valid_until: Option<String>,
984}
985
986pub fn build_killswitch_credential(
988 authority_seed: &[u8],
989 params: &BuildKillswitch,
990) -> Result<Value> {
991 let command = params
992 .command
993 .clone()
994 .unwrap_or_else(|| EMERGENCY_STOP.to_string());
995 let mut subject = Map::new();
996 subject.insert("id".into(), json!(params.target));
997 subject.insert("command".into(), json!(command));
998 subject.insert("reason".into(), json!(params.reason));
999 subject.insert("issuedBy".into(), json!(params.issuer_did));
1000 if let Some(scope) = ¶ms.scope {
1001 subject.insert("scope".into(), json!(scope));
1002 }
1003
1004 let mut cred = Map::new();
1005 cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
1006 cred.insert(
1007 "type".into(),
1008 json!(["VerifiableCredential", KILLSWITCH_TYPE]),
1009 );
1010 cred.insert("issuer".into(), json!(params.issuer_did));
1011 cred.insert("validFrom".into(), json!(params.valid_from));
1012 if let Some(vu) = ¶ms.valid_until {
1013 cred.insert("validUntil".into(), json!(vu));
1014 }
1015 cred.insert("credentialSubject".into(), Value::Object(subject));
1016
1017 let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), ¶ms.valid_from);
1018 data_integrity::sign(&Value::Object(cred), authority_seed, &opts)
1019}
1020
1021pub fn verify_killswitch_credential(
1024 credential: &Value,
1025 public_key: &[u8],
1026 trusted_authorities: Option<&HashSet<String>>,
1027) -> Result<Option<Value>> {
1028 if !has_type(credential.get("type"), KILLSWITCH_TYPE) {
1029 return Ok(None);
1030 }
1031 if !data_integrity::verify_proof(credential, public_key)? {
1032 return Ok(None);
1033 }
1034 if let Some(trusted) = trusted_authorities {
1035 let issuer = credential
1036 .get("issuer")
1037 .and_then(|v| v.as_str())
1038 .unwrap_or("");
1039 if !trusted.contains(issuer) {
1040 return Ok(None);
1041 }
1042 }
1043 Ok(credential.get("credentialSubject").cloned())
1044}
1045
1046pub const ROBOT_PASSPORT_TYPE: &str = "RobotPassport";
1051pub const PASSPORT_URI_SCHEME: &str = "vouch-passport:";
1052pub const STATUS_ACTIVE: &str = "active";
1053pub const STATUS_SUSPENDED: &str = "suspended";
1054pub const STATUS_DECOMMISSIONED: &str = "decommissioned";
1055
1056#[derive(Debug, Clone, Default)]
1059pub struct BuildPassport {
1060 pub issuer_did: String,
1061 pub robot_did: String,
1062 pub make: String,
1063 pub model: String,
1064 pub owner: String,
1065 pub authorized_actions: Vec<String>,
1066 pub certification: Option<String>,
1067 pub status: Option<String>,
1068 pub valid_from: String,
1069 pub valid_until: Option<String>,
1070}
1071
1072pub fn build_passport(signer_seed: &[u8], params: &BuildPassport) -> Result<Value> {
1074 let status = params
1075 .status
1076 .clone()
1077 .unwrap_or_else(|| STATUS_ACTIVE.to_string());
1078 let mut subject = Map::new();
1079 subject.insert("id".into(), json!(params.robot_did));
1080 subject.insert("make".into(), json!(params.make));
1081 subject.insert("model".into(), json!(params.model));
1082 subject.insert("owner".into(), json!(params.owner));
1083 subject.insert("authorizedActions".into(), json!(params.authorized_actions));
1084 subject.insert("status".into(), json!(status));
1085 if let Some(c) = ¶ms.certification {
1086 subject.insert("certification".into(), json!(c));
1087 }
1088
1089 let mut cred = Map::new();
1090 cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
1091 cred.insert(
1092 "type".into(),
1093 json!(["VerifiableCredential", ROBOT_PASSPORT_TYPE]),
1094 );
1095 cred.insert("issuer".into(), json!(params.issuer_did));
1096 cred.insert("validFrom".into(), json!(params.valid_from));
1097 if let Some(vu) = ¶ms.valid_until {
1098 cred.insert("validUntil".into(), json!(vu));
1099 }
1100 cred.insert("credentialSubject".into(), Value::Object(subject));
1101
1102 let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), ¶ms.valid_from);
1103 data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
1104}
1105
1106pub fn encode_passport(passport: &Value) -> String {
1108 format!(
1109 "{}{}",
1110 PASSPORT_URI_SCHEME,
1111 mb64(&jcs::canonicalize(passport))
1112 )
1113}
1114
1115pub fn decode_passport(uri: &str) -> Result<Value> {
1117 let body = uri
1118 .strip_prefix(PASSPORT_URI_SCHEME)
1119 .ok_or_else(|| CoreError::Json(format!("not a {PASSPORT_URI_SCHEME} URI")))?;
1120 let raw = unmb64(body)?;
1121 serde_json::from_slice(&raw).map_err(|e| CoreError::Json(format!("passport decode: {e}")))
1122}
1123
1124pub fn verify_passport(
1128 passport: &Value,
1129 public_key: &[u8],
1130 now_iso: &str,
1131) -> Result<Option<Value>> {
1132 if !has_type(passport.get("type"), ROBOT_PASSPORT_TYPE) {
1133 return Ok(None);
1134 }
1135 if !data_integrity::verify_proof(passport, public_key)? {
1136 return Ok(None);
1137 }
1138 if let Some(vu) = passport.get("validUntil").and_then(|v| v.as_str()) {
1139 if let (Ok(vu_e), Ok(now_e)) = (
1140 crate::time::iso_to_epoch_seconds(vu),
1141 crate::time::iso_to_epoch_seconds(now_iso),
1142 ) {
1143 if now_e > vu_e {
1144 return Ok(None);
1145 }
1146 }
1147 }
1148 Ok(passport.get("credentialSubject").cloned())
1149}
1150
1151pub fn verify_passport_uri(uri: &str, public_key: &[u8], now_iso: &str) -> Result<Option<Value>> {
1153 match decode_passport(uri) {
1154 Ok(p) => verify_passport(&p, public_key, now_iso),
1155 Err(_) => Ok(None),
1156 }
1157}
1158
1159pub const ROBOT_HEARTBEAT_TYPE: &str = "RobotHeartbeatCredential";
1164
1165pub const DEFAULT_GRACE_INTERVALS: i64 = 2;
1167
1168#[derive(Debug, Clone, Default)]
1171pub struct MotionSample {
1172 pub force_n: Option<f64>,
1173 pub speed_mps: Option<f64>,
1174 pub near_humans: bool,
1175 pub zone: Option<String>,
1176 pub time_hm: Option<String>,
1177}
1178
1179#[derive(Debug, Clone, Default)]
1188pub struct MotionCollector {
1189 scope: Option<Value>,
1190 samples: u64,
1191 max_force: f64,
1192 max_speed: f64,
1193 max_speed_near: f64,
1194 zone_breaches: u64,
1195 breaches: u64,
1196}
1197
1198impl MotionCollector {
1199 pub fn new(scope: Option<Value>) -> Self {
1202 Self {
1203 scope,
1204 ..Default::default()
1205 }
1206 }
1207
1208 pub fn record(&mut self, sample: &MotionSample) -> Result<()> {
1211 if let Some(f) = sample.force_n {
1212 if f < 0.0 {
1213 return Err(CoreError::Json(format!(
1214 "force_n must be non-negative, got {f}"
1215 )));
1216 }
1217 }
1218 if let Some(s) = sample.speed_mps {
1219 if s < 0.0 {
1220 return Err(CoreError::Json(format!(
1221 "speed_mps must be non-negative, got {s}"
1222 )));
1223 }
1224 }
1225
1226 self.samples += 1;
1227 if let Some(f) = sample.force_n {
1228 self.max_force = self.max_force.max(f);
1229 }
1230 if let Some(s) = sample.speed_mps {
1231 self.max_speed = self.max_speed.max(s);
1232 if sample.near_humans {
1233 self.max_speed_near = self.max_speed_near.max(s);
1234 }
1235 }
1236
1237 if let Some(scope) = &self.scope {
1238 let action = PhysicalAction {
1239 force_n: sample.force_n,
1240 speed_mps: sample.speed_mps,
1241 near_humans: sample.near_humans,
1242 zone: sample.zone.clone(),
1243 time_hm: sample.time_hm.clone(),
1244 };
1245 let result = check_physical_action(scope, &action);
1246 if !result.ok {
1247 self.breaches += 1;
1248 if result
1249 .reasons
1250 .iter()
1251 .any(|r| r.starts_with("zone_not_allowed"))
1252 {
1253 self.zone_breaches += 1;
1254 }
1255 }
1256 }
1257 Ok(())
1258 }
1259
1260 pub fn digest(&self) -> Value {
1262 json!({
1263 "samples": self.samples,
1264 "maxForceN": self.max_force,
1265 "maxSpeedMps": self.max_speed,
1266 "maxSpeedNearHumansMps": self.max_speed_near,
1267 "zoneBreaches": self.zone_breaches,
1268 "breachCount": self.breaches,
1269 "withinEnvelope": self.breaches == 0,
1270 })
1271 }
1272
1273 pub fn reset(&mut self) {
1275 self.samples = 0;
1276 self.max_force = 0.0;
1277 self.max_speed = 0.0;
1278 self.max_speed_near = 0.0;
1279 self.zone_breaches = 0;
1280 self.breaches = 0;
1281 }
1282}
1283
1284fn digest_non_negative_int(digest: &Map<String, Value>, name: &str) -> Result<()> {
1285 match digest.get(name) {
1286 Some(v) if v.is_u64() => Ok(()),
1287 Some(Value::Number(n)) if n.as_i64().map(|i| i >= 0).unwrap_or(false) => Ok(()),
1288 Some(_) => Err(CoreError::Json(format!(
1289 "motionDigest.{name} must be a non-negative integer"
1290 ))),
1291 None => Err(CoreError::Json(format!("motionDigest.{name} is required"))),
1292 }
1293}
1294
1295pub fn validate_motion_digest(digest: &Value) -> Result<()> {
1298 let obj = digest
1299 .as_object()
1300 .ok_or_else(|| CoreError::Json("motionDigest must be an object".into()))?;
1301
1302 for name in ["samples", "zoneBreaches", "breachCount"] {
1303 digest_non_negative_int(obj, name)?;
1304 }
1305 for name in ["maxForceN", "maxSpeedMps", "maxSpeedNearHumansMps"] {
1306 match obj.get(name) {
1307 Some(Value::Bool(_)) | None => {
1308 return Err(CoreError::Json(format!("motionDigest.{name} is required")))
1309 }
1310 Some(v) => {
1311 let n = v.as_f64().ok_or_else(|| {
1312 CoreError::Json(format!("motionDigest.{name} must be a number"))
1313 })?;
1314 if n < 0.0 {
1315 return Err(CoreError::Json(format!(
1316 "motionDigest.{name} must be non-negative"
1317 )));
1318 }
1319 }
1320 }
1321 }
1322 match obj.get("withinEnvelope") {
1323 Some(Value::Bool(_)) => Ok(()),
1324 Some(_) => Err(CoreError::Json(
1325 "motionDigest.withinEnvelope must be a boolean".into(),
1326 )),
1327 None => Err(CoreError::Json(
1328 "motionDigest.withinEnvelope is required".into(),
1329 )),
1330 }
1331}
1332
1333#[derive(Debug, Clone)]
1337pub struct BuildRobotHeartbeat {
1338 pub robot_did: String,
1339 pub session_id: String,
1340 pub interval_index: i64,
1341 pub interval_seconds: i64,
1342 pub motion_digest: Value,
1343 pub valid_from: String,
1344}
1345
1346pub fn build_robot_heartbeat(robot_seed: &[u8], params: &BuildRobotHeartbeat) -> Result<Value> {
1348 if params.interval_index < 0 {
1349 return Err(CoreError::Json(
1350 "interval_index must be non-negative".into(),
1351 ));
1352 }
1353 if params.interval_seconds <= 0 {
1354 return Err(CoreError::Json("interval_seconds must be positive".into()));
1355 }
1356 validate_motion_digest(¶ms.motion_digest)?;
1357
1358 let mut subject = Map::new();
1359 subject.insert("id".into(), json!(params.robot_did));
1360 subject.insert("sessionId".into(), json!(params.session_id));
1361 subject.insert("intervalIndex".into(), json!(params.interval_index));
1362 subject.insert("intervalSeconds".into(), json!(params.interval_seconds));
1363 subject.insert("motionDigest".into(), params.motion_digest.clone());
1364
1365 let mut cred = Map::new();
1366 cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
1367 cred.insert(
1368 "type".into(),
1369 json!(["VerifiableCredential", ROBOT_HEARTBEAT_TYPE]),
1370 );
1371 cred.insert("issuer".into(), json!(params.robot_did));
1372 cred.insert("validFrom".into(), json!(params.valid_from));
1373 cred.insert("credentialSubject".into(), Value::Object(subject));
1374
1375 let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), ¶ms.valid_from);
1376 data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
1377}
1378
1379pub fn verify_robot_heartbeat(
1384 credential: &Value,
1385 robot_public_key: &[u8],
1386) -> Result<Option<Value>> {
1387 if !has_type(credential.get("type"), ROBOT_HEARTBEAT_TYPE) {
1388 return Ok(None);
1389 }
1390 if !data_integrity::verify_proof(credential, robot_public_key)? {
1391 return Ok(None);
1392 }
1393 let subject = match credential.get("credentialSubject") {
1394 Some(s) if s.is_object() => s,
1395 _ => return Ok(None),
1396 };
1397 let digest = subject.get("motionDigest").cloned().unwrap_or(Value::Null);
1398 if validate_motion_digest(&digest).is_err() {
1399 return Ok(None);
1400 }
1401 Ok(Some(subject.clone()))
1402}
1403
1404pub fn is_live(
1410 credential: &Value,
1411 now_iso: &str,
1412 interval_seconds: Option<i64>,
1413 grace_intervals: i64,
1414) -> Result<bool> {
1415 let subject = credential
1416 .get("credentialSubject")
1417 .and_then(|s| s.as_object());
1418 let digest = subject
1419 .and_then(|s| s.get("motionDigest"))
1420 .and_then(|d| d.as_object());
1421 let within = digest
1422 .and_then(|d| d.get("withinEnvelope"))
1423 .and_then(|v| v.as_bool())
1424 .unwrap_or(false);
1425 if !within {
1426 return Ok(false);
1427 }
1428
1429 let cadence = match interval_seconds {
1430 Some(c) => c,
1431 None => subject
1432 .and_then(|s| s.get("intervalSeconds"))
1433 .and_then(|v| v.as_i64())
1434 .unwrap_or(0),
1435 };
1436 if cadence <= 0 {
1437 return Ok(false);
1438 }
1439 if grace_intervals < 1 {
1440 return Err(CoreError::Json("grace_intervals must be at least 1".into()));
1441 }
1442
1443 let raw = match credential.get("validFrom").and_then(|v| v.as_str()) {
1444 Some(s) if !s.is_empty() => s,
1445 _ => return Ok(false),
1446 };
1447 let issued = match crate::time::iso_to_epoch_seconds(raw) {
1448 Ok(t) => t,
1449 Err(_) => return Ok(false),
1450 };
1451 let moment = match crate::time::iso_to_epoch_seconds(now_iso) {
1452 Ok(t) => t,
1453 Err(_) => return Ok(false),
1454 };
1455 let deadline = issued + cadence * grace_intervals;
1456 if moment + cadence < issued {
1458 return Ok(false);
1459 }
1460 Ok(moment <= deadline)
1461}
1462
1463pub use crate::status_list::{BITSTRING_STATUS_LIST_ENTRY_TYPE, STATUS_PURPOSE_REVOCATION};
1468
1469pub fn build_status_list_entry(
1474 status_list_credential: &str,
1475 status_list_index: i64,
1476 status_purpose: &str,
1477 entry_id: Option<&str>,
1478) -> Result<Value> {
1479 if !matches!(status_purpose, "revocation" | "suspension" | "message") {
1480 return Err(CoreError::Json(format!(
1481 "status_purpose must be one of revocation, suspension, message, got {status_purpose:?}"
1482 )));
1483 }
1484 if status_list_index < 0 {
1485 return Err(CoreError::Json(
1486 "status_list_index must be non-negative".into(),
1487 ));
1488 }
1489 if status_list_credential.is_empty() {
1490 return Err(CoreError::Json(
1491 "status_list_credential URL is required".into(),
1492 ));
1493 }
1494 let id = entry_id
1495 .map(String::from)
1496 .unwrap_or_else(|| format!("{status_list_credential}#{status_list_index}"));
1497 Ok(json!({
1498 "id": id,
1499 "type": BITSTRING_STATUS_LIST_ENTRY_TYPE,
1500 "statusPurpose": status_purpose,
1501 "statusListIndex": status_list_index.to_string(),
1502 "statusListCredential": status_list_credential,
1503 }))
1504}
1505
1506#[derive(Debug, Clone)]
1508pub struct AttachCredentialStatus {
1509 pub status_list_credential: String,
1510 pub status_list_index: i64,
1511 pub status_purpose: String,
1512 pub entry_id: Option<String>,
1513 pub created: String,
1515}
1516
1517pub fn attach_credential_status(
1523 credential: &Value,
1524 signer_seed: &[u8],
1525 params: &AttachCredentialStatus,
1526) -> Result<Value> {
1527 let entry = build_status_list_entry(
1528 ¶ms.status_list_credential,
1529 params.status_list_index,
1530 ¶ms.status_purpose,
1531 params.entry_id.as_deref(),
1532 )?;
1533
1534 let mut obj = credential
1535 .as_object()
1536 .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
1537 .clone();
1538
1539 match obj.get("credentialStatus").cloned() {
1540 None => {
1541 obj.insert("credentialStatus".into(), entry);
1542 }
1543 Some(Value::Array(mut existing)) => {
1544 existing.push(entry);
1545 obj.insert("credentialStatus".into(), Value::Array(existing));
1546 }
1547 Some(existing) => {
1548 obj.insert("credentialStatus".into(), json!([existing, entry]));
1549 }
1550 }
1551
1552 obj.remove("proof");
1554 let issuer = obj.get("issuer").and_then(|v| v.as_str()).unwrap_or("");
1555 let opts = BuildProofOptions::new(format!("{issuer}#key-1"), ¶ms.created);
1556 data_integrity::sign(&Value::Object(obj), signer_seed, &opts)
1557}
1558
1559fn status_entries(credential: &Value) -> Result<Vec<Value>> {
1560 match credential.get("credentialStatus") {
1561 None => Ok(Vec::new()),
1562 Some(Value::Array(a)) => Ok(a.iter().filter(|e| e.is_object()).cloned().collect()),
1563 Some(v) if v.is_object() => Ok(vec![v.clone()]),
1564 Some(_) => Err(CoreError::Json(
1565 "credentialStatus must be an object or a list of objects".into(),
1566 )),
1567 }
1568}
1569
1570pub fn check_credential_status(
1575 credential: &Value,
1576 status_list_credential: &Value,
1577 status_purpose: &str,
1578) -> Result<bool> {
1579 let referenced_id = status_list_credential.get("id").and_then(|v| v.as_str());
1580 for entry in status_entries(credential)? {
1581 if entry.get("statusPurpose").and_then(|v| v.as_str()) != Some(status_purpose) {
1582 continue;
1583 }
1584 if entry.get("statusListCredential").and_then(|v| v.as_str()) != referenced_id {
1585 continue;
1586 }
1587 return crate::status_list::verify_status(&entry, status_list_credential);
1588 }
1589 Ok(false)
1590}
1591
1592pub const SAFETY_RECORD_TYPE: &str = "RobotSafetyRecordCredential";
1597pub const SAFETY_LOG_VERSION: &str = "1.0";
1598
1599pub const EVENT_TYPES: [&str; 6] = [
1602 "incident",
1603 "near_miss",
1604 "manual_override",
1605 "kill_switch",
1606 "envelope_breach",
1607 "maintenance",
1608];
1609
1610pub const SEVERITIES: [&str; 5] = ["info", "low", "medium", "high", "critical"];
1612
1613pub struct SafetyEventLog {
1618 genesis: String,
1619 entries: Vec<Value>,
1620 head: String,
1621}
1622
1623impl SafetyEventLog {
1624 pub fn new(genesis_prev_hash_override: Option<&str>) -> Self {
1626 let genesis = genesis_prev_hash_override
1627 .map(String::from)
1628 .unwrap_or_else(genesis_prev_hash);
1629 Self {
1630 head: genesis.clone(),
1631 genesis,
1632 entries: Vec::new(),
1633 }
1634 }
1635
1636 pub fn append(
1638 &mut self,
1639 event_type: &str,
1640 severity: &str,
1641 details: Option<&Value>,
1642 actor: Option<&str>,
1643 timestamp: &str,
1644 ) -> Result<Value> {
1645 if !EVENT_TYPES.contains(&event_type) {
1646 return Err(CoreError::Json(format!(
1647 "event_type must be one of {EVENT_TYPES:?}, got {event_type:?}"
1648 )));
1649 }
1650 if !SEVERITIES.contains(&severity) {
1651 return Err(CoreError::Json(format!(
1652 "severity must be one of {SEVERITIES:?}, got {severity:?}"
1653 )));
1654 }
1655
1656 let mut body = Map::new();
1657 body.insert("version".into(), json!(SAFETY_LOG_VERSION));
1658 body.insert("seq".into(), json!(self.entries.len() as u64));
1659 body.insert("timestamp".into(), json!(timestamp));
1660 body.insert("eventType".into(), json!(event_type));
1661 body.insert("severity".into(), json!(severity));
1662 body.insert("prevHash".into(), json!(self.head));
1663 if let Some(d) = details {
1664 body.insert("details".into(), d.clone());
1665 }
1666 if let Some(a) = actor {
1667 body.insert("actor".into(), json!(a));
1668 }
1669 let h = entry_hash(&body)?;
1670 body.insert("entryHash".into(), json!(h));
1671 self.head = h;
1672 let entry = Value::Object(body);
1673 self.entries.push(entry.clone());
1674 Ok(entry)
1675 }
1676
1677 pub fn head(&self) -> &str {
1678 &self.head
1679 }
1680
1681 pub fn genesis(&self) -> &str {
1682 &self.genesis
1683 }
1684
1685 pub fn entries(&self) -> &[Value] {
1686 &self.entries
1687 }
1688
1689 pub fn summarize(&self) -> Value {
1691 summarize_entries(&self.entries, Some(&self.head))
1692 }
1693}
1694
1695pub fn verify_safety_log(
1698 entries: &[Value],
1699 genesis_prev_hash_override: Option<&str>,
1700) -> ChainResult {
1701 verify_blackbox_chain(entries, genesis_prev_hash_override)
1702}
1703
1704pub fn summarize_entries(entries: &[Value], head: Option<&str>) -> Value {
1708 let mut sorted_types: Vec<&str> = EVENT_TYPES.to_vec();
1709 sorted_types.sort_unstable();
1710
1711 let mut event_counts = Map::new();
1712 for t in &sorted_types {
1713 event_counts.insert((*t).to_string(), json!(0));
1714 }
1715 let mut severity_counts = Map::new();
1716 for s in SEVERITIES {
1717 severity_counts.insert(s.to_string(), json!(0));
1718 }
1719
1720 for e in entries {
1721 if let Some(et) = e.get("eventType").and_then(|v| v.as_str()) {
1722 if let Some(c) = event_counts.get_mut(et).and_then(|v| v.as_u64()) {
1723 event_counts.insert(et.to_string(), json!(c + 1));
1724 }
1725 }
1726 if let Some(sv) = e.get("severity").and_then(|v| v.as_str()) {
1727 if let Some(c) = severity_counts.get_mut(sv).and_then(|v| v.as_u64()) {
1728 severity_counts.insert(sv.to_string(), json!(c + 1));
1729 }
1730 }
1731 }
1732
1733 let mut summary = Map::new();
1734 summary.insert("eventCounts".into(), Value::Object(event_counts));
1735 summary.insert("severityCounts".into(), Value::Object(severity_counts));
1736 summary.insert("totalEvents".into(), json!(entries.len() as u64));
1737 if let Some(h) = head {
1738 summary.insert("logHead".into(), json!(h));
1739 }
1740 Value::Object(summary)
1741}
1742
1743pub fn validate_safety_summary(summary: &Value) -> Result<()> {
1745 let obj = summary
1746 .as_object()
1747 .ok_or_else(|| CoreError::Json("summary must be an object".into()))?;
1748 for name in ["eventCounts", "severityCounts"] {
1749 let block = obj
1750 .get(name)
1751 .and_then(|v| v.as_object())
1752 .ok_or_else(|| CoreError::Json(format!("summary.{name} must be an object")))?;
1753 for (k, v) in block {
1754 let ok = v.is_u64() || v.as_i64().map(|i| i >= 0).unwrap_or(false);
1755 if v.is_boolean() || !ok {
1756 return Err(CoreError::Json(format!(
1757 "summary.{name}[{k:?}] must be a non-negative integer"
1758 )));
1759 }
1760 }
1761 }
1762 let total_ok = obj
1763 .get("totalEvents")
1764 .map(|v| (v.is_u64() || v.as_i64().map(|i| i >= 0).unwrap_or(false)) && !v.is_boolean())
1765 .unwrap_or(false);
1766 if !total_ok {
1767 return Err(CoreError::Json(
1768 "summary.totalEvents must be a non-negative integer".into(),
1769 ));
1770 }
1771 Ok(())
1772}
1773
1774#[derive(Debug, Clone)]
1778pub struct BuildSafetyRecord {
1779 pub issuer_did: String,
1780 pub robot_did: String,
1781 pub summary: Value,
1782 pub period_start: Option<String>,
1783 pub period_end: Option<String>,
1784 pub valid_from: String,
1785 pub valid_until: Option<String>,
1786}
1787
1788pub fn build_safety_record(signer_seed: &[u8], params: &BuildSafetyRecord) -> Result<Value> {
1791 validate_safety_summary(¶ms.summary)?;
1792
1793 let mut subject = Map::new();
1794 subject.insert("id".into(), json!(params.robot_did));
1795 if let Some(s) = params.summary.as_object() {
1796 for (k, v) in s {
1797 subject.insert(k.clone(), v.clone());
1798 }
1799 }
1800 if params.period_start.is_some() || params.period_end.is_some() {
1801 let mut period = Map::new();
1802 if let Some(start) = ¶ms.period_start {
1803 period.insert("start".into(), json!(start));
1804 }
1805 if let Some(end) = ¶ms.period_end {
1806 period.insert("end".into(), json!(end));
1807 }
1808 subject.insert("period".into(), Value::Object(period));
1809 }
1810
1811 let mut cred = Map::new();
1812 cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
1813 cred.insert(
1814 "type".into(),
1815 json!(["VerifiableCredential", SAFETY_RECORD_TYPE]),
1816 );
1817 cred.insert("issuer".into(), json!(params.issuer_did));
1818 cred.insert("validFrom".into(), json!(params.valid_from));
1819 if let Some(vu) = ¶ms.valid_until {
1820 cred.insert("validUntil".into(), json!(vu));
1821 }
1822 cred.insert("credentialSubject".into(), Value::Object(subject));
1823
1824 let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), ¶ms.valid_from);
1825 data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
1826}
1827
1828pub fn verify_safety_record(credential: &Value, public_key: &[u8]) -> Result<Option<Value>> {
1831 if !has_type(credential.get("type"), SAFETY_RECORD_TYPE) {
1832 return Ok(None);
1833 }
1834 if !data_integrity::verify_proof(credential, public_key)? {
1835 return Ok(None);
1836 }
1837 let subject = match credential.get("credentialSubject") {
1838 Some(s) if s.is_object() => s,
1839 _ => return Ok(None),
1840 };
1841 if validate_safety_summary(subject).is_err() {
1842 return Ok(None);
1843 }
1844 Ok(Some(subject.clone()))
1845}
1846
1847pub const PERCEPTION_TYPE: &str = "PerceptionProvenanceCredential";
1852pub const PERCEPTION_LOG_VERSION: &str = "1.0";
1853
1854pub const MODALITIES: [&str; 6] = ["camera", "lidar", "radar", "depth", "audio", "thermal"];
1857
1858pub fn hash_frame(frame: &[u8]) -> String {
1861 mb64(&Sha256::digest(frame))
1862}
1863
1864pub struct PerceptionLog {
1870 genesis: String,
1871 entries: Vec<Value>,
1872 head: String,
1873}
1874
1875impl PerceptionLog {
1876 pub fn new(genesis_prev_hash_override: Option<&str>) -> Self {
1878 let genesis = genesis_prev_hash_override
1879 .map(String::from)
1880 .unwrap_or_else(genesis_prev_hash);
1881 Self {
1882 head: genesis.clone(),
1883 genesis,
1884 entries: Vec::new(),
1885 }
1886 }
1887
1888 pub fn record(
1892 &mut self,
1893 sensor_id: &str,
1894 modality: &str,
1895 frame: Option<&[u8]>,
1896 frame_hash: Option<&str>,
1897 timestamp: &str,
1898 ) -> Result<Value> {
1899 if !MODALITIES.contains(&modality) {
1900 return Err(CoreError::Json(format!(
1901 "modality must be one of {MODALITIES:?}, got {modality:?}"
1902 )));
1903 }
1904 if sensor_id.is_empty() {
1905 return Err(CoreError::Json("sensor_id is required".into()));
1906 }
1907 if frame.is_some() && frame_hash.is_some() {
1908 return Err(CoreError::Json(
1909 "provide either frame or frame_hash, not both".into(),
1910 ));
1911 }
1912 let resolved = match (frame, frame_hash) {
1913 (Some(f), None) => hash_frame(f),
1914 (None, Some(h)) if !h.is_empty() => h.to_string(),
1915 _ => return Err(CoreError::Json("frame or frame_hash is required".into())),
1916 };
1917
1918 let mut body = Map::new();
1919 body.insert("version".into(), json!(PERCEPTION_LOG_VERSION));
1920 body.insert("seq".into(), json!(self.entries.len() as u64));
1921 body.insert("timestamp".into(), json!(timestamp));
1922 body.insert("sensorId".into(), json!(sensor_id));
1923 body.insert("modality".into(), json!(modality));
1924 body.insert("frameHash".into(), json!(resolved));
1925 body.insert("prevHash".into(), json!(self.head));
1926 let h = entry_hash(&body)?;
1927 body.insert("entryHash".into(), json!(h));
1928 self.head = h;
1929 let entry = Value::Object(body);
1930 self.entries.push(entry.clone());
1931 Ok(entry)
1932 }
1933
1934 pub fn head(&self) -> &str {
1935 &self.head
1936 }
1937
1938 pub fn genesis(&self) -> &str {
1939 &self.genesis
1940 }
1941
1942 pub fn entries(&self) -> &[Value] {
1943 &self.entries
1944 }
1945}
1946
1947pub fn verify_perception_log(
1950 entries: &[Value],
1951 genesis_prev_hash_override: Option<&str>,
1952) -> ChainResult {
1953 verify_blackbox_chain(entries, genesis_prev_hash_override)
1954}
1955
1956#[derive(Debug, Clone)]
1961pub struct BuildPerception {
1962 pub robot_did: String,
1963 pub sensor_id: String,
1964 pub modality: String,
1965 pub frame_hash: String,
1966 pub captured_at: Option<String>,
1967 pub log_head: Option<String>,
1968 pub valid_from: String,
1969 pub valid_until: Option<String>,
1970}
1971
1972pub fn build_perception_attestation(robot_seed: &[u8], params: &BuildPerception) -> Result<Value> {
1976 if !MODALITIES.contains(¶ms.modality.as_str()) {
1977 return Err(CoreError::Json(format!(
1978 "modality must be one of {MODALITIES:?}, got {:?}",
1979 params.modality
1980 )));
1981 }
1982 if params.frame_hash.is_empty() {
1983 return Err(CoreError::Json("frame_hash is required".into()));
1984 }
1985
1986 let captured = params
1987 .captured_at
1988 .clone()
1989 .unwrap_or_else(|| params.valid_from.clone());
1990
1991 let mut subject = Map::new();
1992 subject.insert("id".into(), json!(params.robot_did));
1993 subject.insert("sensorId".into(), json!(params.sensor_id));
1994 subject.insert("modality".into(), json!(params.modality));
1995 subject.insert("frameHash".into(), json!(params.frame_hash));
1996 subject.insert("capturedAt".into(), json!(captured));
1997 if let Some(head) = ¶ms.log_head {
1998 subject.insert("logHead".into(), json!(head));
1999 }
2000
2001 let mut cred = Map::new();
2002 cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
2003 cred.insert(
2004 "type".into(),
2005 json!(["VerifiableCredential", PERCEPTION_TYPE]),
2006 );
2007 cred.insert("issuer".into(), json!(params.robot_did));
2008 cred.insert("validFrom".into(), json!(params.valid_from));
2009 if let Some(vu) = ¶ms.valid_until {
2010 cred.insert("validUntil".into(), json!(vu));
2011 }
2012 cred.insert("credentialSubject".into(), Value::Object(subject));
2013
2014 let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), ¶ms.valid_from);
2015 data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
2016}
2017
2018pub fn verify_perception_attestation(
2022 credential: &Value,
2023 public_key: &[u8],
2024 frame: Option<&[u8]>,
2025) -> Result<Option<Value>> {
2026 if !has_type(credential.get("type"), PERCEPTION_TYPE) {
2027 return Ok(None);
2028 }
2029 if !data_integrity::verify_proof(credential, public_key)? {
2030 return Ok(None);
2031 }
2032 let subject = match credential
2033 .get("credentialSubject")
2034 .and_then(|s| s.as_object())
2035 {
2036 Some(s) => s,
2037 None => return Ok(None),
2038 };
2039 let frame_hash = subject.get("frameHash").and_then(|v| v.as_str());
2040 let modality = subject.get("modality").and_then(|v| v.as_str());
2041 match (frame_hash, modality) {
2042 (Some(fh), Some(m)) if !fh.is_empty() && MODALITIES.contains(&m) => {}
2043 _ => return Ok(None),
2044 }
2045 if let Some(f) = frame {
2046 if hash_frame(f) != frame_hash.unwrap_or("") {
2047 return Ok(None);
2048 }
2049 }
2050 Ok(Some(Value::Object(subject.clone())))
2051}
2052
2053pub const DELEGATION_LEASE_TYPE: &str = "DelegationLeaseCredential";
2058
2059#[derive(Debug, Clone)]
2066pub struct BuildDelegationLease {
2067 pub issuer_did: String,
2068 pub robot_did: String,
2069 pub lease_id: String,
2070 pub scope: Value,
2071 pub parent_lease_id: Option<String>,
2072 pub valid_from: String,
2073 pub valid_until: String,
2074}
2075
2076pub fn build_delegation_lease(signer_seed: &[u8], params: &BuildDelegationLease) -> Result<Value> {
2079 if params.lease_id.is_empty() {
2080 return Err(CoreError::Json("lease_id is required".into()));
2081 }
2082 if !params.scope.is_object() {
2083 return Err(CoreError::Json(
2084 "scope must be a physicalScope object".into(),
2085 ));
2086 }
2087
2088 let mut subject = Map::new();
2089 subject.insert("id".into(), json!(params.robot_did));
2090 subject.insert("leaseId".into(), json!(params.lease_id));
2091 subject.insert("physicalScope".into(), params.scope.clone());
2092 if let Some(parent) = ¶ms.parent_lease_id {
2093 subject.insert("parentLeaseId".into(), json!(parent));
2094 }
2095
2096 let mut cred = Map::new();
2097 cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
2098 cred.insert(
2099 "type".into(),
2100 json!(["VerifiableCredential", DELEGATION_LEASE_TYPE]),
2101 );
2102 cred.insert("issuer".into(), json!(params.issuer_did));
2103 cred.insert("validFrom".into(), json!(params.valid_from));
2104 cred.insert("validUntil".into(), json!(params.valid_until));
2105 cred.insert("credentialSubject".into(), Value::Object(subject));
2106
2107 let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), ¶ms.valid_from);
2108 data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
2109}
2110
2111fn lease_window_current(credential: &Value, now_iso: Option<&str>) -> bool {
2115 let now = match now_iso {
2116 Some(n) => n,
2117 None => return true,
2118 };
2119 let moment = match crate::time::iso_to_epoch_seconds(now) {
2120 Ok(t) => t,
2121 Err(_) => return false,
2122 };
2123 if let Some(vf) = credential.get("validFrom").and_then(|v| v.as_str()) {
2124 match crate::time::iso_to_epoch_seconds(vf) {
2125 Ok(t) if moment < t => return false,
2126 Err(_) => return false,
2127 _ => {}
2128 }
2129 }
2130 if let Some(vu) = credential.get("validUntil").and_then(|v| v.as_str()) {
2131 match crate::time::iso_to_epoch_seconds(vu) {
2132 Ok(t) if moment > t => return false,
2133 Err(_) => return false,
2134 _ => {}
2135 }
2136 }
2137 true
2138}
2139
2140pub fn verify_delegation_lease(
2145 credential: &Value,
2146 public_key: &[u8],
2147 now_iso: Option<&str>,
2148 parent_scope: Option<&Value>,
2149) -> Result<Option<Value>> {
2150 if !has_type(credential.get("type"), DELEGATION_LEASE_TYPE) {
2151 return Ok(None);
2152 }
2153 if !data_integrity::verify_proof(credential, public_key)? {
2154 return Ok(None);
2155 }
2156 if !lease_window_current(credential, now_iso) {
2157 return Ok(None);
2158 }
2159
2160 let subject = match credential
2161 .get("credentialSubject")
2162 .and_then(|s| s.as_object())
2163 {
2164 Some(s) => s,
2165 None => return Ok(None),
2166 };
2167 let scope = match subject.get("physicalScope") {
2168 Some(s) if s.is_object() => s,
2169 _ => return Ok(None),
2170 };
2171 if let Some(parent) = parent_scope {
2172 if !attenuates(parent, scope) {
2173 return Ok(None);
2174 }
2175 }
2176 Ok(Some(Value::Object(subject.clone())))
2177}
2178
2179pub fn lease_permits(
2183 subject: &Value,
2184 action: &PhysicalAction,
2185 credential: Option<&Value>,
2186 now_iso: Option<&str>,
2187) -> bool {
2188 if let Some(cred) = credential {
2189 if !lease_window_current(cred, now_iso) {
2190 return false;
2191 }
2192 }
2193 let empty = json!({});
2194 let scope = subject.get("physicalScope").unwrap_or(&empty);
2195 check_physical_action(scope, action).ok
2196}
2197
2198pub const ACTION_APPROVAL_TYPE: &str = "PhysicalActionApprovalCredential";
2203pub const APPROVE: &str = "approve";
2204pub const REJECT: &str = "reject";
2205
2206#[derive(Debug, Clone)]
2210pub struct BuildActionApproval {
2211 pub approver_did: String,
2212 pub action_id: String,
2213 pub robot_did: String,
2214 pub decision: String,
2215 pub valid_from: String,
2216 pub valid_until: Option<String>,
2217}
2218
2219pub fn build_action_approval(approver_seed: &[u8], params: &BuildActionApproval) -> Result<Value> {
2222 if params.decision != APPROVE && params.decision != REJECT {
2223 return Err(CoreError::Json(format!(
2224 "decision must be {APPROVE:?} or {REJECT:?}, got {:?}",
2225 params.decision
2226 )));
2227 }
2228 if params.action_id.is_empty() {
2229 return Err(CoreError::Json("action_id is required".into()));
2230 }
2231
2232 let mut subject = Map::new();
2233 subject.insert("id".into(), json!(params.approver_did));
2234 subject.insert("actionId".into(), json!(params.action_id));
2235 subject.insert("robotDid".into(), json!(params.robot_did));
2236 subject.insert("decision".into(), json!(params.decision));
2237
2238 let mut cred = Map::new();
2239 cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
2240 cred.insert(
2241 "type".into(),
2242 json!(["VerifiableCredential", ACTION_APPROVAL_TYPE]),
2243 );
2244 cred.insert("issuer".into(), json!(params.approver_did));
2245 cred.insert("validFrom".into(), json!(params.valid_from));
2246 if let Some(vu) = ¶ms.valid_until {
2247 cred.insert("validUntil".into(), json!(vu));
2248 }
2249 cred.insert("credentialSubject".into(), Value::Object(subject));
2250
2251 let opts = BuildProofOptions::new(format!("{}#key-1", params.approver_did), ¶ms.valid_from);
2252 data_integrity::sign(&Value::Object(cred), approver_seed, &opts)
2253}
2254
2255#[derive(Debug, Clone)]
2258pub struct ApproverKey {
2259 pub did: String,
2260 pub public_key: Vec<u8>,
2261}
2262
2263pub fn verify_action_authorization(
2273 approvals: &[Value],
2274 action_id: &str,
2275 robot_did: &str,
2276 approver_keys: &[ApproverKey],
2277 threshold: i64,
2278 approver_set: Option<&HashSet<String>>,
2279 now_iso: Option<&str>,
2280) -> Result<(bool, Vec<String>)> {
2281 if threshold < 1 {
2282 return Err(CoreError::Json("threshold must be at least 1".into()));
2283 }
2284
2285 let mut approvers: HashSet<String> = HashSet::new();
2286 for approval in approvals {
2287 if !has_type(approval.get("type"), ACTION_APPROVAL_TYPE) {
2288 continue;
2289 }
2290 let subject = match approval
2291 .get("credentialSubject")
2292 .and_then(|s| s.as_object())
2293 {
2294 Some(s) => s,
2295 None => continue,
2296 };
2297 let issuer = approval
2298 .get("issuer")
2299 .and_then(|v| v.as_str())
2300 .unwrap_or("");
2301 if subject.get("actionId").and_then(|v| v.as_str()) != Some(action_id)
2302 || subject.get("robotDid").and_then(|v| v.as_str()) != Some(robot_did)
2303 {
2304 continue;
2305 }
2306 if subject.get("decision").and_then(|v| v.as_str()) != Some(APPROVE) {
2307 continue;
2308 }
2309 if let Some(set) = approver_set {
2310 if !set.contains(issuer) {
2311 continue;
2312 }
2313 }
2314 let key = match approver_keys.iter().find(|k| k.did == issuer) {
2315 Some(k) => k,
2316 None => continue,
2317 };
2318 if !lease_window_current(approval, now_iso) {
2319 continue;
2320 }
2321 if !data_integrity::verify_proof(approval, &key.public_key)? {
2322 continue;
2323 }
2324 approvers.insert(issuer.to_string());
2325 }
2326
2327 let mut sorted: Vec<String> = approvers.into_iter().collect();
2328 sorted.sort();
2329 Ok((sorted.len() as i64 >= threshold, sorted))
2330}
2331
2332pub const OWNERSHIP_TRANSFER_TYPE: &str = "RobotOwnershipTransferCredential";
2337pub const KEY_ROTATION_TYPE: &str = "RobotKeyRotationCredential";
2338pub const DECOMMISSION_TYPE: &str = "RobotDecommissionCredential";
2339
2340fn verify_typed(
2345 credential: &Value,
2346 public_key: &[u8],
2347 expected_type: &str,
2348) -> Result<Option<Value>> {
2349 if !has_type(credential.get("type"), expected_type) {
2350 return Ok(None);
2351 }
2352 if !data_integrity::verify_proof(credential, public_key)? {
2353 return Ok(None);
2354 }
2355 match credential
2356 .get("credentialSubject")
2357 .and_then(|s| s.as_object())
2358 {
2359 Some(s) => Ok(Some(Value::Object(s.clone()))),
2360 None => Ok(None),
2361 }
2362}
2363
2364#[derive(Debug, Clone)]
2368pub struct BuildOwnershipTransfer {
2369 pub issuer_did: String,
2370 pub robot_did: String,
2371 pub to_owner: String,
2372 pub from_owner: Option<String>,
2373 pub prev_transfer_id: Option<String>,
2374 pub valid_from: String,
2375}
2376
2377pub fn build_ownership_transfer(
2380 current_owner_seed: &[u8],
2381 params: &BuildOwnershipTransfer,
2382) -> Result<Value> {
2383 if params.robot_did.is_empty() || params.to_owner.is_empty() {
2384 return Err(CoreError::Json(
2385 "robot_did and to_owner are required".into(),
2386 ));
2387 }
2388 let seller = params
2389 .from_owner
2390 .clone()
2391 .unwrap_or_else(|| params.issuer_did.clone());
2392
2393 let mut subject = Map::new();
2394 subject.insert("id".into(), json!(params.robot_did));
2395 subject.insert("fromOwner".into(), json!(seller));
2396 subject.insert("toOwner".into(), json!(params.to_owner));
2397 if let Some(prev) = ¶ms.prev_transfer_id {
2398 subject.insert("prevTransferId".into(), json!(prev));
2399 }
2400
2401 let mut cred = Map::new();
2402 cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
2403 cred.insert(
2404 "type".into(),
2405 json!(["VerifiableCredential", OWNERSHIP_TRANSFER_TYPE]),
2406 );
2407 cred.insert("issuer".into(), json!(params.issuer_did));
2408 cred.insert("validFrom".into(), json!(params.valid_from));
2409 cred.insert("credentialSubject".into(), Value::Object(subject));
2410
2411 let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), ¶ms.valid_from);
2412 data_integrity::sign(&Value::Object(cred), current_owner_seed, &opts)
2413}
2414
2415pub fn verify_ownership_transfer(
2419 credential: &Value,
2420 current_owner_public_key: &[u8],
2421) -> Result<Option<Value>> {
2422 let subject = match verify_typed(
2423 credential,
2424 current_owner_public_key,
2425 OWNERSHIP_TRANSFER_TYPE,
2426 )? {
2427 Some(s) => s,
2428 None => return Ok(None),
2429 };
2430 let to_owner = subject.get("toOwner").and_then(|v| v.as_str());
2431 let from_owner = subject.get("fromOwner").and_then(|v| v.as_str());
2432 match (to_owner, from_owner) {
2433 (Some(t), Some(f)) if !t.is_empty() && !f.is_empty() => {
2434 if credential.get("issuer").and_then(|v| v.as_str()) != Some(f) {
2435 return Ok(None);
2436 }
2437 }
2438 _ => return Ok(None),
2439 }
2440 Ok(Some(subject))
2441}
2442
2443#[derive(Debug, Clone)]
2445pub struct OwnerKey {
2446 pub did: String,
2447 pub public_key: Vec<u8>,
2448}
2449
2450pub fn verify_custody_chain(
2456 transfers: &[Value],
2457 public_keys: &[OwnerKey],
2458 origin_owner: Option<&str>,
2459) -> Result<(bool, Option<String>)> {
2460 let mut expected_from: Option<String> = origin_owner.map(String::from);
2461 let mut current_owner: Option<String> = origin_owner.map(String::from);
2462 for transfer in transfers {
2463 let issuer = transfer
2464 .get("issuer")
2465 .and_then(|v| v.as_str())
2466 .unwrap_or("");
2467 let key = match public_keys.iter().find(|k| k.did == issuer) {
2468 Some(k) => k,
2469 None => return Ok((false, None)),
2470 };
2471 let subject = match verify_ownership_transfer(transfer, &key.public_key)? {
2472 Some(s) => s,
2473 None => return Ok((false, None)),
2474 };
2475 if let Some(expected) = &expected_from {
2476 if subject.get("fromOwner").and_then(|v| v.as_str()) != Some(expected.as_str()) {
2477 return Ok((false, None));
2478 }
2479 }
2480 current_owner = subject
2481 .get("toOwner")
2482 .and_then(|v| v.as_str())
2483 .map(String::from);
2484 expected_from = current_owner.clone();
2485 }
2486 Ok((true, current_owner))
2487}
2488
2489#[derive(Debug, Clone)]
2493pub struct BuildKeyRotation {
2494 pub robot_did: String,
2495 pub new_key_multibase: String,
2496 pub reason: Option<String>,
2497 pub valid_from: String,
2498}
2499
2500pub fn build_key_rotation(old_key_seed: &[u8], params: &BuildKeyRotation) -> Result<Value> {
2504 if params.new_key_multibase.is_empty() {
2505 return Err(CoreError::Json("new_key_multibase is required".into()));
2506 }
2507 let old_kp = keys::Ed25519KeyPair::from_seed_slice(old_key_seed)?;
2508
2509 let mut subject = Map::new();
2510 subject.insert("id".into(), json!(params.robot_did));
2511 subject.insert("previousKey".into(), json!(old_kp.public_multikey()));
2512 subject.insert("newKey".into(), json!(params.new_key_multibase));
2513 if let Some(reason) = ¶ms.reason {
2514 subject.insert("reason".into(), json!(reason));
2515 }
2516
2517 let mut cred = Map::new();
2518 cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
2519 cred.insert(
2520 "type".into(),
2521 json!(["VerifiableCredential", KEY_ROTATION_TYPE]),
2522 );
2523 cred.insert("issuer".into(), json!(params.robot_did));
2524 cred.insert("validFrom".into(), json!(params.valid_from));
2525 cred.insert("credentialSubject".into(), Value::Object(subject));
2526
2527 let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), ¶ms.valid_from);
2528 data_integrity::sign(&Value::Object(cred), old_key_seed, &opts)
2529}
2530
2531pub fn verify_key_rotation(credential: &Value, old_public_key: &[u8]) -> Result<Option<Value>> {
2534 let subject = match verify_typed(credential, old_public_key, KEY_ROTATION_TYPE)? {
2535 Some(s) => s,
2536 None => return Ok(None),
2537 };
2538 let previous = subject.get("previousKey").and_then(|v| v.as_str());
2539 let new_key = subject.get("newKey").and_then(|v| v.as_str());
2540 match (previous, new_key) {
2541 (Some(p), Some(n)) if !p.is_empty() && !n.is_empty() => {}
2542 _ => return Ok(None),
2543 }
2544 Ok(Some(subject))
2545}
2546
2547#[derive(Debug, Clone)]
2549pub struct KeyEntry {
2550 pub multibase: String,
2551 pub public_key: Vec<u8>,
2552}
2553
2554pub fn verify_key_history(
2559 rotations: &[Value],
2560 origin_key_multibase: &str,
2561 public_keys: &[KeyEntry],
2562) -> Result<(bool, Option<String>)> {
2563 let mut current_key = origin_key_multibase.to_string();
2564 for rotation in rotations {
2565 let previous = rotation
2566 .get("credentialSubject")
2567 .and_then(|s| s.get("previousKey"))
2568 .and_then(|v| v.as_str())
2569 .unwrap_or("");
2570 if previous != current_key {
2571 return Ok((false, None));
2572 }
2573 let key = match public_keys.iter().find(|k| k.multibase == current_key) {
2574 Some(k) => k,
2575 None => return Ok((false, None)),
2576 };
2577 let subject = match verify_key_rotation(rotation, &key.public_key)? {
2578 Some(s) => s,
2579 None => return Ok((false, None)),
2580 };
2581 current_key = subject
2582 .get("newKey")
2583 .and_then(|v| v.as_str())
2584 .unwrap_or("")
2585 .to_string();
2586 }
2587 Ok((true, Some(current_key)))
2588}
2589
2590#[derive(Debug, Clone)]
2594pub struct BuildDecommission {
2595 pub issuer_did: String,
2596 pub robot_did: String,
2597 pub reason: String,
2598 pub final_disposition: Option<String>,
2599 pub valid_from: String,
2600 pub valid_until: Option<String>,
2601}
2602
2603pub fn build_decommission(signer_seed: &[u8], params: &BuildDecommission) -> Result<Value> {
2607 if params.reason.is_empty() {
2608 return Err(CoreError::Json("reason is required".into()));
2609 }
2610 let mut subject = Map::new();
2611 subject.insert("id".into(), json!(params.robot_did));
2612 subject.insert("reason".into(), json!(params.reason));
2613 subject.insert("decommissionedBy".into(), json!(params.issuer_did));
2614 if let Some(disposition) = ¶ms.final_disposition {
2615 subject.insert("finalDisposition".into(), json!(disposition));
2616 }
2617
2618 let mut cred = Map::new();
2619 cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
2620 cred.insert(
2621 "type".into(),
2622 json!(["VerifiableCredential", DECOMMISSION_TYPE]),
2623 );
2624 cred.insert("issuer".into(), json!(params.issuer_did));
2625 cred.insert("validFrom".into(), json!(params.valid_from));
2626 if let Some(vu) = ¶ms.valid_until {
2627 cred.insert("validUntil".into(), json!(vu));
2628 }
2629 cred.insert("credentialSubject".into(), Value::Object(subject));
2630
2631 let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), ¶ms.valid_from);
2632 data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
2633}
2634
2635pub fn verify_decommission(
2639 credential: &Value,
2640 public_key: &[u8],
2641 trusted_authorities: Option<&HashSet<String>>,
2642) -> Result<Option<Value>> {
2643 let subject = match verify_typed(credential, public_key, DECOMMISSION_TYPE)? {
2644 Some(s) => s,
2645 None => return Ok(None),
2646 };
2647 if let Some(trusted) = trusted_authorities {
2648 let issuer = credential
2649 .get("issuer")
2650 .and_then(|v| v.as_str())
2651 .unwrap_or("");
2652 if !trusted.contains(issuer) {
2653 return Ok(None);
2654 }
2655 }
2656 Ok(Some(subject))
2657}
2658
2659pub const CONFORMANCE_ATTESTATION_TYPE: &str = "RobotConformanceAttestation";
2675
2676struct ProfileRequirement {
2679 id: &'static str,
2680 clause: &'static str,
2681 title: &'static str,
2682 credential: &'static str,
2683 fields: &'static [&'static str],
2684}
2685
2686struct ConformanceProfile {
2688 regime: &'static str,
2689 version: &'static str,
2690 requirements: &'static [ProfileRequirement],
2691}
2692
2693const ISO_10218_REQUIREMENTS: &[ProfileRequirement] = &[
2694 ProfileRequirement {
2695 id: "iso10218-identification",
2696 clause: "ISO 10218-1:2011, 5.2",
2697 title: "Robot identification bound to its hardware",
2698 credential: "RobotIdentityCredential",
2699 fields: &["hardwareRoot.kind"],
2700 },
2701 ProfileRequirement {
2702 id: "iso10218-software-integrity",
2703 clause: "ISO 10218-1:2011, 5.3",
2704 title: "Control software and configuration integrity",
2705 credential: "ModelProvenanceAttestation",
2706 fields: &["vla.weightsHash"],
2707 },
2708 ProfileRequirement {
2709 id: "iso10218-limits",
2710 clause: "ISO 10218-1:2011, 5.6",
2711 title: "Limiting of speed, force, and workspace",
2712 credential: "PhysicalCapabilityScope",
2713 fields: &["physicalScope.maxForceN", "physicalScope.maxSpeedMps"],
2714 },
2715 ProfileRequirement {
2716 id: "iso10218-records",
2717 clause: "ISO 10218-2:2011, 5.2",
2718 title: "Records of safety-relevant events",
2719 credential: "RobotSafetyRecordCredential",
2720 fields: &["totalEvents"],
2721 },
2722];
2723
2724const ISO_TS_15066_REQUIREMENTS: &[ProfileRequirement] = &[
2725 ProfileRequirement {
2726 id: "iso15066-power-force-limiting",
2727 clause: "ISO/TS 15066:2016, 5.5.4",
2728 title: "Power and force limiting near humans",
2729 credential: "PhysicalCapabilityScope",
2730 fields: &[
2731 "physicalScope.maxSpeedNearHumansMps",
2732 "physicalScope.maxForceN",
2733 ],
2734 },
2735 ProfileRequirement {
2736 id: "iso15066-collaborative-workspace",
2737 clause: "ISO/TS 15066:2016, 5.5.2",
2738 title: "Defined collaborative workspace",
2739 credential: "PhysicalCapabilityScope",
2740 fields: &["physicalScope.allowedZones"],
2741 },
2742 ProfileRequirement {
2743 id: "iso15066-monitoring",
2744 clause: "ISO/TS 15066:2016, 5.2",
2745 title: "Continuous monitoring of the collaborative operation",
2746 credential: "RobotHeartbeatCredential",
2747 fields: &["motionDigest"],
2748 },
2749];
2750
2751const EU_MACHINERY_REQUIREMENTS: &[ProfileRequirement] = &[
2752 ProfileRequirement {
2753 id: "eu-mr-identification",
2754 clause: "Reg (EU) 2023/1230, Annex III 1.7.4",
2755 title: "Machinery identification and traceability",
2756 credential: "RobotIdentityCredential",
2757 fields: &["make", "model", "serial"],
2758 },
2759 ProfileRequirement {
2760 id: "eu-mr-software-integrity",
2761 clause: "Reg (EU) 2023/1230, Annex III 1.1.9",
2762 title: "Protection against corruption of safety software",
2763 credential: "ModelProvenanceAttestation",
2764 fields: &["vla.weightsHash", "vla.safetyPolicy"],
2765 },
2766 ProfileRequirement {
2767 id: "eu-mr-safe-limits",
2768 clause: "Reg (EU) 2023/1230, Annex III 1.2.1",
2769 title: "Safety and reliability of control systems and limits",
2770 credential: "PhysicalCapabilityScope",
2771 fields: &["physicalScope.maxForceN"],
2772 },
2773 ProfileRequirement {
2774 id: "eu-mr-records",
2775 clause: "Reg (EU) 2023/1230, Annex III 1.2.1",
2776 title: "Recording of safety-relevant data",
2777 credential: "RobotSafetyRecordCredential",
2778 fields: &["totalEvents"],
2779 },
2780];
2781
2782const EU_AI_ACT_REQUIREMENTS: &[ProfileRequirement] = &[
2783 ProfileRequirement {
2784 id: "eu-aia-record-keeping",
2785 clause: "Reg (EU) 2024/1689, Art. 12",
2786 title: "Automatic recording of events (logging)",
2787 credential: "RobotSafetyRecordCredential",
2788 fields: &["logHead"],
2789 },
2790 ProfileRequirement {
2791 id: "eu-aia-transparency",
2792 clause: "Reg (EU) 2024/1689, Art. 13",
2793 title: "Model and configuration transparency",
2794 credential: "ModelProvenanceAttestation",
2795 fields: &["vla.modelName", "vla.configHash"],
2796 },
2797 ProfileRequirement {
2798 id: "eu-aia-human-oversight",
2799 clause: "Reg (EU) 2024/1689, Art. 14",
2800 title: "Human oversight through enforced operating limits",
2801 credential: "PhysicalCapabilityScope",
2802 fields: &["physicalScope.maxSpeedNearHumansMps"],
2803 },
2804 ProfileRequirement {
2805 id: "eu-aia-accuracy-robustness",
2806 clause: "Reg (EU) 2024/1689, Art. 15",
2807 title: "Accuracy and robustness traceable to a known build",
2808 credential: "ModelProvenanceAttestation",
2809 fields: &["vla.weightsHash"],
2810 },
2811];
2812
2813const UL_3300_REQUIREMENTS: &[ProfileRequirement] = &[
2814 ProfileRequirement {
2815 id: "ul3300-identity",
2816 clause: "UL 3300, identification",
2817 title: "Robot identity bound to its hardware",
2818 credential: "RobotIdentityCredential",
2819 fields: &["hardwareRoot.kind"],
2820 },
2821 ProfileRequirement {
2822 id: "ul3300-operating-limits",
2823 clause: "UL 3300, operating limits",
2824 title: "Enforced speed and zone limits",
2825 credential: "PhysicalCapabilityScope",
2826 fields: &["physicalScope.maxSpeedMps", "physicalScope.allowedZones"],
2827 },
2828 ProfileRequirement {
2829 id: "ul3300-perception-integrity",
2830 clause: "UL 3300, sensing integrity",
2831 title: "Integrity of perception used for safe operation",
2832 credential: "PerceptionProvenanceCredential",
2833 fields: &["frameHash"],
2834 },
2835 ProfileRequirement {
2836 id: "ul3300-records",
2837 clause: "UL 3300, incident records",
2838 title: "Records of safety-relevant incidents",
2839 credential: "RobotSafetyRecordCredential",
2840 fields: &["totalEvents"],
2841 },
2842];
2843
2844fn conformance_profile(profile_id: &str) -> Option<ConformanceProfile> {
2849 match profile_id {
2850 "iso-10218" => Some(ConformanceProfile {
2851 regime: "ISO 10218-1/-2 industrial robots",
2852 version: "2011",
2853 requirements: ISO_10218_REQUIREMENTS,
2854 }),
2855 "iso-ts-15066" => Some(ConformanceProfile {
2856 regime: "ISO/TS 15066 collaborative robots",
2857 version: "2016",
2858 requirements: ISO_TS_15066_REQUIREMENTS,
2859 }),
2860 "eu-machinery-2023-1230" => Some(ConformanceProfile {
2861 regime: "EU Machinery Regulation 2023/1230",
2862 version: "2023",
2863 requirements: EU_MACHINERY_REQUIREMENTS,
2864 }),
2865 "eu-ai-act-high-risk" => Some(ConformanceProfile {
2866 regime: "EU AI Act high-risk systems",
2867 version: "2024",
2868 requirements: EU_AI_ACT_REQUIREMENTS,
2869 }),
2870 "ul-3300" => Some(ConformanceProfile {
2871 regime: "UL 3300 service, communication, and mobile robots",
2872 version: "2022",
2873 requirements: UL_3300_REQUIREMENTS,
2874 }),
2875 _ => None,
2876 }
2877}
2878
2879fn credential_types(credential: &Value) -> Vec<&str> {
2881 match credential.get("type") {
2882 Some(Value::String(s)) => vec![s.as_str()],
2883 Some(Value::Array(items)) => items.iter().filter_map(|v| v.as_str()).collect(),
2884 _ => Vec::new(),
2885 }
2886}
2887
2888fn path_value<'a>(subject: &'a Value, path: &str) -> Option<&'a Value> {
2891 let mut node = subject;
2892 for part in path.split('.') {
2893 match node {
2894 Value::Object(map) => match map.get(part) {
2895 Some(v) => node = v,
2896 None => return None,
2897 },
2898 _ => return None,
2899 }
2900 }
2901 Some(node)
2902}
2903
2904fn value_present(value: &Value) -> bool {
2907 match value {
2908 Value::Null => false,
2909 Value::Array(a) => !a.is_empty(),
2910 Value::Object(o) => !o.is_empty(),
2911 _ => true,
2912 }
2913}
2914
2915fn credential_satisfies(credential: &Value, requirement: &ProfileRequirement) -> bool {
2919 if !credential_types(credential).contains(&requirement.credential) {
2920 return false;
2921 }
2922 let empty = Value::Object(Map::new());
2923 let subject = credential.get("credentialSubject").unwrap_or(&empty);
2924 for path in requirement.fields {
2925 match path_value(subject, path) {
2926 Some(v) if value_present(v) => {}
2927 _ => return false,
2928 }
2929 }
2930 true
2931}
2932
2933pub fn check_conformance(credentials: &[Value], profile_id: &str) -> Result<Value> {
2942 let prof = conformance_profile(profile_id)
2943 .ok_or_else(|| CoreError::Json(format!("unknown conformance profile: {profile_id}")))?;
2944
2945 let mut results: Vec<Value> = Vec::with_capacity(prof.requirements.len());
2946 let mut satisfied = 0i64;
2947 for requirement in prof.requirements {
2948 let ok = credentials
2949 .iter()
2950 .any(|c| credential_satisfies(c, requirement));
2951 if ok {
2952 satisfied += 1;
2953 }
2954 results.push(json!({
2955 "id": requirement.id,
2956 "clause": requirement.clause,
2957 "title": requirement.title,
2958 "satisfied": ok,
2959 }));
2960 }
2961 let total = prof.requirements.len() as i64;
2962
2963 let mut report = Map::new();
2964 report.insert("profileId".into(), json!(profile_id));
2965 report.insert("regime".into(), json!(prof.regime));
2966 report.insert("version".into(), json!(prof.version));
2967 report.insert("conforms".into(), json!(satisfied == total));
2968 report.insert("satisfiedCount".into(), json!(satisfied));
2969 report.insert("totalCount".into(), json!(total));
2970 report.insert("requirements".into(), Value::Array(results));
2971 Ok(Value::Object(report))
2972}
2973
2974pub fn report_digest(report: &Value) -> String {
2978 mb64(&Sha256::digest(jcs::canonicalize(report)))
2979}
2980
2981#[derive(Debug, Clone)]
2986pub struct BuildConformanceAttestation {
2987 pub issuer_did: String,
2988 pub robot_did: String,
2989 pub report: Value,
2990 pub valid_from: String,
2991 pub valid_until: Option<String>,
2992}
2993
2994pub fn build_conformance_attestation(
2998 signer_seed: &[u8],
2999 params: &BuildConformanceAttestation,
3000) -> Result<Value> {
3001 if params.robot_did.is_empty() {
3002 return Err(CoreError::Json("robot_did is required".into()));
3003 }
3004 let report = params
3005 .report
3006 .as_object()
3007 .ok_or_else(|| CoreError::Json("report must come from check_conformance".into()))?;
3008 if !report.contains_key("profileId") || !report.contains_key("conforms") {
3009 return Err(CoreError::Json(
3010 "report must come from check_conformance".into(),
3011 ));
3012 }
3013
3014 let mut subject = Map::new();
3015 subject.insert("id".into(), json!(params.robot_did));
3016 subject.insert(
3017 "profileId".into(),
3018 report.get("profileId").cloned().unwrap_or(Value::Null),
3019 );
3020 subject.insert(
3021 "regime".into(),
3022 report.get("regime").cloned().unwrap_or(Value::Null),
3023 );
3024 subject.insert(
3025 "conforms".into(),
3026 report.get("conforms").cloned().unwrap_or(Value::Null),
3027 );
3028 subject.insert(
3029 "satisfiedCount".into(),
3030 report.get("satisfiedCount").cloned().unwrap_or(Value::Null),
3031 );
3032 subject.insert(
3033 "totalCount".into(),
3034 report.get("totalCount").cloned().unwrap_or(Value::Null),
3035 );
3036 subject.insert("reportDigest".into(), json!(report_digest(¶ms.report)));
3037 subject.insert("report".into(), params.report.clone());
3038
3039 let mut cred = Map::new();
3040 cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
3041 cred.insert(
3042 "type".into(),
3043 json!(["VerifiableCredential", CONFORMANCE_ATTESTATION_TYPE]),
3044 );
3045 cred.insert("issuer".into(), json!(params.issuer_did));
3046 cred.insert("validFrom".into(), json!(params.valid_from));
3047 if let Some(vu) = ¶ms.valid_until {
3048 cred.insert("validUntil".into(), json!(vu));
3049 }
3050 cred.insert("credentialSubject".into(), Value::Object(subject));
3051
3052 let opts = BuildProofOptions::new(format!("{}#key-1", params.issuer_did), ¶ms.valid_from);
3053 data_integrity::sign(&Value::Object(cred), signer_seed, &opts)
3054}
3055
3056pub fn verify_conformance_attestation(
3060 credential: &Value,
3061 public_key: &[u8],
3062) -> Result<Option<Value>> {
3063 if !has_type(credential.get("type"), CONFORMANCE_ATTESTATION_TYPE) {
3064 return Ok(None);
3065 }
3066 if !data_integrity::verify_proof(credential, public_key)? {
3067 return Ok(None);
3068 }
3069 let subject = match credential
3070 .get("credentialSubject")
3071 .and_then(|s| s.as_object())
3072 {
3073 Some(s) => s,
3074 None => return Ok(None),
3075 };
3076 let embedded = match subject.get("report") {
3077 Some(r) if r.is_object() => r,
3078 _ => return Ok(None),
3079 };
3080 if subject.get("reportDigest").and_then(|v| v.as_str())
3081 != Some(report_digest(embedded).as_str())
3082 {
3083 return Ok(None);
3084 }
3085 if subject.get("conforms") != embedded.get("conforms") {
3086 return Ok(None);
3087 }
3088 Ok(Some(Value::Object(subject.clone())))
3089}
3090
3091pub const CLASSICAL_CRYPTOSUITE: &str = data_integrity::CRYPTOSUITE_ID;
3116pub const HYBRID_CRYPTOSUITE: &str = hybrid::HYBRID_COMPOSITE_CRYPTOSUITE_ID;
3118
3119pub fn coerce_mldsa44_public(mldsa44_public: &[u8]) -> Result<Vec<u8>> {
3123 if mldsa44_public.len() != MLDSA44_PUBLIC_LEN {
3124 return Err(CoreError::InvalidKeyLength {
3125 expected: MLDSA44_PUBLIC_LEN,
3126 got: mldsa44_public.len(),
3127 });
3128 }
3129 Ok(mldsa44_public.to_vec())
3130}
3131
3132pub fn mldsa44_public_from_multikey(multikey_str: &str) -> Result<Vec<u8>> {
3135 let decoded = multikey::decode(multikey_str)?;
3136 if decoded.algorithm != "ML-DSA-44" {
3137 return Err(CoreError::InvalidMultikey(format!(
3138 "expected an ML-DSA-44 multikey, got {}",
3139 decoded.algorithm
3140 )));
3141 }
3142 coerce_mldsa44_public(&decoded.raw_key)
3143}
3144
3145fn pq_verification_method(credential: &Value) -> String {
3146 let issuer = credential
3147 .as_object()
3148 .and_then(|o| o.get("issuer"))
3149 .and_then(|v| v.as_str())
3150 .unwrap_or("");
3151 format!("{issuer}#key-1")
3152}
3153
3154pub fn sign_pq(
3159 credential: &Value,
3160 ed25519_seed: &[u8],
3161 mldsa: &MlDsa44KeyPair,
3162 created: &str,
3163) -> Result<Value> {
3164 let vm = pq_verification_method(credential);
3165 hybrid::sign_composite(credential, ed25519_seed, mldsa, &vm, created)
3166}
3167
3168pub fn is_pq(credential: &Value) -> bool {
3170 credential
3171 .as_object()
3172 .and_then(|o| o.get("proof"))
3173 .and_then(|p| p.as_object())
3174 .and_then(|p| p.get("cryptosuite"))
3175 .and_then(|v| v.as_str())
3176 == Some(HYBRID_CRYPTOSUITE)
3177}
3178
3179pub fn verify_pq(
3183 credential: &Value,
3184 ed25519_public_key: &[u8],
3185 mldsa44_public_key: &[u8],
3186) -> Result<bool> {
3187 let resolved_ml = coerce_mldsa44_public(mldsa44_public_key)?;
3188 hybrid::verify_composite(credential, ed25519_public_key, &resolved_ml)
3189}
3190
3191pub fn verify_robot_credential(
3201 credential: &Value,
3202 ed25519_public_key: &[u8],
3203 mldsa44_public_key: Option<&[u8]>,
3204) -> Result<bool> {
3205 if is_pq(credential) {
3206 let ml = match mldsa44_public_key {
3207 Some(k) => k,
3208 None => return Ok(false),
3209 };
3210 let resolved_ml = resolve_mldsa44_public(ml)?;
3211 return hybrid::verify_composite(credential, ed25519_public_key, &resolved_ml);
3212 }
3213 data_integrity::verify_proof(credential, ed25519_public_key)
3214}
3215
3216pub fn resolve_mldsa44_public(mldsa44_public_key: &[u8]) -> Result<Vec<u8>> {
3219 if mldsa44_public_key.len() == MLDSA44_PUBLIC_LEN {
3220 return Ok(mldsa44_public_key.to_vec());
3221 }
3222 let s = std::str::from_utf8(mldsa44_public_key).map_err(|_| {
3223 CoreError::InvalidMultikey("ML-DSA-44 key must be raw bytes or a Multikey string".into())
3224 })?;
3225 mldsa44_public_from_multikey(s)
3226}
3227
3228pub fn migrate_to_pq(
3232 credential: &Value,
3233 ed25519_seed: &[u8],
3234 mldsa: &MlDsa44KeyPair,
3235 created: &str,
3236) -> Result<Value> {
3237 sign_pq(credential, ed25519_seed, mldsa, created)
3238}
3239
3240pub const EMBODIMENT_TYPE: &str = "AgentEmbodimentCredential";
3262
3263#[derive(Debug, Clone)]
3269pub struct BuildEmbodiment {
3270 pub agent_did: String,
3271 pub body_did: String,
3272 pub body_hardware_root: String,
3273 pub from_body: Option<String>,
3274 pub embodied_at: String,
3275 pub valid_until: Option<String>,
3276}
3277
3278pub fn build_embodiment(agent_seed: &[u8], params: &BuildEmbodiment) -> Result<Value> {
3283 if params.agent_did.is_empty()
3284 || params.body_did.is_empty()
3285 || params.body_hardware_root.is_empty()
3286 {
3287 return Err(CoreError::Json(
3288 "agent_did, body_did, and body_hardware_root are required".into(),
3289 ));
3290 }
3291
3292 let mut subject = Map::new();
3293 subject.insert("id".into(), json!(params.agent_did));
3294 subject.insert("body".into(), json!(params.body_did));
3295 subject.insert("bodyHardwareRoot".into(), json!(params.body_hardware_root));
3296 if let Some(from_body) = ¶ms.from_body {
3297 subject.insert("fromBody".into(), json!(from_body));
3298 }
3299
3300 let mut cred = Map::new();
3301 cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
3302 cred.insert(
3303 "type".into(),
3304 json!(["VerifiableCredential", EMBODIMENT_TYPE]),
3305 );
3306 cred.insert("issuer".into(), json!(params.agent_did));
3307 cred.insert("validFrom".into(), json!(params.embodied_at));
3308 if let Some(vu) = ¶ms.valid_until {
3309 cred.insert("validUntil".into(), json!(vu));
3310 }
3311 cred.insert("credentialSubject".into(), Value::Object(subject));
3312
3313 let opts = BuildProofOptions::new(format!("{}#key-1", params.agent_did), ¶ms.embodied_at);
3314 data_integrity::sign(&Value::Object(cred), agent_seed, &opts)
3315}
3316
3317pub fn verify_embodiment(credential: &Value, agent_public_key: &[u8]) -> Result<Option<Value>> {
3322 let subject = match verify_typed(credential, agent_public_key, EMBODIMENT_TYPE)? {
3323 Some(s) => s,
3324 None => return Ok(None),
3325 };
3326 let has_body = subject
3327 .get("body")
3328 .and_then(|v| v.as_str())
3329 .map(|s| !s.is_empty())
3330 .unwrap_or(false);
3331 let has_root = subject
3332 .get("bodyHardwareRoot")
3333 .and_then(|v| v.as_str())
3334 .map(|s| !s.is_empty())
3335 .unwrap_or(false);
3336 if !has_body || !has_root {
3337 return Ok(None);
3338 }
3339 let subject_id = subject.get("id").and_then(|v| v.as_str());
3340 if credential.get("issuer").and_then(|v| v.as_str()) != subject_id {
3341 return Ok(None);
3342 }
3343 Ok(Some(subject))
3344}
3345
3346pub fn verify_continuity_chain(
3351 embodiments: &[Value],
3352 agent_public_key: &[u8],
3353 origin_body: Option<&str>,
3354) -> Result<(bool, Option<String>)> {
3355 let mut expected_from: Option<String> = origin_body.map(String::from);
3356 let mut current_body: Option<String> = origin_body.map(String::from);
3357 for embodiment in embodiments {
3358 let subject = match verify_embodiment(embodiment, agent_public_key)? {
3359 Some(s) => s,
3360 None => return Ok((false, None)),
3361 };
3362 if let Some(expected) = &expected_from {
3363 if subject.get("fromBody").and_then(|v| v.as_str()) != Some(expected.as_str()) {
3364 return Ok((false, None));
3365 }
3366 }
3367 current_body = subject
3368 .get("body")
3369 .and_then(|v| v.as_str())
3370 .map(String::from);
3371 expected_from = current_body.clone();
3372 }
3373 Ok((true, current_body))
3374}
3375
3376#[derive(Debug, Clone, PartialEq, Eq)]
3378pub struct ForkConflict {
3379 pub body_a: String,
3380 pub body_b: String,
3381}
3382
3383fn windows_overlap(start_a: i64, end_a: Option<i64>, start_b: i64, end_b: Option<i64>) -> bool {
3387 let a_before_b = end_a.map(|e| e <= start_b).unwrap_or(false);
3388 let b_before_a = end_b.map(|e| e <= start_a).unwrap_or(false);
3389 !(a_before_b || b_before_a)
3390}
3391
3392pub fn check_no_fork(embodiments: &[Value]) -> Result<(bool, Option<ForkConflict>)> {
3398 let mut windows: Vec<(String, i64, Option<i64>)> = Vec::with_capacity(embodiments.len());
3399 for embodiment in embodiments {
3400 let subject = embodiment
3401 .get("credentialSubject")
3402 .and_then(|s| s.as_object());
3403 let body = subject
3404 .and_then(|s| s.get("body"))
3405 .and_then(|v| v.as_str())
3406 .filter(|s| !s.is_empty());
3407 let start = embodiment
3408 .get("validFrom")
3409 .and_then(|v| v.as_str())
3410 .and_then(|s| crate::time::iso_to_epoch_seconds(s).ok());
3411 let (body, start) = match (body, start) {
3412 (Some(b), Some(s)) => (b.to_string(), s),
3413 _ => return Ok((false, None)),
3414 };
3415 let end = embodiment
3416 .get("validUntil")
3417 .and_then(|v| v.as_str())
3418 .and_then(|s| crate::time::iso_to_epoch_seconds(s).ok());
3419 windows.push((body, start, end));
3420 }
3421
3422 for i in 0..windows.len() {
3423 let (body_i, start_i, end_i) = &windows[i];
3424 for window_j in windows.iter().skip(i + 1) {
3425 let (body_j, start_j, end_j) = window_j;
3426 if body_i == body_j {
3427 continue;
3428 }
3429 if windows_overlap(*start_i, *end_i, *start_j, *end_j) {
3430 return Ok((
3431 false,
3432 Some(ForkConflict {
3433 body_a: body_i.clone(),
3434 body_b: body_j.clone(),
3435 }),
3436 ));
3437 }
3438 }
3439 }
3440 Ok((true, None))
3441}
3442
3443pub const CUSTODY_HANDOFF_TYPE: &str = "CustodyHandoffCredential";
3463
3464#[derive(Debug, Clone)]
3473pub struct BuildHandoff {
3474 pub task_id: String,
3475 pub from_actor: String,
3476 pub to_actor: String,
3477 pub condition: Option<String>,
3478 pub handoff_at: String,
3479 pub valid_until: Option<String>,
3480}
3481
3482pub fn build_handoff(receiver_seed: &[u8], params: &BuildHandoff) -> Result<Value> {
3486 if params.task_id.is_empty() || params.from_actor.is_empty() || params.to_actor.is_empty() {
3487 return Err(CoreError::Json(
3488 "task_id, from_actor, and to_actor are required".into(),
3489 ));
3490 }
3491
3492 let mut subject = Map::new();
3493 subject.insert("id".into(), json!(params.task_id));
3494 subject.insert("fromActor".into(), json!(params.from_actor));
3495 subject.insert("toActor".into(), json!(params.to_actor));
3496 if let Some(condition) = ¶ms.condition {
3497 subject.insert("condition".into(), json!(condition));
3498 }
3499
3500 let mut cred = Map::new();
3501 cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
3502 cred.insert(
3503 "type".into(),
3504 json!(["VerifiableCredential", CUSTODY_HANDOFF_TYPE]),
3505 );
3506 cred.insert("issuer".into(), json!(params.to_actor));
3507 cred.insert("validFrom".into(), json!(params.handoff_at));
3508 if let Some(vu) = ¶ms.valid_until {
3509 cred.insert("validUntil".into(), json!(vu));
3510 }
3511 cred.insert("credentialSubject".into(), Value::Object(subject));
3512
3513 let opts = BuildProofOptions::new(format!("{}#key-1", params.to_actor), ¶ms.handoff_at);
3514 data_integrity::sign(&Value::Object(cred), receiver_seed, &opts)
3515}
3516
3517pub fn verify_handoff(credential: &Value, receiver_public_key: &[u8]) -> Result<Option<Value>> {
3522 let subject = match verify_typed(credential, receiver_public_key, CUSTODY_HANDOFF_TYPE)? {
3523 Some(s) => s,
3524 None => return Ok(None),
3525 };
3526 let from_actor = subject.get("fromActor").and_then(|v| v.as_str());
3527 let to_actor = subject.get("toActor").and_then(|v| v.as_str());
3528 match (from_actor, to_actor) {
3529 (Some(f), Some(t)) if !f.is_empty() && !t.is_empty() => {
3530 if credential.get("issuer").and_then(|v| v.as_str()) != Some(t) {
3531 return Ok(None);
3532 }
3533 }
3534 _ => return Ok(None),
3535 }
3536 Ok(Some(subject))
3537}
3538
3539#[derive(Debug, Clone)]
3541pub struct ActorKey {
3542 pub did: String,
3543 pub public_key: Vec<u8>,
3544}
3545
3546pub fn verify_handoff_chain(
3552 handoffs: &[Value],
3553 public_keys: &[ActorKey],
3554 origin_actor: Option<&str>,
3555) -> Result<(bool, Option<String>)> {
3556 let mut expected_from: Option<String> = origin_actor.map(String::from);
3557 let mut current_holder: Option<String> = origin_actor.map(String::from);
3558 for handoff in handoffs {
3559 let receiver = handoff.get("issuer").and_then(|v| v.as_str()).unwrap_or("");
3560 let key = match public_keys.iter().find(|k| k.did == receiver) {
3561 Some(k) => k,
3562 None => return Ok((false, None)),
3563 };
3564 let subject = match verify_handoff(handoff, &key.public_key)? {
3565 Some(s) => s,
3566 None => return Ok((false, None)),
3567 };
3568 if let Some(expected) = &expected_from {
3569 if subject.get("fromActor").and_then(|v| v.as_str()) != Some(expected.as_str()) {
3570 return Ok((false, None));
3571 }
3572 }
3573 current_holder = subject
3574 .get("toActor")
3575 .and_then(|v| v.as_str())
3576 .map(String::from);
3577 expected_from = current_holder.clone();
3578 }
3579 Ok((true, current_holder))
3580}
3581
3582pub fn holder_at(handoffs: &[Value], at: &str) -> Option<String> {
3587 let when = crate::time::iso_to_epoch_seconds(at).ok()?;
3588 let mut holder: Option<String> = None;
3589 for handoff in handoffs {
3590 let start = handoff
3591 .get("validFrom")
3592 .and_then(|v| v.as_str())
3593 .and_then(|s| crate::time::iso_to_epoch_seconds(s).ok());
3594 if let Some(start) = start {
3595 if start <= when {
3596 holder = handoff
3597 .get("credentialSubject")
3598 .and_then(|s| s.get("toActor"))
3599 .and_then(|v| v.as_str())
3600 .map(String::from);
3601 }
3602 }
3603 }
3604 holder
3605}
3606
3607#[derive(Debug, Clone, PartialEq, Eq)]
3610pub struct ConditionChange {
3611 pub responsible_holder: Option<String>,
3612 pub from_condition: String,
3613 pub to_condition: String,
3614}
3615
3616pub fn locate_condition_change(handoffs: &[Value]) -> Option<ConditionChange> {
3622 let mut prev_condition: Option<String> = None;
3623 let mut prev_holder: Option<String> = None;
3624 for handoff in handoffs {
3625 let subject = handoff.get("credentialSubject");
3626 let condition = subject
3627 .and_then(|s| s.get("condition"))
3628 .and_then(|v| v.as_str());
3629 let condition = match condition {
3630 Some(c) => c,
3631 None => continue,
3632 };
3633 if let Some(prev) = &prev_condition {
3634 if condition != prev {
3635 return Some(ConditionChange {
3636 responsible_holder: prev_holder,
3637 from_condition: prev.clone(),
3638 to_condition: condition.to_string(),
3639 });
3640 }
3641 }
3642 prev_condition = Some(condition.to_string());
3643 prev_holder = subject
3644 .and_then(|s| s.get("toActor"))
3645 .and_then(|v| v.as_str())
3646 .map(String::from);
3647 }
3648 None
3649}
3650
3651pub const ACCESS_GRANT_TYPE: &str = "InfrastructureAccessGrant";
3671pub const ACCESS_REQUEST_TYPE: &str = "InfrastructureAccessRequest";
3672
3673#[derive(Debug, Clone)]
3679pub struct BuildAccessGrant {
3680 pub operator_did: String,
3681 pub robot_did: String,
3682 pub resource: String,
3683 pub operations: Vec<String>,
3684 pub zone: Option<String>,
3685 pub granted_at: String,
3686 pub valid_until: Option<String>,
3687}
3688
3689pub fn build_access_grant(operator_seed: &[u8], params: &BuildAccessGrant) -> Result<Value> {
3693 if params.robot_did.is_empty() || params.resource.is_empty() {
3694 return Err(CoreError::Json(
3695 "robot_did and resource are required".into(),
3696 ));
3697 }
3698 if params.operations.is_empty() {
3699 return Err(CoreError::Json(
3700 "operations must be a non-empty list".into(),
3701 ));
3702 }
3703
3704 let mut subject = Map::new();
3705 subject.insert("id".into(), json!(params.robot_did));
3706 subject.insert("resource".into(), json!(params.resource));
3707 subject.insert("operations".into(), json!(params.operations));
3708 if let Some(zone) = ¶ms.zone {
3709 subject.insert("zone".into(), json!(zone));
3710 }
3711
3712 let mut cred = Map::new();
3713 cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
3714 cred.insert(
3715 "type".into(),
3716 json!(["VerifiableCredential", ACCESS_GRANT_TYPE]),
3717 );
3718 cred.insert("issuer".into(), json!(params.operator_did));
3719 cred.insert("validFrom".into(), json!(params.granted_at));
3720 if let Some(vu) = ¶ms.valid_until {
3721 cred.insert("validUntil".into(), json!(vu));
3722 }
3723 cred.insert("credentialSubject".into(), Value::Object(subject));
3724
3725 let opts = BuildProofOptions::new(format!("{}#key-1", params.operator_did), ¶ms.granted_at);
3726 data_integrity::sign(&Value::Object(cred), operator_seed, &opts)
3727}
3728
3729pub fn verify_access_grant(
3734 credential: &Value,
3735 operator_public_key: &[u8],
3736 now_iso: Option<&str>,
3737) -> Result<Option<Value>> {
3738 let subject = match verify_typed(credential, operator_public_key, ACCESS_GRANT_TYPE)? {
3739 Some(s) => s,
3740 None => return Ok(None),
3741 };
3742 let resource = subject.get("resource").and_then(|v| v.as_str());
3743 let operations = subject.get("operations").and_then(|v| v.as_array());
3744 match (resource, operations) {
3745 (Some(r), Some(ops)) if !r.is_empty() && !ops.is_empty() => {}
3746 _ => return Ok(None),
3747 }
3748 if !lease_window_current(credential, now_iso) {
3749 return Ok(None);
3750 }
3751 Ok(Some(subject))
3752}
3753
3754#[derive(Debug, Clone)]
3757pub struct BuildAccessRequest {
3758 pub robot_did: String,
3759 pub resource: String,
3760 pub operation: String,
3761 pub requested_at: String,
3762}
3763
3764pub fn build_access_request(robot_seed: &[u8], params: &BuildAccessRequest) -> Result<Value> {
3767 if params.robot_did.is_empty() || params.resource.is_empty() || params.operation.is_empty() {
3768 return Err(CoreError::Json(
3769 "robot_did, resource, and operation are required".into(),
3770 ));
3771 }
3772
3773 let mut subject = Map::new();
3774 subject.insert("id".into(), json!(params.robot_did));
3775 subject.insert("resource".into(), json!(params.resource));
3776 subject.insert("operation".into(), json!(params.operation));
3777
3778 let mut cred = Map::new();
3779 cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
3780 cred.insert(
3781 "type".into(),
3782 json!(["VerifiableCredential", ACCESS_REQUEST_TYPE]),
3783 );
3784 cred.insert("issuer".into(), json!(params.robot_did));
3785 cred.insert("validFrom".into(), json!(params.requested_at));
3786 cred.insert("credentialSubject".into(), Value::Object(subject));
3787
3788 let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), ¶ms.requested_at);
3789 data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
3790}
3791
3792#[derive(Debug, Clone)]
3795pub struct AuthorizeResult {
3796 pub ok: bool,
3797 pub reasons: Vec<String>,
3798}
3799
3800pub fn authorize_access(
3806 grant: &Value,
3807 request: &Value,
3808 operator_public_key: &[u8],
3809 robot_public_key: &[u8],
3810 now_iso: Option<&str>,
3811) -> Result<AuthorizeResult> {
3812 let mut reasons: Vec<String> = Vec::new();
3813
3814 let grant_subject = match verify_access_grant(grant, operator_public_key, now_iso)? {
3815 Some(s) => s,
3816 None => {
3817 reasons.push("grant invalid or out of window".into());
3818 return Ok(AuthorizeResult { ok: false, reasons });
3819 }
3820 };
3821
3822 let req_subject = match verify_typed(request, robot_public_key, ACCESS_REQUEST_TYPE)? {
3823 Some(s) => s,
3824 None => {
3825 reasons.push("request invalid".into());
3826 return Ok(AuthorizeResult { ok: false, reasons });
3827 }
3828 };
3829 let req_id = req_subject.get("id").and_then(|v| v.as_str());
3830 if request.get("issuer").and_then(|v| v.as_str()) != req_id {
3831 reasons.push("request invalid".into());
3832 return Ok(AuthorizeResult { ok: false, reasons });
3833 }
3834
3835 if grant_subject.get("id").and_then(|v| v.as_str()) != req_id {
3836 reasons.push("grant and request name different robots".into());
3837 }
3838 if grant_subject.get("resource").and_then(|v| v.as_str())
3839 != req_subject.get("resource").and_then(|v| v.as_str())
3840 {
3841 reasons.push("grant and request name different resources".into());
3842 }
3843 let operation = req_subject.get("operation").and_then(|v| v.as_str());
3844 let permitted = grant_subject
3845 .get("operations")
3846 .and_then(|v| v.as_array())
3847 .map(|ops| operation.is_some() && ops.iter().any(|o| o.as_str() == operation))
3848 .unwrap_or(false);
3849 if !permitted {
3850 reasons.push("operation not permitted by the grant".into());
3851 }
3852
3853 Ok(AuthorizeResult {
3854 ok: reasons.is_empty(),
3855 reasons,
3856 })
3857}
3858
3859pub fn attenuates_grant(parent: &Value, child: &Value) -> bool {
3863 let p = parent.get("credentialSubject");
3864 let c = child.get("credentialSubject");
3865 let p_resource = p.and_then(|s| s.get("resource")).and_then(|v| v.as_str());
3866 let c_resource = c.and_then(|s| s.get("resource")).and_then(|v| v.as_str());
3867 if p_resource != c_resource {
3868 return false;
3869 }
3870 let p_ops: HashSet<&str> = p
3871 .and_then(|s| s.get("operations"))
3872 .and_then(|v| v.as_array())
3873 .map(|a| a.iter().filter_map(|o| o.as_str()).collect())
3874 .unwrap_or_default();
3875 let c_ops: HashSet<&str> = c
3876 .and_then(|s| s.get("operations"))
3877 .and_then(|v| v.as_array())
3878 .map(|a| a.iter().filter_map(|o| o.as_str()).collect())
3879 .unwrap_or_default();
3880 if !c_ops.is_subset(&p_ops) {
3881 return false;
3882 }
3883 let p_zone = p.and_then(|s| s.get("zone")).and_then(|v| v.as_str());
3884 let c_zone = c.and_then(|s| s.get("zone")).and_then(|v| v.as_str());
3885 if p_zone.is_some() && c_zone != p_zone {
3886 return false;
3887 }
3888 true
3889}
3890
3891pub const FUSED_PERCEPTION_TYPE: &str = "FusedPerceptionAttestation";
3917
3918pub fn hash_fused_output(output: &[u8]) -> String {
3921 mb64(&Sha256::digest(output))
3922}
3923
3924pub fn fusion_inputs_digest(input_frame_hashes: &[String]) -> Result<String> {
3929 if input_frame_hashes.is_empty() {
3930 return Err(CoreError::Json(
3931 "input_frame_hashes must be a non-empty list".into(),
3932 ));
3933 }
3934 for h in input_frame_hashes {
3935 if h.is_empty() {
3936 return Err(CoreError::Json(
3937 "each input frame hash must be a non-empty string".into(),
3938 ));
3939 }
3940 }
3941 let joined = input_frame_hashes.join("\n");
3942 Ok(mb64(&Sha256::digest(joined.as_bytes())))
3943}
3944
3945#[derive(Debug, Clone)]
3950pub struct BuildFusedAttestation {
3951 pub robot_did: String,
3952 pub fusion_method: String,
3953 pub input_frame_hashes: Vec<String>,
3954 pub fused_output: Option<Vec<u8>>,
3955 pub fused_output_hash: Option<String>,
3956 pub captured_at: Option<String>,
3957 pub valid_from: String,
3958 pub valid_until: Option<String>,
3959}
3960
3961pub fn build_fused_attestation(robot_seed: &[u8], params: &BuildFusedAttestation) -> Result<Value> {
3966 if params.robot_did.is_empty() {
3967 return Err(CoreError::Json("robot_did is required".into()));
3968 }
3969 if params.fusion_method.is_empty() {
3970 return Err(CoreError::Json("fusion_method is required".into()));
3971 }
3972 if params.input_frame_hashes.is_empty() {
3973 return Err(CoreError::Json(
3974 "input_frame_hashes must be a non-empty list".into(),
3975 ));
3976 }
3977 if params.fused_output.is_some() && params.fused_output_hash.is_some() {
3978 return Err(CoreError::Json(
3979 "provide either fused_output or fused_output_hash, not both".into(),
3980 ));
3981 }
3982 let fused_output_hash = match (¶ms.fused_output, ¶ms.fused_output_hash) {
3983 (Some(o), None) => hash_fused_output(o),
3984 (None, Some(h)) if !h.is_empty() => h.clone(),
3985 _ => {
3986 return Err(CoreError::Json(
3987 "fused_output or fused_output_hash is required".into(),
3988 ))
3989 }
3990 };
3991
3992 let captured = params
3993 .captured_at
3994 .clone()
3995 .unwrap_or_else(|| params.valid_from.clone());
3996
3997 let mut subject = Map::new();
3998 subject.insert("id".into(), json!(params.robot_did));
3999 subject.insert("fusionMethod".into(), json!(params.fusion_method));
4000 subject.insert("fusedOutputHash".into(), json!(fused_output_hash));
4001 subject.insert("inputFrameHashes".into(), json!(params.input_frame_hashes));
4002 subject.insert(
4003 "inputsDigest".into(),
4004 json!(fusion_inputs_digest(¶ms.input_frame_hashes)?),
4005 );
4006 subject.insert("capturedAt".into(), json!(captured));
4007
4008 let mut cred = Map::new();
4009 cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
4010 cred.insert(
4011 "type".into(),
4012 json!(["VerifiableCredential", FUSED_PERCEPTION_TYPE]),
4013 );
4014 cred.insert("issuer".into(), json!(params.robot_did));
4015 cred.insert("validFrom".into(), json!(params.valid_from));
4016 if let Some(vu) = ¶ms.valid_until {
4017 cred.insert("validUntil".into(), json!(vu));
4018 }
4019 cred.insert("credentialSubject".into(), Value::Object(subject));
4020
4021 let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), ¶ms.valid_from);
4022 data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
4023}
4024
4025pub fn verify_fused_attestation(
4031 credential: &Value,
4032 public_key: &[u8],
4033 fused_output: Option<&[u8]>,
4034) -> Result<Option<Value>> {
4035 let subject = match verify_typed(credential, public_key, FUSED_PERCEPTION_TYPE)? {
4036 Some(s) => s,
4037 None => return Ok(None),
4038 };
4039 let fused_output_hash = subject.get("fusedOutputHash").and_then(|v| v.as_str());
4040 let inputs: Vec<String> = subject
4041 .get("inputFrameHashes")
4042 .and_then(|v| v.as_array())
4043 .map(|a| {
4044 a.iter()
4045 .filter_map(|e| e.as_str().map(String::from))
4046 .collect()
4047 })
4048 .unwrap_or_default();
4049 match fused_output_hash {
4050 Some(h) if !h.is_empty() && !inputs.is_empty() => {}
4051 _ => return Ok(None),
4052 }
4053 match fusion_inputs_digest(&inputs) {
4054 Ok(d) => {
4055 if Some(d.as_str()) != subject.get("inputsDigest").and_then(|v| v.as_str()) {
4056 return Ok(None);
4057 }
4058 }
4059 Err(_) => return Ok(None),
4060 }
4061 if let Some(o) = fused_output {
4062 if hash_fused_output(o) != fused_output_hash.unwrap_or("") {
4063 return Ok(None);
4064 }
4065 }
4066 Ok(Some(subject))
4067}
4068
4069#[derive(Debug, Clone)]
4072pub struct FusionInputsResult {
4073 pub ok: bool,
4074 pub missing: Vec<String>,
4075}
4076
4077pub fn verify_fusion_inputs(credential: &Value, log_entries: &[Value]) -> FusionInputsResult {
4082 let recorded: HashSet<&str> = log_entries
4083 .iter()
4084 .filter_map(|e| e.get("frameHash").and_then(|v| v.as_str()))
4085 .collect();
4086 let inputs: Vec<String> = credential
4087 .get("credentialSubject")
4088 .and_then(|s| s.get("inputFrameHashes"))
4089 .and_then(|v| v.as_array())
4090 .map(|a| {
4091 a.iter()
4092 .filter_map(|e| e.as_str().map(String::from))
4093 .collect()
4094 })
4095 .unwrap_or_default();
4096 let missing: Vec<String> = inputs
4097 .into_iter()
4098 .filter(|h| !recorded.contains(h.as_str()))
4099 .collect();
4100 FusionInputsResult {
4101 ok: missing.is_empty(),
4102 missing,
4103 }
4104}
4105
4106pub const WEAR_ATTESTATION_TYPE: &str = "RobotWearAttestation";
4132
4133const WEAR_DERATED_CAPS: [&str; 3] = ["maxForceN", "maxSpeedMps", "maxSpeedNearHumansMps"];
4136
4137#[derive(Debug, Clone)]
4143pub struct BuildWearAttestation {
4144 pub robot_did: String,
4145 pub wear_level: f64,
4146 pub metrics: Option<Value>,
4147 pub prev_proof: Option<String>,
4148 pub attested_at: Option<String>,
4149 pub valid_from: String,
4150 pub valid_until: Option<String>,
4151}
4152
4153pub fn build_wear_attestation(robot_seed: &[u8], params: &BuildWearAttestation) -> Result<Value> {
4158 if params.robot_did.is_empty() {
4159 return Err(CoreError::Json("robot_did is required".into()));
4160 }
4161 if params.wear_level < 0.0 || params.wear_level > 1.0 {
4162 return Err(CoreError::Json(
4163 "wear_level must be between 0.0 and 1.0".into(),
4164 ));
4165 }
4166
4167 let attested = params
4168 .attested_at
4169 .clone()
4170 .unwrap_or_else(|| params.valid_from.clone());
4171
4172 let mut subject = Map::new();
4173 subject.insert("id".into(), json!(params.robot_did));
4174 subject.insert("wearLevel".into(), json!(params.wear_level));
4175 subject.insert("attestedAt".into(), json!(attested));
4176 if let Some(m) = ¶ms.metrics {
4177 subject.insert("metrics".into(), m.clone());
4178 }
4179 if let Some(prev) = ¶ms.prev_proof {
4180 subject.insert("prevProof".into(), json!(prev));
4181 }
4182
4183 let mut cred = Map::new();
4184 cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
4185 cred.insert(
4186 "type".into(),
4187 json!(["VerifiableCredential", WEAR_ATTESTATION_TYPE]),
4188 );
4189 cred.insert("issuer".into(), json!(params.robot_did));
4190 cred.insert("validFrom".into(), json!(params.valid_from));
4191 if let Some(vu) = ¶ms.valid_until {
4192 cred.insert("validUntil".into(), json!(vu));
4193 }
4194 cred.insert("credentialSubject".into(), Value::Object(subject));
4195
4196 let opts = BuildProofOptions::new(format!("{}#key-1", params.robot_did), ¶ms.valid_from);
4197 data_integrity::sign(&Value::Object(cred), robot_seed, &opts)
4198}
4199
4200pub fn verify_wear_attestation(credential: &Value, public_key: &[u8]) -> Result<Option<Value>> {
4204 let subject = match verify_typed(credential, public_key, WEAR_ATTESTATION_TYPE)? {
4205 Some(s) => s,
4206 None => return Ok(None),
4207 };
4208 if credential.get("issuer") != subject.get("id") {
4209 return Ok(None);
4210 }
4211 match subject.get("wearLevel").and_then(|v| v.as_f64()) {
4212 Some(level) if (0.0..=1.0).contains(&level) => {}
4213 _ => return Ok(None),
4214 }
4215 Ok(Some(subject))
4216}
4217
4218pub fn verify_wear_chain(attestations: &[Value], public_key: &[u8]) -> Result<Option<Value>> {
4222 if attestations.is_empty() {
4223 return Ok(None);
4224 }
4225 let mut prev_proof: Option<String> = None;
4226 let mut latest: Option<Value> = None;
4227 for att in attestations {
4228 let subject = match verify_wear_attestation(att, public_key)? {
4229 Some(s) => s,
4230 None => return Ok(None),
4231 };
4232 if let Some(prev) = &prev_proof {
4233 let linked = subject.get("prevProof").and_then(|v| v.as_str());
4234 if linked != Some(prev.as_str()) {
4235 return Ok(None);
4236 }
4237 }
4238 prev_proof = att
4239 .get("proof")
4240 .and_then(|p| p.get("proofValue"))
4241 .and_then(|v| v.as_str())
4242 .map(String::from);
4243 latest = Some(subject);
4244 }
4245 Ok(latest)
4246}
4247
4248pub fn attenuate_for_wear(scope: &Value, wear_level: f64) -> Result<Value> {
4254 if wear_level < 0.0 || wear_level > 1.0 {
4255 return Err(CoreError::Json(
4256 "wear_level must be between 0.0 and 1.0".into(),
4257 ));
4258 }
4259 let factor = 1.0 - wear_level;
4260 let empty = Map::new();
4261 let src = scope.as_object().unwrap_or(&empty);
4262 let mut narrowed = Map::new();
4263 for (key, value) in src {
4264 if WEAR_DERATED_CAPS.contains(&key.as_str()) {
4265 if let Some(n) = value.as_f64() {
4266 narrowed.insert(key.clone(), json!(n * factor));
4267 continue;
4268 }
4269 }
4270 narrowed.insert(key.clone(), value.clone());
4271 }
4272 Ok(Value::Object(narrowed))
4273}
4274
4275#[cfg(test)]
4276mod tests {
4277 use super::*;
4278 use crate::keys::Ed25519KeyPair;
4279 use std::fs;
4280
4281 fn load_vector() -> Value {
4282 let raw = fs::read_to_string("../../test-vectors/robotics/vector.json")
4283 .expect("interop vector present");
4284 serde_json::from_str(&raw).unwrap()
4285 }
4286
4287 fn software_root_attest(root_seed: &[u8], robot_did: &str, robot_key_mb: &str) -> Vec<u8> {
4288 let kp = Ed25519KeyPair::from_seed_slice(root_seed).unwrap();
4289 let binding = robot_identity_binding(robot_did, robot_key_mb);
4290 kp.sign(&binding).to_vec()
4291 }
4292
4293 #[test]
4296 fn verifies_python_interop_vector() {
4297 let raw = fs::read_to_string("../../test-vectors/robotics/vector.json")
4298 .expect("interop vector present");
4299 let vector: Value = serde_json::from_str(&raw).unwrap();
4300 let jwk_x = vector["robot_public_key_jwk"]["x"].as_str().unwrap();
4301 let robot_pub = URL_SAFE_NO_PAD.decode(jwk_x).unwrap();
4302 let cred = vector["robot_identity_credential"].clone();
4303
4304 let subject = verify_robot_identity(&cred, &robot_pub).unwrap();
4305 let subject = subject.expect("the Python interop vector must verify in Rust");
4306 assert_eq!(subject["make"], json!("Acme Robotics"));
4307 }
4308
4309 #[test]
4310 fn mint_verify_roundtrip() {
4311 let robot_seed = [3u8; 32];
4312 let root_seed = [7u8; 32];
4313 let robot_did = "did:web:robot.example.com";
4314 let robot_kp = Ed25519KeyPair::from_seed(&robot_seed);
4315 let root_kp = Ed25519KeyPair::from_seed(&root_seed);
4316
4317 let attestation = software_root_attest(&root_seed, robot_did, &robot_kp.public_multikey());
4318 let params = MintRobotIdentity {
4319 robot_did: robot_did.into(),
4320 make: "Acme".into(),
4321 model: "AR-7".into(),
4322 serial: "SN-1".into(),
4323 owner: Some("did:web:owner.example.com".into()),
4324 root_kind: "TPM".into(),
4325 root_public_multibase: root_kp.public_multikey(),
4326 attestation,
4327 lifecycle: None,
4328 valid_from: "2026-01-01T00:00:00Z".into(),
4329 valid_until: None,
4330 };
4331 let cred = mint_robot_identity(&robot_seed, ¶ms).unwrap();
4332 let subject = verify_robot_identity(&cred, &robot_kp.public_key()).unwrap();
4333 assert!(subject.is_some(), "round-trip identity must verify");
4334 }
4335
4336 #[test]
4337 fn forged_hardware_root_fails() {
4338 let robot_seed = [3u8; 32];
4339 let root_seed = [7u8; 32];
4340 let attacker_seed = [9u8; 32];
4341 let robot_did = "did:web:robot.example.com";
4342 let robot_kp = Ed25519KeyPair::from_seed(&robot_seed);
4343 let root_kp = Ed25519KeyPair::from_seed(&root_seed);
4344 let attacker_kp = Ed25519KeyPair::from_seed(&attacker_seed);
4345
4346 let attestation = software_root_attest(&root_seed, robot_did, &robot_kp.public_multikey());
4347 let params = MintRobotIdentity {
4348 robot_did: robot_did.into(),
4349 make: "Acme".into(),
4350 model: "AR-7".into(),
4351 serial: "SN-1".into(),
4352 owner: None,
4353 root_kind: "TPM".into(),
4354 root_public_multibase: root_kp.public_multikey(),
4355 attestation,
4356 lifecycle: None,
4357 valid_from: "2026-01-01T00:00:00Z".into(),
4358 valid_until: None,
4359 };
4360 let mut cred = mint_robot_identity(&robot_seed, ¶ms).unwrap();
4361
4362 cred["credentialSubject"]["hardwareRoot"]["publicKeyMultibase"] =
4365 json!(attacker_kp.public_multikey());
4366 let resigned = {
4367 let mut bare = cred.clone();
4368 bare.as_object_mut().unwrap().remove("proof");
4369 let opts = BuildProofOptions::new(format!("{robot_did}#key-1"), "2026-01-01T00:00:00Z");
4370 data_integrity::sign(&bare, &robot_seed, &opts).unwrap()
4371 };
4372 assert!(verify_robot_identity(&resigned, &robot_kp.public_key())
4373 .unwrap()
4374 .is_none());
4375 }
4376
4377 #[test]
4379 fn config_hash_matches_interop_vector() {
4380 let vector = load_vector();
4381 let got = config_hash(&vector["config"]);
4382 assert_eq!(got, vector["expected_config_hash"].as_str().unwrap());
4383 assert_eq!(got, "uMh9_H2Lk51-m9SpBhiEa1oqIwwwA7yT27e2QFS0YKUs");
4384 }
4385
4386 #[test]
4387 fn provenance_roundtrip_and_config_tamper() {
4388 let seed = [4u8; 32];
4389 let kp = Ed25519KeyPair::from_seed(&seed);
4390 let config = load_vector()["config"].clone();
4391 let params = BuildProvenance {
4392 issuer_did: "did:web:robot.example.com".into(),
4393 robot_did: "did:web:robot.example.com".into(),
4394 model_name: "openvla-7b".into(),
4395 weights_hash: "uABCDEF".into(),
4396 safety_policy: "did:web:authority.example.com#policy-v3".into(),
4397 config: Some(config.clone()),
4398 version: Some("2026.06".into()),
4399 supersedes: None,
4400 valid_from: "2026-01-01T00:00:00Z".into(),
4401 valid_until: None,
4402 };
4403 let att = build_provenance_attestation(&seed, ¶ms).unwrap();
4404 assert!(
4405 verify_provenance_attestation(&att, &kp.public_key(), Some(&config))
4406 .unwrap()
4407 .is_some()
4408 );
4409 let tampered = json!({"temperature": 1.0, "max_torque": 99.0});
4411 assert!(
4412 verify_provenance_attestation(&att, &kp.public_key(), Some(&tampered))
4413 .unwrap()
4414 .is_none()
4415 );
4416 }
4417
4418 #[test]
4419 fn capability_build_check_attenuate() {
4420 let seed = [6u8; 32];
4421 let kp = Ed25519KeyPair::from_seed(&seed);
4422 let params = BuildPhysicalScope {
4423 issuer_did: "did:web:fleet.example.com".into(),
4424 subject_did: "did:web:robot.example.com".into(),
4425 max_force_n: Some(80.0),
4426 max_speed_mps: Some(2.0),
4427 max_speed_near_humans_mps: Some(0.5),
4428 allowed_zones: Some(vec!["warehouse-a".into(), "dock-3".into()]),
4429 shift_windows: Some(vec![ShiftWindow {
4430 start: "08:00".into(),
4431 end: "18:00".into(),
4432 }]),
4433 valid_from: "2026-01-01T00:00:00Z".into(),
4434 valid_until: None,
4435 };
4436 let cred = build_physical_scope_credential(&seed, ¶ms).unwrap();
4437 assert!(has_type(cred.get("type"), PHYSICAL_SCOPE_TYPE));
4438 assert!(data_integrity::verify_proof(&cred, &kp.public_key()).unwrap());
4439
4440 let scope = cred["credentialSubject"]["physicalScope"].clone();
4441 let within = check_physical_action(
4442 &scope,
4443 &PhysicalAction {
4444 force_n: Some(50.0),
4445 speed_mps: Some(1.5),
4446 zone: Some("warehouse-a".into()),
4447 time_hm: Some("09:30".into()),
4448 ..Default::default()
4449 },
4450 );
4451 assert!(within.ok, "within-scope action: {:?}", within.reasons);
4452 assert!(
4453 !check_physical_action(
4454 &scope,
4455 &PhysicalAction {
4456 force_n: Some(120.0),
4457 ..Default::default()
4458 }
4459 )
4460 .ok
4461 );
4462 assert!(
4464 !check_physical_action(
4465 &scope,
4466 &PhysicalAction {
4467 speed_mps: Some(1.5),
4468 near_humans: true,
4469 ..Default::default()
4470 }
4471 )
4472 .ok
4473 );
4474 assert!(
4475 check_physical_action(
4476 &scope,
4477 &PhysicalAction {
4478 speed_mps: Some(1.5),
4479 near_humans: false,
4480 ..Default::default()
4481 }
4482 )
4483 .ok
4484 );
4485 assert!(
4486 !check_physical_action(
4487 &scope,
4488 &PhysicalAction {
4489 zone: Some("loading-bay-9".into()),
4490 ..Default::default()
4491 }
4492 )
4493 .ok
4494 );
4495 assert!(
4496 !check_physical_action(
4497 &scope,
4498 &PhysicalAction {
4499 time_hm: Some("23:00".into()),
4500 ..Default::default()
4501 }
4502 )
4503 .ok
4504 );
4505 }
4506
4507 #[test]
4508 fn attenuation_rules() {
4509 let parent = json!({
4510 "maxForceN": 80.0, "maxSpeedMps": 2.0, "maxSpeedNearHumansMps": 0.5,
4511 "allowedZones": ["warehouse-a", "dock-3"],
4512 "shiftWindows": [{"start": "08:00", "end": "18:00"}]
4513 });
4514 let narrower = json!({
4515 "maxForceN": 50.0, "maxSpeedMps": 1.0, "maxSpeedNearHumansMps": 0.3,
4516 "allowedZones": ["warehouse-a"],
4517 "shiftWindows": [{"start": "09:00", "end": "17:00"}]
4518 });
4519 assert!(attenuates(&parent, &narrower));
4520 assert!(!attenuates(
4521 &parent,
4522 &json!({"maxForceN": 100.0, "maxSpeedMps": 1.0, "maxSpeedNearHumansMps": 0.3, "allowedZones": ["warehouse-a"]})
4523 ));
4524 assert!(!attenuates(
4525 &parent,
4526 &json!({"maxForceN": 50.0, "allowedZones": ["warehouse-a"]})
4527 ));
4528 assert!(!attenuates(
4529 &parent,
4530 &json!({"maxForceN": 50.0, "maxSpeedMps": 1.0, "maxSpeedNearHumansMps": 0.3, "allowedZones": ["loading-bay-9"]})
4531 ));
4532 assert!(!attenuates(
4533 &parent,
4534 &json!({"maxForceN": 50.0, "maxSpeedMps": 1.0, "maxSpeedNearHumansMps": 0.3, "allowedZones": ["warehouse-a"], "shiftWindows": [{"start": "06:00", "end": "20:00"}]})
4535 ));
4536 }
4537
4538 #[test]
4539 fn handshake_full_flow() {
4540 let a_seed = [11u8; 32];
4541 let b_seed = [12u8; 32];
4542 let a = Ed25519KeyPair::from_seed(&a_seed);
4543 let b = Ed25519KeyPair::from_seed(&b_seed);
4544 let a_did = "did:web:robot-a.example.com";
4545 let b_did = "did:web:robot-b.example.com";
4546 let policy_b = TrustPolicy::new(["robot-a.example.com".to_string()], false);
4547
4548 let hello = build_hello(
4549 &a_seed,
4550 &BuildHello {
4551 from_did: a_did.into(),
4552 proposed_scope: vec!["lift".into(), "carry".into(), "scan".into()],
4553 nonce: "abc123".into(),
4554 peer_did: Some(b_did.into()),
4555 issued_at: "2026-01-01T00:00:00Z".into(),
4556 },
4557 )
4558 .unwrap();
4559
4560 let accept = build_accept(
4561 &b_seed,
4562 &hello,
4563 &a.public_key(),
4564 &policy_b,
4565 &BuildAccept {
4566 from_did: b_did.into(),
4567 offered_scope: vec!["carry".into(), "scan".into(), "weld".into()],
4568 session_id: "urn:uuid:sess-1".into(),
4569 valid_until: "2026-01-01T00:05:00Z".into(),
4570 created: "2026-01-01T00:00:01Z".into(),
4571 },
4572 )
4573 .unwrap();
4574
4575 let session = verify_accept(&accept, &b.public_key(), "abc123", None)
4576 .unwrap()
4577 .expect("accept verifies");
4578 assert_eq!(session.scope, vec!["carry".to_string(), "scan".to_string()]);
4579 assert_eq!(session.initiator, a_did);
4580 assert_eq!(session.responder, b_did);
4581
4582 let confirm = build_confirm(&a_seed, a_did, &session, "2026-01-01T00:00:02Z").unwrap();
4583 assert!(verify_confirm(&confirm, &a.public_key(), &session.session_id, "abc123").unwrap());
4584 }
4585
4586 #[test]
4587 fn handshake_untrusted_tamper_and_nonce() {
4588 let a_seed = [11u8; 32];
4589 let b_seed = [12u8; 32];
4590 let a = Ed25519KeyPair::from_seed(&a_seed);
4591 let b = Ed25519KeyPair::from_seed(&b_seed);
4592 let a_did = "did:web:robot-a.example.com";
4593 let b_did = "did:web:robot-b.example.com";
4594
4595 let hello = build_hello(
4596 &a_seed,
4597 &BuildHello {
4598 from_did: a_did.into(),
4599 proposed_scope: vec!["lift".into()],
4600 nonce: "n1".into(),
4601 peer_did: None,
4602 issued_at: "2026-01-01T00:00:00Z".into(),
4603 },
4604 )
4605 .unwrap();
4606
4607 let strict = TrustPolicy::new(["someone-else.example.com".to_string()], false);
4609 assert!(build_accept(
4610 &b_seed,
4611 &hello,
4612 &a.public_key(),
4613 &strict,
4614 &BuildAccept {
4615 from_did: b_did.into(),
4616 offered_scope: vec!["lift".into()],
4617 session_id: "s".into(),
4618 valid_until: "2026-01-01T00:05:00Z".into(),
4619 created: "2026-01-01T00:00:01Z".into(),
4620 },
4621 )
4622 .is_err());
4623
4624 let open = TrustPolicy::new(Vec::<String>::new(), true);
4626 let mut tampered = hello.clone();
4627 tampered["proposedScope"] = json!(["lift", "weld"]);
4628 assert!(build_accept(
4629 &b_seed,
4630 &tampered,
4631 &a.public_key(),
4632 &open,
4633 &BuildAccept {
4634 from_did: b_did.into(),
4635 offered_scope: vec!["lift".into(), "weld".into()],
4636 session_id: "s".into(),
4637 valid_until: "2026-01-01T00:05:00Z".into(),
4638 created: "2026-01-01T00:00:01Z".into(),
4639 },
4640 )
4641 .is_err());
4642
4643 let accept = build_accept(
4645 &b_seed,
4646 &hello,
4647 &a.public_key(),
4648 &open,
4649 &BuildAccept {
4650 from_did: b_did.into(),
4651 offered_scope: vec!["lift".into()],
4652 session_id: "s".into(),
4653 valid_until: "2026-01-01T00:05:00Z".into(),
4654 created: "2026-01-01T00:00:01Z".into(),
4655 },
4656 )
4657 .unwrap();
4658 assert!(verify_accept(&accept, &b.public_key(), "wrong-nonce", None)
4659 .unwrap()
4660 .is_none());
4661 }
4662
4663 #[test]
4664 fn did_web_domain_parsing() {
4665 assert_eq!(did_web_domain("did:web:example.com"), Some("example.com"));
4666 assert_eq!(
4667 did_web_domain("did:web:robot.example.com:agent"),
4668 Some("robot.example.com")
4669 );
4670 assert_eq!(did_web_domain("did:key:z6Mk"), None);
4671 }
4672
4673 #[test]
4674 fn blackbox_append_open_and_chain() {
4675 let key = [0x11u8; 32];
4676 let mut log = BlackBoxLog::new(&key, None).unwrap();
4677 let e0 = log
4678 .append(
4679 "motion",
4680 &json!({"speed": 1.5, "joint": "elbow"}),
4681 "2026-01-01T00:00:00Z",
4682 )
4683 .unwrap();
4684 log.append("stop", &json!({"reason": "human"}), "2026-01-01T00:00:01Z")
4685 .unwrap();
4686
4687 let opened = log.open(&e0).unwrap();
4689 assert_eq!(opened["joint"], json!("elbow"));
4690
4691 assert!(verify_blackbox_chain(log.entries(), None).ok);
4693 let wire: Vec<Value> =
4694 serde_json::from_str(&serde_json::to_string(log.entries()).unwrap()).unwrap();
4695 assert!(verify_blackbox_chain(&wire, None).ok);
4696 assert_eq!(open_entry(&wire[0], &key).unwrap()["joint"], json!("elbow"));
4697
4698 let mut tampered = wire.clone();
4700 tampered[1]["event"] = json!("tampered");
4701 assert!(!verify_blackbox_chain(&tampered, None).ok);
4702
4703 assert!(open_entry(&e0, &[0x22u8; 32]).is_err());
4705 assert!(BlackBoxLog::new(&[0u8; 16], None).is_err());
4706
4707 assert_eq!(genesis_prev_hash(), format!("u{}", "A".repeat(43)));
4709 }
4710
4711 #[test]
4712 fn killswitch_build_verify_and_trust() {
4713 let seed = [13u8; 32];
4714 let kp = Ed25519KeyPair::from_seed(&seed);
4715 let cred = build_killswitch_credential(
4716 &seed,
4717 &BuildKillswitch {
4718 issuer_did: "did:web:safety.example.com".into(),
4719 target: "did:web:robot.example.com".into(),
4720 reason: "human in path".into(),
4721 command: None,
4722 scope: Some(vec!["arm".into(), "drive".into()]),
4723 valid_from: "2026-01-01T00:00:00Z".into(),
4724 valid_until: None,
4725 },
4726 )
4727 .unwrap();
4728
4729 let mut trusted = HashSet::new();
4730 trusted.insert("did:web:safety.example.com".to_string());
4731 let subject = verify_killswitch_credential(&cred, &kp.public_key(), Some(&trusted))
4732 .unwrap()
4733 .expect("trusted authority verifies");
4734 assert_eq!(subject["command"], json!(EMERGENCY_STOP));
4735
4736 let mut other = HashSet::new();
4738 other.insert("did:web:someone-else.example.com".to_string());
4739 assert!(
4740 verify_killswitch_credential(&cred, &kp.public_key(), Some(&other))
4741 .unwrap()
4742 .is_none()
4743 );
4744
4745 let mut wrong = cred.clone();
4747 wrong["type"] = json!(["VerifiableCredential"]);
4748 assert!(verify_killswitch_credential(&wrong, &kp.public_key(), None)
4749 .unwrap()
4750 .is_none());
4751 }
4752
4753 #[test]
4754 fn passport_build_encode_verify() {
4755 let seed = [14u8; 32];
4756 let kp = Ed25519KeyPair::from_seed(&seed);
4757 let did = "did:web:robot.example.com";
4758 let pass = build_passport(
4759 &seed,
4760 &BuildPassport {
4761 issuer_did: did.into(),
4762 robot_did: did.into(),
4763 make: "Acme Robotics".into(),
4764 model: "AR-7".into(),
4765 owner: "did:web:owner.example.com".into(),
4766 authorized_actions: vec!["lift".into(), "carry".into()],
4767 certification: Some("ISO-10218".into()),
4768 status: None,
4769 valid_from: "2026-01-01T00:00:00Z".into(),
4770 valid_until: None,
4771 },
4772 )
4773 .unwrap();
4774
4775 let subject = verify_passport(&pass, &kp.public_key(), "2026-06-01T00:00:00Z")
4777 .unwrap()
4778 .expect("passport verifies");
4779 assert_eq!(subject["owner"], json!("did:web:owner.example.com"));
4780 assert_eq!(subject["status"], json!(STATUS_ACTIVE));
4781
4782 let uri = encode_passport(&pass);
4784 assert!(uri.starts_with("vouch-passport:u"));
4785 let decoded = decode_passport(&uri).unwrap();
4786 assert!(
4787 verify_passport(&decoded, &kp.public_key(), "2026-06-01T00:00:00Z")
4788 .unwrap()
4789 .is_some()
4790 );
4791 assert!(
4792 verify_passport_uri(&uri, &kp.public_key(), "2026-06-01T00:00:00Z")
4793 .unwrap()
4794 .is_some()
4795 );
4796
4797 let mut tampered = pass.clone();
4799 tampered["credentialSubject"]["owner"] = json!("did:web:attacker.example.com");
4800 assert!(
4801 verify_passport(&tampered, &kp.public_key(), "2026-06-01T00:00:00Z")
4802 .unwrap()
4803 .is_none()
4804 );
4805
4806 assert!(decode_passport("https://example.com/x").is_err());
4808 }
4809
4810 #[test]
4811 fn passport_expiry_and_suspended() {
4812 let seed = [15u8; 32];
4813 let kp = Ed25519KeyPair::from_seed(&seed);
4814 let did = "did:web:robot.example.com";
4815
4816 let timed = build_passport(
4818 &seed,
4819 &BuildPassport {
4820 issuer_did: did.into(),
4821 robot_did: did.into(),
4822 make: "Acme".into(),
4823 model: "AR-7".into(),
4824 owner: "did:web:owner.example.com".into(),
4825 authorized_actions: vec!["lift".into()],
4826 certification: None,
4827 status: None,
4828 valid_from: "2026-01-01T00:00:00Z".into(),
4829 valid_until: Some("2026-01-01T00:01:00Z".into()),
4830 },
4831 )
4832 .unwrap();
4833 assert!(
4834 verify_passport(&timed, &kp.public_key(), "2026-01-01T00:00:30Z")
4835 .unwrap()
4836 .is_some()
4837 );
4838 assert!(
4839 verify_passport(&timed, &kp.public_key(), "2026-01-01T00:02:00Z")
4840 .unwrap()
4841 .is_none()
4842 );
4843
4844 let suspended = build_passport(
4846 &seed,
4847 &BuildPassport {
4848 issuer_did: did.into(),
4849 robot_did: did.into(),
4850 make: "Acme".into(),
4851 model: "AR-7".into(),
4852 owner: "did:web:owner.example.com".into(),
4853 authorized_actions: vec!["lift".into()],
4854 certification: None,
4855 status: Some(STATUS_SUSPENDED.into()),
4856 valid_from: "2026-01-01T00:00:00Z".into(),
4857 valid_until: None,
4858 },
4859 )
4860 .unwrap();
4861 let subject = verify_passport(&suspended, &kp.public_key(), "2026-06-01T00:00:00Z")
4862 .unwrap()
4863 .expect("a suspended passport still verifies");
4864 assert_eq!(subject["status"], json!(STATUS_SUSPENDED));
4865 }
4866
4867 #[test]
4870 fn motion_digest_matches_interop_vector() {
4871 let vector = load_vector();
4872 let scope = vector["physical_scope"].clone();
4873 let mut collector = MotionCollector::new(Some(scope));
4874 collector
4875 .record(&MotionSample {
4876 force_n: Some(12.0),
4877 speed_mps: Some(0.4),
4878 near_humans: false,
4879 zone: Some("cell-3".into()),
4880 time_hm: None,
4881 })
4882 .unwrap();
4883 collector
4884 .record(&MotionSample {
4885 force_n: Some(20.0),
4886 speed_mps: Some(0.2),
4887 near_humans: true,
4888 zone: Some("cell-3".into()),
4889 time_hm: None,
4890 })
4891 .unwrap();
4892 assert_eq!(collector.digest(), vector["expected_motion_digest"]);
4893 }
4894
4895 #[test]
4896 fn heartbeat_build_verify_and_liveness() {
4897 let seed = [21u8; 32];
4898 let kp = Ed25519KeyPair::from_seed(&seed);
4899 let did = "did:web:robot.example.com";
4900 let digest = json!({
4901 "samples": 2, "maxForceN": 20.0, "maxSpeedMps": 0.4,
4902 "maxSpeedNearHumansMps": 0.2, "zoneBreaches": 0, "breachCount": 0,
4903 "withinEnvelope": true
4904 });
4905 let hb = build_robot_heartbeat(
4906 &seed,
4907 &BuildRobotHeartbeat {
4908 robot_did: did.into(),
4909 session_id: "urn:uuid:sess-1".into(),
4910 interval_index: 0,
4911 interval_seconds: 60,
4912 motion_digest: digest,
4913 valid_from: "2026-01-01T00:00:00Z".into(),
4914 },
4915 )
4916 .unwrap();
4917
4918 let subject = verify_robot_heartbeat(&hb, &kp.public_key())
4919 .unwrap()
4920 .expect("heartbeat verifies");
4921 assert_eq!(subject["sessionId"], json!("urn:uuid:sess-1"));
4922
4923 assert!(is_live(&hb, "2026-01-01T00:01:00Z", None, DEFAULT_GRACE_INTERVALS).unwrap());
4925 assert!(!is_live(&hb, "2026-01-01T01:00:00Z", None, DEFAULT_GRACE_INTERVALS).unwrap());
4926
4927 let breached = json!({
4929 "samples": 1, "maxForceN": 99.0, "maxSpeedMps": 0.4,
4930 "maxSpeedNearHumansMps": 0.2, "zoneBreaches": 0, "breachCount": 1,
4931 "withinEnvelope": false
4932 });
4933 let hb2 = build_robot_heartbeat(
4934 &seed,
4935 &BuildRobotHeartbeat {
4936 robot_did: did.into(),
4937 session_id: "s".into(),
4938 interval_index: 1,
4939 interval_seconds: 60,
4940 motion_digest: breached,
4941 valid_from: "2026-01-01T00:00:00Z".into(),
4942 },
4943 )
4944 .unwrap();
4945 assert!(!is_live(&hb2, "2026-01-01T00:00:30Z", None, DEFAULT_GRACE_INTERVALS).unwrap());
4946
4947 let mut tampered = hb.clone();
4949 tampered["credentialSubject"]["sessionId"] = json!("urn:uuid:other");
4950 assert!(verify_robot_heartbeat(&tampered, &kp.public_key())
4951 .unwrap()
4952 .is_none());
4953 }
4954
4955 #[test]
4958 fn safety_log_matches_interop_vector() {
4959 let vector = load_vector();
4960 let mut log = SafetyEventLog::new(None);
4961 log.append(
4962 "near_miss",
4963 "low",
4964 Some(&json!({"zone": "cell-3"})),
4965 None,
4966 "2026-01-01T00:00:00Z",
4967 )
4968 .unwrap();
4969 log.append(
4970 "envelope_breach",
4971 "high",
4972 None,
4973 None,
4974 "2026-01-01T00:01:00Z",
4975 )
4976 .unwrap();
4977
4978 assert_eq!(
4979 Value::Array(log.entries().to_vec()),
4980 vector["safety_log_entries"]
4981 );
4982 assert_eq!(
4983 log.head(),
4984 vector["expected_safety_log_head"].as_str().unwrap()
4985 );
4986 assert_eq!(log.summarize(), vector["expected_safety_summary"]);
4987 assert!(verify_safety_log(log.entries(), None).ok);
4988 }
4989
4990 #[test]
4991 fn safety_record_build_verify_and_tamper() {
4992 let seed = [22u8; 32];
4993 let kp = Ed25519KeyPair::from_seed(&seed);
4994 let mut log = SafetyEventLog::new(None);
4995 log.append("near_miss", "low", None, None, "2026-01-01T00:00:00Z")
4996 .unwrap();
4997 let summary = log.summarize();
4998
4999 let record = build_safety_record(
5000 &seed,
5001 &BuildSafetyRecord {
5002 issuer_did: "did:web:owner.example.com".into(),
5003 robot_did: "did:web:robot.example.com".into(),
5004 summary,
5005 period_start: Some("2026-01-01T00:00:00Z".into()),
5006 period_end: Some("2026-01-31T00:00:00Z".into()),
5007 valid_from: "2026-02-01T00:00:00Z".into(),
5008 valid_until: None,
5009 },
5010 )
5011 .unwrap();
5012
5013 let subject = verify_safety_record(&record, &kp.public_key())
5014 .unwrap()
5015 .expect("safety record verifies");
5016 assert_eq!(subject["totalEvents"], json!(1));
5017 assert_eq!(subject["period"]["start"], json!("2026-01-01T00:00:00Z"));
5018
5019 let mut tampered = record.clone();
5020 tampered["credentialSubject"]["totalEvents"] = json!(99);
5021 assert!(verify_safety_record(&tampered, &kp.public_key())
5022 .unwrap()
5023 .is_none());
5024
5025 let mut entries = log.entries().to_vec();
5027 entries[0]["severity"] = json!("critical");
5028 assert!(!verify_safety_log(&entries, None).ok);
5029 }
5030
5031 #[test]
5033 fn status_entry_matches_interop_vector() {
5034 let vector = load_vector();
5035 let entry = build_status_list_entry(
5036 "https://fleet.example.com/status/1",
5037 42,
5038 STATUS_PURPOSE_REVOCATION,
5039 None,
5040 )
5041 .unwrap();
5042 assert_eq!(entry, vector["expected_credential_status_entry"]);
5043 }
5044
5045 #[test]
5046 fn attach_and_check_credential_status() {
5047 let seed = [23u8; 32];
5048 let kp = Ed25519KeyPair::from_seed(&seed);
5049 let did = "did:web:robot.example.com";
5050
5051 let pass = build_passport(
5053 &seed,
5054 &BuildPassport {
5055 issuer_did: did.into(),
5056 robot_did: did.into(),
5057 make: "Acme".into(),
5058 model: "AR-7".into(),
5059 owner: "did:web:owner.example.com".into(),
5060 authorized_actions: vec!["lift".into()],
5061 certification: None,
5062 status: None,
5063 valid_from: "2026-01-01T00:00:00Z".into(),
5064 valid_until: None,
5065 },
5066 )
5067 .unwrap();
5068
5069 let with_status = attach_credential_status(
5070 &pass,
5071 &seed,
5072 &AttachCredentialStatus {
5073 status_list_credential: "https://fleet.example.com/status/1".into(),
5074 status_list_index: 42,
5075 status_purpose: STATUS_PURPOSE_REVOCATION.into(),
5076 entry_id: None,
5077 created: "2026-01-01T00:00:00Z".into(),
5078 },
5079 )
5080 .unwrap();
5081
5082 assert!(data_integrity::verify_proof(&with_status, &kp.public_key()).unwrap());
5084 assert_eq!(
5085 with_status["credentialStatus"]["statusListIndex"],
5086 json!("42")
5087 );
5088
5089 let mut bits = vec![0u8; crate::status_list::DEFAULT_BITSTRING_LENGTH / 8];
5091 crate::status_list::set_status(&mut bits, 42, true).unwrap();
5092 let encoded = crate::status_list::encode_bitstring(&bits).unwrap();
5093 let status_list = json!({
5094 "id": "https://fleet.example.com/status/1",
5095 "type": ["VerifiableCredential", "BitstringStatusListCredential"],
5096 "credentialSubject": {
5097 "type": "BitstringStatusList",
5098 "statusPurpose": "revocation",
5099 "encodedList": encoded,
5100 }
5101 });
5102 assert!(
5103 check_credential_status(&with_status, &status_list, STATUS_PURPOSE_REVOCATION).unwrap()
5104 );
5105
5106 assert!(!check_credential_status(&pass, &status_list, STATUS_PURPOSE_REVOCATION).unwrap());
5108
5109 let clear_bits = vec![0u8; crate::status_list::DEFAULT_BITSTRING_LENGTH / 8];
5111 let clear_encoded = crate::status_list::encode_bitstring(&clear_bits).unwrap();
5112 let mut clear_list = status_list.clone();
5113 clear_list["credentialSubject"]["encodedList"] = json!(clear_encoded);
5114 assert!(
5115 !check_credential_status(&with_status, &clear_list, STATUS_PURPOSE_REVOCATION).unwrap()
5116 );
5117 }
5118
5119 #[test]
5121 fn frame_hash_matches_interop_vector() {
5122 let vector = load_vector();
5123 let sample_frame: Vec<u8> = (0u8..64).collect();
5124 let got = hash_frame(&sample_frame);
5125 assert_eq!(got, vector["expected_frame_hash"].as_str().unwrap());
5126 assert_eq!(got, "u_eq5rPNxA2K9JljNyaKej5x1f8-YEWA6jER80dkVEQg");
5127 }
5128
5129 #[test]
5132 fn perception_log_matches_interop_vector() {
5133 let vector = load_vector();
5134 let sample_frame: Vec<u8> = (0u8..64).collect();
5135 let mut log = PerceptionLog::new(None);
5136 log.record(
5137 "cam-front",
5138 "camera",
5139 Some(&sample_frame),
5140 None,
5141 "2026-01-01T00:00:00Z",
5142 )
5143 .unwrap();
5144 log.record(
5145 "lidar-top",
5146 "lidar",
5147 None,
5148 Some(&hash_frame(b"scan-0")),
5149 "2026-01-01T00:00:01Z",
5150 )
5151 .unwrap();
5152
5153 assert_eq!(
5154 Value::Array(log.entries().to_vec()),
5155 vector["perception_log_entries"]
5156 );
5157 assert_eq!(
5158 log.head(),
5159 vector["expected_perception_log_head"].as_str().unwrap()
5160 );
5161 assert!(verify_perception_log(log.entries(), None).ok);
5162 }
5163
5164 #[test]
5165 fn perception_record_validation_and_tamper() {
5166 let mut log = PerceptionLog::new(None);
5167 assert!(log
5169 .record("cam", "sonar", Some(b"x"), None, "2026-01-01T00:00:00Z")
5170 .is_err());
5171 assert!(log
5173 .record(
5174 "cam",
5175 "camera",
5176 Some(b"x"),
5177 Some("uABC"),
5178 "2026-01-01T00:00:00Z"
5179 )
5180 .is_err());
5181 assert!(log
5183 .record("cam", "camera", None, None, "2026-01-01T00:00:00Z")
5184 .is_err());
5185 assert!(log
5187 .record("", "camera", Some(b"x"), None, "2026-01-01T00:00:00Z")
5188 .is_err());
5189
5190 log.record(
5191 "cam",
5192 "camera",
5193 Some(b"frame-0"),
5194 None,
5195 "2026-01-01T00:00:00Z",
5196 )
5197 .unwrap();
5198 log.record(
5199 "cam",
5200 "camera",
5201 Some(b"frame-1"),
5202 None,
5203 "2026-01-01T00:00:01Z",
5204 )
5205 .unwrap();
5206 assert!(verify_perception_log(log.entries(), None).ok);
5207
5208 let mut entries = log.entries().to_vec();
5210 entries[0]["frameHash"] = json!("uTAMPERED");
5211 assert!(!verify_perception_log(&entries, None).ok);
5212 }
5213
5214 #[test]
5215 fn perception_attestation_build_verify_and_tamper() {
5216 let seed = [24u8; 32];
5217 let kp = Ed25519KeyPair::from_seed(&seed);
5218 let did = "did:web:robot.example.com";
5219 let frame = b"sensor-frame-bytes";
5220 let frame_hash = hash_frame(frame);
5221
5222 let cred = build_perception_attestation(
5223 &seed,
5224 &BuildPerception {
5225 robot_did: did.into(),
5226 sensor_id: "cam-front".into(),
5227 modality: "camera".into(),
5228 frame_hash: frame_hash.clone(),
5229 captured_at: Some("2026-01-01T00:00:00Z".into()),
5230 log_head: Some("uHEAD".into()),
5231 valid_from: "2026-01-01T00:00:00Z".into(),
5232 valid_until: None,
5233 },
5234 )
5235 .unwrap();
5236
5237 let subject = verify_perception_attestation(&cred, &kp.public_key(), Some(frame))
5239 .unwrap()
5240 .expect("perception attestation verifies");
5241 assert_eq!(subject["sensorId"], json!("cam-front"));
5242 assert_eq!(subject["frameHash"], json!(frame_hash));
5243 assert_eq!(subject["logHead"], json!("uHEAD"));
5244
5245 assert!(verify_perception_attestation(&cred, &kp.public_key(), None)
5247 .unwrap()
5248 .is_some());
5249
5250 assert!(
5252 verify_perception_attestation(&cred, &kp.public_key(), Some(b"other-frame"))
5253 .unwrap()
5254 .is_none()
5255 );
5256
5257 let mut tampered = cred.clone();
5259 tampered["credentialSubject"]["sensorId"] = json!("cam-rear");
5260 assert!(
5261 verify_perception_attestation(&tampered, &kp.public_key(), None)
5262 .unwrap()
5263 .is_none()
5264 );
5265
5266 let mut wrong = cred.clone();
5268 wrong["type"] = json!(["VerifiableCredential"]);
5269 assert!(
5270 verify_perception_attestation(&wrong, &kp.public_key(), None)
5271 .unwrap()
5272 .is_none()
5273 );
5274
5275 assert!(build_perception_attestation(
5277 &seed,
5278 &BuildPerception {
5279 robot_did: did.into(),
5280 sensor_id: "s".into(),
5281 modality: "sonar".into(),
5282 frame_hash: frame_hash.clone(),
5283 captured_at: None,
5284 log_head: None,
5285 valid_from: "2026-01-01T00:00:00Z".into(),
5286 valid_until: None,
5287 },
5288 )
5289 .is_err());
5290 assert!(build_perception_attestation(
5291 &seed,
5292 &BuildPerception {
5293 robot_did: did.into(),
5294 sensor_id: "s".into(),
5295 modality: "camera".into(),
5296 frame_hash: String::new(),
5297 captured_at: None,
5298 log_head: None,
5299 valid_from: "2026-01-01T00:00:00Z".into(),
5300 valid_until: None,
5301 },
5302 )
5303 .is_err());
5304 }
5305
5306 fn jwk_pub(jwk: &Value) -> Vec<u8> {
5307 URL_SAFE_NO_PAD
5308 .decode(jwk["x"].as_str().unwrap())
5309 .expect("base64url JWK x")
5310 }
5311
5312 #[test]
5315 fn verifies_python_lease_interop_vector() {
5316 let vector = load_vector();
5317 let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
5318 let lease = vector["delegation_lease_credential"].clone();
5319
5320 let subject = verify_delegation_lease(&lease, &robot_pub, None, None)
5321 .unwrap()
5322 .expect("the Python lease interop vector must verify in Rust");
5323 assert_eq!(subject["leaseId"], json!("lease-vector-1"));
5324 }
5325
5326 #[test]
5329 fn verifies_python_quorum_interop_vector() {
5330 let vector = load_vector();
5331 let approvals = vector["quorum_approvals"].as_array().unwrap().clone();
5332 let action_id = vector["quorum_action_id"].as_str().unwrap();
5333 let keys: Vec<ApproverKey> = vector["quorum_approver_keys"]
5334 .as_object()
5335 .unwrap()
5336 .iter()
5337 .map(|(did, jwk)| ApproverKey {
5338 did: did.clone(),
5339 public_key: jwk_pub(jwk),
5340 })
5341 .collect();
5342
5343 let (ok, approvers) = verify_action_authorization(
5344 &approvals,
5345 action_id,
5346 "did:web:robot.example.com",
5347 &keys,
5348 2,
5349 None,
5350 None,
5351 )
5352 .unwrap();
5353 assert!(
5354 ok,
5355 "the Python quorum interop vector must authorize in Rust"
5356 );
5357 assert_eq!(approvers.len(), 2);
5358 assert_eq!(approvers[0], "did:web:approver-1.example.com");
5359 assert_eq!(approvers[1], "did:web:approver-2.example.com");
5360 }
5361
5362 #[test]
5363 fn lease_build_verify_permits_and_expiry() {
5364 let seed = [31u8; 32];
5365 let kp = Ed25519KeyPair::from_seed(&seed);
5366 let did = "did:web:robot.example.com";
5367 let scope = json!({
5368 "maxForceN": 80.0, "maxSpeedMps": 2.0, "maxSpeedNearHumansMps": 0.5,
5369 "allowedZones": ["warehouse-a", "dock-3"]
5370 });
5371 let lease = build_delegation_lease(
5372 &seed,
5373 &BuildDelegationLease {
5374 issuer_did: did.into(),
5375 robot_did: did.into(),
5376 lease_id: "lease-1".into(),
5377 scope: scope.clone(),
5378 parent_lease_id: None,
5379 valid_from: "2026-01-01T00:00:00Z".into(),
5380 valid_until: "2026-01-01T01:00:00Z".into(),
5381 },
5382 )
5383 .unwrap();
5384
5385 let subject =
5387 verify_delegation_lease(&lease, &kp.public_key(), Some("2026-01-01T00:30:00Z"), None)
5388 .unwrap()
5389 .expect("lease verifies in window");
5390 assert_eq!(subject["leaseId"], json!("lease-1"));
5391
5392 assert!(lease_permits(
5394 &subject,
5395 &PhysicalAction {
5396 force_n: Some(50.0),
5397 zone: Some("warehouse-a".into()),
5398 ..Default::default()
5399 },
5400 Some(&lease),
5401 Some("2026-01-01T00:30:00Z"),
5402 ));
5403 assert!(!lease_permits(
5404 &subject,
5405 &PhysicalAction {
5406 force_n: Some(120.0),
5407 ..Default::default()
5408 },
5409 Some(&lease),
5410 Some("2026-01-01T00:30:00Z"),
5411 ));
5412
5413 assert!(verify_delegation_lease(
5415 &lease,
5416 &kp.public_key(),
5417 Some("2026-01-01T02:00:00Z"),
5418 None,
5419 )
5420 .unwrap()
5421 .is_none());
5422 assert!(!lease_permits(
5423 &subject,
5424 &PhysicalAction {
5425 force_n: Some(50.0),
5426 ..Default::default()
5427 },
5428 Some(&lease),
5429 Some("2026-01-01T02:00:00Z"),
5430 ));
5431
5432 let mut tampered = lease.clone();
5434 tampered["credentialSubject"]["leaseId"] = json!("lease-other");
5435 assert!(
5436 verify_delegation_lease(&tampered, &kp.public_key(), None, None)
5437 .unwrap()
5438 .is_none()
5439 );
5440 }
5441
5442 #[test]
5443 fn lease_sub_grant_attenuation() {
5444 let parent_seed = [32u8; 32];
5445 let child_seed = [33u8; 32];
5446 let parent_kp = Ed25519KeyPair::from_seed(&parent_seed);
5447 let child_kp = Ed25519KeyPair::from_seed(&child_seed);
5448 let parent_scope = json!({
5449 "maxForceN": 80.0, "maxSpeedMps": 2.0,
5450 "allowedZones": ["warehouse-a", "dock-3"]
5451 });
5452
5453 let narrower = build_delegation_lease(
5455 &child_seed,
5456 &BuildDelegationLease {
5457 issuer_did: "did:web:integrator.example.com".into(),
5458 robot_did: "did:web:robot.example.com".into(),
5459 lease_id: "lease-2".into(),
5460 scope: json!({
5461 "maxForceN": 50.0, "maxSpeedMps": 1.0,
5462 "allowedZones": ["warehouse-a"]
5463 }),
5464 parent_lease_id: Some("lease-1".into()),
5465 valid_from: "2026-01-01T00:00:00Z".into(),
5466 valid_until: "2026-01-01T01:00:00Z".into(),
5467 },
5468 )
5469 .unwrap();
5470 assert!(verify_delegation_lease(
5471 &narrower,
5472 &child_kp.public_key(),
5473 None,
5474 Some(&parent_scope),
5475 )
5476 .unwrap()
5477 .is_some());
5478
5479 let wider = build_delegation_lease(
5482 &parent_seed,
5483 &BuildDelegationLease {
5484 issuer_did: "did:web:integrator.example.com".into(),
5485 robot_did: "did:web:robot.example.com".into(),
5486 lease_id: "lease-3".into(),
5487 scope: json!({
5488 "maxForceN": 200.0, "maxSpeedMps": 1.0,
5489 "allowedZones": ["warehouse-a"]
5490 }),
5491 parent_lease_id: Some("lease-1".into()),
5492 valid_from: "2026-01-01T00:00:00Z".into(),
5493 valid_until: "2026-01-01T01:00:00Z".into(),
5494 },
5495 )
5496 .unwrap();
5497 assert!(verify_delegation_lease(
5498 &wider,
5499 &parent_kp.public_key(),
5500 None,
5501 Some(&parent_scope),
5502 )
5503 .unwrap()
5504 .is_none());
5505 }
5506
5507 #[test]
5508 fn quorum_threshold_and_distinct_counting() {
5509 let s1 = [41u8; 32];
5510 let s2 = [42u8; 32];
5511 let k1 = Ed25519KeyPair::from_seed(&s1);
5512 let k2 = Ed25519KeyPair::from_seed(&s2);
5513 let a1 = "did:web:approver-1.example.com";
5514 let a2 = "did:web:approver-2.example.com";
5515 let robot = "did:web:robot.example.com";
5516 let action = "action-x";
5517
5518 let build = |seed: &[u8], did: &str, decision: &str| {
5519 build_action_approval(
5520 seed,
5521 &BuildActionApproval {
5522 approver_did: did.into(),
5523 action_id: action.into(),
5524 robot_did: robot.into(),
5525 decision: decision.into(),
5526 valid_from: "2026-01-01T00:00:00Z".into(),
5527 valid_until: None,
5528 },
5529 )
5530 .unwrap()
5531 };
5532
5533 let ap1 = build(&s1, a1, APPROVE);
5534 let ap2 = build(&s2, a2, APPROVE);
5535 let keys = vec![
5536 ApproverKey {
5537 did: a1.into(),
5538 public_key: k1.public_key().to_vec(),
5539 },
5540 ApproverKey {
5541 did: a2.into(),
5542 public_key: k2.public_key().to_vec(),
5543 },
5544 ];
5545
5546 let (ok, approvers) =
5548 verify_action_authorization(&[ap1.clone(), ap2], action, robot, &keys, 2, None, None)
5549 .unwrap();
5550 assert!(ok);
5551 assert_eq!(approvers, vec![a1.to_string(), a2.to_string()]);
5552
5553 let dup = build(&s1, a1, APPROVE);
5555 let (ok2, approvers2) =
5556 verify_action_authorization(&[ap1.clone(), dup], action, robot, &keys, 2, None, None)
5557 .unwrap();
5558 assert!(!ok2);
5559 assert_eq!(approvers2, vec![a1.to_string()]);
5560
5561 let (ok3, _) =
5563 verify_action_authorization(&[ap1], action, robot, &keys, 2, None, None).unwrap();
5564 assert!(!ok3);
5565
5566 let rej = build(&s1, a1, REJECT);
5568 let approve2 = build(&s2, a2, APPROVE);
5569 let (ok4, approvers4) =
5570 verify_action_authorization(&[rej, approve2], action, robot, &keys, 2, None, None)
5571 .unwrap();
5572 assert!(!ok4);
5573 assert_eq!(approvers4, vec![a2.to_string()]);
5574 }
5575
5576 #[test]
5579 fn verifies_python_ownership_transfer_interop_vector() {
5580 let vector = load_vector();
5581 let owner_pub = jwk_pub(&vector["ownership_transfer_owner_key"]);
5582 let cred = vector["ownership_transfer_credential"].clone();
5583
5584 let subject = verify_ownership_transfer(&cred, &owner_pub)
5585 .unwrap()
5586 .expect("the Python ownership-transfer interop vector must verify in Rust");
5587 assert_eq!(subject["toOwner"], json!("did:web:owner-b.example.com"));
5588 }
5589
5590 #[test]
5593 fn verifies_python_key_rotation_interop_vector() {
5594 let vector = load_vector();
5595 let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
5596 let cred = vector["key_rotation_credential"].clone();
5597
5598 let subject = verify_key_rotation(&cred, &robot_pub)
5599 .unwrap()
5600 .expect("the Python key-rotation interop vector must verify in Rust");
5601 assert_eq!(
5602 subject["newKey"],
5603 json!("z6MkmtWtY63GQVBrpMyRJWEzsnxfsGkemu6CtMDwGTv4RYj2")
5604 );
5605 }
5606
5607 #[test]
5610 fn verifies_python_decommission_interop_vector() {
5611 let vector = load_vector();
5612 let authority_pub = jwk_pub(&vector["decommission_authority_key"]);
5613 let cred = vector["decommission_credential"].clone();
5614
5615 let subject = verify_decommission(&cred, &authority_pub, None)
5616 .unwrap()
5617 .expect("the Python decommission interop vector must verify in Rust");
5618 assert_eq!(subject["reason"], json!("end of service life"));
5619 assert_eq!(subject["finalDisposition"], json!("recycled"));
5620 }
5621
5622 #[test]
5623 fn ownership_transfer_roundtrip_and_issuer_rule() {
5624 let owner_a_seed = [51u8; 32];
5625 let owner_b_seed = [52u8; 32];
5626 let a = Ed25519KeyPair::from_seed(&owner_a_seed);
5627 let b = Ed25519KeyPair::from_seed(&owner_b_seed);
5628 let owner_a = "did:web:owner-a.example.com";
5629 let owner_b = "did:web:owner-b.example.com";
5630 let robot = "did:web:robot.example.com";
5631
5632 let transfer = build_ownership_transfer(
5633 &owner_a_seed,
5634 &BuildOwnershipTransfer {
5635 issuer_did: owner_a.into(),
5636 robot_did: robot.into(),
5637 to_owner: owner_b.into(),
5638 from_owner: None,
5639 prev_transfer_id: None,
5640 valid_from: "2026-01-01T00:00:00Z".into(),
5641 },
5642 )
5643 .unwrap();
5644
5645 let subject = verify_ownership_transfer(&transfer, &a.public_key())
5646 .unwrap()
5647 .expect("transfer verifies under the current owner key");
5648 assert_eq!(subject["fromOwner"], json!(owner_a));
5649 assert_eq!(subject["toOwner"], json!(owner_b));
5650
5651 let mut wrong = transfer.clone();
5653 wrong["type"] = json!(["VerifiableCredential"]);
5654 assert!(verify_ownership_transfer(&wrong, &a.public_key())
5655 .unwrap()
5656 .is_none());
5657
5658 let forged = build_ownership_transfer(
5662 &owner_b_seed,
5663 &BuildOwnershipTransfer {
5664 issuer_did: owner_b.into(),
5665 robot_did: robot.into(),
5666 to_owner: "did:web:owner-c.example.com".into(),
5667 from_owner: Some(owner_a.into()),
5669 prev_transfer_id: None,
5670 valid_from: "2026-01-01T00:00:00Z".into(),
5671 },
5672 )
5673 .unwrap();
5674 assert!(verify_ownership_transfer(&forged, &b.public_key())
5675 .unwrap()
5676 .is_none());
5677 }
5678
5679 #[test]
5680 fn custody_chain_links_and_rejects() {
5681 let owner_a_seed = [51u8; 32];
5682 let owner_b_seed = [52u8; 32];
5683 let owner_c_seed = [53u8; 32];
5684 let a = Ed25519KeyPair::from_seed(&owner_a_seed);
5685 let b = Ed25519KeyPair::from_seed(&owner_b_seed);
5686 let c = Ed25519KeyPair::from_seed(&owner_c_seed);
5687 let owner_a = "did:web:owner-a.example.com";
5688 let owner_b = "did:web:owner-b.example.com";
5689 let owner_c = "did:web:owner-c.example.com";
5690 let robot = "did:web:robot.example.com";
5691
5692 let t1 = build_ownership_transfer(
5693 &owner_a_seed,
5694 &BuildOwnershipTransfer {
5695 issuer_did: owner_a.into(),
5696 robot_did: robot.into(),
5697 to_owner: owner_b.into(),
5698 from_owner: None,
5699 prev_transfer_id: None,
5700 valid_from: "2026-01-01T00:00:00Z".into(),
5701 },
5702 )
5703 .unwrap();
5704 let t2 = build_ownership_transfer(
5705 &owner_b_seed,
5706 &BuildOwnershipTransfer {
5707 issuer_did: owner_b.into(),
5708 robot_did: robot.into(),
5709 to_owner: owner_c.into(),
5710 from_owner: None,
5711 prev_transfer_id: Some("transfer-1".into()),
5712 valid_from: "2026-02-01T00:00:00Z".into(),
5713 },
5714 )
5715 .unwrap();
5716
5717 let keys = vec![
5718 OwnerKey {
5719 did: owner_a.into(),
5720 public_key: a.public_key().to_vec(),
5721 },
5722 OwnerKey {
5723 did: owner_b.into(),
5724 public_key: b.public_key().to_vec(),
5725 },
5726 OwnerKey {
5727 did: owner_c.into(),
5728 public_key: c.public_key().to_vec(),
5729 },
5730 ];
5731
5732 let (ok, current) =
5734 verify_custody_chain(&[t1.clone(), t2.clone()], &keys, Some(owner_a)).unwrap();
5735 assert!(ok);
5736 assert_eq!(current.as_deref(), Some(owner_c));
5737
5738 let (bad_origin, _) =
5740 verify_custody_chain(&[t1.clone(), t2.clone()], &keys, Some(owner_c)).unwrap();
5741 assert!(!bad_origin);
5742
5743 let (gap, _) =
5745 verify_custody_chain(std::slice::from_ref(&t2), &keys, Some(owner_a)).unwrap();
5746 assert!(!gap);
5747
5748 let partial = vec![OwnerKey {
5750 did: owner_a.into(),
5751 public_key: a.public_key().to_vec(),
5752 }];
5753 let (no_key, _) = verify_custody_chain(&[t1, t2], &partial, Some(owner_a)).unwrap();
5754 assert!(!no_key);
5755 }
5756
5757 #[test]
5758 fn key_rotation_roundtrip_and_history() {
5759 let k1_seed = [61u8; 32];
5760 let k2_seed = [62u8; 32];
5761 let k3_seed = [63u8; 32];
5762 let k1 = Ed25519KeyPair::from_seed(&k1_seed);
5763 let k2 = Ed25519KeyPair::from_seed(&k2_seed);
5764 let k3 = Ed25519KeyPair::from_seed(&k3_seed);
5765 let robot = "did:web:robot.example.com";
5766
5767 let r1 = build_key_rotation(
5769 &k1_seed,
5770 &BuildKeyRotation {
5771 robot_did: robot.into(),
5772 new_key_multibase: k2.public_multikey(),
5773 reason: Some("scheduled rotation".into()),
5774 valid_from: "2026-01-01T00:00:00Z".into(),
5775 },
5776 )
5777 .unwrap();
5778
5779 let subject = verify_key_rotation(&r1, &k1.public_key())
5780 .unwrap()
5781 .expect("rotation verifies under the old key");
5782 assert_eq!(subject["previousKey"], json!(k1.public_multikey()));
5783 assert_eq!(subject["newKey"], json!(k2.public_multikey()));
5784
5785 assert!(verify_key_rotation(&r1, &k2.public_key())
5787 .unwrap()
5788 .is_none());
5789
5790 let mut wrong = r1.clone();
5792 wrong["type"] = json!(["VerifiableCredential"]);
5793 assert!(verify_key_rotation(&wrong, &k1.public_key())
5794 .unwrap()
5795 .is_none());
5796
5797 let r2 = build_key_rotation(
5799 &k2_seed,
5800 &BuildKeyRotation {
5801 robot_did: robot.into(),
5802 new_key_multibase: k3.public_multikey(),
5803 reason: None,
5804 valid_from: "2026-02-01T00:00:00Z".into(),
5805 },
5806 )
5807 .unwrap();
5808
5809 let public_keys = vec![
5810 KeyEntry {
5811 multibase: k1.public_multikey(),
5812 public_key: k1.public_key().to_vec(),
5813 },
5814 KeyEntry {
5815 multibase: k2.public_multikey(),
5816 public_key: k2.public_key().to_vec(),
5817 },
5818 KeyEntry {
5819 multibase: k3.public_multikey(),
5820 public_key: k3.public_key().to_vec(),
5821 },
5822 ];
5823
5824 let (ok, current) = verify_key_history(
5825 &[r1.clone(), r2.clone()],
5826 &k1.public_multikey(),
5827 &public_keys,
5828 )
5829 .unwrap();
5830 assert!(ok);
5831 assert_eq!(current.as_deref(), Some(k3.public_multikey().as_str()));
5832
5833 let (bad_origin, _) =
5835 verify_key_history(&[r1, r2], &k3.public_multikey(), &public_keys).unwrap();
5836 assert!(!bad_origin);
5837 }
5838
5839 #[test]
5840 fn decommission_roundtrip_and_trusted_authority() {
5841 let seed = [71u8; 32];
5842 let kp = Ed25519KeyPair::from_seed(&seed);
5843 let authority = "did:web:authority.example.com";
5844 let robot = "did:web:robot.example.com";
5845
5846 let cred = build_decommission(
5847 &seed,
5848 &BuildDecommission {
5849 issuer_did: authority.into(),
5850 robot_did: robot.into(),
5851 reason: "end of service life".into(),
5852 final_disposition: Some("recycled".into()),
5853 valid_from: "2026-01-01T00:00:00Z".into(),
5854 valid_until: None,
5855 },
5856 )
5857 .unwrap();
5858
5859 let mut trusted = HashSet::new();
5860 trusted.insert(authority.to_string());
5861 let subject = verify_decommission(&cred, &kp.public_key(), Some(&trusted))
5862 .unwrap()
5863 .expect("a trusted authority decommission verifies");
5864 assert_eq!(subject["decommissionedBy"], json!(authority));
5865
5866 let mut other = HashSet::new();
5868 other.insert("did:web:someone-else.example.com".to_string());
5869 assert!(verify_decommission(&cred, &kp.public_key(), Some(&other))
5870 .unwrap()
5871 .is_none());
5872
5873 assert!(verify_decommission(&cred, &kp.public_key(), None)
5875 .unwrap()
5876 .is_some());
5877
5878 let mut wrong = cred.clone();
5880 wrong["type"] = json!(["VerifiableCredential"]);
5881 assert!(verify_decommission(&wrong, &kp.public_key(), None)
5882 .unwrap()
5883 .is_none());
5884
5885 assert!(build_decommission(
5887 &seed,
5888 &BuildDecommission {
5889 issuer_did: authority.into(),
5890 robot_did: robot.into(),
5891 reason: String::new(),
5892 final_disposition: None,
5893 valid_from: "2026-01-01T00:00:00Z".into(),
5894 valid_until: None,
5895 },
5896 )
5897 .is_err());
5898 }
5899
5900 #[test]
5903 fn conformance_matches_interop_vector() {
5904 let vector = load_vector();
5905 let credentials: Vec<Value> = vector["conformance_credentials"]
5906 .as_array()
5907 .expect("conformance_credentials present")
5908 .clone();
5909 let profile_id = vector["conformance_profile_id"].as_str().unwrap();
5910
5911 let report = check_conformance(&credentials, profile_id).unwrap();
5912 assert_eq!(report, vector["expected_conformance_report"]);
5913
5914 let digest = report_digest(&report);
5915 assert_eq!(
5916 digest,
5917 vector["expected_conformance_report_digest"]
5918 .as_str()
5919 .unwrap()
5920 );
5921 }
5922
5923 #[test]
5924 fn conformance_unknown_profile_and_missing_field() {
5925 assert!(check_conformance(&[], "no-such-profile").is_err());
5926
5927 let empty = check_conformance(&[], "eu-ai-act-high-risk").unwrap();
5929 assert_eq!(empty["conforms"], json!(false));
5930 assert_eq!(empty["satisfiedCount"], json!(0));
5931 assert_eq!(empty["totalCount"], json!(4));
5932
5933 let creds = vec![json!({
5936 "type": ["VerifiableCredential", "RobotSafetyRecordCredential"],
5937 "credentialSubject": { "id": "did:web:robot.example.com", "totalEvents": 2 }
5938 })];
5939 let report = check_conformance(&creds, "eu-ai-act-high-risk").unwrap();
5940 let record_keeping = report["requirements"]
5941 .as_array()
5942 .unwrap()
5943 .iter()
5944 .find(|r| r["id"] == json!("eu-aia-record-keeping"))
5945 .unwrap();
5946 assert_eq!(record_keeping["satisfied"], json!(false));
5947
5948 let zone_creds = vec![json!({
5950 "type": ["VerifiableCredential", "PhysicalCapabilityScope"],
5951 "credentialSubject": {
5952 "id": "did:web:robot.example.com",
5953 "physicalScope": { "maxSpeedMps": 1.5, "allowedZones": [] }
5954 }
5955 })];
5956 let ul = check_conformance(&zone_creds, "ul-3300").unwrap();
5957 let limits = ul["requirements"]
5958 .as_array()
5959 .unwrap()
5960 .iter()
5961 .find(|r| r["id"] == json!("ul3300-operating-limits"))
5962 .unwrap();
5963 assert_eq!(limits["satisfied"], json!(false));
5964 }
5965
5966 #[test]
5967 fn conformance_attestation_roundtrip_and_rejections() {
5968 let seed = [77u8; 32];
5969 let kp = Ed25519KeyPair::from_seed(&seed);
5970 let vector = load_vector();
5971 let credentials: Vec<Value> = vector["conformance_credentials"]
5972 .as_array()
5973 .unwrap()
5974 .clone();
5975 let report = check_conformance(&credentials, "eu-ai-act-high-risk").unwrap();
5976
5977 let att = build_conformance_attestation(
5978 &seed,
5979 &BuildConformanceAttestation {
5980 issuer_did: "did:web:authority.example.com".into(),
5981 robot_did: "did:web:robot.example.com".into(),
5982 report: report.clone(),
5983 valid_from: "2026-01-01T00:00:00Z".into(),
5984 valid_until: Some("2027-01-01T00:00:00Z".into()),
5985 },
5986 )
5987 .unwrap();
5988
5989 let subject = verify_conformance_attestation(&att, &kp.public_key())
5991 .unwrap()
5992 .expect("a valid conformance attestation verifies");
5993 assert_eq!(subject["profileId"], json!("eu-ai-act-high-risk"));
5994 assert_eq!(subject["conforms"], json!(true));
5995 assert_eq!(
5996 subject["reportDigest"],
5997 vector["expected_conformance_report_digest"]
5998 );
5999
6000 let wrong_kp = Ed25519KeyPair::from_seed(&[88u8; 32]);
6002 assert!(verify_conformance_attestation(&att, &wrong_kp.public_key())
6003 .unwrap()
6004 .is_none());
6005
6006 let mut tampered = att.clone();
6008 tampered["credentialSubject"]["report"]["conforms"] = json!(false);
6009 assert!(verify_conformance_attestation(&tampered, &kp.public_key())
6010 .unwrap()
6011 .is_none());
6012
6013 let mut wrong_type = att.clone();
6015 wrong_type["type"] = json!(["VerifiableCredential"]);
6016 assert!(
6017 verify_conformance_attestation(&wrong_type, &kp.public_key())
6018 .unwrap()
6019 .is_none()
6020 );
6021
6022 assert!(build_conformance_attestation(
6024 &seed,
6025 &BuildConformanceAttestation {
6026 issuer_did: "did:web:authority.example.com".into(),
6027 robot_did: String::new(),
6028 report,
6029 valid_from: "2026-01-01T00:00:00Z".into(),
6030 valid_until: None,
6031 },
6032 )
6033 .is_err());
6034 }
6035
6036 fn classical_robot_credential(issuer: &str, seed: &[u8]) -> Value {
6039 let cred = json!({
6040 "@context": [VC_CONTEXT_V2, VOUCH_CONTEXT_V1],
6041 "type": ["VerifiableCredential", ROBOT_IDENTITY_TYPE],
6042 "issuer": issuer,
6043 "validFrom": "2026-01-01T00:00:00Z",
6044 "credentialSubject": {
6045 "id": issuer,
6046 "make": "Acme Robotics",
6047 "model": "AR-7",
6048 "serial": "SN-000123"
6049 }
6050 });
6051 let opts = BuildProofOptions::new(format!("{issuer}#key-1"), "2026-01-01T00:00:00Z");
6052 data_integrity::sign(&cred, seed, &opts).unwrap()
6053 }
6054
6055 #[test]
6058 fn verifies_python_pq_robot_identity_interop_vector() {
6059 let vector = load_vector();
6060 let ed_pub = jwk_pub(&vector["robot_public_key_jwk"]);
6061 let ml_multikey = vector["robot_mldsa44_public_multikey"].as_str().unwrap();
6062 let cred = vector["pq_robot_identity_credential"].clone();
6063
6064 assert!(is_pq(&cred));
6066
6067 let ok = verify_robot_credential(&cred, &ed_pub, Some(ml_multikey.as_bytes()))
6069 .expect("the Python hybrid PQ interop vector must verify in Rust");
6070 assert!(ok);
6071
6072 let resolved = mldsa44_public_from_multikey(ml_multikey).unwrap();
6074 assert!(verify_pq(&cred, &ed_pub, &resolved).unwrap());
6075 }
6076
6077 #[test]
6078 fn pq_sign_verify_roundtrip_and_rejects() {
6079 let issuer = "did:web:robot.example.com";
6080 let seed = [21u8; 32];
6081 let kp = Ed25519KeyPair::from_seed(&seed);
6082 let ml = MlDsa44KeyPair::generate().unwrap();
6083
6084 let classical = classical_robot_credential(issuer, &seed);
6085 assert!(!is_pq(&classical));
6086
6087 let signed = sign_pq(&classical, &seed, &ml, "2026-02-01T00:00:00Z").unwrap();
6089 assert!(is_pq(&signed));
6090 assert!(signed["proof"].is_object());
6091 assert_eq!(signed["proof"]["cryptosuite"], json!(HYBRID_CRYPTOSUITE));
6092
6093 assert!(verify_pq(&signed, &kp.public_key(), &ml.public_key()).unwrap());
6095 assert!(
6096 verify_robot_credential(&signed, &kp.public_key(), Some(&ml.public_key())).unwrap()
6097 );
6098
6099 let ml_mk = multikey::encode_mldsa44_public(&ml.public_key()).unwrap();
6101 assert!(
6102 verify_robot_credential(&signed, &kp.public_key(), Some(ml_mk.as_bytes())).unwrap()
6103 );
6104
6105 let mut tampered = signed.clone();
6107 tampered["credentialSubject"]["model"] = json!("AR-9");
6108 assert!(!verify_pq(&tampered, &kp.public_key(), &ml.public_key()).unwrap());
6109
6110 let other_ed = Ed25519KeyPair::from_seed(&[99u8; 32]);
6112 assert!(!verify_pq(&signed, &other_ed.public_key(), &ml.public_key()).unwrap());
6113
6114 let other_ml = MlDsa44KeyPair::generate().unwrap();
6116 assert!(!verify_pq(&signed, &kp.public_key(), &other_ml.public_key()).unwrap());
6117
6118 assert!(!verify_robot_credential(&signed, &kp.public_key(), None).unwrap());
6120 }
6121
6122 #[test]
6123 fn classical_credential_passes_dual_verify_without_pq_key() {
6124 let issuer = "did:web:robot.example.com";
6125 let seed = [22u8; 32];
6126 let kp = Ed25519KeyPair::from_seed(&seed);
6127 let classical = classical_robot_credential(issuer, &seed);
6128
6129 assert!(!is_pq(&classical));
6130 assert!(verify_robot_credential(&classical, &kp.public_key(), None).unwrap());
6132
6133 let other = Ed25519KeyPair::from_seed(&[7u8; 32]);
6135 assert!(!verify_robot_credential(&classical, &other.public_key(), None).unwrap());
6136 }
6137
6138 #[test]
6139 fn migrate_to_pq_resigns_classical_credential() {
6140 let issuer = "did:web:robot.example.com";
6141 let seed = [23u8; 32];
6142 let kp = Ed25519KeyPair::from_seed(&seed);
6143 let ml = MlDsa44KeyPair::generate().unwrap();
6144
6145 let classical = classical_robot_credential(issuer, &seed);
6146 assert!(verify_robot_credential(&classical, &kp.public_key(), None).unwrap());
6147
6148 let migrated = migrate_to_pq(&classical, &seed, &ml, "2026-03-01T00:00:00Z").unwrap();
6149 assert!(is_pq(&migrated));
6150 assert_eq!(
6152 migrated["credentialSubject"],
6153 classical["credentialSubject"]
6154 );
6155 assert!(
6156 verify_robot_credential(&migrated, &kp.public_key(), Some(&ml.public_key())).unwrap()
6157 );
6158 }
6159
6160 #[test]
6163 fn verifies_python_embodiment_interop_vector() {
6164 let vector = load_vector();
6165 let agent_pub = jwk_pub(&vector["embodiment_agent_key"]);
6166 let chain: Vec<Value> = vector["embodiment_chain"]
6167 .as_array()
6168 .expect("embodiment_chain array")
6169 .clone();
6170
6171 let (ok, current) = verify_continuity_chain(&chain, &agent_pub, None).unwrap();
6172 assert!(ok, "the Python embodiment chain must verify in Rust");
6173 assert_eq!(
6174 current.as_deref(),
6175 Some("did:web:body-b.example.com"),
6176 "the chain ends on body-b"
6177 );
6178
6179 let (no_fork, conflict) = check_no_fork(&chain).unwrap();
6180 assert!(no_fork, "the Python embodiment chain has no fork");
6181 assert!(conflict.is_none());
6182 }
6183
6184 #[test]
6185 fn embodiment_roundtrip_and_issuer_rule() {
6186 let agent_seed = [61u8; 32];
6187 let other_seed = [62u8; 32];
6188 let agent = Ed25519KeyPair::from_seed(&agent_seed);
6189 let other = Ed25519KeyPair::from_seed(&other_seed);
6190 let agent_did = "did:web:agent.example.com";
6191 let body_a = "did:web:body-a.example.com";
6192
6193 let cred = build_embodiment(
6194 &agent_seed,
6195 &BuildEmbodiment {
6196 agent_did: agent_did.into(),
6197 body_did: body_a.into(),
6198 body_hardware_root: "uROOTA".into(),
6199 from_body: None,
6200 embodied_at: "2026-01-01T00:00:00Z".into(),
6201 valid_until: None,
6202 },
6203 )
6204 .unwrap();
6205
6206 let subject = verify_embodiment(&cred, &agent.public_key())
6207 .unwrap()
6208 .expect("embodiment verifies under the agent key");
6209 assert_eq!(subject["body"], json!(body_a));
6210 assert_eq!(subject["bodyHardwareRoot"], json!("uROOTA"));
6211
6212 let forged = {
6217 let mut bare = cred.clone();
6218 bare.as_object_mut().unwrap().remove("proof");
6219 bare["issuer"] = json!("did:web:impostor.example.com");
6220 let opts = BuildProofOptions::new(
6221 "did:web:impostor.example.com#key-1".to_string(),
6222 "2026-01-01T00:00:00Z",
6223 );
6224 data_integrity::sign(&bare, &other_seed, &opts).unwrap()
6225 };
6226 assert!(verify_embodiment(&forged, &other.public_key())
6227 .unwrap()
6228 .is_none());
6229 }
6230
6231 #[test]
6232 fn continuity_chain_links_and_rejects() {
6233 let agent_seed = [61u8; 32];
6234 let stranger_seed = [63u8; 32];
6235 let agent = Ed25519KeyPair::from_seed(&agent_seed);
6236 let stranger = Ed25519KeyPair::from_seed(&stranger_seed);
6237 let agent_did = "did:web:agent.example.com";
6238 let body_a = "did:web:body-a.example.com";
6239 let body_b = "did:web:body-b.example.com";
6240
6241 let e1 = build_embodiment(
6242 &agent_seed,
6243 &BuildEmbodiment {
6244 agent_did: agent_did.into(),
6245 body_did: body_a.into(),
6246 body_hardware_root: "uROOTA".into(),
6247 from_body: None,
6248 embodied_at: "2026-01-01T00:00:00Z".into(),
6249 valid_until: Some("2026-01-01T01:00:00Z".into()),
6250 },
6251 )
6252 .unwrap();
6253 let e2 = build_embodiment(
6254 &agent_seed,
6255 &BuildEmbodiment {
6256 agent_did: agent_did.into(),
6257 body_did: body_b.into(),
6258 body_hardware_root: "uROOTB".into(),
6259 from_body: Some(body_a.into()),
6260 embodied_at: "2026-01-01T01:00:00Z".into(),
6261 valid_until: None,
6262 },
6263 )
6264 .unwrap();
6265
6266 let (ok, current) =
6269 verify_continuity_chain(&[e1.clone(), e2.clone()], &agent.public_key(), None).unwrap();
6270 assert!(ok);
6271 assert_eq!(current.as_deref(), Some(body_b));
6272
6273 let (bad_origin, _) =
6276 verify_continuity_chain(&[e1.clone(), e2.clone()], &agent.public_key(), Some(body_b))
6277 .unwrap();
6278 assert!(!bad_origin);
6279
6280 let broken = build_embodiment(
6283 &agent_seed,
6284 &BuildEmbodiment {
6285 agent_did: agent_did.into(),
6286 body_did: body_b.into(),
6287 body_hardware_root: "uROOTB".into(),
6288 from_body: Some("did:web:body-x.example.com".into()),
6289 embodied_at: "2026-01-01T01:00:00Z".into(),
6290 valid_until: None,
6291 },
6292 )
6293 .unwrap();
6294 let (bad_link, _) =
6295 verify_continuity_chain(&[e1.clone(), broken], &agent.public_key(), None).unwrap();
6296 assert!(!bad_link);
6297
6298 let e2_stranger = build_embodiment(
6301 &stranger_seed,
6302 &BuildEmbodiment {
6303 agent_did: agent_did.into(),
6304 body_did: body_b.into(),
6305 body_hardware_root: "uROOTB".into(),
6306 from_body: Some(body_a.into()),
6307 embodied_at: "2026-01-01T01:00:00Z".into(),
6308 valid_until: None,
6309 },
6310 )
6311 .unwrap();
6312 assert!(verify_embodiment(&e2_stranger, &stranger.public_key())
6313 .unwrap()
6314 .is_some());
6315 let (mixed_keys, _) =
6316 verify_continuity_chain(&[e1, e2_stranger], &agent.public_key(), None).unwrap();
6317 assert!(!mixed_keys);
6318 }
6319
6320 #[test]
6321 fn fork_detection_flags_overlapping_bodies() {
6322 let agent_seed = [61u8; 32];
6323 let agent_did = "did:web:agent.example.com";
6324 let body_a = "did:web:body-a.example.com";
6325 let body_b = "did:web:body-b.example.com";
6326
6327 let build = |body: &str, root: &str, from: &str, until: &str| {
6328 build_embodiment(
6329 &agent_seed,
6330 &BuildEmbodiment {
6331 agent_did: agent_did.into(),
6332 body_did: body.into(),
6333 body_hardware_root: root.into(),
6334 from_body: None,
6335 embodied_at: from.into(),
6336 valid_until: Some(until.into()),
6337 },
6338 )
6339 .unwrap()
6340 };
6341
6342 let clean_a = build(
6345 body_a,
6346 "uROOTA",
6347 "2026-01-01T00:00:00Z",
6348 "2026-01-01T01:00:00Z",
6349 );
6350 let clean_b = build(
6351 body_b,
6352 "uROOTB",
6353 "2026-01-01T01:00:00Z",
6354 "2026-01-01T02:00:00Z",
6355 );
6356 let (clean, conflict) = check_no_fork(&[clean_a, clean_b]).unwrap();
6357 assert!(clean);
6358 assert!(conflict.is_none());
6359
6360 let fork_a = build(
6363 body_a,
6364 "uROOTA",
6365 "2026-01-01T00:00:00Z",
6366 "2026-01-01T02:00:00Z",
6367 );
6368 let fork_b = build(
6369 body_b,
6370 "uROOTB",
6371 "2026-01-01T01:00:00Z",
6372 "2026-01-01T03:00:00Z",
6373 );
6374 let (forked, conflict) = check_no_fork(&[fork_a, fork_b]).unwrap();
6375 assert!(!forked);
6376 let conflict = conflict.expect("a fork names the two conflicting bodies");
6377 assert_eq!(conflict.body_a, body_a);
6378 assert_eq!(conflict.body_b, body_b);
6379 }
6380
6381 fn actor_keys_from_vector(map: &Value) -> Vec<ActorKey> {
6384 map.as_object()
6385 .expect("custody_actor_keys object")
6386 .iter()
6387 .map(|(did, jwk)| ActorKey {
6388 did: did.clone(),
6389 public_key: jwk_pub(jwk),
6390 })
6391 .collect()
6392 }
6393
6394 #[test]
6398 fn verifies_python_custody_interop_vector() {
6399 let vector = load_vector();
6400 let chain: Vec<Value> = vector["custody_chain"]
6401 .as_array()
6402 .expect("custody_chain array")
6403 .clone();
6404 let keys = actor_keys_from_vector(&vector["custody_actor_keys"]);
6405 let origin = vector["custody_origin_actor"].as_str().unwrap();
6406
6407 let (ok, current) = verify_handoff_chain(&chain, &keys, Some(origin)).unwrap();
6408 assert!(ok, "the Python custody chain must verify in Rust");
6409 assert_eq!(
6410 current.as_deref(),
6411 Some("did:web:robot-b.example.com"),
6412 "the chain ends holding at robot-b"
6413 );
6414
6415 let change = locate_condition_change(&chain).expect("the condition changed");
6416 assert_eq!(
6417 change.responsible_holder.as_deref(),
6418 Some("did:web:robot-a.example.com"),
6419 "robot-a held the task while its condition changed"
6420 );
6421 assert_eq!(change.from_condition, "intact");
6422 assert_eq!(change.to_condition, "damaged");
6423 }
6424
6425 #[test]
6426 fn handoff_roundtrip_and_receiver_rule() {
6427 let robot_seed = [71u8; 32];
6428 let other_seed = [72u8; 32];
6429 let robot = Ed25519KeyPair::from_seed(&robot_seed);
6430 let other = Ed25519KeyPair::from_seed(&other_seed);
6431 let worker = "did:web:worker-jane.example.com";
6432 let robot_a = "did:web:robot-a.example.com";
6433
6434 let cred = build_handoff(
6435 &robot_seed,
6436 &BuildHandoff {
6437 task_id: "tote-42".into(),
6438 from_actor: worker.into(),
6439 to_actor: robot_a.into(),
6440 condition: Some("intact".into()),
6441 handoff_at: "2026-01-01T00:00:00Z".into(),
6442 valid_until: None,
6443 },
6444 )
6445 .unwrap();
6446
6447 let subject = verify_handoff(&cred, &robot.public_key())
6448 .unwrap()
6449 .expect("handoff verifies under the receiver key");
6450 assert_eq!(subject["fromActor"], json!(worker));
6451 assert_eq!(subject["toActor"], json!(robot_a));
6452
6453 let forged = {
6458 let mut bare = cred.clone();
6459 bare.as_object_mut().unwrap().remove("proof");
6460 bare["issuer"] = json!("did:web:impostor.example.com");
6461 let opts = BuildProofOptions::new(
6462 "did:web:impostor.example.com#key-1".to_string(),
6463 "2026-01-01T00:00:00Z",
6464 );
6465 data_integrity::sign(&bare, &other_seed, &opts).unwrap()
6466 };
6467 assert!(verify_handoff(&forged, &other.public_key())
6468 .unwrap()
6469 .is_none());
6470 }
6471
6472 #[test]
6473 fn handoff_chain_links_and_rejects() {
6474 let a_seed = [73u8; 32];
6475 let b_seed = [74u8; 32];
6476 let a = Ed25519KeyPair::from_seed(&a_seed);
6477 let b = Ed25519KeyPair::from_seed(&b_seed);
6478 let worker = "did:web:worker-jane.example.com";
6479 let robot_a = "did:web:robot-a.example.com";
6480 let robot_b = "did:web:robot-b.example.com";
6481
6482 let h1 = build_handoff(
6483 &a_seed,
6484 &BuildHandoff {
6485 task_id: "tote-42".into(),
6486 from_actor: worker.into(),
6487 to_actor: robot_a.into(),
6488 condition: Some("intact".into()),
6489 handoff_at: "2026-01-01T00:00:00Z".into(),
6490 valid_until: None,
6491 },
6492 )
6493 .unwrap();
6494 let h2 = build_handoff(
6495 &b_seed,
6496 &BuildHandoff {
6497 task_id: "tote-42".into(),
6498 from_actor: robot_a.into(),
6499 to_actor: robot_b.into(),
6500 condition: Some("damaged".into()),
6501 handoff_at: "2026-01-01T00:10:00Z".into(),
6502 valid_until: None,
6503 },
6504 )
6505 .unwrap();
6506
6507 let keys = vec![
6508 ActorKey {
6509 did: robot_a.into(),
6510 public_key: a.public_key().to_vec(),
6511 },
6512 ActorKey {
6513 did: robot_b.into(),
6514 public_key: b.public_key().to_vec(),
6515 },
6516 ];
6517
6518 let (ok, current) =
6521 verify_handoff_chain(&[h1.clone(), h2.clone()], &keys, Some(worker)).unwrap();
6522 assert!(ok);
6523 assert_eq!(current.as_deref(), Some(robot_b));
6524
6525 let (bad_origin, _) =
6527 verify_handoff_chain(&[h1.clone(), h2.clone()], &keys, Some(robot_b)).unwrap();
6528 assert!(!bad_origin);
6529
6530 let broken = build_handoff(
6533 &b_seed,
6534 &BuildHandoff {
6535 task_id: "tote-42".into(),
6536 from_actor: "did:web:robot-x.example.com".into(),
6537 to_actor: robot_b.into(),
6538 condition: Some("damaged".into()),
6539 handoff_at: "2026-01-01T00:10:00Z".into(),
6540 valid_until: None,
6541 },
6542 )
6543 .unwrap();
6544 let (bad_link, _) =
6545 verify_handoff_chain(&[h1.clone(), broken], &keys, Some(worker)).unwrap();
6546 assert!(!bad_link);
6547
6548 let partial = vec![ActorKey {
6550 did: robot_a.into(),
6551 public_key: a.public_key().to_vec(),
6552 }];
6553 let (no_key, _) =
6554 verify_handoff_chain(&[h1.clone(), h2.clone()], &partial, Some(worker)).unwrap();
6555 assert!(!no_key);
6556
6557 assert_eq!(
6560 holder_at(&[h1.clone(), h2.clone()], "2026-01-01T00:05:00Z").as_deref(),
6561 Some(robot_a)
6562 );
6563 assert_eq!(
6564 holder_at(&[h1.clone(), h2.clone()], "2026-01-01T00:15:00Z").as_deref(),
6565 Some(robot_b)
6566 );
6567
6568 let steady = build_handoff(
6570 &b_seed,
6571 &BuildHandoff {
6572 task_id: "tote-42".into(),
6573 from_actor: robot_a.into(),
6574 to_actor: robot_b.into(),
6575 condition: Some("intact".into()),
6576 handoff_at: "2026-01-01T00:10:00Z".into(),
6577 valid_until: None,
6578 },
6579 )
6580 .unwrap();
6581 assert!(locate_condition_change(&[h1, steady]).is_none());
6582 }
6583
6584 #[test]
6589 fn authorizes_python_access_interop_vector() {
6590 let vector = load_vector();
6591 let grant = vector["access_grant_credential"].clone();
6592 let request = vector["access_request_credential"].clone();
6593 let operator_pub = jwk_pub(&vector["access_operator_key"]);
6594 let robot_pub = jwk_pub(&vector["access_robot_key"]);
6595
6596 let res = authorize_access(
6597 &grant,
6598 &request,
6599 &operator_pub,
6600 &robot_pub,
6601 Some("2026-01-01T00:05:00Z"),
6602 )
6603 .unwrap();
6604 assert!(
6605 res.ok,
6606 "the Python grant and request must authorize in Rust"
6607 );
6608 assert!(res.reasons.is_empty());
6609 }
6610
6611 #[test]
6616 fn verifies_python_fused_interop_vector() {
6617 let vector = load_vector();
6618 let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
6619
6620 let inputs: Vec<String> = vector["fused_input_frame_hashes"]
6621 .as_array()
6622 .unwrap()
6623 .iter()
6624 .map(|v| v.as_str().unwrap().to_string())
6625 .collect();
6626 assert_eq!(
6627 fusion_inputs_digest(&inputs).unwrap(),
6628 vector["expected_fusion_inputs_digest"].as_str().unwrap()
6629 );
6630
6631 assert_eq!(
6632 hash_fused_output(b"world-model-0"),
6633 vector["expected_fused_output_hash"].as_str().unwrap()
6634 );
6635
6636 let cred = vector["fused_perception_attestation"].clone();
6637 let subject = verify_fused_attestation(&cred, &robot_pub, None)
6638 .unwrap()
6639 .expect("fused attestation verifies");
6640 assert_eq!(subject["fusionMethod"], "occupancy-grid-v1");
6641 assert_eq!(
6642 subject["inputsDigest"].as_str().unwrap(),
6643 vector["expected_fusion_inputs_digest"].as_str().unwrap()
6644 );
6645 }
6646
6647 #[test]
6652 fn verifies_python_wear_interop_vector() {
6653 let vector = load_vector();
6654 let robot_pub = jwk_pub(&vector["robot_public_key_jwk"]);
6655
6656 let chain: Vec<Value> = vector["wear_chain"].as_array().unwrap().clone();
6657 let latest = verify_wear_chain(&chain, &robot_pub)
6658 .unwrap()
6659 .expect("wear chain verifies");
6660 assert_eq!(latest["wearLevel"].as_f64().unwrap(), 0.3);
6661
6662 let scope = vector["wear_input_scope"].clone();
6663 let level = vector["wear_attenuation_level"].as_f64().unwrap();
6664 let narrowed = attenuate_for_wear(&scope, level).unwrap();
6665 assert_eq!(narrowed, vector["expected_attenuated_scope"]);
6666 assert_eq!(narrowed["maxForceN"].as_f64().unwrap(), 60.0);
6667 assert_eq!(narrowed["maxSpeedMps"].as_f64().unwrap(), 1.125);
6668 assert_eq!(narrowed["maxSpeedNearHumansMps"].as_f64().unwrap(), 0.1875);
6669 assert!(attenuates(&scope, &narrowed));
6670 }
6671}