Skip to main content

rings_node/mail/
open.rs

1//! The recipient's opening of its mail topic (pure).
2//!
3//! ```text
4//!   by_digest  = { H(e) ↦ e | e ∈ elements }
5//!   manifests  = { M | e ∈ elements decodes to M ∧ 1 ≤ |M.chunks| ≤ N_max }
6//!   open(M)    = Incomplete             some H(chunk_i) of M names no chunk element
7//!              | ⊥ (forged)             H(chunk_0 ‖ … ‖ chunk_{n−1}) ≠ M.mail_id
8//!              | Unreadable             the recipient's key does not open c
9//!              | Opened(m)
10//!   opening(x) = max { open(M) | M ∈ manifests, M.mail_id = x }
11//!                under Incomplete < Unreadable < Opened
12//! ```
13//!
14//! Laws:
15//! - **Integrity.** A chunk is read only through a manifest that lists its element's digest, in
16//!   that manifest's order, and the mail opens only if the listed chunks concatenate to the
17//!   preimage of its `mail_id`: a forged chunk, or a manifest listing one, never alters a mail.
18//! - **All or nothing.** The AEAD tag covers all of `c`: a missing chunk leaves the mail
19//!   `Incomplete`, and an altered one is a different element, so its digest is not listed.
20//! - **Content address.** A manifest whose chunks do not concatenate to `H⁻¹(mail_id)` is
21//!   forged and ignored: no forger can make a mail `Unreadable` and so stop it being retried.
22//! - **Join.** The outcome per `mail_id` is the maximum over its manifests, so the result does
23//!   not depend on the order of elements, and a forged manifest never hides a genuine one.
24//! - **Round trip.** `seal(m, (d, ek))` opens to `Opened(m)` under `ek`'s secret.
25
26use std::collections::BTreeMap;
27
28use bytes::Bytes;
29use rings_core::delegation::DelegateeKey;
30use rings_core::dht::Did;
31use rings_core::ecc::elgamal::impls::secp256k1::AeadCiphertext;
32use rings_core::ecc::PublicKey;
33
34use super::envelope::mail_aad;
35use super::envelope::MailDigest;
36use super::envelope::MailElement;
37use super::envelope::MailManifest;
38
39/// A mail opened from its recipient's topic.
40#[derive(Clone, Debug, Eq, PartialEq)]
41pub struct OpenedMail {
42    /// `H(c)` of the ciphertext it was opened from.
43    pub mail_id: MailDigest,
44    /// The message, as the gateway received it with its trace headers.
45    pub message: Vec<u8>,
46}
47
48impl OpenedMail {
49    /// The message's `Message-ID` (RFC 5322 §3.6.4), unfolded and trimmed, if its header has
50    /// one: what the recipient deduplicates by.
51    pub fn message_id(&self) -> Option<String> {
52        header_field(&self.message, "message-id")
53    }
54}
55
56/// What one mail id in a topic opens to.
57#[derive(Clone, Debug, Eq, PartialEq)]
58pub enum Opening {
59    /// A manifest lists a chunk the topic does not hold: the mail is not filed, and is
60    /// tried again on the next read.
61    Incomplete {
62        /// The mail's id.
63        mail_id: MailDigest,
64    },
65    /// The whole ciphertext is present but the key does not open it: it is remembered and not
66    /// tried again.
67    Unreadable {
68        /// The mail's id.
69        mail_id: MailDigest,
70    },
71    /// The mail.
72    Opened(OpenedMail),
73}
74
75impl Opening {
76    /// The id of the mail this outcome is for.
77    pub fn mail_id(&self) -> MailDigest {
78        match self {
79            Self::Incomplete { mail_id } | Self::Unreadable { mail_id } => *mail_id,
80            Self::Opened(mail) => mail.mail_id,
81        }
82    }
83
84    /// This outcome's rank in `Incomplete < Unreadable < Opened`.
85    fn rank(&self) -> u8 {
86        match self {
87            Self::Incomplete { .. } => 0,
88            Self::Unreadable { .. } => 1,
89            Self::Opened(_) => 2,
90        }
91    }
92}
93
94/// Open the mail in `elements` for `recipient` with the secret of `key`, skipping every mail id
95/// `fresh` rejects: one outcome per mail id with a well-formed manifest whose chunks are not
96/// forged (the laws of this module).
97pub fn open_mail(
98    elements: &[Bytes],
99    recipient: Did,
100    key: &DelegateeKey,
101    fresh: impl Fn(&MailDigest) -> bool,
102) -> Vec<Opening> {
103    open_mail_with_keys(elements, recipient, std::slice::from_ref(key), fresh)
104        .into_iter()
105        .map(|(opening, _)| opening)
106        .collect()
107}
108
109/// Bounded join-semilattice join (`⊔`) over `(Opening, Option<PublicKey<33>>)` ordered by
110/// `Incomplete < Unreadable < Opened` (`Law (Join)`).
111///
112/// # Semilattice Laws
113///
114/// - **Idempotency**: `join_opening(a, a) == a`.
115/// - **Associativity**: `join_opening(join_opening(a, b), c) == join_opening(a, join_opening(b, c))`.
116/// - **Rank Commutativity**: `join_opening(a, b).0.rank() == join_opening(b, a).0.rank()`.
117/// - **Bottom Element**: `(Opening::Incomplete { mail_id }, None)` is the identity element for a
118///   given `mail_id`.
119fn join_opening(
120    earlier: (Opening, Option<PublicKey<33>>),
121    candidate: (Opening, Option<PublicKey<33>>),
122) -> (Opening, Option<PublicKey<33>>) {
123    if candidate.0.rank() > earlier.0.rank() {
124        candidate
125    } else {
126        earlier
127    }
128}
129
130/// Open the mail in `elements` for `recipient` trying `keys` in order, returning each mail id's
131/// outcome and the delegatee public key of the key that decrypted it when opened (#1153).
132pub(crate) fn open_mail_with_keys(
133    elements: &[Bytes],
134    recipient: Did,
135    keys: &[DelegateeKey],
136    fresh: impl Fn(&MailDigest) -> bool,
137) -> Vec<(Opening, Option<PublicKey<33>>)> {
138    let by_digest = elements
139        .iter()
140        .map(|element| (MailDigest::of(element), element))
141        .collect::<BTreeMap<_, _>>();
142    elements
143        .iter()
144        .filter_map(|element| match MailElement::decode(element) {
145            Ok(MailElement::Manifest(manifest)) => Some(manifest),
146            Ok(MailElement::Chunk(_)) | Err(_) => None,
147        })
148        .filter(|manifest| fresh(&manifest.mail_id) && manifest.is_well_formed())
149        .filter_map(|manifest| open_manifest(&manifest, &by_digest, recipient, keys))
150        .fold(
151            BTreeMap::<MailDigest, (Opening, Option<PublicKey<33>>)>::new(),
152            |mut outcomes, candidate| {
153                let mail_id = candidate.0.mail_id();
154                let joined = match outcomes.remove(&mail_id) {
155                    Some(earlier) => join_opening(earlier, candidate),
156                    None => candidate,
157                };
158                outcomes.insert(mail_id, joined);
159                outcomes
160            },
161        )
162        .into_values()
163        .collect()
164}
165
166/// What the well-formed `manifest` opens to over the elements `by_digest`, or `None` when it is
167/// forged (the content-address law).
168fn open_manifest(
169    manifest: &MailManifest,
170    by_digest: &BTreeMap<MailDigest, &Bytes>,
171    recipient: Did,
172    keys: &[DelegateeKey],
173) -> Option<(Opening, Option<PublicKey<33>>)> {
174    let mail_id = manifest.mail_id;
175    let Some(ciphertext) = assemble(manifest, by_digest) else {
176        return Some((Opening::Incomplete { mail_id }, None));
177    };
178    if MailDigest::of(&ciphertext) != mail_id {
179        return None;
180    }
181    let aad = mail_aad(recipient);
182    let message = rings_codec::deserialize::<AeadCiphertext>(&ciphertext)
183        .ok()
184        .and_then(|sealed| {
185            keys.iter().find_map(|key| {
186                key.decrypt_elgamal_aead(&sealed, &aad)
187                    .ok()
188                    .map(|plaintext| (plaintext, key.delegatee_public_key()))
189            })
190        });
191    Some(match message {
192        Some((message, opened_by)) => (
193            Opening::Opened(OpenedMail { mail_id, message }),
194            Some(opened_by),
195        ),
196        None => (Opening::Unreadable { mail_id }, None),
197    })
198}
199
200/// The ciphertext the chunks `manifest` lists concatenate to, in its order, or `None` when one
201/// is missing or is not a chunk element.
202fn assemble(manifest: &MailManifest, by_digest: &BTreeMap<MailDigest, &Bytes>) -> Option<Vec<u8>> {
203    manifest
204        .chunks
205        .iter()
206        .try_fold(Vec::new(), |mut ciphertext, digest| {
207            let MailElement::Chunk(slice) = MailElement::decode(by_digest.get(digest)?).ok()?
208            else {
209                return None;
210            };
211            ciphertext.extend_from_slice(&slice);
212            Some(ciphertext)
213        })
214}
215
216/// The value of the first header field `name` (lower case) of `message`, unfolded (RFC 5322
217/// §2.2.3) and trimmed; the header ends at the first empty line.
218fn header_field(message: &[u8], name: &str) -> Option<String> {
219    let text = String::from_utf8_lossy(message);
220    let folded = text
221        .split('\n')
222        .map(|line| line.trim_end_matches('\r'))
223        .take_while(|line| !line.is_empty())
224        .try_fold(None::<String>, |acc, line| {
225            let is_continuation = line.starts_with([' ', '\t']);
226            match (acc, is_continuation) {
227                (Some(mut value), true) => {
228                    value.push_str(line);
229                    std::ops::ControlFlow::Continue(Some(value))
230                }
231                (Some(value), false) => std::ops::ControlFlow::Break(Some(value)),
232                (None, true) => std::ops::ControlFlow::Continue(None),
233                (None, false) => std::ops::ControlFlow::Continue(
234                    line.split_once(':')
235                        .filter(|(field, _)| field.trim().eq_ignore_ascii_case(name))
236                        .map(|(_, rest)| rest.to_owned()),
237                ),
238            }
239        });
240    let value = match folded {
241        std::ops::ControlFlow::Break(value) | std::ops::ControlFlow::Continue(value) => value,
242    };
243    value
244        .map(|value| value.trim().to_owned())
245        .filter(|value| !value.is_empty())
246}