Skip to main content

qualia_peer/
clinical.rs

1//! Public application API for known-peer medical communications (E14).
2//!
3//! Pairing, standing permits, envelopes, mailbox and confidential help go
4//! through this owner. Transport delivery never asserts clinical review.
5
6use crate::{PeerHost, QdnfError};
7use qualia_core_db::net::qdnf::authority::{ContactState, PolicyOutcome};
8use qualia_core_db::net::qdnf::clinical::{
9    diagnosis_discovery_allowed, enqueue_offline, public_patient_index_allowed, release_queued,
10    seal_envelope, vip_association_indexed, CareGrant, ClinicalPair, GrantTable, Mailbox,
11    OfflineQueue, OfflineSlot, PairingTable, PayloadEnvelope, PermitTable, StandingPermit,
12};
13use qualia_core_db::net::qdnf::contracts::{BoundGenerations, LiveGenerations};
14use qualia_core_db::net::qdnf::policy_labels::VerifiedLabel;
15use qualia_core_db::net::qdnf::types::StrongDigest;
16
17/// Session-owned clinical tables. Not a public patient index.
18#[derive(Clone, Copy, Debug)]
19pub struct ClinicalSession {
20    pairings: PairingTable,
21    permits: PermitTable,
22    grants: GrantTable,
23    mailbox: Mailbox,
24    offline: OfflineQueue,
25}
26
27impl PeerHost {
28    /// Application clinical owner for this host cell. Independent of pairing IPC.
29    pub fn clinical_session(&self) -> ClinicalSession {
30        ClinicalSession::new()
31    }
32}
33
34impl ClinicalSession {
35    /// Creates a new instance.
36    pub fn new() -> Self {
37        Self {
38            pairings: PairingTable::new(),
39            permits: PermitTable::new(),
40            grants: GrantTable::new(),
41            mailbox: Mailbox::new(),
42            offline: OfflineQueue::new(),
43        }
44    }
45
46    /// Admits a clinical pair (denied when public-index/VIP/discovery flags set).
47    pub fn admit_pair(&mut self, pair: ClinicalPair) -> Result<usize, QdnfError> {
48        if public_patient_index_allowed()
49            || vip_association_indexed()
50            || diagnosis_discovery_allowed()
51        {
52            return Err(QdnfError::Denied);
53        }
54        self.pairings.admit(pair)
55    }
56
57    /// `refuse-public` index.
58    pub fn refuse_public_index(&self, pair: ClinicalPair) -> Result<(), QdnfError> {
59        self.pairings.index_public(pair)
60    }
61
62    /// Adds permit.
63    pub fn add_permit(&mut self, permit: StandingPermit) -> Result<usize, QdnfError> {
64        self.permits.add(permit)
65    }
66
67    /// Sets live.
68    pub fn set_live(&mut self, live: LiveGenerations) {
69        self.permits.set_live(live);
70    }
71
72    /// Authorizes a standing permit.
73    pub fn authorize_permit(
74        &self,
75        permit: &StandingPermit,
76        recipient: StrongDigest,
77        patient_contact: ContactState,
78        clinician_contact: ContactState,
79        now_unix: u64,
80    ) -> Result<(), QdnfError> {
81        self.permits.authorize(
82            permit.patient,
83            permit.clinician,
84            permit.purpose,
85            permit.record_scope,
86            recipient,
87            patient_contact,
88            clinician_contact,
89            PolicyOutcome::Allow,
90            now_unix,
91        )
92    }
93
94    /// Adds grant.
95    pub fn add_grant(&mut self, grant: CareGrant) -> Result<usize, QdnfError> {
96        self.grants.add(grant)
97    }
98
99    /// Seals a payload envelope.
100    pub fn seal(
101        &self,
102        label: &VerifiedLabel,
103        projection: StrongDigest,
104        purpose: StrongDigest,
105        expires_unix: u64,
106        ciphertext: &[u8],
107        patient_contact: ContactState,
108        clinician_contact: ContactState,
109        now_unix: u64,
110    ) -> Result<PayloadEnvelope, QdnfError> {
111        seal_envelope(
112            &self.grants,
113            label,
114            projection,
115            purpose,
116            expires_unix,
117            ciphertext,
118            PolicyOutcome::Allow,
119            patient_contact,
120            clinician_contact,
121            now_unix,
122        )
123    }
124
125    /// Stores a mailbox.
126    pub fn store_mailbox(
127        &mut self,
128        ct: &[u8],
129        recipient: StrongDigest,
130        bound: BoundGenerations,
131    ) -> Result<usize, QdnfError> {
132        self.mailbox.store_bound(ct, recipient, bound)
133    }
134
135    /// Delivers a mailbox.
136    pub fn deliver_mailbox(
137        &mut self,
138        slot: usize,
139        recipient: StrongDigest,
140        live: LiveGenerations,
141    ) -> Result<(), QdnfError> {
142        self.mailbox.deliver_live(slot, recipient, live)
143    }
144
145    /// Revokes clinician.
146    pub fn revoke_clinician(&mut self, clinician: StrongDigest) -> Result<(), QdnfError> {
147        self.mailbox.revoke_clinician(clinician)
148    }
149
150    /// Enqueues for offline delivery.
151    pub fn enqueue_offline(&mut self, slot: OfflineSlot, now: u64) -> Result<usize, QdnfError> {
152        enqueue_offline(&mut self.offline, slot, now)
153    }
154
155    /// Releases offline queue.
156    pub fn release_offline(
157        &self,
158        slot: usize,
159        now: u64,
160        patient_contact: ContactState,
161        clinician_contact: ContactState,
162    ) -> Result<(), QdnfError> {
163        release_queued(&self.offline, slot, now, patient_contact, clinician_contact)
164    }
165}
166
167impl Default for ClinicalSession {
168    fn default() -> Self {
169        Self::new()
170    }
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176    use qualia_core_db::net::qdnf::authority::TemporalGrant;
177    use qualia_core_db::net::qdnf::clinical::{
178        admit_confidential_help, export_interchange, inherit_response_label,
179        network_asserts_clinical_review, notify_guardian, notify_guardian_automatically,
180        patient_record_associated, restore_labelled_backup, stream_attachment,
181        CapacityMandatePolicy, CareGrantKind, InterchangeAdapter, STREAM_PAGE_BYTES,
182    };
183    use qualia_core_db::net::qdnf::policy_labels::{
184        encode_label_into, verify_label, Confidentiality, LabelFields,
185    };
186    use qualia_core_db::net::qdnf::types::{Generation, ProfileId};
187
188    fn digest(tag: u8) -> StrongDigest {
189        let mut d = StrongDigest::ZERO;
190        d.0[0] = tag;
191        d.0[47] = 0xC1;
192        d
193    }
194
195    fn grant_until(audience: StrongDigest, exp: u64) -> TemporalGrant {
196        TemporalGrant {
197            purpose_digest: digest(0x11),
198            audience_digest: audience,
199            authority_generation: 1,
200            not_before_unix: 0,
201            expires_unix: exp,
202            profile: ProfileId::QDNF_CRYPTO_1,
203        }
204    }
205
206    fn label(conf: Confidentiality, iss: StrongDigest) -> VerifiedLabel {
207        let mut fields = LabelFields::request(conf, iss);
208        if conf.requires_audience() {
209            fields.audience = iss;
210        }
211        let mut buf = [0u8; 256];
212        let n = encode_label_into(&fields, &mut buf).expect("encode");
213        verify_label(fields, &buf[..n]).expect("verify")
214    }
215
216    fn host() -> PeerHost {
217        PeerHost::new(4096).unwrap()
218    }
219
220    #[test]
221    fn public_indexes_and_diagnosis_discovery_are_denied() {
222        let mut c = host().clinical_session();
223        let pair = ClinicalPair {
224            patient: digest(1),
225            clinician: digest(2),
226            patient_contact: ContactState::Active,
227            clinician_contact: ContactState::Active,
228            route: digest(3),
229        };
230        assert!(c.admit_pair(pair).is_ok());
231        assert_eq!(c.refuse_public_index(pair), Err(QdnfError::Denied));
232        assert!(!public_patient_index_allowed());
233        assert!(!vip_association_indexed());
234        assert!(!diagnosis_discovery_allowed());
235    }
236
237    #[test]
238    fn blocked_contact_cannot_release_permit() {
239        let mut c = host().clinical_session();
240        let clinician = digest(2);
241        let p = StandingPermit {
242            patient: digest(1),
243            clinician,
244            purpose: digest(3),
245            record_scope: digest(4),
246            grant: grant_until(clinician, 100),
247        };
248        c.add_permit(p).unwrap();
249        assert_eq!(
250            c.authorize_permit(
251                &p,
252                clinician,
253                ContactState::Active,
254                ContactState::Blocked,
255                10
256            ),
257            Err(QdnfError::Denied)
258        );
259        assert!(c
260            .authorize_permit(
261                &p,
262                clinician,
263                ContactState::Active,
264                ContactState::Active,
265                10
266            )
267            .is_ok());
268        c.set_live(LiveGenerations {
269            source: Generation(1),
270            policy: Generation(2),
271            identity: Generation(1),
272        });
273        assert_eq!(
274            c.authorize_permit(
275                &p,
276                clinician,
277                ContactState::Active,
278                ContactState::Active,
279                10
280            ),
281            Err(QdnfError::StaleGeneration)
282        );
283    }
284
285    #[test]
286    fn envelope_mailbox_offline_backup_and_help() {
287        let mut c = host().clinical_session();
288        let clinician = digest(2);
289        let patient = digest(1);
290        c.add_grant(CareGrant {
291            kind: CareGrantKind::Clinician,
292            recipient: clinician,
293            grant: grant_until(clinician, 100),
294        })
295        .unwrap();
296        c.add_grant(CareGrant {
297            kind: CareGrantKind::Referral,
298            recipient: digest(8),
299            grant: grant_until(digest(8), 100),
300        })
301        .unwrap();
302        let lbl = label(Confidentiality::C2Sensitive, digest(1));
303        assert_eq!(
304            c.seal(
305                &lbl,
306                digest(0x21),
307                digest(0x11),
308                100,
309                b"",
310                ContactState::Active,
311                ContactState::Active,
312                10
313            )
314            .unwrap_err(),
315            QdnfError::Malformed
316        );
317        let env = c
318            .seal(
319                &lbl,
320                digest(0x21),
321                digest(0x11),
322                100,
323                b"sealed-ct",
324                ContactState::Active,
325                ContactState::Active,
326                10,
327            )
328            .unwrap();
329        assert_eq!(env.recipient_count(), 2);
330
331        let bound = BoundGenerations::new(Generation(1), Generation(1), Generation(1));
332        let slot = c.store_mailbox(b"mailbox-ct", clinician, bound).unwrap();
333        c.revoke_clinician(clinician).unwrap();
334        assert_eq!(
335            c.deliver_mailbox(slot, clinician, bound.as_live()),
336            Err(QdnfError::Revoked)
337        );
338
339        let mut c2 = host().clinical_session();
340        let slot = c2.store_mailbox(b"mailbox-ct", clinician, bound).unwrap();
341        let mut live = bound.as_live();
342        live.identity = Generation(2);
343        assert_eq!(
344            c2.deliver_mailbox(slot, clinician, live),
345            Err(QdnfError::StaleGeneration)
346        );
347        assert_eq!(
348            c2.deliver_mailbox(slot, digest(9), bound.as_live()),
349            Err(QdnfError::Unauthorized)
350        );
351        assert!(c2.deliver_mailbox(slot, clinician, bound.as_live()).is_ok());
352        assert!(!network_asserts_clinical_review());
353
354        let off = c2
355            .enqueue_offline(
356                OfflineSlot {
357                    recipient: clinician,
358                    expires_unix: 20,
359                    ciphertext_len: 8,
360                    ciphertext_digest: digest(9),
361                },
362                1,
363            )
364            .unwrap();
365        assert_eq!(
366            c2.release_offline(off, 20, ContactState::Active, ContactState::Active),
367            Err(QdnfError::Expired)
368        );
369
370        let stored = label(Confidentiality::C2Sensitive, digest(1));
371        let mut dropped = *stored.fields();
372        dropped.confidentiality = Confidentiality::C0Public;
373        assert_eq!(
374            restore_labelled_backup(&stored, &dropped),
375            Err(QdnfError::Denied)
376        );
377        let mut out = LabelFields::request(Confidentiality::C0Public, digest(2));
378        inherit_response_label(stored.fields(), &stored, &mut out).unwrap();
379        assert_eq!(out.confidentiality, Confidentiality::C2Sensitive);
380
381        assert!(!notify_guardian_automatically());
382        assert_eq!(
383            notify_guardian(
384                CapacityMandatePolicy::IndependentConfidentialHelp,
385                digest(3),
386                ContactState::Active,
387            ),
388            Err(QdnfError::Denied)
389        );
390        assert!(admit_confidential_help(
391            digest(8),
392            CapacityMandatePolicy::IndependentConfidentialHelp,
393            ContactState::Blocked,
394        )
395        .is_ok());
396
397        let adapter = InterchangeAdapter {
398            mapping_digest: digest(9),
399            retains_full_label: false,
400        };
401        assert_eq!(
402            export_interchange(&stored, &adapter),
403            Err(QdnfError::Denied)
404        );
405        assert_eq!(
406            patient_record_associated(patient, digest(4), digest(9)),
407            Err(QdnfError::Denied)
408        );
409        let pages = digest(5);
410        let mut page = [0u8; STREAM_PAGE_BYTES as usize];
411        let imaging = [7u8; 64];
412        let expected =
413            qualia_core_db::net::qdnf::clinical::digest_attachment_pages(&imaging).unwrap();
414        stream_attachment(&imaging, imaging.len() as u32, expected, &mut page).unwrap();
415        let _ = pages;
416    }
417}