Skip to main content

qualia_core_db/net/qdnf/clinical/
permit.rs

1//! Standing care permits. Release requires active mutual contact and a current grant.
2
3use super::{admit_outcome, first_empty, require_active_mutual, MAX_SLOTS};
4use crate::net::qdnf::authority::{ContactState, PolicyOutcome, TemporalGrant};
5use crate::net::qdnf::contracts::{recheck_permit, BoundGenerations, LiveGenerations};
6use crate::net::qdnf::errors::QdnfError;
7use crate::net::qdnf::types::{Generation, StrongDigest};
8
9/// Routine transfer/reply between a pair, bound to purpose and record scope.
10#[repr(C)]
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub struct StandingPermit {
13    pub patient: StrongDigest,
14    pub clinician: StrongDigest,
15    pub purpose: StrongDigest,
16    pub record_scope: StrongDigest,
17    pub grant: TemporalGrant,
18}
19
20/// Eight-slot standing-permit table with independent revocation flags.
21#[derive(Clone, Copy, Debug)]
22pub struct PermitTable {
23    slots: [Option<StandingPermit>; MAX_SLOTS],
24    revoked: [bool; MAX_SLOTS],
25    live: LiveGenerations,
26}
27
28impl PermitTable {
29    /// Creates a default `PermitTable`.
30    pub const fn new() -> Self {
31        Self {
32            slots: [None; MAX_SLOTS],
33            revoked: [false; MAX_SLOTS],
34            live: LiveGenerations {
35                source: Generation(1),
36                policy: Generation(1),
37                identity: Generation(1),
38            },
39        }
40    }
41
42    fn find(
43        &self,
44        patient: StrongDigest,
45        clinician: StrongDigest,
46        purpose: StrongDigest,
47        record_scope: StrongDigest,
48    ) -> Option<usize> {
49        let mut i = 0usize;
50        while i < MAX_SLOTS {
51            if let Some(p) = self.slots[i] {
52                if p.patient == patient
53                    && p.clinician == clinician
54                    && p.purpose == purpose
55                    && p.record_scope == record_scope
56                {
57                    return Some(i);
58                }
59            }
60            i += 1;
61        }
62        None
63    }
64
65    /// Duplicate (pair, purpose, scope) is idempotent.
66    pub fn add(&mut self, permit: StandingPermit) -> Result<usize, QdnfError> {
67        if permit.patient == StrongDigest::ZERO
68            || permit.clinician == StrongDigest::ZERO
69            || permit.purpose == StrongDigest::ZERO
70            || permit.record_scope == StrongDigest::ZERO
71        {
72            return Err(QdnfError::Malformed);
73        }
74        if let Some(i) = self.find(
75            permit.patient,
76            permit.clinician,
77            permit.purpose,
78            permit.record_scope,
79        ) {
80            self.slots[i] = Some(permit);
81            self.revoked[i] = false;
82            return Ok(i);
83        }
84        let idx = first_empty(&self.slots).ok_or(QdnfError::Capacity)?;
85        self.slots[idx] = Some(permit);
86        self.revoked[idx] = false;
87        Ok(idx)
88    }
89
90    /// Live generations at commit/release. A policy bump stale-fails authorize.
91    pub fn set_live(&mut self, live: LiveGenerations) {
92        self.live = live;
93    }
94
95    /// Revokes.
96    pub fn revoke(
97        &mut self,
98        patient: StrongDigest,
99        clinician: StrongDigest,
100        purpose: StrongDigest,
101        record_scope: StrongDigest,
102    ) -> Result<(), QdnfError> {
103        let i = self
104            .find(patient, clinician, purpose, record_scope)
105            .ok_or(QdnfError::Unauthorized)?;
106        self.revoked[i] = true;
107        Ok(())
108    }
109
110    /// Extra recipients and other scopes are Unauthorized until a matching permit
111    /// is added. Live Active mutual contact and `grant.current_at(now)` required.
112    pub fn authorize(
113        &self,
114        patient: StrongDigest,
115        clinician: StrongDigest,
116        purpose: StrongDigest,
117        record_scope: StrongDigest,
118        recipient: StrongDigest,
119        patient_contact: ContactState,
120        clinician_contact: ContactState,
121        outcome: PolicyOutcome,
122        now_unix: u64,
123    ) -> Result<(), QdnfError> {
124        if recipient != clinician && recipient != patient {
125            return Err(QdnfError::Unauthorized);
126        }
127        let i = self
128            .find(patient, clinician, purpose, record_scope)
129            .ok_or(QdnfError::Unauthorized)?;
130        if self.revoked[i] {
131            return Err(QdnfError::Denied);
132        }
133        let p = self.slots[i].ok_or(QdnfError::Unauthorized)?;
134        let bound = BoundGenerations::new(
135            Generation(p.grant.authority_generation),
136            Generation(p.grant.authority_generation),
137            Generation(p.grant.authority_generation),
138        );
139        recheck_permit(bound, self.live)?;
140        require_active_mutual(patient_contact, clinician_contact)?;
141        p.grant.current_at(now_unix)?;
142        if p.grant.audience_digest != StrongDigest::ZERO
143            && p.grant.audience_digest != recipient
144            && p.grant.audience_digest != patient
145            && p.grant.audience_digest != clinician
146        {
147            return Err(QdnfError::Denied);
148        }
149        admit_outcome(outcome)
150    }
151}
152
153impl Default for PermitTable {
154    fn default() -> Self {
155        Self::new()
156    }
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162    use crate::net::qdnf::types::ProfileId;
163
164    fn d(tag: u8) -> StrongDigest {
165        let mut x = StrongDigest::ZERO;
166        x.0[0] = tag;
167        x
168    }
169
170    fn grant_until(audience: StrongDigest, exp: u64) -> TemporalGrant {
171        TemporalGrant {
172            purpose_digest: d(0x11),
173            audience_digest: audience,
174            authority_generation: 1,
175            not_before_unix: 0,
176            expires_unix: exp,
177            profile: ProfileId::QDNF_CRYPTO_1,
178        }
179    }
180
181    fn auth(
182        t: &PermitTable,
183        p: &StandingPermit,
184        scope: StrongDigest,
185        recip: StrongDigest,
186        pc: ContactState,
187        cc: ContactState,
188        now: u64,
189    ) -> Result<(), QdnfError> {
190        t.authorize(
191            p.patient,
192            p.clinician,
193            p.purpose,
194            scope,
195            recip,
196            pc,
197            cc,
198            PolicyOutcome::Allow,
199            now,
200        )
201    }
202
203    #[test]
204    fn active_current_grant_authorizes_pair() {
205        let mut t = PermitTable::new();
206        let clinician = d(2);
207        let p = StandingPermit {
208            patient: d(1),
209            clinician,
210            purpose: d(3),
211            record_scope: d(4),
212            grant: grant_until(clinician, 100),
213        };
214        assert!(t.add(p).is_ok());
215        assert!(auth(
216            &t,
217            &p,
218            p.record_scope,
219            p.clinician,
220            ContactState::Active,
221            ContactState::Active,
222            10
223        )
224        .is_ok());
225        assert!(auth(
226            &t,
227            &p,
228            p.record_scope,
229            p.patient,
230            ContactState::Active,
231            ContactState::Active,
232            10
233        )
234        .is_ok());
235        assert_eq!(
236            auth(
237                &t,
238                &p,
239                p.record_scope,
240                d(9),
241                ContactState::Active,
242                ContactState::Active,
243                10
244            ),
245            Err(QdnfError::Unauthorized)
246        );
247    }
248
249    #[test]
250    fn suspended_blocked_revoked_wrong_audience_cannot_release() {
251        let mut t = PermitTable::new();
252        let clinician = d(2);
253        let p = StandingPermit {
254            patient: d(1),
255            clinician,
256            purpose: d(3),
257            record_scope: d(4),
258            grant: grant_until(clinician, 100),
259        };
260        t.add(p).unwrap();
261        assert_eq!(
262            auth(
263                &t,
264                &p,
265                p.record_scope,
266                p.clinician,
267                ContactState::Active,
268                ContactState::Suspended,
269                10
270            ),
271            Err(QdnfError::Denied)
272        );
273        assert_eq!(
274            auth(
275                &t,
276                &p,
277                p.record_scope,
278                p.clinician,
279                ContactState::Blocked,
280                ContactState::Active,
281                10
282            ),
283            Err(QdnfError::Denied)
284        );
285        assert_eq!(
286            auth(
287                &t,
288                &p,
289                p.record_scope,
290                p.clinician,
291                ContactState::Request,
292                ContactState::Active,
293                10
294            ),
295            Err(QdnfError::Unauthorized)
296        );
297        t.revoke(p.patient, p.clinician, p.purpose, p.record_scope)
298            .unwrap();
299        assert_eq!(
300            auth(
301                &t,
302                &p,
303                p.record_scope,
304                p.clinician,
305                ContactState::Active,
306                ContactState::Active,
307                10
308            ),
309            Err(QdnfError::Denied)
310        );
311        let mut t2 = PermitTable::new();
312        let wrong = StandingPermit {
313            grant: grant_until(d(9), 100),
314            ..p
315        };
316        t2.add(wrong).unwrap();
317        assert_eq!(
318            auth(
319                &t2,
320                &wrong,
321                wrong.record_scope,
322                wrong.clinician,
323                ContactState::Active,
324                ContactState::Active,
325                10
326            ),
327            Err(QdnfError::Denied)
328        );
329    }
330
331    #[test]
332    fn expired_grant_is_expired() {
333        let mut t = PermitTable::new();
334        let clinician = d(2);
335        let p = StandingPermit {
336            patient: d(1),
337            clinician,
338            purpose: d(3),
339            record_scope: d(7),
340            grant: grant_until(clinician, 5),
341        };
342        t.add(p).unwrap();
343        assert_eq!(
344            auth(
345                &t,
346                &p,
347                p.record_scope,
348                p.clinician,
349                ContactState::Active,
350                ContactState::Active,
351                10
352            ),
353            Err(QdnfError::Expired)
354        );
355    }
356
357    #[test]
358    fn live_policy_generation_advance_is_stale() {
359        let mut t = PermitTable::new();
360        let clinician = d(2);
361        let p = StandingPermit {
362            patient: d(1),
363            clinician,
364            purpose: d(3),
365            record_scope: d(4),
366            grant: grant_until(clinician, 100),
367        };
368        t.add(p).unwrap();
369        t.set_live(LiveGenerations {
370            source: Generation(1),
371            policy: Generation(2),
372            identity: Generation(1),
373        });
374        assert_eq!(
375            auth(
376                &t,
377                &p,
378                p.record_scope,
379                p.clinician,
380                ContactState::Active,
381                ContactState::Active,
382                10
383            ),
384            Err(QdnfError::StaleGeneration)
385        );
386    }
387}