1use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
14
15use crate::governance::consent_contract::ConsentGrant;
16use crate::sensing::acquisition::{self, Derivation, Original};
17use crate::sensing::authorization::{
18 authorize_sensing, AuthorizationError, IdentityAuthority, RevalidatedSensingUse,
19 RevocationAuthority, SensingAction, SensingModality, SensingPermit, SensingRequest,
20 SensingScopeAuthority, TrustedUnixClock,
21};
22use crate::sensing::sidecar_attestation::{
23 SidecarReceipt, SidecarReceiptAuthority, SidecarReceiptError, SIDECAR_BYTES,
24};
25
26#[cfg(not(target_arch = "wasm32"))]
27use crate::sensing::local_custody::{
28 publish_bundle, read_bundle, CustodyAuthority, CustodyError, PublishedBundle, ReadBundle,
29};
30#[cfg(not(target_arch = "wasm32"))]
31use std::path::Path;
32
33pub const AUTHORITY_RECEIPT_DOMAIN: &[u8] = b"QUALIA-SENSING-AUTHORITY-RECEIPT-v1\0";
35
36pub const AUTHORITY_SIGNATURE_DOMAIN: &[u8] = b"QUALIA-SENSING-AUTHORITY-SIG-v1\0";
38
39pub const MAX_RECEIPT_REPLAY_WINDOW: usize = 64;
41
42#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44#[repr(u16)]
45pub enum AuthorityReceiptTarget {
46 ProvenanceSchema4 = 4,
48 AcquisitionDerivationSchema7 = 7,
50 BioContextSchema137 = 137,
52 HapticSchema207 = 207,
54}
55
56impl AuthorityReceiptTarget {
57 pub const fn schema_id(self) -> u16 {
58 self as u16
59 }
60}
61
62#[derive(Clone, Copy, Debug, PartialEq, Eq)]
64pub enum CustodyBridgeError {
65 Authorization(AuthorizationError),
66 InvalidIdentifier,
67 InvalidTimeWindow,
68 InvalidSignature,
69 InvalidSigner,
70 ReceiptDigestMismatch,
71 OriginalDigestMismatch,
72 IndexCommitmentMismatch,
73 SourceIdMismatch,
74 ActorIdMismatch,
75 PurposeHashMismatch,
76 ModalityMismatch,
77 ActionEscalation {
78 granted: SensingAction,
79 requested: SensingAction,
80 },
81 TargetSchemaMismatch {
82 expected: AuthorityReceiptTarget,
83 actual: AuthorityReceiptTarget,
84 },
85 ReplayDetected,
86 ReplayWindowFull,
87 DerivationInputMismatch,
88 SidecarReceipt(SidecarReceiptError),
89}
90
91impl From<AuthorizationError> for CustodyBridgeError {
92 fn from(err: AuthorizationError) -> Self {
93 Self::Authorization(err)
94 }
95}
96
97impl From<SidecarReceiptError> for CustodyBridgeError {
98 fn from(err: SidecarReceiptError) -> Self {
99 Self::SidecarReceipt(err)
100 }
101}
102
103#[derive(Clone, Copy, Debug, PartialEq, Eq)]
105pub struct AuthorityBindingClaims {
106 pub target_schema: AuthorityReceiptTarget,
107 pub grant_id: [u8; 32],
108 pub grant_digest: [u8; 32],
109 pub actor_id: [u8; 32],
110 pub source_id: u64,
111 pub modality: SensingModality,
112 pub action: SensingAction,
113 pub purpose_hash: u64,
114 pub original_blake3: [u8; 32],
115 pub index_commitment: [u8; 32],
116 pub issued_at_unix: u64,
117 pub expires_at_unix: u64,
118 pub receipt_nonce: u64,
119}
120
121impl AuthorityBindingClaims {
122 pub fn validate(&self) -> Result<(), CustodyBridgeError> {
123 if self.grant_id == [0u8; 32]
124 || self.grant_digest == [0u8; 32]
125 || self.actor_id == [0u8; 32]
126 || self.source_id == 0
127 || self.purpose_hash == 0
128 || self.original_blake3 == [0u8; 32]
129 || self.index_commitment == [0u8; 32]
130 || self.receipt_nonce == 0
131 {
132 return Err(CustodyBridgeError::InvalidIdentifier);
133 }
134 if self.issued_at_unix >= self.expires_at_unix {
135 return Err(CustodyBridgeError::InvalidTimeWindow);
136 }
137 Ok(())
138 }
139}
140
141#[derive(Clone, Copy, Debug, PartialEq, Eq)]
144pub struct SignedAuthorityReceipt {
145 claims: AuthorityBindingClaims,
146 signer_public_key: [u8; 32],
147 signature: [u8; 64],
148}
149
150impl SignedAuthorityReceipt {
151 pub fn issue(
155 revalidated: &RevalidatedSensingUse,
156 grant_expires_at_unix: u64,
157 target_schema: AuthorityReceiptTarget,
158 original_blake3: [u8; 32],
159 index_commitment: [u8; 32],
160 receipt_nonce: u64,
161 signing_key: &SigningKey,
162 ) -> Result<Self, CustodyBridgeError> {
163 let req = revalidated.request();
164 let claims = AuthorityBindingClaims {
165 target_schema,
166 grant_id: revalidated.grant_id(),
167 grant_digest: revalidated.grant_digest(),
168 actor_id: req.actor_id(),
169 source_id: req.source_id(),
170 modality: req.modality(),
171 action: req.action(),
172 purpose_hash: req.purpose_hash(),
173 original_blake3,
174 index_commitment,
175 issued_at_unix: revalidated.checked_at_unix(),
176 expires_at_unix: grant_expires_at_unix,
177 receipt_nonce,
178 };
179 claims.validate()?;
180 let signer_public_key = signing_key.verifying_key().to_bytes();
181 let signing_bytes = Self::signing_preimage(&claims, &signer_public_key);
182 let signature = signing_key.sign(&signing_bytes).to_bytes();
183 Ok(Self {
184 claims,
185 signer_public_key,
186 signature,
187 })
188 }
189
190 pub const fn claims(&self) -> &AuthorityBindingClaims {
191 &self.claims
192 }
193
194 pub const fn signer_public_key(&self) -> &[u8; 32] {
195 &self.signer_public_key
196 }
197
198 pub const fn signature(&self) -> &[u8; 64] {
199 &self.signature
200 }
201
202 pub fn receipt_digest(&self) -> [u8; 32] {
204 let mut hasher = blake3::Hasher::new();
205 hasher.update(AUTHORITY_RECEIPT_DOMAIN);
206 Self::hash_claims(&mut hasher, &self.claims);
207 hasher.update(&self.signer_public_key);
208 hasher.update(&self.signature);
209 *hasher.finalize().as_bytes()
210 }
211
212 pub fn verify_signature(&self) -> Result<(), CustodyBridgeError> {
214 self.claims.validate()?;
215 let vk = VerifyingKey::from_bytes(&self.signer_public_key)
216 .map_err(|_| CustodyBridgeError::InvalidSigner)?;
217 let preimage = Self::signing_preimage(&self.claims, &self.signer_public_key);
218 let sig = Signature::from_bytes(&self.signature);
219 vk.verify_strict(&preimage, &sig)
220 .map_err(|_| CustodyBridgeError::InvalidSignature)
221 }
222
223 fn signing_preimage(
224 claims: &AuthorityBindingClaims,
225 signer_public_key: &[u8; 32],
226 ) -> [u8; 32] {
227 let mut hasher = blake3::Hasher::new();
228 hasher.update(AUTHORITY_SIGNATURE_DOMAIN);
229 Self::hash_claims(&mut hasher, claims);
230 hasher.update(signer_public_key);
231 *hasher.finalize().as_bytes()
232 }
233
234 fn hash_claims(hasher: &mut blake3::Hasher, claims: &AuthorityBindingClaims) {
235 hasher.update(&claims.target_schema.schema_id().to_le_bytes());
236 hasher.update(&claims.grant_id);
237 hasher.update(&claims.grant_digest);
238 hasher.update(&claims.actor_id);
239 hasher.update(&claims.source_id.to_le_bytes());
240 hasher.update(&[modality_code(claims.modality), action_code(claims.action)]);
241 hasher.update(&claims.purpose_hash.to_le_bytes());
242 hasher.update(&claims.original_blake3);
243 hasher.update(&claims.index_commitment);
244 hasher.update(&claims.issued_at_unix.to_le_bytes());
245 hasher.update(&claims.expires_at_unix.to_le_bytes());
246 hasher.update(&claims.receipt_nonce.to_le_bytes());
247 }
248}
249
250#[derive(Clone, Copy, Debug, PartialEq, Eq)]
251struct SeenReceiptEntry {
252 receipt_digest: [u8; 32],
253 grant_id: [u8; 32],
254 receipt_nonce: u64,
255 action: SensingAction,
256}
257
258#[derive(Clone, Debug)]
260pub struct ReceiptReplayWindow {
261 entries: [Option<SeenReceiptEntry>; MAX_RECEIPT_REPLAY_WINDOW],
262 len: usize,
263}
264
265impl Default for ReceiptReplayWindow {
266 fn default() -> Self {
267 Self::new()
268 }
269}
270
271impl ReceiptReplayWindow {
272 pub const fn new() -> Self {
273 Self {
274 entries: [None; MAX_RECEIPT_REPLAY_WINDOW],
275 len: 0,
276 }
277 }
278
279 pub const fn len(&self) -> usize {
280 self.len
281 }
282
283 pub const fn is_empty(&self) -> bool {
284 self.len == 0
285 }
286
287 pub fn consume(&mut self, receipt: &SignedAuthorityReceipt) -> Result<[u8; 32], CustodyBridgeError> {
290 let digest = receipt.receipt_digest();
291 let claims = receipt.claims();
292 for slot in self.entries.iter().take(self.len).flatten() {
293 if slot.receipt_digest == digest
294 || (slot.grant_id == claims.grant_id && slot.receipt_nonce == claims.receipt_nonce)
295 {
296 return Err(CustodyBridgeError::ReplayDetected);
297 }
298 }
299 if self.len >= MAX_RECEIPT_REPLAY_WINDOW {
300 return Err(CustodyBridgeError::ReplayWindowFull);
301 }
302 self.entries[self.len] = Some(SeenReceiptEntry {
303 receipt_digest: digest,
304 grant_id: claims.grant_id,
305 receipt_nonce: claims.receipt_nonce,
306 action: claims.action,
307 });
308 self.len += 1;
309 Ok(digest)
310 }
311}
312
313#[derive(Clone, Copy, Debug, PartialEq, Eq)]
315pub struct ExpectedStreamBinding {
316 pub expected_target: AuthorityReceiptTarget,
317 pub stored_receipt_digest: [u8; 32],
318 pub original_blake3: [u8; 32],
319 pub index_commitment: [u8; 32],
320 pub requested_operation: SensingRequest,
321}
322
323#[allow(clippy::too_many_arguments)]
333pub fn verify_and_consume_stream_receipt(
334 receipt: &SignedAuthorityReceipt,
335 binding: &ExpectedStreamBinding,
336 grant: &ConsentGrant,
337 identity: &impl IdentityAuthority,
338 sensor_scope: &impl SensingScopeAuthority,
339 revocations: &impl RevocationAuthority,
340 clock: &mut impl TrustedUnixClock,
341 replay_window: &mut ReceiptReplayWindow,
342) -> Result<RevalidatedSensingUse, CustodyBridgeError> {
343 receipt.verify_signature()?;
344
345 let computed_digest = receipt.receipt_digest();
346 if computed_digest != binding.stored_receipt_digest {
347 return Err(CustodyBridgeError::ReceiptDigestMismatch);
348 }
349
350 let claims = receipt.claims();
351 if claims.target_schema != binding.expected_target {
352 return Err(CustodyBridgeError::TargetSchemaMismatch {
353 expected: binding.expected_target,
354 actual: claims.target_schema,
355 });
356 }
357 if claims.action != binding.requested_operation.action() {
358 return Err(CustodyBridgeError::ActionEscalation {
359 granted: claims.action,
360 requested: binding.requested_operation.action(),
361 });
362 }
363 if claims.source_id != binding.requested_operation.source_id() {
364 return Err(CustodyBridgeError::SourceIdMismatch);
365 }
366 if claims.actor_id != binding.requested_operation.actor_id() {
367 return Err(CustodyBridgeError::ActorIdMismatch);
368 }
369 if claims.purpose_hash != binding.requested_operation.purpose_hash() {
370 return Err(CustodyBridgeError::PurposeHashMismatch);
371 }
372 if claims.modality != binding.requested_operation.modality() {
373 return Err(CustodyBridgeError::ModalityMismatch);
374 }
375 if claims.original_blake3 != binding.original_blake3 {
376 return Err(CustodyBridgeError::OriginalDigestMismatch);
377 }
378 if claims.index_commitment != binding.index_commitment {
379 return Err(CustodyBridgeError::IndexCommitmentMismatch);
380 }
381 if claims.grant_id != grant.grant_id || claims.grant_digest != grant.compute_digest() {
382 return Err(CustodyBridgeError::Authorization(
383 AuthorizationError::InvalidGrant,
384 ));
385 }
386
387 let permit: SensingPermit = authorize_sensing(
388 grant,
389 binding.requested_operation,
390 identity,
391 sensor_scope,
392 revocations,
393 clock,
394 )?;
395 let revalidated = permit.revalidate(grant, identity, sensor_scope, revocations, clock)?;
396 if revalidated.checked_at_unix() >= claims.expires_at_unix {
397 return Err(CustodyBridgeError::Authorization(
398 AuthorizationError::GrantExpired,
399 ));
400 }
401
402 replay_window.consume(receipt)?;
403 Ok(revalidated)
404}
405
406#[allow(clippy::too_many_arguments)]
409pub fn verify_acquisition_original_custody<'a>(
410 original: Original<'a>,
411 index_commitment: [u8; 32],
412 stored_receipt_digest: [u8; 32],
413 target_schema: AuthorityReceiptTarget,
414 receipt: &SignedAuthorityReceipt,
415 requested_operation: SensingRequest,
416 grant: &ConsentGrant,
417 identity: &impl IdentityAuthority,
418 sensor_scope: &impl SensingScopeAuthority,
419 revocations: &impl RevocationAuthority,
420 clock: &mut impl TrustedUnixClock,
421 replay_window: &mut ReceiptReplayWindow,
422) -> Result<(Original<'a>, RevalidatedSensingUse), CustodyBridgeError> {
423 let actual_blake3 = *blake3::hash(original.bytes()).as_bytes();
424 if actual_blake3 != original.digest() {
425 return Err(CustodyBridgeError::OriginalDigestMismatch);
426 }
427 let expected = ExpectedStreamBinding {
428 expected_target: target_schema,
429 stored_receipt_digest,
430 original_blake3: actual_blake3,
431 index_commitment,
432 requested_operation,
433 };
434 let revalidated = verify_and_consume_stream_receipt(
435 receipt,
436 &expected,
437 grant,
438 identity,
439 sensor_scope,
440 revocations,
441 clock,
442 replay_window,
443 )?;
444 Ok((original, revalidated))
445}
446
447#[allow(clippy::too_many_arguments)]
451pub fn verify_acquisition_derivation_custody<'a>(
452 derivation: Derivation<'a>,
453 index_commitment: [u8; 32],
454 stored_receipt_digest: [u8; 32],
455 receipt: &SignedAuthorityReceipt,
456 requested_operation: SensingRequest,
457 grant: &ConsentGrant,
458 identity: &impl IdentityAuthority,
459 sensor_scope: &impl SensingScopeAuthority,
460 revocations: &impl RevocationAuthority,
461 clock: &mut impl TrustedUnixClock,
462 replay_window: &mut ReceiptReplayWindow,
463) -> Result<(Derivation<'a>, RevalidatedSensingUse), CustodyBridgeError> {
464 if requested_operation.action() != SensingAction::Process {
465 return Err(CustodyBridgeError::ActionEscalation {
466 granted: receipt.claims().action,
467 requested: requested_operation.action(),
468 });
469 }
470 for input in derivation.inputs() {
471 let rehashed = *blake3::hash(input.bytes()).as_bytes();
472 if rehashed != input.digest() {
473 return Err(CustodyBridgeError::DerivationInputMismatch);
474 }
475 }
476 let output_digest = *blake3::hash(derivation.output().bytes()).as_bytes();
477 if output_digest != derivation.output().digest() {
478 return Err(CustodyBridgeError::OriginalDigestMismatch);
479 }
480 let expected = ExpectedStreamBinding {
481 expected_target: AuthorityReceiptTarget::AcquisitionDerivationSchema7,
482 stored_receipt_digest,
483 original_blake3: output_digest,
484 index_commitment,
485 requested_operation,
486 };
487 let revalidated = verify_and_consume_stream_receipt(
488 receipt,
489 &expected,
490 grant,
491 identity,
492 sensor_scope,
493 revocations,
494 clock,
495 replay_window,
496 )?;
497 Ok((derivation, revalidated))
498}
499
500pub struct ConsentBoundSidecarAuthority {
503 expected_signer: [u8; 32],
504 expected_policy_commitment: [u8; 32],
505 expected_chain_id: [u8; 32],
506}
507
508impl ConsentBoundSidecarAuthority {
509 pub fn new(
510 authority_receipt: &SignedAuthorityReceipt,
511 expected_chain_id: [u8; 32],
512 ) -> Result<Self, CustodyBridgeError> {
513 authority_receipt.verify_signature()?;
514 if expected_chain_id == [0u8; 32] {
515 return Err(CustodyBridgeError::InvalidIdentifier);
516 }
517 Ok(Self {
518 expected_signer: *authority_receipt.signer_public_key(),
519 expected_policy_commitment: authority_receipt.receipt_digest(),
520 expected_chain_id,
521 })
522 }
523}
524
525impl SidecarReceiptAuthority for ConsentBoundSidecarAuthority {
526 fn permits(
527 &self,
528 receipt: &SidecarReceipt,
529 _sidecar: &[u8; SIDECAR_BYTES],
530 _payload: &[u8],
531 ) -> bool {
532 receipt.signer() == &self.expected_signer
533 && receipt.policy_commitment() == &self.expected_policy_commitment
534 && receipt.chain_id() == &self.expected_chain_id
535 }
536}
537
538#[cfg(not(target_arch = "wasm32"))]
539pub struct LocalCustodyStoreBridge {
542 sidecar_auth: ConsentBoundSidecarAuthority,
543 allowed_checkpoint: Option<[u8; 32]>,
544 max_publish_bytes: usize,
545 publish_consumed: bool,
546}
547
548#[cfg(not(target_arch = "wasm32"))]
549impl LocalCustodyStoreBridge {
550 pub fn for_store(
551 revalidated: RevalidatedSensingUse,
552 authority_receipt: &SignedAuthorityReceipt,
553 expected_chain_id: [u8; 32],
554 allowed_checkpoint: Option<[u8; 32]>,
555 max_publish_bytes: usize,
556 ) -> Result<Self, CustodyBridgeError> {
557 if revalidated.request().action() != SensingAction::Store {
558 return Err(CustodyBridgeError::ActionEscalation {
559 granted: revalidated.request().action(),
560 requested: SensingAction::Store,
561 });
562 }
563 if authority_receipt.claims().action != SensingAction::Store {
564 return Err(CustodyBridgeError::ActionEscalation {
565 granted: authority_receipt.claims().action,
566 requested: SensingAction::Store,
567 });
568 }
569 let sidecar_auth = ConsentBoundSidecarAuthority::new(authority_receipt, expected_chain_id)?;
570 Ok(Self {
571 sidecar_auth,
572 allowed_checkpoint,
573 max_publish_bytes,
574 publish_consumed: false,
575 })
576 }
577
578 pub fn publish_authorized_bundle(
580 &mut self,
581 root: &Path,
582 receipt: &SidecarReceipt,
583 sidecar: &[u8; SIDECAR_BYTES],
584 payload: &[u8],
585 ) -> Result<PublishedBundle, CustodyError> {
586 publish_bundle(
587 root,
588 sidecar,
589 payload,
590 receipt,
591 self.max_publish_bytes,
592 self,
593 )
594 }
595
596 pub fn read_authorized_bundle(
598 &mut self,
599 root: &Path,
600 checkpoint: &[u8; 32],
601 sidecar: &mut [u8; SIDECAR_BYTES],
602 buffer: &mut [u8],
603 ) -> Result<ReadBundle, CustodyError> {
604 read_bundle(
605 root,
606 checkpoint,
607 self.max_publish_bytes,
608 sidecar,
609 buffer,
610 self,
611 )
612 }
613}
614
615#[cfg(not(target_arch = "wasm32"))]
616impl SidecarReceiptAuthority for LocalCustodyStoreBridge {
617 fn permits(
618 &self,
619 receipt: &SidecarReceipt,
620 sidecar: &[u8; SIDECAR_BYTES],
621 payload: &[u8],
622 ) -> bool {
623 self.sidecar_auth.permits(receipt, sidecar, payload)
624 }
625}
626
627#[cfg(not(target_arch = "wasm32"))]
628impl CustodyAuthority for LocalCustodyStoreBridge {
629 fn permit_publish(
630 &mut self,
631 _root: &Path,
632 receipt: &SidecarReceipt,
633 sidecar: &[u8; SIDECAR_BYTES],
634 payload: &[u8],
635 total_bytes: usize,
636 ) -> bool {
637 if self.publish_consumed || total_bytes > self.max_publish_bytes {
638 return false;
639 }
640 if !self.sidecar_auth.permits(receipt, sidecar, payload) {
641 return false;
642 }
643 self.publish_consumed = true;
644 true
645 }
646
647 fn permit_read(&mut self, _root: &Path, checkpoint: &[u8; 32], max_bytes: usize) -> bool {
648 max_bytes <= self.max_publish_bytes
649 && self
650 .allowed_checkpoint
651 .is_some_and(|expected| &expected == checkpoint)
652 }
653}
654
655const fn modality_code(modality: SensingModality) -> u8 {
656 match modality {
657 SensingModality::Wifi => 1,
658 SensingModality::Bluetooth => 2,
659 SensingModality::Cellular => 3,
660 SensingModality::Sdr => 4,
661 SensingModality::Radar => 5,
662 SensingModality::VisibleCamera => 6,
663 SensingModality::NearInfraredCamera => 7,
664 SensingModality::ThermalCamera => 8,
665 SensingModality::Microphone => 9,
666 SensingModality::FieldInstrument => 10,
667 SensingModality::Nfc => 11,
668 }
669}
670
671const fn action_code(action: SensingAction) -> u8 {
672 match action {
673 SensingAction::Acquire => 1,
674 SensingAction::Process => 2,
675 SensingAction::Store => 3,
676 SensingAction::Export => 4,
677 SensingAction::Share => 5,
678 }
679}
680
681pub const fn verify_artifact_link_digest(
683 link: acquisition::ArtifactLink,
684 expected_digest: &[u8; 32],
685) -> bool {
686 link.identifier.value().is_some() && constant_time_eq_32(&link.digest, expected_digest)
687}
688
689const fn constant_time_eq_32(a: &[u8; 32], b: &[u8; 32]) -> bool {
690 let mut diff = 0u8;
691 let mut i = 0;
692 while i < 32 {
693 diff |= a[i] ^ b[i];
694 i += 1;
695 }
696 diff == 0
697}