Skip to main content

qualia_core_db/net/qdnf/clinical/
envelope.rs

1//! Verified recipient envelopes. Intermediaries cannot decrypt.
2
3use super::grants::{visible_from, GrantTable, MAX_VISIBLE};
4use super::{admit_outcome, first_empty, require_active_mutual, MAX_SLOTS};
5use crate::crypto::network::digest::sha384;
6use crate::net::qdnf::authority::{ContactState, PolicyOutcome};
7use crate::net::qdnf::errors::QdnfError;
8use crate::net::qdnf::policy_labels::{
9    join_labels_into, Confidentiality, LabelFields, VerifiedLabel,
10};
11use crate::net::qdnf::profiles::ProtectionProfile;
12use crate::net::qdnf::types::StrongDigest;
13
14#[inline]
15/// `?::intermediary_decrypts`.
16pub const fn intermediary_decrypts() -> bool {
17    false
18}
19
20#[inline]
21/// `?::generic_log_contains_medical_payload`.
22pub const fn generic_log_contains_medical_payload() -> bool {
23    false
24}
25
26/// Payload envelope bound to projection, label, purpose, expiry and recipients.
27#[repr(C)]
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub struct PayloadEnvelope {
30    pub projection: StrongDigest,
31    pub label_digest: StrongDigest,
32    pub purpose: StrongDigest,
33    pub expires_unix: u64,
34    pub profile: ProtectionProfile,
35    pub binding: StrongDigest,
36    pub ciphertext_len: u32,
37    pub ciphertext_digest: StrongDigest,
38    recipients: [StrongDigest; MAX_VISIBLE],
39    recipient_count: u8,
40}
41
42impl PayloadEnvelope {
43    /// Visible recipients on the envelope.
44    pub fn recipient_count(&self) -> u8 {
45        self.recipient_count
46    }
47
48    /// Fixed array of visible recipient digests.
49    pub fn recipients(&self) -> [StrongDigest; MAX_VISIBLE] {
50        self.recipients
51    }
52}
53
54fn bind_envelope(
55    projection: StrongDigest,
56    label_digest: StrongDigest,
57    purpose: StrongDigest,
58    expires_unix: u64,
59    ciphertext_digest: StrongDigest,
60    recipients: &[StrongDigest],
61) -> StrongDigest {
62    let mut buf = [0u8; 48 * 6 + 8];
63    buf[..48].copy_from_slice(&projection.0);
64    buf[48..96].copy_from_slice(&label_digest.0);
65    buf[96..144].copy_from_slice(&purpose.0);
66    buf[144..152].copy_from_slice(&expires_unix.to_be_bytes());
67    buf[152..200].copy_from_slice(&ciphertext_digest.0);
68    let mut rec = StrongDigest::ZERO;
69    if !recipients.is_empty() {
70        rec = recipients[0];
71    }
72    buf[200..248].copy_from_slice(&rec.0);
73    sha384(&buf)
74}
75
76/// Seal ciphertext under a verified label and the actual grant recipients.
77#[allow(clippy::too_many_arguments)]
78pub fn seal_envelope(
79    grants: &GrantTable,
80    label: &VerifiedLabel,
81    projection: StrongDigest,
82    purpose: StrongDigest,
83    expires_unix: u64,
84    ciphertext: &[u8],
85    outcome: PolicyOutcome,
86    patient_contact: ContactState,
87    clinician_contact: ContactState,
88    now_unix: u64,
89) -> Result<PayloadEnvelope, QdnfError> {
90    if ciphertext.is_empty() || projection == StrongDigest::ZERO || purpose == StrongDigest::ZERO {
91        return Err(QdnfError::Malformed);
92    }
93    if label.confidentiality() == Confidentiality::Unknown {
94        return Err(QdnfError::Conflict);
95    }
96    require_active_mutual(patient_contact, clinician_contact)?;
97    admit_outcome(outcome)?;
98    if now_unix >= expires_unix {
99        return Err(QdnfError::Expired);
100    }
101    let recipients = visible_from(grants);
102    let mut count = 0u8;
103    let mut recs = [StrongDigest::ZERO; MAX_VISIBLE];
104    let mut i = 0usize;
105    while i < MAX_VISIBLE {
106        if recipients[i] != StrongDigest::ZERO {
107            recs[count as usize] = recipients[i];
108            count = count.checked_add(1).ok_or(QdnfError::Capacity)?;
109        }
110        i += 1;
111    }
112    if count == 0 {
113        return Err(QdnfError::Unauthorized);
114    }
115    let ciphertext_len = u32::try_from(ciphertext.len()).map_err(|_| QdnfError::Range)?;
116    let ciphertext_digest = sha384(ciphertext);
117    let label_digest = label.exact_bytes_digest();
118    let binding = bind_envelope(
119        projection,
120        label_digest,
121        purpose,
122        expires_unix,
123        ciphertext_digest,
124        &recs[..count as usize],
125    );
126    Ok(PayloadEnvelope {
127        projection,
128        label_digest,
129        purpose,
130        expires_unix,
131        profile: ProtectionProfile::P2,
132        binding,
133        ciphertext_len,
134        ciphertext_digest,
135        recipients: recs,
136        recipient_count: count,
137    })
138}
139
140/// Actual key recipients bound on the envelope. Unused slots are ZERO.
141pub fn visible_recipients(envelope: &PayloadEnvelope) -> [StrongDigest; MAX_VISIBLE] {
142    envelope.recipients()
143}
144
145/// Ordinary bytes are not an envelope. Recipient must be a bound key holder.
146pub fn verify_envelope(
147    envelope: &PayloadEnvelope,
148    recipient: StrongDigest,
149    now_unix: u64,
150) -> Result<(), QdnfError> {
151    if envelope.ciphertext_len == 0
152        || envelope.binding == StrongDigest::ZERO
153        || envelope.ciphertext_digest == StrongDigest::ZERO
154    {
155        return Err(QdnfError::Malformed);
156    }
157    if now_unix >= envelope.expires_unix {
158        return Err(QdnfError::Expired);
159    }
160    let expected = bind_envelope(
161        envelope.projection,
162        envelope.label_digest,
163        envelope.purpose,
164        envelope.expires_unix,
165        envelope.ciphertext_digest,
166        &envelope.recipients[..envelope.recipient_count as usize],
167    );
168    if expected != envelope.binding {
169        return Err(QdnfError::Conflict);
170    }
171    let mut i = 0usize;
172    while i < envelope.recipient_count as usize {
173        if envelope.recipients[i] == recipient {
174            return Ok(());
175        }
176        i += 1;
177    }
178    Err(QdnfError::Denied)
179}
180
181/// Network intermediary. Generic relays set `decrypts` to false.
182#[repr(C)]
183#[derive(Clone, Copy, Debug, PartialEq, Eq)]
184pub struct IntermediaryRole {
185    pub decrypts: bool,
186}
187
188impl IntermediaryRole {
189    pub const NETWORK: Self = Self { decrypts: false };
190
191    /// Forwards ciphertext `ct` under this role, logging the hop.
192    pub fn forward(self, ct: &[u8], log: &mut GenericLog) -> Result<StrongDigest, QdnfError> {
193        if self.decrypts {
194            return Err(QdnfError::Denied);
195        }
196        forward_ciphertext(ct, log)
197    }
198}
199
200/// Declared clinical-service decryption boundary.
201#[repr(C)]
202#[derive(Clone, Copy, Debug, PartialEq, Eq)]
203pub struct ClinicalBoundary {
204    pub service: StrongDigest,
205}
206
207impl ClinicalBoundary {
208    /// Decrypts `ct` for `service`; fails closed across the clinical boundary.
209    pub fn decrypt(&self, service: StrongDigest, ct: &[u8]) -> Result<(), QdnfError> {
210        if ct.is_empty() {
211            return Err(QdnfError::Malformed);
212        }
213        if self.service == StrongDigest::ZERO || self.service != service {
214            return Err(QdnfError::Denied);
215        }
216        Ok(())
217    }
218}
219
220/// Generic network/payment log: length and digest only.
221#[repr(C)]
222#[derive(Clone, Copy, Debug, PartialEq, Eq)]
223pub struct GenericLogRecord {
224    pub ciphertext_len: u32,
225    pub ciphertext_digest: StrongDigest,
226}
227
228/// Eight-slot generic log. Payload bytes are never stored.
229#[derive(Clone, Copy, Debug)]
230pub struct GenericLog {
231    records: [Option<GenericLogRecord>; MAX_SLOTS],
232}
233
234impl GenericLog {
235    /// Creates a default `GenericLog`.
236    pub const fn new() -> Self {
237        Self {
238            records: [None; MAX_SLOTS],
239        }
240    }
241
242    /// Most recent log record.
243    pub fn last(&self) -> Option<GenericLogRecord> {
244        let mut i = MAX_SLOTS;
245        while i > 0 {
246            i -= 1;
247            if let Some(r) = self.records[i] {
248                return Some(r);
249            }
250        }
251        None
252    }
253
254    /// Appends a ciphertext record to the generic log.
255    pub fn append_ciphertext_bytes(&mut self, ct: &[u8]) -> Result<(), QdnfError> {
256        let _ = ct;
257        Err(QdnfError::Denied)
258    }
259
260    fn record_meta(&mut self, len: u32, digest: StrongDigest) -> Result<(), QdnfError> {
261        let i = first_empty(&self.records).ok_or(QdnfError::Capacity)?;
262        self.records[i] = Some(GenericLogRecord {
263            ciphertext_len: len,
264            ciphertext_digest: digest,
265        });
266        Ok(())
267    }
268}
269
270/// Forward ciphertext. Records only length and digest on `log`.
271pub fn forward_ciphertext(ct: &[u8], log: &mut GenericLog) -> Result<StrongDigest, QdnfError> {
272    if ct.is_empty() {
273        return Err(QdnfError::Malformed);
274    }
275    let len = u32::try_from(ct.len()).map_err(|_| QdnfError::Range)?;
276    let digest = sha384(ct);
277    log.record_meta(len, digest)?;
278    Ok(digest)
279}
280
281/// Backup restore cannot drop confidentiality or restriction bits.
282pub fn restore_labelled_backup(
283    stored: &VerifiedLabel,
284    restored: &LabelFields,
285) -> Result<(), QdnfError> {
286    let stored_rank = stored.confidentiality().lattice_rank()?;
287    let restored_rank = restored.confidentiality.lattice_rank()?;
288    if restored_rank < stored_rank {
289        return Err(QdnfError::Denied);
290    }
291    if restored.restriction_bits & stored.fields().restriction_bits
292        != stored.fields().restriction_bits
293    {
294        return Err(QdnfError::Denied);
295    }
296    Ok(())
297}
298
299/// Response inherits the request and every consulted record label.
300pub fn inherit_response_label(
301    request: &LabelFields,
302    consulted: &VerifiedLabel,
303    out: &mut LabelFields,
304) -> Result<(), QdnfError> {
305    join_labels_into(request, core::slice::from_ref(consulted.fields()), out)
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311    use crate::net::qdnf::authority::TemporalGrant;
312    use crate::net::qdnf::clinical::grants::{CareGrant, CareGrantKind};
313    use crate::net::qdnf::policy_labels::{encode_label_into, verify_label};
314    use crate::net::qdnf::types::ProfileId;
315
316    fn d(tag: u8) -> StrongDigest {
317        let mut x = StrongDigest::ZERO;
318        x.0[0] = tag;
319        x.0[47] = 7;
320        x
321    }
322
323    fn grant_until(audience: StrongDigest, exp: u64) -> TemporalGrant {
324        TemporalGrant {
325            purpose_digest: d(0x11),
326            audience_digest: audience,
327            authority_generation: 1,
328            not_before_unix: 0,
329            expires_unix: exp,
330            profile: ProfileId::QDNF_CRYPTO_1,
331        }
332    }
333
334    fn label() -> VerifiedLabel {
335        let mut fields = LabelFields::request(Confidentiality::C2Sensitive, d(1));
336        fields.audience = d(2);
337        let mut buf = [0u8; 256];
338        let n = encode_label_into(&fields, &mut buf).unwrap();
339        verify_label(fields, &buf[..n]).unwrap()
340    }
341
342    #[test]
343    fn intermediary_cannot_decrypt_and_log_has_no_payload() {
344        let ct = b"envelope-ct";
345        let mut log = GenericLog::new();
346        let got = forward_ciphertext(ct, &mut log).expect("forward");
347        let rec = log.last().expect("meta");
348        assert_eq!(rec.ciphertext_len as usize, ct.len());
349        assert_eq!(rec.ciphertext_digest, got);
350        assert_eq!(log.append_ciphertext_bytes(ct), Err(QdnfError::Denied));
351        assert!(!generic_log_contains_medical_payload());
352        assert!(!intermediary_decrypts());
353        assert!(!IntermediaryRole::NETWORK.decrypts);
354        assert_eq!(
355            IntermediaryRole { decrypts: true }.forward(ct, &mut GenericLog::new()),
356            Err(QdnfError::Denied)
357        );
358        let boundary = ClinicalBoundary { service: d(0x42) };
359        assert!(boundary.decrypt(d(0x42), ct).is_ok());
360        assert_eq!(boundary.decrypt(d(0x43), ct), Err(QdnfError::Denied));
361    }
362
363    #[test]
364    fn seal_binds_projection_label_purpose_expiry_and_recipient() {
365        let mut grants = GrantTable::new();
366        grants
367            .add(CareGrant {
368                kind: CareGrantKind::Clinician,
369                recipient: d(2),
370                grant: grant_until(d(2), 100),
371            })
372            .unwrap();
373        let env = seal_envelope(
374            &grants,
375            &label(),
376            d(0x21),
377            d(0x11),
378            100,
379            b"sealed-ct",
380            PolicyOutcome::Allow,
381            ContactState::Active,
382            ContactState::Active,
383            10,
384        )
385        .unwrap();
386        assert_eq!(env.projection, d(0x21));
387        assert_eq!(env.purpose, d(0x11));
388        assert_eq!(env.expires_unix, 100);
389        assert_eq!(env.ciphertext_digest, sha384(b"sealed-ct"));
390        assert!(verify_envelope(&env, d(2), 10).is_ok());
391        assert_eq!(verify_envelope(&env, d(9), 10), Err(QdnfError::Denied));
392        assert_eq!(
393            seal_envelope(
394                &grants,
395                &label(),
396                d(0x21),
397                d(0x11),
398                100,
399                b"sealed-ct",
400                PolicyOutcome::Allow,
401                ContactState::Suspended,
402                ContactState::Active,
403                10,
404            ),
405            Err(QdnfError::Denied)
406        );
407    }
408}