Fundamentum client v0.5.0
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "envelope"
|
||||
description = "The signed Domi event envelope (TEV1): strict decoding, verification against trusted roots (docs/TESSERA.md §8)"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
tessera = { path = "../tessera" }
|
||||
thiserror.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
proptest = "1"
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
//! The mandatory tests for the envelope (docs/TESSERA.md §8): hostile input, verification, convergence.
|
||||
//! Written before the code.
|
||||
|
||||
use envelope::{DecodeError, Envelope, MAX_PAYLOAD, SealError, VerifyError};
|
||||
use proptest::prelude::*;
|
||||
use tessera::{CertError, CertRequest, Clock, Hlc, Id, Log, PublicKey, RootKey, Subkey, SubkeyCert, certify, merge};
|
||||
|
||||
const ALICE: &str = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon \
|
||||
abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art";
|
||||
const MALLORY: &str = "legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth \
|
||||
useful legal winner thank year wave sausage worth title";
|
||||
|
||||
const DAY: u64 = 86_400;
|
||||
const NOW_S: u64 = 1_793_000_000;
|
||||
const NOW_MS: u64 = NOW_S * 1000;
|
||||
const DRIFT: u64 = 5 * 60 * 1000;
|
||||
|
||||
fn root(m: &str) -> RootKey {
|
||||
RootKey::from_mnemonic(m).unwrap()
|
||||
}
|
||||
|
||||
fn cert_for(root: &RootKey, sub: &Subkey, app: &str) -> SubkeyCert {
|
||||
let req = CertRequest {
|
||||
subkey: sub.public(),
|
||||
app_id: Id::new(app).unwrap(),
|
||||
purpose: Id::new("sync").unwrap(),
|
||||
not_before: NOW_S - DAY,
|
||||
not_after: NOW_S + 30 * DAY,
|
||||
};
|
||||
certify(root, &req).unwrap()
|
||||
}
|
||||
|
||||
/// Alice's Fiscus subkey and an event from it at `NOW`.
|
||||
fn alice_event(payload: &[u8]) -> (Subkey, SubkeyCert, Envelope) {
|
||||
let sub = Subkey::from_seed(&[1; 32]);
|
||||
let cert = cert_for(&root(ALICE), &sub, "fiscus");
|
||||
let e = Envelope::seal(&sub, &cert, 1, Hlc { wall: NOW_MS, logical: 0 }, payload).unwrap();
|
||||
(sub, cert, e)
|
||||
}
|
||||
|
||||
fn alice() -> Vec<PublicKey> {
|
||||
vec![root(ALICE).public()]
|
||||
}
|
||||
|
||||
/// Builds envelope bytes field by field, independently of the crate, so tests can make what `seal` never
|
||||
/// would. `fields` are (tag, value); the signature (tag 7) is computed over everything before it.
|
||||
fn raw(fields: &[(u8, Vec<u8>)], signer: &Subkey) -> Vec<u8> {
|
||||
let mut out = b"TEV1".to_vec();
|
||||
for (tag, v) in fields {
|
||||
out.push(*tag);
|
||||
out.extend_from_slice(&(v.len() as u32).to_be_bytes());
|
||||
out.extend_from_slice(v);
|
||||
}
|
||||
let sig = signer.sign_event_tbs(&out);
|
||||
out.push(7);
|
||||
out.extend_from_slice(&64u32.to_be_bytes());
|
||||
out.extend_from_slice(sig.as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
fn fields(app: &str, hlc: Hlc, author: &Subkey, cert: &SubkeyCert, payload: &[u8]) -> Vec<(u8, Vec<u8>)> {
|
||||
vec![
|
||||
(1, app.as_bytes().to_vec()),
|
||||
(2, 1u32.to_be_bytes().to_vec()),
|
||||
(3, hlc.to_bytes().to_vec()),
|
||||
(4, author.public().as_bytes().to_vec()),
|
||||
(5, cert.to_bytes()),
|
||||
(6, payload.to_vec()),
|
||||
]
|
||||
}
|
||||
|
||||
// ---------- round trip ----------
|
||||
|
||||
#[test]
|
||||
fn a_sealed_event_decodes_to_itself_and_verifies() {
|
||||
let (sub, cert, e) = alice_event(b"ciphertext");
|
||||
let back = Envelope::decode(e.as_bytes()).unwrap();
|
||||
assert_eq!(back.as_bytes(), e.as_bytes());
|
||||
assert_eq!(back.app().as_str(), "fiscus");
|
||||
assert_eq!(back.schema(), 1);
|
||||
assert_eq!(back.author(), sub.public());
|
||||
assert_eq!(back.cert(), &cert);
|
||||
assert_eq!(back.payload(), b"ciphertext");
|
||||
assert_eq!(back.verify(&alice(), NOW_MS, DRIFT), Ok(()));
|
||||
// The independent encoder agrees with seal byte for byte.
|
||||
let same = raw(&fields("fiscus", Hlc { wall: NOW_MS, logical: 0 }, &sub, &cert, b"ciphertext"), &sub);
|
||||
assert_eq!(same, e.as_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seal_refuses_a_cert_for_another_key_and_an_oversized_payload() {
|
||||
let sub = Subkey::from_seed(&[1; 32]);
|
||||
let other = Subkey::from_seed(&[2; 32]);
|
||||
let cert = cert_for(&root(ALICE), &other, "fiscus");
|
||||
assert!(Envelope::seal(&sub, &cert, 1, Hlc::default(), b"x").is_err());
|
||||
let cert = cert_for(&root(ALICE), &sub, "fiscus");
|
||||
assert!(Envelope::seal(&sub, &cert, 1, Hlc::default(), &vec![0; MAX_PAYLOAD + 1]).is_err());
|
||||
assert!(Envelope::seal(&sub, &cert, 1, Hlc::default(), &vec![0; MAX_PAYLOAD]).is_ok());
|
||||
}
|
||||
|
||||
/// The two-step seal for a signer that cannot sign at once (docs/V1_1B.md §2) makes the same bytes as `seal`,
|
||||
/// and refuses a signature that is not the author's.
|
||||
#[test]
|
||||
fn the_two_step_seal_equals_seal_and_refuses_a_wrong_signature() {
|
||||
let (sub, cert, e) = alice_event(b"two steps");
|
||||
let hlc = Hlc { wall: NOW_MS, logical: 0 };
|
||||
let tbs = Envelope::to_be_signed(&sub.public(), &cert, 1, hlc, b"two steps").unwrap();
|
||||
let sig = sub.sign_event_tbs(&tbs);
|
||||
assert_eq!(Envelope::with_signature(tbs.clone(), sig).unwrap().as_bytes(), e.as_bytes());
|
||||
|
||||
let other = Subkey::from_seed(&[9; 32]);
|
||||
assert_eq!(Envelope::with_signature(tbs.clone(), other.sign_event_tbs(&tbs)).unwrap_err(), SealError::BadSignature);
|
||||
// A signature in the credential domain is not an event signature.
|
||||
assert_eq!(
|
||||
Envelope::with_signature(tbs.clone(), sub.sign_credential_tbs(&tbs)).unwrap_err(),
|
||||
SealError::BadSignature
|
||||
);
|
||||
assert_eq!(Envelope::with_signature(tbs[..10].to_vec(), sig).unwrap_err(), SealError::NotToBeSigned);
|
||||
assert_eq!(Envelope::to_be_signed(&other.public(), &cert, 1, hlc, b"x").unwrap_err(), SealError::CertForAnotherKey);
|
||||
}
|
||||
|
||||
// ---------- hostile events: dropped with a reason ----------
|
||||
|
||||
#[test]
|
||||
fn a_wrong_signature_is_rejected() {
|
||||
let (_, _, e) = alice_event(b"x");
|
||||
let mut b = e.as_bytes().to_vec();
|
||||
let last = b.len() - 1;
|
||||
b[last] ^= 1;
|
||||
let d = Envelope::decode(&b).unwrap();
|
||||
assert_eq!(d.verify(&alice(), NOW_MS, DRIFT), Err(VerifyError::BadSignature));
|
||||
// Signed by a key other than the author's.
|
||||
let sub = Subkey::from_seed(&[1; 32]);
|
||||
let cert = cert_for(&root(ALICE), &sub, "fiscus");
|
||||
let forged =
|
||||
raw(&fields("fiscus", Hlc { wall: NOW_MS, logical: 0 }, &sub, &cert, b"x"), &Subkey::from_seed(&[9; 32]));
|
||||
assert_eq!(Envelope::decode(&forged).unwrap().verify(&alice(), NOW_MS, DRIFT), Err(VerifyError::BadSignature));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_expired_or_premature_cert_is_rejected() {
|
||||
let sub = Subkey::from_seed(&[1; 32]);
|
||||
let cert = cert_for(&root(ALICE), &sub, "fiscus");
|
||||
let late = Hlc { wall: (NOW_S + 30 * DAY) * 1000, logical: 0 };
|
||||
let e = Envelope::seal(&sub, &cert, 1, late, b"x").unwrap();
|
||||
assert_eq!(e.verify(&alice(), late.wall, DRIFT), Err(VerifyError::Cert(CertError::Expired)));
|
||||
let early = Hlc { wall: (NOW_S - DAY - 1) * 1000, logical: 0 };
|
||||
let e = Envelope::seal(&sub, &cert, 1, early, b"x").unwrap();
|
||||
assert_eq!(e.verify(&alice(), NOW_MS, DRIFT), Err(VerifyError::Cert(CertError::NotYetValid)));
|
||||
// An event made while the cert was valid stays valid after it expires: logs can be rebuilt.
|
||||
let (_, _, e) = alice_event(b"x");
|
||||
assert_eq!(e.verify(&alice(), (NOW_S + 400 * DAY) * 1000, DRIFT), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cert_from_a_root_outside_the_group_is_rejected() {
|
||||
let sub = Subkey::from_seed(&[1; 32]);
|
||||
let cert = cert_for(&root(MALLORY), &sub, "fiscus");
|
||||
let e = Envelope::seal(&sub, &cert, 1, Hlc { wall: NOW_MS, logical: 0 }, b"x").unwrap();
|
||||
assert_eq!(e.verify(&alice(), NOW_MS, DRIFT), Err(VerifyError::UnknownRoot));
|
||||
let both = vec![root(ALICE).public(), root(MALLORY).public()];
|
||||
assert_eq!(e.verify(&both, NOW_MS, DRIFT), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_event_for_another_app_or_author_is_rejected() {
|
||||
let sub = Subkey::from_seed(&[1; 32]);
|
||||
let cert = cert_for(&root(ALICE), &sub, "calenda");
|
||||
let hlc = Hlc { wall: NOW_MS, logical: 0 };
|
||||
let wrong_app = raw(&fields("fiscus", hlc, &sub, &cert, b"x"), &sub);
|
||||
assert_eq!(Envelope::decode(&wrong_app).unwrap().verify(&alice(), NOW_MS, DRIFT), Err(VerifyError::WrongApp));
|
||||
// The author field names another key than the cert (and that key signed).
|
||||
let other = Subkey::from_seed(&[2; 32]);
|
||||
let cert = cert_for(&root(ALICE), &sub, "fiscus");
|
||||
let wrong_author = raw(&fields("fiscus", hlc, &other, &cert, b"x"), &other);
|
||||
assert_eq!(
|
||||
Envelope::decode(&wrong_author).unwrap().verify(&alice(), NOW_MS, DRIFT),
|
||||
Err(VerifyError::AuthorNotCert)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_event_from_the_future_is_rejected() {
|
||||
let sub = Subkey::from_seed(&[1; 32]);
|
||||
let cert = cert_for(&root(ALICE), &sub, "fiscus");
|
||||
let e = Envelope::seal(&sub, &cert, 1, Hlc { wall: NOW_MS + DRIFT + 1, logical: 0 }, b"x").unwrap();
|
||||
assert_eq!(e.verify(&alice(), NOW_MS, DRIFT), Err(VerifyError::FromTheFuture));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_bodies_are_typed_errors() {
|
||||
let (sub, cert, e) = alice_event(b"x");
|
||||
let hlc = Hlc { wall: NOW_MS, logical: 0 };
|
||||
let good = e.as_bytes().to_vec();
|
||||
|
||||
let mut magic = good.clone();
|
||||
magic[3] = b'2';
|
||||
assert_eq!(Envelope::decode(&magic).err(), Some(DecodeError::BadMagic));
|
||||
|
||||
let mut trailing = good.clone();
|
||||
trailing.push(0);
|
||||
assert_eq!(Envelope::decode(&trailing).err(), Some(DecodeError::TrailingBytes));
|
||||
|
||||
assert!(matches!(Envelope::decode(&good[..good.len() - 1]), Err(DecodeError::Truncated { .. })));
|
||||
assert_eq!(Envelope::decode(b"TE").err(), Some(DecodeError::TooShort));
|
||||
|
||||
let mut f = fields("fiscus", hlc, &sub, &cert, b"x");
|
||||
f.insert(2, (9, b"surprise".to_vec()));
|
||||
assert_eq!(Envelope::decode(&raw(&f, &sub)).err(), Some(DecodeError::UnknownField(9)));
|
||||
|
||||
let mut f = fields("fiscus", hlc, &sub, &cert, b"x");
|
||||
f.swap(1, 2);
|
||||
assert_eq!(Envelope::decode(&raw(&f, &sub)).err(), Some(DecodeError::FieldOutOfOrder { expected: 2, found: 3 }));
|
||||
|
||||
let mut f = fields("fiscus", hlc, &sub, &cert, b"x");
|
||||
f.insert(1, (1, b"fiscus".to_vec()));
|
||||
assert_eq!(Envelope::decode(&raw(&f, &sub)).err(), Some(DecodeError::FieldOutOfOrder { expected: 2, found: 1 }));
|
||||
|
||||
let mut f = fields("fiscus", hlc, &sub, &cert, b"x");
|
||||
f[1].1 = vec![0, 0, 1];
|
||||
assert!(matches!(Envelope::decode(&raw(&f, &sub)), Err(DecodeError::BadLength { field: "schema", .. })));
|
||||
|
||||
let f = fields("Fiscus", hlc, &sub, &cert, b"x");
|
||||
assert!(matches!(Envelope::decode(&raw(&f, &sub)), Err(DecodeError::Invalid { field: "app", .. })));
|
||||
|
||||
let mut f = fields("fiscus", hlc, &sub, &cert, b"x");
|
||||
let mut bad_cert = cert.to_bytes();
|
||||
bad_cert[0] = b'X';
|
||||
f[4].1 = bad_cert;
|
||||
assert!(matches!(Envelope::decode(&raw(&f, &sub)), Err(DecodeError::Cert(_))));
|
||||
|
||||
let mut huge = good.clone();
|
||||
huge.resize(envelope::MAX_ENVELOPE + 1, 0);
|
||||
assert!(matches!(Envelope::decode(&huge), Err(DecodeError::TooLarge(_))));
|
||||
|
||||
// A length that claims more than there is.
|
||||
let mut lie = good.clone();
|
||||
lie[5..9].copy_from_slice(&u32::MAX.to_be_bytes());
|
||||
assert!(Envelope::decode(&lie).is_err());
|
||||
|
||||
// Every error has a reason.
|
||||
for b in [&magic, &trailing, &huge, &lie] {
|
||||
assert!(!Envelope::decode(b).unwrap_err().to_string().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(2000))]
|
||||
|
||||
/// Random bytes: never a panic, and every rejection says why.
|
||||
#[test]
|
||||
fn random_bytes_never_panic(b in prop::collection::vec(any::<u8>(), 0..600), magic in any::<bool>()) {
|
||||
let mut b = b;
|
||||
if magic && b.len() >= 4 {
|
||||
b[..4].copy_from_slice(b"TEV1");
|
||||
}
|
||||
match Envelope::decode(&b) {
|
||||
Ok(e) => prop_assert_eq!(e.as_bytes(), &b[..]),
|
||||
Err(err) => prop_assert!(!err.to_string().is_empty()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A valid envelope with random damage: either a typed error, or a whole envelope that is exactly the
|
||||
/// input — and then it verifies only if nothing changed.
|
||||
#[test]
|
||||
fn damaged_envelopes_are_all_or_nothing(
|
||||
edits in prop::collection::vec((any::<prop::sample::Index>(), any::<u8>(), 0u8..3), 1..4),
|
||||
) {
|
||||
let (_, _, e) = alice_event(b"some ciphertext");
|
||||
let original = e.as_bytes().to_vec();
|
||||
let mut b = original.clone();
|
||||
for (at, byte, kind) in edits {
|
||||
if b.is_empty() { break; }
|
||||
let i = at.index(b.len());
|
||||
match kind {
|
||||
0 => b[i] ^= byte | 1,
|
||||
1 => { b.remove(i); }
|
||||
_ => b.insert(i, byte),
|
||||
}
|
||||
}
|
||||
match Envelope::decode(&b) {
|
||||
Ok(d) => {
|
||||
prop_assert_eq!(d.as_bytes(), &b[..]);
|
||||
if d.verify(&alice(), NOW_MS, DRIFT).is_ok() {
|
||||
prop_assert_eq!(&b, &original);
|
||||
}
|
||||
}
|
||||
Err(err) => prop_assert!(!err.to_string().is_empty()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- two devices converge ----------
|
||||
|
||||
#[test]
|
||||
fn two_devices_writing_offline_converge_in_either_order() {
|
||||
let r = root(ALICE);
|
||||
let (pc, phone) = (Subkey::from_seed(&[1; 32]), Subkey::from_seed(&[2; 32]));
|
||||
let (pc_cert, phone_cert) = (cert_for(&r, &pc, "fiscus"), cert_for(&r, &phone, "fiscus"));
|
||||
let (mut pc_clock, mut phone_clock) = (Clock::default(), Clock::default());
|
||||
// Both offline, writing at overlapping times; the phone's clock is 2 s behind.
|
||||
let mut a = Vec::new();
|
||||
let mut b = Vec::new();
|
||||
for i in 0..5u64 {
|
||||
let t = NOW_MS + i * 1000;
|
||||
a.push(Envelope::seal(&pc, &pc_cert, 1, pc_clock.tick(t).unwrap(), format!("pc {i}").as_bytes()).unwrap());
|
||||
b.push(
|
||||
Envelope::seal(
|
||||
&phone,
|
||||
&phone_cert,
|
||||
1,
|
||||
phone_clock.tick(t - 2000).unwrap(),
|
||||
format!("phone {i}").as_bytes(),
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
let roots = alice();
|
||||
let check = |e: &Envelope| e.verify(&roots, NOW_MS + 10_000, DRIFT);
|
||||
// Each device has its own log; then they exchange in either order.
|
||||
let pc_log = merge(&Log::new(), a.clone(), check).log;
|
||||
let phone_log = merge(&Log::new(), b.clone(), check).log;
|
||||
let on_pc = merge(&pc_log, phone_log.events().to_vec(), check).log;
|
||||
let on_phone = merge(&phone_log, pc_log.events().to_vec(), check).log;
|
||||
assert_eq!(on_pc.len(), 10);
|
||||
assert_eq!(on_pc.to_bytes(), on_phone.to_bytes(), "byte-identical");
|
||||
// Receiving everything again changes nothing.
|
||||
let again = merge(&on_pc, [a, b].concat(), check);
|
||||
assert_eq!(again.added, 0);
|
||||
assert_eq!(again.log.to_bytes(), on_pc.to_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hostile_event_leaves_the_log_unchanged() {
|
||||
let (_, _, good) = alice_event(b"x");
|
||||
let roots = alice();
|
||||
let check = |e: &Envelope| e.verify(&roots, NOW_MS, DRIFT);
|
||||
let log = merge(&Log::new(), vec![good], check).log;
|
||||
let before = log.to_bytes();
|
||||
let sub = Subkey::from_seed(&[5; 32]);
|
||||
let evil =
|
||||
Envelope::seal(&sub, &cert_for(&root(MALLORY), &sub, "fiscus"), 1, Hlc { wall: NOW_MS, logical: 1 }, b"y")
|
||||
.unwrap();
|
||||
let m = merge(&log, vec![evil], check);
|
||||
assert_eq!(m.log.to_bytes(), before);
|
||||
assert_eq!(m.rejected.len(), 1);
|
||||
assert_eq!(m.rejected[0].1, VerifyError::UnknownRoot);
|
||||
assert!(!m.rejected[0].1.to_string().is_empty());
|
||||
}
|
||||
Reference in New Issue
Block a user