mailcycle 0.1.0

Rust client for the Mailcycle API. Create addresses that receive mail, read and decrypt it on your machine, send, and listen for events.
Documentation
//! The wire shapes around [`sealedbox`]: the JSON box the API stores for a
//! message, and the fixed-width framing an attachment body uses in object
//! storage.
//!
//! [`sealedbox`]: super::sealedbox

use serde::{Deserialize, Serialize};

use crate::encoding::{from_b64u, to_b64u};
use crate::error::{Error, Result};

use super::identity::address_key_pair;
use super::primitives::{random_bytes, KEY_BYTES};
use super::sealedbox::{open_raw, seal_raw, RawSealedBox};

/// "MCA1" and "MCA2": Mailcycle attachment, by version. The layout is the
/// same; the magic is the only thing that says whether the MAC framed the
/// additional data.
const MAGIC_V1: &[u8; 4] = b"MCA1";
const MAGIC_V2: &[u8; 4] = b"MCA2";
const ATTACHMENT_HEADER: usize = 4 + KEY_BYTES + 12 + 32;

/// The wire shape the mail server writes into a message's content.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AsymmetricBox {
    #[serde(default = "one")]
    pub v: u8,
    /// The sender's ephemeral public key.
    pub epk: String,
    pub n: String,
    pub c: String,
    pub t: String,
}

fn one() -> u8 {
    1
}

impl AsymmetricBox {
    fn version(&self) -> u8 {
        if self.v == 2 {
            2
        } else {
            1
        }
    }

    fn decode(&self) -> Result<RawSealedBox> {
        Ok(RawSealedBox {
            ephemeral_public_key: from_b64u(&self.epk).map_err(|_| Error::Decryption)?,
            nonce: from_b64u(&self.n).map_err(|_| Error::Decryption)?,
            ciphertext: from_b64u(&self.c).map_err(|_| Error::Decryption)?,
            tag: from_b64u(&self.t).map_err(|_| Error::Decryption)?,
        })
    }
}

pub fn seal_to_public_key(
    recipient_public_key: &[u8],
    plaintext: &[u8],
    aad: &str,
    version: u8,
) -> Result<AsymmetricBox> {
    let mut random = |length: usize| random_bytes(length);
    let box_ = seal_raw(recipient_public_key, plaintext, aad.as_bytes(), &mut random, version)?;
    Ok(AsymmetricBox {
        v: version,
        epk: to_b64u(&box_.ephemeral_public_key),
        n: to_b64u(&box_.nonce),
        c: to_b64u(&box_.ciphertext),
        t: to_b64u(&box_.tag),
    })
}

pub fn open_with_private_key(private_key: &[u8], box_: &AsymmetricBox, aad: &str) -> Result<Vec<u8>> {
    open_raw(private_key, &box_.decode()?, aad.as_bytes(), box_.version())
}

pub fn open_json_with_private_key<T: serde::de::DeserializeOwned>(
    private_key: &[u8],
    box_: &AsymmetricBox,
    aad: &str,
) -> Result<T> {
    serde_json::from_slice(&open_with_private_key(private_key, box_, aad)?).map_err(|_| Error::Decryption)
}

/// Opens mail the mail server sealed for one address.
///
/// The additional data is the address id AND the message id, matching what the
/// server seals with. The address binding stops a ciphertext being moved
/// between mailboxes; the message binding stops it being replayed within one.
/// Without the second, a server holding no key could re-file an old message as
/// a new arrival.
pub fn open_inbound_mail(
    vault_key: &[u8],
    address_id: &str,
    message_id: &str,
    box_: &AsymmetricBox,
) -> Result<Vec<u8>> {
    let (private_key, _) = address_key_pair(vault_key, address_id).ok_or(Error::Decryption)?;
    open_with_private_key(&private_key, box_, &format!("{address_id}:{message_id}"))
}

/// Opens an attachment body.
///
/// Raw bytes rather than JSON, because object storage holds bytes and base64
/// would cost a third of the size for nothing. The layout is fixed-width, so
/// this slices rather than parses:
///
/// ```text
/// magic(4) | ephemeral public key(32) | nonce(12) | tag(32) | ciphertext
/// ```
///
/// The additional data is the address id and the object's own key, so an
/// object served from the wrong row fails the MAC instead of handing back the
/// wrong file under the right name.
pub fn open_attachment_with_key(
    private_key: &[u8],
    address_id: &str,
    object_key: &str,
    data: &[u8],
) -> Result<Vec<u8>> {
    if data.len() < ATTACHMENT_HEADER {
        return Err(Error::Decryption);
    }
    let version = match &data[..4] {
        m if m == MAGIC_V1 => 1,
        m if m == MAGIC_V2 => 2,
        _ => return Err(Error::Decryption),
    };

    let box_ = RawSealedBox {
        ephemeral_public_key: data[4..36].to_vec(),
        nonce: data[36..48].to_vec(),
        tag: data[48..80].to_vec(),
        ciphertext: data[ATTACHMENT_HEADER..].to_vec(),
    };
    open_raw(private_key, &box_, format!("{address_id}:{object_key}").as_bytes(), version)
}

pub fn open_attachment(vault_key: &[u8], address_id: &str, object_key: &str, data: &[u8]) -> Result<Vec<u8>> {
    let (private_key, _) = address_key_pair(vault_key, address_id).ok_or(Error::Decryption)?;
    open_attachment_with_key(&private_key, address_id, object_key, data)
}