use std::{
collections::HashMap,
sync::Mutex,
time::{Duration, Instant},
};
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
use hpke::{
aead::ChaCha20Poly1305, kdf::HkdfSha256, kem::X25519HkdfSha256, Deserializable, Kem as _,
OpModeR, OpModeS, Serializable,
};
use zeroize::Zeroizing;
type Kem = X25519HkdfSha256;
type PrivateKey = <Kem as hpke::Kem>::PrivateKey;
type PublicKey = <Kem as hpke::Kem>::PublicKey;
type EncappedKey = <Kem as hpke::Kem>::EncappedKey;
pub(super) const RECIPIENT_LIFETIME: Duration = Duration::from_secs(5 * 60);
#[derive(Debug, PartialEq, Eq)]
pub(super) struct Sealed {
pub(super) encapped_key: String,
pub(super) ciphertext: String,
}
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
pub(super) enum OpenError {
#[error("this daemon holds no key for that recipient; it expired, was used, or the daemon restarted")]
Gone,
#[error("the sealed bundle does not open: {0}")]
Invalid(InvalidBundle),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub(super) enum InvalidBundle {
#[error("the encapsulated key is malformed")]
EncappedKey,
#[error("the ciphertext is not standard base64")]
Ciphertext,
#[error("it was not sealed to this recipient, or was altered")]
Unauthentic,
}
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
pub(super) enum SealError {
#[error("the recipient is not a usable X25519 public key in standard base64")]
InvalidRecipient,
}
#[derive(Default)]
pub(super) struct Recipients {
held: Mutex<HashMap<String, Held>>,
}
struct Held {
private: PrivateKey,
expires: Instant,
}
impl Recipients {
pub(super) fn issue(&self, now: Instant) -> String {
let (private, public) = Kem::gen_keypair();
let public = BASE64.encode(public.to_bytes());
let mut held = self.held.lock().expect("recipients lock");
sweep(&mut held, now);
held.insert(
public.clone(),
Held {
private,
expires: now + RECIPIENT_LIFETIME,
},
);
public
}
pub(super) fn sweep(&self, now: Instant) {
sweep(&mut self.held.lock().expect("recipients lock"), now);
}
pub(super) fn open(
&self,
now: Instant,
recipient: &str,
sealed: &Sealed,
info: &[u8],
aad: &[u8],
) -> Result<Zeroizing<Vec<u8>>, OpenError> {
let key = {
let mut held = self.held.lock().expect("recipients lock");
sweep(&mut held, now);
held.remove(recipient).ok_or(OpenError::Gone)?
};
let encapped = BASE64
.decode(&sealed.encapped_key)
.ok()
.and_then(|bytes| EncappedKey::from_bytes(&bytes).ok())
.ok_or(OpenError::Invalid(InvalidBundle::EncappedKey))?;
let ciphertext = BASE64
.decode(&sealed.ciphertext)
.map_err(|_| OpenError::Invalid(InvalidBundle::Ciphertext))?;
hpke::single_shot_open::<ChaCha20Poly1305, HkdfSha256, Kem>(
&OpModeR::Base,
&key.private,
&encapped,
info,
&ciphertext,
aad,
)
.map(Zeroizing::new)
.map_err(|_| OpenError::Invalid(InvalidBundle::Unauthentic))
}
}
fn sweep(held: &mut HashMap<String, Held>, now: Instant) {
held.retain(|_, key| key.expires > now);
}
pub(super) fn seal(
recipient: &str,
info: &[u8],
aad: &[u8],
plaintext: &[u8],
) -> Result<Sealed, SealError> {
let public = BASE64
.decode(recipient)
.ok()
.and_then(|bytes| PublicKey::from_bytes(&bytes).ok())
.ok_or(SealError::InvalidRecipient)?;
let (encapped, ciphertext) = hpke::single_shot_seal::<ChaCha20Poly1305, HkdfSha256, Kem>(
&OpModeS::Base,
&public,
info,
plaintext,
aad,
)
.map_err(|_| SealError::InvalidRecipient)?;
Ok(Sealed {
encapped_key: BASE64.encode(encapped.to_bytes()),
ciphertext: BASE64.encode(ciphertext),
})
}
#[cfg(test)]
#[path = "seal_tests.rs"]
mod tests;