Fundamentum client v0.5.0
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "tabellarius-proto"
|
||||
description = "Tabellarius wire protocol: mailbox ids, per-mailbox request signatures, limits (docs/TABELLARIUS.md §3)"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
ed25519-dalek.workspace = true
|
||||
sha2.workspace = true
|
||||
zeroize.workspace = true
|
||||
thiserror.workspace = true
|
||||
data-encoding.workspace = true
|
||||
getrandom = "0.3"
|
||||
@@ -0,0 +1,201 @@
|
||||
//! The Tabellarius wire protocol (docs/TABELLARIUS.md §3), shared by the relay and the client.
|
||||
//!
|
||||
//! - Mailbox ids: a group's is `SHA-256("tabellarius mailbox v1" ‖ group id)`, an invite's is random.
|
||||
//! - Every request is signed by a random **per-mailbox** key ([`MailboxKey`]), never by an identity key.
|
||||
|
||||
use data_encoding::{BASE64URL_NOPAD, HEXLOWER};
|
||||
use ed25519_dalek::{Signer, SigningKey, VerifyingKey};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::fmt;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
/// The largest message (MLS ciphertext) the relay keeps.
|
||||
pub const MAX_MESSAGE: usize = 300 * 1024;
|
||||
/// The most messages in one upload.
|
||||
pub const MAX_BATCH: usize = 100;
|
||||
/// The largest request body.
|
||||
pub const MAX_BODY: usize = 2 * 1024 * 1024;
|
||||
/// The most messages one fetch returns.
|
||||
pub const FETCH_LIMIT: usize = 200;
|
||||
/// How far a request's time may be from the relay's, in seconds.
|
||||
pub const MAX_SKEW: u64 = 120;
|
||||
|
||||
/// Live subscribe (docs/V1_1B.md §3): the most subscriptions on one socket.
|
||||
pub const LIVE_MAX_SUBS: usize = 32;
|
||||
/// The most open subscriptions per mailbox key, over all sockets.
|
||||
pub const LIVE_MAX_PER_KEY: u32 = 4;
|
||||
/// A socket with nothing from its client for this long is closed.
|
||||
pub const LIVE_IDLE_SECS: u64 = 600;
|
||||
/// The method a subscription is signed with.
|
||||
pub const LIVE_METHOD: &str = "LIVE";
|
||||
|
||||
/// The path a subscription to `mailbox` from `after` is signed with (method [`LIVE_METHOD`], empty body).
|
||||
pub fn live_path(mailbox: &str, after: u64) -> String {
|
||||
format!("/v1/mailboxes/{mailbox}/live?after={after}")
|
||||
}
|
||||
|
||||
pub const H_KEY: &str = "tab-key";
|
||||
pub const H_TIME: &str = "tab-time";
|
||||
pub const H_NONCE: &str = "tab-nonce";
|
||||
pub const H_SIG: &str = "tab-sig";
|
||||
|
||||
const REQUEST_DOMAIN: &[u8] = b"tabellarius request v1\0";
|
||||
const MAILBOX_DOMAIN: &[u8] = b"tabellarius mailbox v1";
|
||||
|
||||
pub fn b64(b: &[u8]) -> String {
|
||||
BASE64URL_NOPAD.encode(b)
|
||||
}
|
||||
|
||||
pub fn unb64(s: &str) -> Option<Vec<u8>> {
|
||||
BASE64URL_NOPAD.decode(s.as_bytes()).ok()
|
||||
}
|
||||
|
||||
pub fn unb64_32(s: &str) -> Option<[u8; 32]> {
|
||||
unb64(s)?.try_into().ok()
|
||||
}
|
||||
|
||||
/// A group's mailbox id.
|
||||
pub fn group_mailbox(group_id: &[u8]) -> [u8; 32] {
|
||||
Sha256::new().chain_update(MAILBOX_DOMAIN).chain_update(group_id).finalize().into()
|
||||
}
|
||||
|
||||
/// 32 bytes from the OS CSPRNG.
|
||||
pub fn random32() -> [u8; 32] {
|
||||
let mut b = [0u8; 32];
|
||||
getrandom::fill(&mut b).expect("the OS has randomness");
|
||||
b
|
||||
}
|
||||
|
||||
/// What a request's signature covers.
|
||||
pub fn signed_bytes(method: &str, path_and_query: &str, time: u64, nonce: &str, body: &[u8]) -> Vec<u8> {
|
||||
let body_hash = HEXLOWER.encode(&Sha256::digest(body));
|
||||
let mut out = REQUEST_DOMAIN.to_vec();
|
||||
out.extend_from_slice(format!("{method}\n{path_and_query}\n{time}\n{nonce}\n{body_hash}").as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
/// The four headers of a signed request.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct SignedHeaders {
|
||||
pub key: String,
|
||||
pub time: String,
|
||||
pub nonce: String,
|
||||
pub sig: String,
|
||||
}
|
||||
|
||||
impl SignedHeaders {
|
||||
pub fn pairs(&self) -> [(&'static str, &str); 4] {
|
||||
[(H_KEY, &self.key), (H_TIME, &self.time), (H_NONCE, &self.nonce), (H_SIG, &self.sig)]
|
||||
}
|
||||
}
|
||||
|
||||
/// A random key for one mailbox. It identifies a device in that mailbox and nowhere else.
|
||||
pub struct MailboxKey(SigningKey);
|
||||
|
||||
impl MailboxKey {
|
||||
pub fn generate() -> MailboxKey {
|
||||
let seed = Zeroizing::new(random32());
|
||||
MailboxKey(SigningKey::from_bytes(&seed))
|
||||
}
|
||||
|
||||
/// From a seed kept in the client's encrypted state.
|
||||
pub fn from_seed(seed: &[u8; 32]) -> MailboxKey {
|
||||
MailboxKey(SigningKey::from_bytes(seed))
|
||||
}
|
||||
|
||||
/// For the client's encrypted state only.
|
||||
pub fn seed(&self) -> Zeroizing<[u8; 32]> {
|
||||
Zeroizing::new(self.0.to_bytes())
|
||||
}
|
||||
|
||||
pub fn public(&self) -> [u8; 32] {
|
||||
self.0.verifying_key().to_bytes()
|
||||
}
|
||||
|
||||
pub fn sign_request(&self, method: &str, path_and_query: &str, body: &[u8], time: u64) -> SignedHeaders {
|
||||
let nonce = b64(&random32()[..16]);
|
||||
let sig = self.0.sign(&signed_bytes(method, path_and_query, time, &nonce, body));
|
||||
SignedHeaders { key: b64(&self.public()), time: time.to_string(), nonce, sig: b64(&sig.to_bytes()) }
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for MailboxKey {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("MailboxKey([redacted])")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum AuthError {
|
||||
#[error("unsigned")]
|
||||
Unsigned,
|
||||
#[error("stale")]
|
||||
Stale,
|
||||
#[error("bad_signature")]
|
||||
BadSignature,
|
||||
}
|
||||
|
||||
/// Checks a request's signature and time. Returns the key and nonce; registration and replay are the
|
||||
/// relay's to check.
|
||||
pub fn verify_request(
|
||||
method: &str,
|
||||
path_and_query: &str,
|
||||
body: &[u8],
|
||||
headers: [Option<&str>; 4],
|
||||
now: u64,
|
||||
) -> Result<([u8; 32], Vec<u8>), AuthError> {
|
||||
let [Some(key), Some(time), Some(nonce), Some(sig)] = headers else { return Err(AuthError::Unsigned) };
|
||||
let key = unb64_32(key).ok_or(AuthError::Unsigned)?;
|
||||
let t: u64 = time.parse().map_err(|_| AuthError::Unsigned)?;
|
||||
let nonce_bytes = unb64(nonce).filter(|n| n.len() == 16).ok_or(AuthError::Unsigned)?;
|
||||
let sig: [u8; 64] = unb64(sig).and_then(|s| s.try_into().ok()).ok_or(AuthError::Unsigned)?;
|
||||
if now.abs_diff(t) > MAX_SKEW {
|
||||
return Err(AuthError::Stale);
|
||||
}
|
||||
let vk = VerifyingKey::from_bytes(&key).map_err(|_| AuthError::BadSignature)?;
|
||||
vk.verify_strict(
|
||||
&signed_bytes(method, path_and_query, t, nonce, body),
|
||||
&ed25519_dalek::Signature::from_bytes(&sig),
|
||||
)
|
||||
.map_err(|_| AuthError::BadSignature)?;
|
||||
Ok((key, nonce_bytes))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_signed_request_verifies_and_any_change_breaks_it() {
|
||||
let k = MailboxKey::generate();
|
||||
let h = k.sign_request("POST", "/v1/mailboxes/x/messages", b"{}", 1000);
|
||||
fn hs(h: &SignedHeaders) -> [Option<&str>; 4] {
|
||||
[Some(h.key.as_str()), Some(h.time.as_str()), Some(h.nonce.as_str()), Some(h.sig.as_str())]
|
||||
}
|
||||
assert_eq!(verify_request("POST", "/v1/mailboxes/x/messages", b"{}", hs(&h), 1000).unwrap().0, k.public());
|
||||
assert_eq!(
|
||||
verify_request("POST", "/v1/mailboxes/y/messages", b"{}", hs(&h), 1000),
|
||||
Err(AuthError::BadSignature)
|
||||
);
|
||||
assert_eq!(
|
||||
verify_request("POST", "/v1/mailboxes/x/messages", b"{ }", hs(&h), 1000),
|
||||
Err(AuthError::BadSignature)
|
||||
);
|
||||
assert_eq!(
|
||||
verify_request("GET", "/v1/mailboxes/x/messages", b"{}", hs(&h), 1000),
|
||||
Err(AuthError::BadSignature)
|
||||
);
|
||||
assert_eq!(
|
||||
verify_request("POST", "/v1/mailboxes/x/messages", b"{}", hs(&h), 1000 + MAX_SKEW + 1),
|
||||
Err(AuthError::Stale)
|
||||
);
|
||||
assert_eq!(verify_request("POST", "/", b"", [None, None, None, None], 1000), Err(AuthError::Unsigned));
|
||||
assert_eq!(format!("{k:?}"), "MailboxKey([redacted])");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_mailboxes_are_distinct_and_stable() {
|
||||
assert_eq!(group_mailbox(b"g1"), group_mailbox(b"g1"));
|
||||
assert_ne!(group_mailbox(b"g1"), group_mailbox(b"g2"));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user