use std::collections::BTreeMap;
use bytes::Bytes;
use rings_core::delegation::DelegateeKey;
use rings_core::dht::Did;
use rings_core::ecc::elgamal::impls::secp256k1::AeadCiphertext;
use rings_core::ecc::PublicKey;
use super::envelope::mail_aad;
use super::envelope::MailDigest;
use super::envelope::MailElement;
use super::envelope::MailManifest;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OpenedMail {
pub mail_id: MailDigest,
pub message: Vec<u8>,
}
impl OpenedMail {
pub fn message_id(&self) -> Option<String> {
header_field(&self.message, "message-id")
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Opening {
Incomplete {
mail_id: MailDigest,
},
Unreadable {
mail_id: MailDigest,
},
Opened(OpenedMail),
}
impl Opening {
pub fn mail_id(&self) -> MailDigest {
match self {
Self::Incomplete { mail_id } | Self::Unreadable { mail_id } => *mail_id,
Self::Opened(mail) => mail.mail_id,
}
}
fn rank(&self) -> u8 {
match self {
Self::Incomplete { .. } => 0,
Self::Unreadable { .. } => 1,
Self::Opened(_) => 2,
}
}
}
pub fn open_mail(
elements: &[Bytes],
recipient: Did,
key: &DelegateeKey,
fresh: impl Fn(&MailDigest) -> bool,
) -> Vec<Opening> {
open_mail_with_keys(elements, recipient, std::slice::from_ref(key), fresh)
.into_iter()
.map(|(opening, _)| opening)
.collect()
}
fn join_opening(
earlier: (Opening, Option<PublicKey<33>>),
candidate: (Opening, Option<PublicKey<33>>),
) -> (Opening, Option<PublicKey<33>>) {
if candidate.0.rank() > earlier.0.rank() {
candidate
} else {
earlier
}
}
pub(crate) fn open_mail_with_keys(
elements: &[Bytes],
recipient: Did,
keys: &[DelegateeKey],
fresh: impl Fn(&MailDigest) -> bool,
) -> Vec<(Opening, Option<PublicKey<33>>)> {
let by_digest = elements
.iter()
.map(|element| (MailDigest::of(element), element))
.collect::<BTreeMap<_, _>>();
elements
.iter()
.filter_map(|element| match MailElement::decode(element) {
Ok(MailElement::Manifest(manifest)) => Some(manifest),
Ok(MailElement::Chunk(_)) | Err(_) => None,
})
.filter(|manifest| fresh(&manifest.mail_id) && manifest.is_well_formed())
.filter_map(|manifest| open_manifest(&manifest, &by_digest, recipient, keys))
.fold(
BTreeMap::<MailDigest, (Opening, Option<PublicKey<33>>)>::new(),
|mut outcomes, candidate| {
let mail_id = candidate.0.mail_id();
let joined = match outcomes.remove(&mail_id) {
Some(earlier) => join_opening(earlier, candidate),
None => candidate,
};
outcomes.insert(mail_id, joined);
outcomes
},
)
.into_values()
.collect()
}
fn open_manifest(
manifest: &MailManifest,
by_digest: &BTreeMap<MailDigest, &Bytes>,
recipient: Did,
keys: &[DelegateeKey],
) -> Option<(Opening, Option<PublicKey<33>>)> {
let mail_id = manifest.mail_id;
let Some(ciphertext) = assemble(manifest, by_digest) else {
return Some((Opening::Incomplete { mail_id }, None));
};
if MailDigest::of(&ciphertext) != mail_id {
return None;
}
let aad = mail_aad(recipient);
let message = rings_codec::deserialize::<AeadCiphertext>(&ciphertext)
.ok()
.and_then(|sealed| {
keys.iter().find_map(|key| {
key.decrypt_elgamal_aead(&sealed, &aad)
.ok()
.map(|plaintext| (plaintext, key.delegatee_public_key()))
})
});
Some(match message {
Some((message, opened_by)) => (
Opening::Opened(OpenedMail { mail_id, message }),
Some(opened_by),
),
None => (Opening::Unreadable { mail_id }, None),
})
}
fn assemble(manifest: &MailManifest, by_digest: &BTreeMap<MailDigest, &Bytes>) -> Option<Vec<u8>> {
manifest
.chunks
.iter()
.try_fold(Vec::new(), |mut ciphertext, digest| {
let MailElement::Chunk(slice) = MailElement::decode(by_digest.get(digest)?).ok()?
else {
return None;
};
ciphertext.extend_from_slice(&slice);
Some(ciphertext)
})
}
fn header_field(message: &[u8], name: &str) -> Option<String> {
let text = String::from_utf8_lossy(message);
let folded = text
.split('\n')
.map(|line| line.trim_end_matches('\r'))
.take_while(|line| !line.is_empty())
.try_fold(None::<String>, |acc, line| {
let is_continuation = line.starts_with([' ', '\t']);
match (acc, is_continuation) {
(Some(mut value), true) => {
value.push_str(line);
std::ops::ControlFlow::Continue(Some(value))
}
(Some(value), false) => std::ops::ControlFlow::Break(Some(value)),
(None, true) => std::ops::ControlFlow::Continue(None),
(None, false) => std::ops::ControlFlow::Continue(
line.split_once(':')
.filter(|(field, _)| field.trim().eq_ignore_ascii_case(name))
.map(|(_, rest)| rest.to_owned()),
),
}
});
let value = match folded {
std::ops::ControlFlow::Break(value) | std::ops::ControlFlow::Continue(value) => value,
};
value
.map(|value| value.trim().to_owned())
.filter(|value| !value.is_empty())
}