Skip to main content

qualia_core_db/net/qdnf/clinical/
grants.rs

1//! Separate clinician, hospital-team, guardian, referral, recording,
2//! transcription and AI-processing grants. The sender sees actual key holders.
3
4use super::{first_empty, require_active_mutual, MAX_SLOTS};
5use crate::net::qdnf::authority::{ContactState, TemporalGrant};
6use crate::net::qdnf::errors::QdnfError;
7use crate::net::qdnf::types::StrongDigest;
8
9/// Maximum visible key recipients on one envelope.
10pub const MAX_VISIBLE: usize = 8;
11
12/// Distinct care-grant kinds. Association does not imply another kind.
13#[repr(u8)]
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub enum CareGrantKind {
16    Clinician = 1,
17    HospitalTeam = 2,
18    Guardian = 3,
19    Referral = 4,
20    Recording = 5,
21    Transcription = 6,
22    AiProcessing = 7,
23}
24
25/// One kinded recipient grant.
26#[repr(C)]
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub struct CareGrant {
29    pub kind: CareGrantKind,
30    pub recipient: StrongDigest,
31    pub grant: TemporalGrant,
32}
33
34/// Eight-slot grant table with independent revocation.
35#[derive(Clone, Copy, Debug)]
36pub struct GrantTable {
37    slots: [Option<CareGrant>; MAX_SLOTS],
38    revoked: [bool; MAX_SLOTS],
39}
40
41impl GrantTable {
42    /// Creates a default `GrantTable`.
43    pub const fn new() -> Self {
44        Self {
45            slots: [None; MAX_SLOTS],
46            revoked: [false; MAX_SLOTS],
47        }
48    }
49
50    fn find(&self, kind: CareGrantKind, recipient: StrongDigest) -> Option<usize> {
51        let mut i = 0usize;
52        while i < MAX_SLOTS {
53            if let Some(g) = self.slots[i] {
54                if g.kind == kind && g.recipient == recipient {
55                    return Some(i);
56                }
57            }
58            i += 1;
59        }
60        None
61    }
62
63    /// Adds an entry.
64    pub fn add(&mut self, grant: CareGrant) -> Result<usize, QdnfError> {
65        if grant.recipient == StrongDigest::ZERO {
66            return Err(QdnfError::Malformed);
67        }
68        if let Some(i) = self.find(grant.kind, grant.recipient) {
69            self.slots[i] = Some(grant);
70            self.revoked[i] = false;
71            return Ok(i);
72        }
73        let i = first_empty(&self.slots).ok_or(QdnfError::Capacity)?;
74        self.slots[i] = Some(grant);
75        self.revoked[i] = false;
76        Ok(i)
77    }
78
79    /// Revokes the grant.
80    pub fn revoke(
81        &mut self,
82        kind: CareGrantKind,
83        recipient: StrongDigest,
84    ) -> Result<(), QdnfError> {
85        let i = self.find(kind, recipient).ok_or(QdnfError::Unauthorized)?;
86        self.revoked[i] = true;
87        Ok(())
88    }
89
90    /// Kind and recipient must match. Live Active mutual contact and current grant.
91    pub fn authorize_kind(
92        &self,
93        kind: CareGrantKind,
94        recipient: StrongDigest,
95        patient_contact: ContactState,
96        clinician_contact: ContactState,
97        now_unix: u64,
98    ) -> Result<(), QdnfError> {
99        let i = self.find(kind, recipient).ok_or(QdnfError::Unauthorized)?;
100        if self.revoked[i] {
101            return Err(QdnfError::Denied);
102        }
103        let g = self.slots[i].ok_or(QdnfError::Unauthorized)?;
104        require_active_mutual(patient_contact, clinician_contact)?;
105        g.grant.current_at(now_unix)?;
106        if g.grant.audience_digest != StrongDigest::ZERO && g.grant.audience_digest != recipient {
107            return Err(QdnfError::Denied);
108        }
109        Ok(())
110    }
111}
112
113impl Default for GrantTable {
114    fn default() -> Self {
115        Self::new()
116    }
117}
118
119/// `true` when visible from.
120pub(super) fn visible_from(grants: &GrantTable) -> [StrongDigest; MAX_VISIBLE] {
121    let mut out = [StrongDigest::ZERO; MAX_VISIBLE];
122    let mut n = 0usize;
123    let mut i = 0usize;
124    while i < MAX_SLOTS && n < MAX_VISIBLE {
125        if let Some(g) = grants.slots[i] {
126            if !grants.revoked[i] {
127                let mut dup = false;
128                let mut j = 0usize;
129                while j < n {
130                    if out[j] == g.recipient {
131                        dup = true;
132                        break;
133                    }
134                    j += 1;
135                }
136                if !dup {
137                    out[n] = g.recipient;
138                    n += 1;
139                }
140            }
141        }
142        i += 1;
143    }
144    out
145}
146
147#[cfg(test)]
148mod tests {
149    use super::*;
150    use crate::net::qdnf::types::ProfileId;
151
152    fn d(tag: u8) -> StrongDigest {
153        let mut x = StrongDigest::ZERO;
154        x.0[0] = tag;
155        x
156    }
157
158    fn grant_until(audience: StrongDigest, exp: u64) -> TemporalGrant {
159        TemporalGrant {
160            purpose_digest: d(0x11),
161            audience_digest: audience,
162            authority_generation: 1,
163            not_before_unix: 0,
164            expires_unix: exp,
165            profile: ProfileId::QDNF_CRYPTO_1,
166        }
167    }
168
169    #[test]
170    fn kinds_are_independent_and_visible() {
171        let mut t = GrantTable::new();
172        let clinician = d(2);
173        let team = d(3);
174        t.add(CareGrant {
175            kind: CareGrantKind::Clinician,
176            recipient: clinician,
177            grant: grant_until(clinician, 100),
178        })
179        .unwrap();
180        t.add(CareGrant {
181            kind: CareGrantKind::HospitalTeam,
182            recipient: team,
183            grant: grant_until(team, 100),
184        })
185        .unwrap();
186        assert!(t
187            .authorize_kind(
188                CareGrantKind::Clinician,
189                clinician,
190                ContactState::Active,
191                ContactState::Active,
192                10
193            )
194            .is_ok());
195        assert_eq!(
196            t.authorize_kind(
197                CareGrantKind::Guardian,
198                clinician,
199                ContactState::Active,
200                ContactState::Active,
201                10
202            ),
203            Err(QdnfError::Unauthorized)
204        );
205        assert_eq!(
206            t.authorize_kind(
207                CareGrantKind::AiProcessing,
208                team,
209                ContactState::Active,
210                ContactState::Active,
211                10
212            ),
213            Err(QdnfError::Unauthorized)
214        );
215        let seen = visible_from(&t);
216        assert_eq!(seen[0], clinician);
217        assert_eq!(seen[1], team);
218        assert_eq!(seen[2], StrongDigest::ZERO);
219    }
220
221    #[test]
222    fn recording_transcription_ai_need_own_grants() {
223        let mut t = GrantTable::new();
224        let rec = d(5);
225        assert_eq!(
226            t.authorize_kind(
227                CareGrantKind::Recording,
228                rec,
229                ContactState::Active,
230                ContactState::Active,
231                10
232            ),
233            Err(QdnfError::Unauthorized)
234        );
235        t.add(CareGrant {
236            kind: CareGrantKind::Recording,
237            recipient: rec,
238            grant: grant_until(rec, 100),
239        })
240        .unwrap();
241        t.add(CareGrant {
242            kind: CareGrantKind::Transcription,
243            recipient: rec,
244            grant: grant_until(rec, 100),
245        })
246        .unwrap();
247        t.add(CareGrant {
248            kind: CareGrantKind::AiProcessing,
249            recipient: rec,
250            grant: grant_until(rec, 100),
251        })
252        .unwrap();
253        assert!(t
254            .authorize_kind(
255                CareGrantKind::Transcription,
256                rec,
257                ContactState::Active,
258                ContactState::Active,
259                10
260            )
261            .is_ok());
262        t.revoke(CareGrantKind::AiProcessing, rec).unwrap();
263        assert_eq!(
264            t.authorize_kind(
265                CareGrantKind::AiProcessing,
266                rec,
267                ContactState::Active,
268                ContactState::Active,
269                10
270            ),
271            Err(QdnfError::Denied)
272        );
273    }
274}