1use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
11use serde::{Deserialize, Serialize};
12use sha2::{Digest, Sha256};
13
14use crate::modalities::logic::deontic::{DEFEATER_BIT, OP_FORBID, OP_PERMIT};
15use crate::NQuin;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
19pub struct ConsentScope(pub u32);
20
21impl ConsentScope {
22 pub const VITALS: u32 = 1 << 0;
23 pub const LABS: u32 = 1 << 1;
24 pub const CONDITIONS: u32 = 1 << 2;
25 pub const MEDICATIONS: u32 = 1 << 3;
26 pub const DOCUMENTS: u32 = 1 << 4;
27
28 pub const ALL: u32 =
29 Self::VITALS | Self::LABS | Self::CONDITIONS | Self::MEDICATIONS | Self::DOCUMENTS;
30
31 pub const fn empty() -> Self {
33 Self(0)
34 }
35
36 pub const fn contains(&self, flag: u32) -> bool {
38 (self.0 & flag) == flag
39 }
40
41 pub fn category_from_family(family: &str) -> Option<u32> {
45 match family {
46 "health_vital" | "vitals" => Some(Self::VITALS),
47 "health_lab" | "labs" | "lab_results" => Some(Self::LABS),
48 "health_condition" | "conditions" => Some(Self::CONDITIONS),
49 "health_medication" | "medications" => Some(Self::MEDICATIONS),
50 "health_document" | "documents" => Some(Self::DOCUMENTS),
51 _ => None,
52 }
53 }
54
55 pub fn from_labels(labels: &[&str]) -> Result<Self, ConsentError> {
58 if labels.is_empty() {
59 return Err(ConsentError::ScopeViolation { requested_flag: 0 });
60 }
61 let mut bits = 0u32;
62 for label in labels {
63 let flag = Self::category_from_family(label.trim())
64 .ok_or(ConsentError::ScopeViolation { requested_flag: 0 })?;
65 bits |= flag;
66 }
67 Ok(Self(bits))
68 }
69}
70
71#[derive(Debug, Clone, PartialEq, Eq)]
73pub enum ConsentError {
74 InvalidSignature,
75 Expired { expires_at: u64, now: u64 },
76 Revoked { revoked_at: u64 },
77 UnauthorizedRevocation { actor: [u8; 32] },
78 TargetMismatch,
79 RequesterMismatch,
80 ScopeViolation { requested_flag: u32 },
81 ReplayDetected,
82 LedgerFull,
83 MalformedKey,
84}
85
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
88pub struct ConsentGrant {
89 #[serde(with = "serde_bytes")]
90 pub grant_id: [u8; 32],
91 #[serde(with = "serde_bytes")]
92 pub principal_did: [u8; 32],
93 #[serde(with = "serde_bytes")]
94 pub recipient_did: [u8; 32],
95 pub scope: ConsentScope,
96 pub purpose_hash: u64,
97 pub created_at: u64,
98 pub expires_at: u64,
99 pub nonce: u64,
100 #[serde(with = "serde_bytes")]
101 pub signature: [u8; 64],
102}
103
104impl ConsentGrant {
105 pub fn compute_digest(&self) -> [u8; 32] {
107 let mut hasher = Sha256::new();
108 hasher.update(&self.grant_id);
109 hasher.update(&self.principal_did);
110 hasher.update(&self.recipient_did);
111 hasher.update(&self.scope.0.to_be_bytes());
112 hasher.update(&self.purpose_hash.to_be_bytes());
113 hasher.update(&self.created_at.to_be_bytes());
114 hasher.update(&self.expires_at.to_be_bytes());
115 hasher.update(&self.nonce.to_be_bytes());
116 let result = hasher.finalize();
117 let mut digest = [0u8; 32];
118 digest.copy_from_slice(&result);
119 digest
120 }
121
122 pub fn new_signed(
124 grant_id: [u8; 32],
125 principal_signing_key: &SigningKey,
126 recipient_did: [u8; 32],
127 scope: ConsentScope,
128 purpose_hash: u64,
129 created_at: u64,
130 expires_at: u64,
131 nonce: u64,
132 ) -> Self {
133 let mut grant = Self {
134 grant_id,
135 principal_did: principal_signing_key.verifying_key().to_bytes(),
136 recipient_did,
137 scope,
138 purpose_hash,
139 created_at,
140 expires_at,
141 nonce,
142 signature: [0u8; 64],
143 };
144 let digest = grant.compute_digest();
145 grant.signature = principal_signing_key.sign(&digest).to_bytes();
146 grant
147 }
148
149 pub fn verify(&self, now: u64) -> Result<(), ConsentError> {
151 let verifying_key = VerifyingKey::from_bytes(&self.principal_did)
152 .map_err(|_| ConsentError::MalformedKey)?;
153 let signature = Signature::from_bytes(&self.signature);
154 let digest = self.compute_digest();
155 verifying_key
156 .verify(&digest, &signature)
157 .map_err(|_| ConsentError::InvalidSignature)?;
158
159 if now >= self.expires_at {
160 return Err(ConsentError::Expired {
161 expires_at: self.expires_at,
162 now,
163 });
164 }
165 Ok(())
166 }
167
168 pub fn to_deontic_quin(&self, category_flag: u32) -> NQuin {
170 let subject = u64::from_le_bytes(self.recipient_did[0..8].try_into().unwrap())
171 & 0x7FFF_FFFF_FFFF_FFFF;
172 let predicate = ((category_flag as u64) << 8) | (OP_PERMIT as u64);
173 let object = u64::from_le_bytes(self.principal_did[0..8].try_into().unwrap())
174 & 0x7FFF_FFFF_FFFF_FFFF;
175 let context =
176 u64::from_le_bytes(self.grant_id[0..8].try_into().unwrap()) & 0x7FFF_FFFF_FFFF_FFFF;
177 let metadata = self.expires_at.min(0xFFFF_FFFF);
178 let parity = subject ^ predicate ^ object ^ context;
179 NQuin {
180 subject,
181 predicate,
182 object,
183 context,
184 metadata,
185 parity,
186 }
187 }
188}
189
190#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
192pub struct RevocationReceipt {
193 #[serde(with = "serde_bytes")]
194 pub receipt_id: [u8; 32],
195 #[serde(with = "serde_bytes")]
196 pub grant_id: [u8; 32],
197 #[serde(with = "serde_bytes")]
198 pub revoked_by: [u8; 32],
199 pub revoked_at: u64,
200 pub reason_hash: u64,
201 #[serde(with = "serde_bytes")]
202 pub signature: [u8; 64],
203}
204
205impl RevocationReceipt {
206 pub fn compute_digest(&self) -> [u8; 32] {
210 let mut hasher = Sha256::new();
211 hasher.update(&self.receipt_id);
212 hasher.update(&self.grant_id);
213 hasher.update(&self.revoked_by);
214 hasher.update(&self.revoked_at.to_be_bytes());
215 hasher.update(&self.reason_hash.to_be_bytes());
216 let result = hasher.finalize();
217 let mut digest = [0u8; 32];
218 digest.copy_from_slice(&result);
219 digest
220 }
221
222 pub fn new_signed(
224 receipt_id: [u8; 32],
225 grant: &ConsentGrant,
226 revoking_key: &SigningKey,
227 revoked_at: u64,
228 reason_hash: u64,
229 ) -> Self {
230 let mut receipt = Self {
231 receipt_id,
232 grant_id: grant.grant_id,
233 revoked_by: revoking_key.verifying_key().to_bytes(),
234 revoked_at,
235 reason_hash,
236 signature: [0u8; 64],
237 };
238 let digest = receipt.compute_digest();
239 receipt.signature = revoking_key.sign(&digest).to_bytes();
240 receipt
241 }
242
243 pub fn verify_against_grant(&self, grant: &ConsentGrant) -> Result<(), ConsentError> {
245 if self.grant_id != grant.grant_id {
246 return Err(ConsentError::TargetMismatch);
247 }
248 if self.revoked_by != grant.principal_did {
249 return Err(ConsentError::UnauthorizedRevocation {
250 actor: self.revoked_by,
251 });
252 }
253 let verifying_key =
254 VerifyingKey::from_bytes(&self.revoked_by).map_err(|_| ConsentError::MalformedKey)?;
255 let signature = Signature::from_bytes(&self.signature);
256 let digest = self.compute_digest();
257 verifying_key
258 .verify(&digest, &signature)
259 .map_err(|_| ConsentError::InvalidSignature)?;
260 Ok(())
261 }
262
263 pub fn to_defeater_quin(&self, grant: &ConsentGrant, category_flag: u32) -> NQuin {
265 let subject = u64::from_le_bytes(grant.recipient_did[0..8].try_into().unwrap())
266 & 0x7FFF_FFFF_FFFF_FFFF;
267 let predicate = DEFEATER_BIT | ((category_flag as u64) << 8) | (OP_FORBID as u64);
268 let object = u64::from_le_bytes(grant.principal_did[0..8].try_into().unwrap())
269 & 0x7FFF_FFFF_FFFF_FFFF;
270 let context =
271 u64::from_le_bytes(self.grant_id[0..8].try_into().unwrap()) & 0x7FFF_FFFF_FFFF_FFFF;
272 let metadata = self.revoked_at.min(0xFFFF_FFFF);
273 let parity = subject ^ predicate ^ object ^ context;
274 NQuin {
275 subject,
276 predicate,
277 object,
278 context,
279 metadata,
280 parity,
281 }
282 }
283}
284
285pub const MAX_CONSENT_LEDGER: usize = 32;
287
288#[derive(Debug, Clone, Copy, PartialEq, Eq)]
289struct SeenGrant {
290 grant_id: [u8; 32],
291 nonce: u64,
292}
293
294#[derive(Debug, Clone, Copy, PartialEq, Eq)]
295struct RevokedGrant {
296 grant_id: [u8; 32],
297 revoked_at: u64,
298}
299
300#[derive(Debug, Clone)]
303pub struct ConsentLedger {
304 seen: [Option<SeenGrant>; MAX_CONSENT_LEDGER],
305 n_seen: usize,
306 revoked: [Option<RevokedGrant>; MAX_CONSENT_LEDGER],
307 n_revoked: usize,
308}
309
310impl Default for ConsentLedger {
311 fn default() -> Self {
313 Self::new()
314 }
315}
316
317impl ConsentLedger {
318 pub const fn new() -> Self {
321 Self {
322 seen: [None; MAX_CONSENT_LEDGER],
323 n_seen: 0,
324 revoked: [None; MAX_CONSENT_LEDGER],
325 n_revoked: 0,
326 }
327 }
328
329 fn is_replay(&self, grant: &ConsentGrant) -> bool {
332 self.seen.iter().take(self.n_seen).any(|slot| {
333 slot.is_some_and(|seen| seen.grant_id == grant.grant_id && seen.nonce == grant.nonce)
334 })
335 }
336
337 fn revoked_at(&self, grant_id: &[u8; 32]) -> Option<u64> {
340 self.revoked.iter().take(self.n_revoked).find_map(|slot| {
341 slot.and_then(|rev| (rev.grant_id == *grant_id).then_some(rev.revoked_at))
342 })
343 }
344
345 pub fn issue(&mut self, grant: &ConsentGrant, now: u64) -> Result<(), ConsentError> {
347 grant.verify(now)?;
348 if self.is_replay(grant) {
349 return Err(ConsentError::ReplayDetected);
350 }
351 if self.n_seen >= MAX_CONSENT_LEDGER {
352 return Err(ConsentError::LedgerFull);
353 }
354 self.seen[self.n_seen] = Some(SeenGrant {
355 grant_id: grant.grant_id,
356 nonce: grant.nonce,
357 });
358 self.n_seen += 1;
359 Ok(())
360 }
361
362 pub fn revoke(
365 &mut self,
366 grant: &ConsentGrant,
367 receipt: &RevocationReceipt,
368 ) -> Result<(), ConsentError> {
369 receipt.verify_against_grant(grant)?;
370 if self.revoked_at(&grant.grant_id).is_some() {
371 return Ok(());
372 }
373 if self.n_revoked >= MAX_CONSENT_LEDGER {
374 return Err(ConsentError::LedgerFull);
375 }
376 self.revoked[self.n_revoked] = Some(RevokedGrant {
377 grant_id: grant.grant_id,
378 revoked_at: receipt.revoked_at,
379 });
380 self.n_revoked += 1;
381 Ok(())
382 }
383
384 pub fn authorize_category_access(
390 &self,
391 grant: &ConsentGrant,
392 revocations: &[RevocationReceipt],
393 requested_category: u32,
394 actor_did: &[u8; 32],
395 current_timestamp: u64,
396 ) -> Result<(), ConsentError> {
397 if let Some(revoked_at) = self.revoked_at(&grant.grant_id) {
398 return Err(ConsentError::Revoked { revoked_at });
399 }
400 authorize_category_access(
401 grant,
402 revocations,
403 requested_category,
404 actor_did,
405 current_timestamp,
406 )
407 }
408}
409
410pub fn authorize_category_access(
416 grant: &ConsentGrant,
417 revocations: &[RevocationReceipt],
418 requested_category: u32,
419 actor_did: &[u8; 32],
420 current_timestamp: u64,
421) -> Result<(), ConsentError> {
422 for receipt in revocations {
423 if receipt.grant_id != grant.grant_id {
424 continue;
425 }
426 receipt.verify_against_grant(grant)?;
427 return Err(ConsentError::Revoked {
428 revoked_at: receipt.revoked_at,
429 });
430 }
431
432 grant.verify(current_timestamp)?;
433
434 if &grant.recipient_did != actor_did {
435 return Err(ConsentError::RequesterMismatch);
436 }
437
438 if !grant.scope.contains(requested_category) {
439 return Err(ConsentError::ScopeViolation {
440 requested_flag: requested_category,
441 });
442 }
443
444 Ok(())
445}
446
447#[cfg(test)]
448mod tests {
449 use super::*;
450 use crate::modalities::logic::deontic::{
451 evaluate_deontic_contract, DeonticStatus, DeonticVerdict,
452 };
453 use ed25519_dalek::SigningKey;
454
455 fn test_key(seed: u8) -> SigningKey {
456 SigningKey::from_bytes(&[seed; 32])
457 }
458
459 #[test]
460 fn valid_grant_authorizes_scoped_category() {
461 let alice_key = test_key(1);
462 let dr_bob_did = test_key(2).verifying_key().to_bytes();
463 let now = 1_000_000;
464 let grant = ConsentGrant::new_signed(
465 [42u8; 32],
466 &alice_key,
467 dr_bob_did,
468 ConsentScope(ConsentScope::VITALS | ConsentScope::LABS),
469 100,
470 now,
471 now + 3600,
472 1,
473 );
474
475 assert!(authorize_category_access(
476 &grant,
477 &[],
478 ConsentScope::VITALS,
479 &dr_bob_did,
480 now + 100
481 )
482 .is_ok());
483 assert!(
484 authorize_category_access(&grant, &[], ConsentScope::LABS, &dr_bob_did, now + 100)
485 .is_ok()
486 );
487 }
488
489 #[test]
490 fn expired_grant_fails_closed() {
491 let alice_key = test_key(1);
492 let dr_bob_did = test_key(2).verifying_key().to_bytes();
493 let now = 1_000_000;
494 let grant = ConsentGrant::new_signed(
495 [42u8; 32],
496 &alice_key,
497 dr_bob_did,
498 ConsentScope(ConsentScope::VITALS),
499 100,
500 now,
501 now + 3600,
502 1,
503 );
504
505 let err =
506 authorize_category_access(&grant, &[], ConsentScope::VITALS, &dr_bob_did, now + 3601)
507 .unwrap_err();
508 assert_eq!(
509 err,
510 ConsentError::Expired {
511 expires_at: now + 3600,
512 now: now + 3601
513 }
514 );
515 }
516
517 #[test]
518 fn revoked_grant_fails_closed_and_cannot_reactivate() {
519 let alice_key = test_key(1);
520 let dr_bob_did = test_key(2).verifying_key().to_bytes();
521 let now = 1_000_000;
522 let grant = ConsentGrant::new_signed(
523 [42u8; 32],
524 &alice_key,
525 dr_bob_did,
526 ConsentScope(ConsentScope::VITALS),
527 100,
528 now,
529 now + 3600,
530 1,
531 );
532 let receipt = RevocationReceipt::new_signed([99u8; 32], &grant, &alice_key, now + 500, 200);
533
534 let err = authorize_category_access(
535 &grant,
536 &[receipt],
537 ConsentScope::VITALS,
538 &dr_bob_did,
539 now + 600,
540 )
541 .unwrap_err();
542 assert_eq!(
543 err,
544 ConsentError::Revoked {
545 revoked_at: now + 500
546 }
547 );
548 }
549
550 #[test]
551 fn unauthorized_actor_cannot_revoke() {
552 let alice_key = test_key(1);
553 let mallory_key = test_key(9);
554 let dr_bob_did = test_key(2).verifying_key().to_bytes();
555 let now = 1_000_000;
556 let grant = ConsentGrant::new_signed(
557 [42u8; 32],
558 &alice_key,
559 dr_bob_did,
560 ConsentScope(ConsentScope::VITALS),
561 100,
562 now,
563 now + 3600,
564 1,
565 );
566 let receipt =
568 RevocationReceipt::new_signed([99u8; 32], &grant, &mallory_key, now + 500, 200);
569
570 let err = authorize_category_access(
571 &grant,
572 &[receipt],
573 ConsentScope::VITALS,
574 &dr_bob_did,
575 now + 600,
576 )
577 .unwrap_err();
578 assert!(matches!(err, ConsentError::UnauthorizedRevocation { .. }));
579 }
580
581 #[test]
582 fn out_of_scope_category_is_denied() {
583 let alice_key = test_key(1);
584 let dr_bob_did = test_key(2).verifying_key().to_bytes();
585 let now = 1_000_000;
586 let grant = ConsentGrant::new_signed(
587 [42u8; 32],
588 &alice_key,
589 dr_bob_did,
590 ConsentScope(ConsentScope::VITALS), 100,
592 now,
593 now + 3600,
594 1,
595 );
596
597 let err =
598 authorize_category_access(&grant, &[], ConsentScope::DOCUMENTS, &dr_bob_did, now + 100)
599 .unwrap_err();
600 assert_eq!(
601 err,
602 ConsentError::ScopeViolation {
603 requested_flag: ConsentScope::DOCUMENTS
604 }
605 );
606 }
607
608 #[test]
609 fn tampered_grant_fails_signature_check() {
610 let alice_key = test_key(1);
611 let dr_bob_did = test_key(2).verifying_key().to_bytes();
612 let now = 1_000_000;
613 let mut grant = ConsentGrant::new_signed(
614 [42u8; 32],
615 &alice_key,
616 dr_bob_did,
617 ConsentScope(ConsentScope::VITALS),
618 100,
619 now,
620 now + 3600,
621 1,
622 );
623 grant.scope = ConsentScope(ConsentScope::ALL);
625 assert_eq!(
626 grant.verify(now).unwrap_err(),
627 ConsentError::InvalidSignature
628 );
629 }
630
631 #[test]
632 fn deontic_frame_integration_evaluates_active_and_defeated_states() {
633 let alice_key = test_key(1);
634 let dr_bob_did = test_key(2).verifying_key().to_bytes();
635 let now = 1_000_000;
636 let grant = ConsentGrant::new_signed(
637 [42u8; 32],
638 &alice_key,
639 dr_bob_did,
640 ConsentScope(ConsentScope::VITALS),
641 100,
642 now,
643 now + 3600,
644 1,
645 );
646 let grant_quin = grant.to_deontic_quin(ConsentScope::VITALS);
647
648 let frame_active = [grant_quin.clone()];
650 let mut verdicts = [DeonticVerdict::default()];
651 let count =
652 evaluate_deontic_contract(&frame_active, (now + 100) as u32, &mut verdicts).unwrap();
653 assert_eq!(count, 1);
654 assert_eq!(verdicts[0].status, DeonticStatus::Active);
655
656 let receipt = RevocationReceipt::new_signed([99u8; 32], &grant, &alice_key, now + 500, 200);
658 let defeater_quin = receipt.to_defeater_quin(&grant, ConsentScope::VITALS);
659 let frame_revoked = [grant_quin, defeater_quin];
660 let mut verdicts_revoked = [DeonticVerdict::default()];
661 let count =
662 evaluate_deontic_contract(&frame_revoked, (now + 600) as u32, &mut verdicts_revoked)
663 .unwrap();
664 assert_eq!(count, 1);
665 assert_eq!(verdicts_revoked[0].status, DeonticStatus::Defeated);
666 }
667
668 fn vitals_grant(alice: &SigningKey, recipient: [u8; 32], now: u64, nonce: u64) -> ConsentGrant {
669 ConsentGrant::new_signed(
670 [nonce as u8; 32],
671 alice,
672 recipient,
673 ConsentScope(ConsentScope::VITALS),
674 100,
675 now,
676 now + 3600,
677 nonce,
678 )
679 }
680
681 #[test]
682 fn exact_expiry_instant_fails_closed() {
683 let alice_key = test_key(1);
684 let dr_bob_did = test_key(2).verifying_key().to_bytes();
685 let now = 1_000_000;
686 let grant = vitals_grant(&alice_key, dr_bob_did, now, 1);
687 let err =
688 authorize_category_access(&grant, &[], ConsentScope::VITALS, &dr_bob_did, now + 3600)
689 .unwrap_err();
690 assert!(matches!(err, ConsentError::Expired { .. }));
691 }
692
693 #[test]
694 fn non_recipient_actor_is_denied() {
695 let alice_key = test_key(1);
696 let dr_bob_did = test_key(2).verifying_key().to_bytes();
697 let mallory_did = test_key(9).verifying_key().to_bytes();
698 let now = 1_000_000;
699 let grant = vitals_grant(&alice_key, dr_bob_did, now, 1);
700 let err =
701 authorize_category_access(&grant, &[], ConsentScope::VITALS, &mallory_did, now + 100)
702 .unwrap_err();
703 assert_eq!(err, ConsentError::RequesterMismatch);
704 }
705
706 #[test]
707 fn labels_reject_unknown_and_empty_without_widening() {
708 assert!(ConsentScope::from_labels(&[]).is_err());
709 assert!(ConsentScope::from_labels(&["clinical_notes"]).is_err());
710 assert!(ConsentScope::from_labels(&["vitals", "owl:Thing"]).is_err());
711 let scope = ConsentScope::from_labels(&["vitals", "lab_results"]).unwrap();
712 assert!(scope.contains(ConsentScope::VITALS));
713 assert!(scope.contains(ConsentScope::LABS));
714 assert!(!scope.contains(ConsentScope::DOCUMENTS));
715 }
716
717 #[test]
718 fn ledger_detects_replay_and_blocks_reactivation_without_receipt() {
719 let alice_key = test_key(1);
720 let dr_bob_did = test_key(2).verifying_key().to_bytes();
721 let now = 1_000_000;
722 let grant = vitals_grant(&alice_key, dr_bob_did, now, 7);
723 let mut ledger = ConsentLedger::new();
724 ledger.issue(&grant, now + 1).unwrap();
725 assert_eq!(
726 ledger.issue(&grant, now + 2).unwrap_err(),
727 ConsentError::ReplayDetected
728 );
729
730 let receipt = RevocationReceipt::new_signed([99u8; 32], &grant, &alice_key, now + 500, 200);
731 ledger.revoke(&grant, &receipt).unwrap();
732
733 let err = ledger
734 .authorize_category_access(&grant, &[], ConsentScope::VITALS, &dr_bob_did, now + 600)
735 .unwrap_err();
736 assert_eq!(
737 err,
738 ConsentError::Revoked {
739 revoked_at: now + 500
740 }
741 );
742 }
743
744 #[test]
745 fn grant_struct_holds_no_private_key_material() {
746 let alice_key = test_key(1);
747 let dr_bob_did = test_key(2).verifying_key().to_bytes();
748 let grant = vitals_grant(&alice_key, dr_bob_did, 1_000_000, 1);
749 assert_eq!(grant.principal_did, alice_key.verifying_key().to_bytes());
750 assert_ne!(grant.principal_did, alice_key.to_bytes());
751 assert_eq!(grant.signature.len(), 64);
752 }
753}