Fundamentum client v0.5.0
This commit is contained in:
@@ -0,0 +1,296 @@
|
||||
//! The Domi event envelope, `TEV1` (docs/TESSERA.md §8).
|
||||
//!
|
||||
//! Decoding is strict and total: it returns a whole [`Envelope`] or a [`DecodeError`] that says why, never
|
||||
//! a panic and never part of an event. Encoding is canonical, so `decode(b).as_bytes() == b`. A decoded
|
||||
//! envelope is not trusted until [`Envelope::verify`] passes.
|
||||
|
||||
use std::fmt;
|
||||
use tessera::{CertError, Hlc, Id, LogEvent, OrderKey, PublicKey, Signature, Subkey, SubkeyCert, verify_event_sig};
|
||||
|
||||
pub const MAGIC: &[u8; 4] = b"TEV1";
|
||||
/// The largest payload (MLS ciphertext) one event may carry.
|
||||
pub const MAX_PAYLOAD: usize = 256 * 1024;
|
||||
/// The largest envelope: the payload plus room for every other field.
|
||||
pub const MAX_ENVELOPE: usize = MAX_PAYLOAD + 1024;
|
||||
|
||||
const CERT_MIN: usize = 4 + 32 + 32 + 2 + 2 + 8 + 8 + 64;
|
||||
const CERT_MAX: usize = CERT_MIN + 2 * 31;
|
||||
|
||||
/// The fields in their only allowed order: (tag, name, smallest and largest length).
|
||||
const FIELDS: [(u8, &str, usize, usize); 7] = [
|
||||
(1, "app", 1, 32),
|
||||
(2, "schema", 4, 4),
|
||||
(3, "hlc", 12, 12),
|
||||
(4, "author", 32, 32),
|
||||
(5, "cert", CERT_MIN, CERT_MAX),
|
||||
(6, "payload", 0, MAX_PAYLOAD),
|
||||
(7, "sig", 64, 64),
|
||||
];
|
||||
|
||||
/// One signed event.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct Envelope {
|
||||
app: Id,
|
||||
schema: u32,
|
||||
hlc: Hlc,
|
||||
author: PublicKey,
|
||||
cert: SubkeyCert,
|
||||
payload: Vec<u8>,
|
||||
sig: Signature,
|
||||
/// The canonical encoding; the signature covers `bytes[..sig_at]`.
|
||||
bytes: Vec<u8>,
|
||||
sig_at: usize,
|
||||
hash: [u8; 32],
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum DecodeError {
|
||||
#[error("the envelope is {0} bytes, more than the limit")]
|
||||
TooLarge(usize),
|
||||
#[error("too short to be an envelope")]
|
||||
TooShort,
|
||||
#[error("not a TEV1 envelope")]
|
||||
BadMagic,
|
||||
#[error("unknown field {0}")]
|
||||
UnknownField(u8),
|
||||
#[error("field {found} where field {expected} must be")]
|
||||
FieldOutOfOrder { expected: u8, found: u8 },
|
||||
#[error("the envelope ends inside field {field}")]
|
||||
Truncated { field: &'static str },
|
||||
#[error("field {field} has a wrong length ({len})")]
|
||||
BadLength { field: &'static str, len: u64 },
|
||||
#[error("field {field} is invalid: {reason}")]
|
||||
Invalid { field: &'static str, reason: &'static str },
|
||||
#[error("bytes after the last field")]
|
||||
TrailingBytes,
|
||||
#[error("the certificate does not decode: {0}")]
|
||||
Cert(CertError),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum SealError {
|
||||
#[error("the certificate is for another key than the one signing")]
|
||||
CertForAnotherKey,
|
||||
#[error("the payload is larger than {MAX_PAYLOAD} bytes")]
|
||||
PayloadTooLarge,
|
||||
#[error("the bytes are not the to-be-signed part of an envelope")]
|
||||
NotToBeSigned,
|
||||
#[error("the signature does not verify for the author")]
|
||||
BadSignature,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum VerifyError {
|
||||
#[error("the author is not the key the certificate certifies")]
|
||||
AuthorNotCert,
|
||||
#[error("the certificate is for another app")]
|
||||
WrongApp,
|
||||
#[error("the certificate's identity is not a member of this group")]
|
||||
UnknownRoot,
|
||||
#[error("the certificate was not valid at the event's time: {0}")]
|
||||
Cert(CertError),
|
||||
#[error("the event's clock is too far in the future")]
|
||||
FromTheFuture,
|
||||
#[error("the event's signature is not valid")]
|
||||
BadSignature,
|
||||
}
|
||||
|
||||
fn put(out: &mut Vec<u8>, tag: u8, value: &[u8]) {
|
||||
out.push(tag);
|
||||
out.extend_from_slice(&(value.len() as u32).to_be_bytes());
|
||||
out.extend_from_slice(value);
|
||||
}
|
||||
|
||||
impl Envelope {
|
||||
/// Signs an event with `subkey`, whose cert is `cert`. The app is the cert's app.
|
||||
pub fn seal(
|
||||
subkey: &Subkey,
|
||||
cert: &SubkeyCert,
|
||||
schema: u32,
|
||||
hlc: Hlc,
|
||||
payload: &[u8],
|
||||
) -> Result<Envelope, SealError> {
|
||||
let tbs = Envelope::to_be_signed(&subkey.public(), cert, schema, hlc, payload)?;
|
||||
let sig = subkey.sign_event_tbs(&tbs);
|
||||
Envelope::with_signature(tbs, sig)
|
||||
}
|
||||
|
||||
/// The bytes `author` signs (after `EVENT_DOMAIN`), for a signer that cannot sign at once (a WebCrypto
|
||||
/// key in the browser, docs/V1_1B.md §2). Finish with [`Envelope::with_signature`].
|
||||
pub fn to_be_signed(
|
||||
author: &PublicKey,
|
||||
cert: &SubkeyCert,
|
||||
schema: u32,
|
||||
hlc: Hlc,
|
||||
payload: &[u8],
|
||||
) -> Result<Vec<u8>, SealError> {
|
||||
if cert.subkey() != *author {
|
||||
return Err(SealError::CertForAnotherKey);
|
||||
}
|
||||
if payload.len() > MAX_PAYLOAD {
|
||||
return Err(SealError::PayloadTooLarge);
|
||||
}
|
||||
let mut bytes = MAGIC.to_vec();
|
||||
put(&mut bytes, 1, cert.app_id().as_str().as_bytes());
|
||||
put(&mut bytes, 2, &schema.to_be_bytes());
|
||||
put(&mut bytes, 3, &hlc.to_bytes());
|
||||
put(&mut bytes, 4, author.as_bytes());
|
||||
put(&mut bytes, 5, &cert.to_bytes());
|
||||
put(&mut bytes, 6, payload);
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// Finishes an envelope from [`Envelope::to_be_signed`]'s bytes and the author's signature over them.
|
||||
/// Refuses a signature that does not verify, so a broken signer cannot make an event others would drop.
|
||||
pub fn with_signature(tbs: Vec<u8>, sig: Signature) -> Result<Envelope, SealError> {
|
||||
let mut bytes = tbs;
|
||||
let sig_at = bytes.len();
|
||||
put(&mut bytes, 7, sig.as_bytes());
|
||||
let e = Envelope::decode(&bytes).map_err(|_| SealError::NotToBeSigned)?;
|
||||
if e.sig_at != sig_at || !verify_event_sig(&e.author, &e.bytes[..sig_at], &sig) {
|
||||
return Err(SealError::BadSignature);
|
||||
}
|
||||
Ok(e)
|
||||
}
|
||||
|
||||
/// Decodes untrusted bytes. All or nothing.
|
||||
pub fn decode(b: &[u8]) -> Result<Envelope, DecodeError> {
|
||||
if b.len() > MAX_ENVELOPE {
|
||||
return Err(DecodeError::TooLarge(b.len()));
|
||||
}
|
||||
if b.len() < MAGIC.len() {
|
||||
return Err(DecodeError::TooShort);
|
||||
}
|
||||
if &b[..4] != MAGIC {
|
||||
return Err(DecodeError::BadMagic);
|
||||
}
|
||||
let mut pos = 4;
|
||||
let mut values: [&[u8]; 7] = [&[]; 7];
|
||||
let mut sig_at = 0;
|
||||
for (i, &(tag, field, min, max)) in FIELDS.iter().enumerate() {
|
||||
let found = *b.get(pos).ok_or(DecodeError::Truncated { field })?;
|
||||
if found != tag {
|
||||
return Err(if (1..=7).contains(&found) {
|
||||
DecodeError::FieldOutOfOrder { expected: tag, found }
|
||||
} else {
|
||||
DecodeError::UnknownField(found)
|
||||
});
|
||||
}
|
||||
if tag == 7 {
|
||||
sig_at = pos;
|
||||
}
|
||||
let len_bytes: [u8; 4] =
|
||||
b.get(pos + 1..pos + 5).and_then(|s| s.try_into().ok()).ok_or(DecodeError::Truncated { field })?;
|
||||
let len = u32::from_be_bytes(len_bytes) as usize;
|
||||
if len < min || len > max {
|
||||
return Err(DecodeError::BadLength { field, len: len as u64 });
|
||||
}
|
||||
let start = pos + 5;
|
||||
values[i] = b.get(start..start + len).ok_or(DecodeError::Truncated { field })?;
|
||||
pos = start + len;
|
||||
}
|
||||
if pos != b.len() {
|
||||
return Err(DecodeError::TrailingBytes);
|
||||
}
|
||||
let invalid = |field, reason| DecodeError::Invalid { field, reason };
|
||||
let app = std::str::from_utf8(values[0])
|
||||
.ok()
|
||||
.and_then(|s| Id::new(s).ok())
|
||||
.ok_or(invalid("app", "not an id (a-z, 0-9, '-')"))?;
|
||||
let schema = u32::from_be_bytes(values[1].try_into().map_err(|_| invalid("schema", "length"))?);
|
||||
let hlc = Hlc::from_bytes(values[2].try_into().map_err(|_| invalid("hlc", "length"))?);
|
||||
let author = PublicKey::from_bytes(values[3].try_into().map_err(|_| invalid("author", "length"))?);
|
||||
let cert = SubkeyCert::from_bytes(values[4]).map_err(DecodeError::Cert)?;
|
||||
let sig = Signature::from_bytes(values[6].try_into().map_err(|_| invalid("sig", "length"))?);
|
||||
Ok(Envelope {
|
||||
app,
|
||||
schema,
|
||||
hlc,
|
||||
author,
|
||||
cert,
|
||||
payload: values[5].to_vec(),
|
||||
sig,
|
||||
bytes: b.to_vec(),
|
||||
sig_at,
|
||||
hash: tessera::hash(b),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn as_bytes(&self) -> &[u8] {
|
||||
&self.bytes
|
||||
}
|
||||
|
||||
pub fn hash(&self) -> [u8; 32] {
|
||||
self.hash
|
||||
}
|
||||
|
||||
pub fn app(&self) -> &Id {
|
||||
&self.app
|
||||
}
|
||||
|
||||
pub fn schema(&self) -> u32 {
|
||||
self.schema
|
||||
}
|
||||
|
||||
pub fn hlc(&self) -> Hlc {
|
||||
self.hlc
|
||||
}
|
||||
|
||||
pub fn author(&self) -> PublicKey {
|
||||
self.author
|
||||
}
|
||||
|
||||
pub fn cert(&self) -> &SubkeyCert {
|
||||
&self.cert
|
||||
}
|
||||
|
||||
pub fn payload(&self) -> &[u8] {
|
||||
&self.payload
|
||||
}
|
||||
|
||||
/// Whether this event comes from an app subkey of one of `roots`, for this app, made while its cert
|
||||
/// was valid, and not from the future (`now_ms` + `max_drift_ms`). The first failure is the reason.
|
||||
pub fn verify(&self, roots: &[PublicKey], now_ms: u64, max_drift_ms: u64) -> Result<(), VerifyError> {
|
||||
if self.author != self.cert.subkey() {
|
||||
return Err(VerifyError::AuthorNotCert);
|
||||
}
|
||||
if self.cert.app_id() != &self.app {
|
||||
return Err(VerifyError::WrongApp);
|
||||
}
|
||||
let root = self.cert.root();
|
||||
if !roots.contains(&root) {
|
||||
return Err(VerifyError::UnknownRoot);
|
||||
}
|
||||
self.cert.verify(&root, self.hlc.wall / 1000).map_err(VerifyError::Cert)?;
|
||||
if self.hlc.wall > now_ms.saturating_add(max_drift_ms) {
|
||||
return Err(VerifyError::FromTheFuture);
|
||||
}
|
||||
if !verify_event_sig(&self.author, &self.bytes[..self.sig_at], &self.sig) {
|
||||
return Err(VerifyError::BadSignature);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl LogEvent for Envelope {
|
||||
fn order_key(&self) -> OrderKey {
|
||||
OrderKey { hlc: self.hlc, author: self.author, hash: self.hash }
|
||||
}
|
||||
|
||||
fn encoded(&self) -> &[u8] {
|
||||
&self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
/// Metadata only; the payload is shown by its length.
|
||||
impl fmt::Debug for Envelope {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("Envelope")
|
||||
.field("app", &self.app)
|
||||
.field("schema", &self.schema)
|
||||
.field("hlc", &self.hlc)
|
||||
.field("author", &self.author)
|
||||
.field("payload_len", &self.payload.len())
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user