Fundamentum client v0.5.0

This commit is contained in:
2026-11-05 09:05:13 +01:00
commit 353f08e0bb
36 changed files with 8844 additions and 0 deletions
+33
View File
@@ -0,0 +1,33 @@
[package]
name = "tabellarius-client"
description = "Tabellarius client: MLS groups (OpenMLS) of Domi devices, signed event logs, offline-first sync (docs/TABELLARIUS.md)"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
[lints]
workspace = true
[dependencies]
tessera = { path = "../tessera" }
envelope = { path = "../envelope" }
tabellarius-proto = { path = "../proto" }
openmls = "0.9"
openmls_rust_crypto = "0.6"
openmls_basic_credential = "0.6"
openmls_memory_storage = "0.6"
openmls_traits = "0.6"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
chacha20poly1305 = "0.10"
sha2.workspace = true
zeroize.workspace = true
thiserror.workspace = true
data-encoding.workspace = true
# The native driver only (docs/V1_1B.md §1); the browser talks through fetch.
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
ureq = "3"
File diff suppressed because it is too large Load Diff
+161
View File
@@ -0,0 +1,161 @@
//! The native driver (docs/V1_1B.md §1): [`Client`] is the [`Core`] over `ureq` and the app's [`Subkey`],
//! with the blocking API apps have used since v0.2. Neither the transport nor the signer ever waits, so each
//! operation completes the first time its future is polled: no executor, no thread.
use crate::{
AppEvent, Core, Device, GroupId, HttpRequest, HttpResponse, Result, StateStore, SyncReport, Transport,
VerifiedEvent,
};
use std::future::Future;
use std::ops::{Deref, DerefMut};
use std::sync::Arc;
use std::task::{Context, Poll, Waker};
use std::time::Duration;
use tessera::{BackupSecret, Revocation, Subkey, SubkeyCert};
/// The blocking HTTP transport: no redirects, 15 s for a whole request.
pub struct Ureq(ureq::Agent);
impl Default for Ureq {
fn default() -> Self {
Ureq(
ureq::Agent::config_builder()
.max_redirects(0)
.http_status_as_error(false)
.timeout_global(Some(Duration::from_secs(15)))
.build()
.into(),
)
}
}
impl Transport for Ureq {
async fn send(&self, req: HttpRequest) -> std::result::Result<HttpResponse, String> {
fn with<B>(mut r: ureq::RequestBuilder<B>, headers: &[(&'static str, String)]) -> ureq::RequestBuilder<B> {
for (n, v) in headers {
r = r.header(*n, v);
}
r
}
let resp = match req.method.as_str() {
"GET" => with(self.0.get(&req.url), &req.headers).call(),
"DELETE" => with(self.0.delete(&req.url), &req.headers).call(),
"PUT" => with(self.0.put(&req.url), &req.headers).send(&req.body[..]),
_ => with(self.0.post(&req.url), &req.headers).send(&req.body[..]),
};
let mut resp = resp.map_err(|e| e.to_string())?;
let status = resp.status().as_u16();
let body = resp.body_mut().read_to_vec().unwrap_or_default();
Ok(HttpResponse { status, body })
}
}
/// Runs a core operation over the native transport and signer: it is ready on the first poll.
fn now<F: Future>(f: F) -> F::Output {
let mut f = std::pin::pin!(f);
match f.as_mut().poll(&mut Context::from_waker(Waker::noop())) {
Poll::Ready(v) => v,
// Unreachable: `Ureq` and `Subkey` never return Pending, and the core awaits nothing else.
Poll::Pending => unreachable!("a native operation waited"),
}
}
fn system_ms() -> u64 {
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
}
/// The native client. Every operation that does not talk to the relay or sign (`groups`, `log`, `members`,
/// `import`, …) is the [`Core`]'s, reached through `Deref`.
pub struct Client(Core<Ureq, Subkey>);
impl Deref for Client {
type Target = Core<Ureq, Subkey>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for Client {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl Client {
/// Opens the client for `device`'s app, with its state from `store` (or empty).
pub fn open(relay: &str, device: Device, store: Box<dyn StateStore>) -> Result<Client> {
Core::open(relay, device.cert, device.subkey, Ureq::default(), store, Arc::new(system_ms)).map(Client)
}
/// The group of this person's own devices for this app; created on first use.
pub fn self_group(&mut self) -> Result<GroupId> {
now(self.0.self_group())
}
/// A new group shared with people you will invite.
pub fn open_group(&mut self, name: &str) -> Result<GroupId> {
now(self.0.open_group(name))
}
/// Signs `events`, applies them to the local log at once, and queues them for the group. Never needs the
/// relay.
pub fn send(&mut self, g: &GroupId, events: Vec<AppEvent>) -> Result<()> {
now(self.0.send(g, events))
}
/// An invite token (`tab1:…`). Needs the relay. See [`Core::invite`].
pub fn invite(&mut self, g: &GroupId) -> Result<String> {
now(self.0.invite(g))
}
/// Asks to join with an invite token. Needs the relay. See [`Core::join`].
pub fn join(&mut self, token: &str) -> Result<()> {
now(self.0.join(token))
}
/// Removes a member. Needs the relay.
pub fn remove(&mut self, g: &GroupId, member: u32) -> Result<()> {
now(self.0.remove(g, member))
}
/// See [`Core::apply_revocation`].
pub fn apply_revocation(&mut self, statements: &[Revocation]) -> Result<usize> {
now(self.0.apply_revocation(statements))
}
/// See [`Core::announce_revocation`].
pub fn announce_revocation(&mut self, g: &GroupId, statements: Vec<Revocation>) -> Result<()> {
now(self.0.announce_revocation(g, statements))
}
/// See [`Core::revoke`].
pub fn revoke(&mut self, g: &GroupId, statements: Vec<Revocation>) -> Result<usize> {
now(self.0.revoke(g, statements))
}
/// See [`Core::renew`].
pub fn renew(&mut self, cert: SubkeyCert) -> Result<()> {
now(self.0.renew(cert))
}
/// See [`Core::backup`].
pub fn backup(&mut self, secret: &BackupSecret) -> Result<bool> {
now(self.0.backup(secret))
}
/// See [`Core::restore`].
pub fn restore(&self, secret: &BackupSecret) -> Result<Vec<Vec<u8>>> {
now(self.0.restore(secret))
}
/// Uploads what is queued, downloads and verifies what is new, admits invited devices, picks up groups this
/// device was admitted to. An unreachable relay is `relay_ok: false`, not an error.
pub fn sync(&mut self) -> Result<SyncReport> {
now(self.0.sync())
}
/// `sync`, then the group's log.
pub fn pull(&mut self, g: &GroupId) -> Result<Vec<VerifiedEvent>> {
now(self.0.pull(g))
}
}
+117
View File
@@ -0,0 +1,117 @@
//! Where the client keeps its state (docs/TABELLARIUS.md §5). The state holds MLS secrets, so on disk it is
//! always encrypted, with a key the app keeps in Custos.
#[cfg(not(target_arch = "wasm32"))]
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
#[cfg(not(target_arch = "wasm32"))]
use chacha20poly1305::{XChaCha20Poly1305, XNonce};
use std::io;
#[cfg(not(target_arch = "wasm32"))]
use std::path::PathBuf;
use std::sync::Mutex;
use zeroize::Zeroizing;
/// `Send`, so a [`crate::Client`] can live in a server task or a Tauri app's state.
pub trait StateStore: Send {
fn load(&self) -> io::Result<Option<Vec<u8>>>;
fn save(&self, state: &[u8]) -> io::Result<()>;
}
/// State in memory only: tests, and apps that persist it themselves.
#[derive(Default)]
pub struct MemoryStore(Mutex<Option<Zeroizing<Vec<u8>>>>);
impl MemoryStore {
pub fn with(state: Vec<u8>) -> MemoryStore {
MemoryStore(Mutex::new(Some(Zeroizing::new(state))))
}
}
impl StateStore for MemoryStore {
fn load(&self) -> io::Result<Option<Vec<u8>>> {
Ok(self.0.lock().map_err(|_| io::Error::other("lock"))?.as_ref().map(|s| s.to_vec()))
}
fn save(&self, state: &[u8]) -> io::Result<()> {
*self.0.lock().map_err(|_| io::Error::other("lock"))? = Some(Zeroizing::new(state.to_vec()));
Ok(())
}
}
#[cfg(not(target_arch = "wasm32"))]
const MAGIC: &[u8; 4] = b"TSF1";
#[cfg(not(target_arch = "wasm32"))]
/// State in a file: `TSF1 ‖ nonce (24) ‖ XChaCha20-Poly1305(key, nonce, state, aad = TSF1)`, written to a temporary
/// file and renamed. The key comes from Custos (`domi://<app>/tabellarius-state`), never from a file.
pub struct EncryptedFileStore {
path: PathBuf,
key: Zeroizing<[u8; 32]>,
}
#[cfg(not(target_arch = "wasm32"))]
impl EncryptedFileStore {
pub fn new(path: impl Into<PathBuf>, key: [u8; 32]) -> EncryptedFileStore {
EncryptedFileStore { path: path.into(), key: Zeroizing::new(key) }
}
fn cipher(&self) -> XChaCha20Poly1305 {
XChaCha20Poly1305::new_from_slice(self.key.as_ref()).expect("32-byte key")
}
}
#[cfg(not(target_arch = "wasm32"))]
impl StateStore for EncryptedFileStore {
fn load(&self) -> io::Result<Option<Vec<u8>>> {
let bytes = match std::fs::read(&self.path) {
Ok(b) => b,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(e),
};
if bytes.len() < 4 + 24 || &bytes[..4] != MAGIC {
return Err(io::Error::other("not a Tabellarius state file"));
}
let nonce = XNonce::from_slice(&bytes[4..28]);
let plain = self
.cipher()
.decrypt(nonce, Payload { msg: &bytes[28..], aad: MAGIC })
.map_err(|_| io::Error::other("the state file does not open with this key (wrong key or damaged)"))?;
Ok(Some(plain))
}
fn save(&self, state: &[u8]) -> io::Result<()> {
let nonce_bytes = tabellarius_proto::random32();
let nonce = XNonce::from_slice(&nonce_bytes[..24]);
let ct = self
.cipher()
.encrypt(nonce, Payload { msg: state, aad: MAGIC })
.map_err(|_| io::Error::other("encryption"))?;
let mut out = MAGIC.to_vec();
out.extend_from_slice(&nonce_bytes[..24]);
out.extend_from_slice(&ct);
let tmp = self.path.with_extension("tmp");
std::fs::write(&tmp, &out)?;
std::fs::rename(&tmp, &self.path)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_file_is_ciphertext_and_opens_only_with_its_key() {
let dir =
std::env::temp_dir().join(format!("tsf-{}", tabellarius_proto::b64(&tabellarius_proto::random32()[..6])));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("state.tsf");
let s = EncryptedFileStore::new(&path, [7; 32]);
assert_eq!(s.load().unwrap(), None);
s.save(b"MARKER-SECRET-STATE").unwrap();
let raw = std::fs::read(&path).unwrap();
assert!(!raw.windows(6).any(|w| w == b"MARKER"));
assert_eq!(s.load().unwrap().unwrap(), b"MARKER-SECRET-STATE");
assert!(EncryptedFileStore::new(&path, [8; 32]).load().is_err());
std::fs::remove_dir_all(dir).unwrap();
}
}
+51
View File
@@ -0,0 +1,51 @@
//! What the core needs from its surroundings (docs/V1_1B.md §1, §2): a way to reach the relay and the device
//! key. The native driver implements both without ever waiting; the browser's wait on `fetch` and WebCrypto.
use std::future::Future;
use tessera::{PublicKey, Signature, Subkey};
/// One HTTP request to the relay, already signed with a mailbox key.
#[derive(Clone, Debug)]
pub struct HttpRequest {
pub method: String,
pub url: String,
pub headers: Vec<(&'static str, String)>,
pub body: Vec<u8>,
}
/// The relay's answer: any status, and the body.
#[derive(Clone, Debug)]
pub struct HttpResponse {
pub status: u16,
pub body: Vec<u8>,
}
/// Reaches the relay. `Err` only when it could not be reached (offline); every HTTP status is an `Ok` answer.
/// No redirects are followed.
pub trait Transport {
fn send(&self, req: HttpRequest) -> impl Future<Output = Result<HttpResponse, String>>;
}
/// The device key: the app subkey its cert certifies. The domains are prepended here, never by the caller,
/// so a signer cannot be asked to sign one kind of statement as another.
pub trait DeviceSigner {
fn public(&self) -> PublicKey;
/// A signature over `tessera::EVENT_DOMAIN ‖ tbs`.
fn sign_event_tbs(&self, tbs: &[u8]) -> impl Future<Output = Result<Signature, String>>;
/// A signature over `tessera::CREDENTIAL_DOMAIN ‖ tbs`.
fn sign_credential_tbs(&self, tbs: &[u8]) -> impl Future<Output = Result<Signature, String>>;
}
impl DeviceSigner for Subkey {
fn public(&self) -> PublicKey {
Subkey::public(self)
}
async fn sign_event_tbs(&self, tbs: &[u8]) -> Result<Signature, String> {
Ok(Subkey::sign_event_tbs(self, tbs))
}
async fn sign_credential_tbs(&self, tbs: &[u8]) -> Result<Signature, String> {
Ok(Subkey::sign_credential_tbs(self, tbs))
}
}
+20
View File
@@ -0,0 +1,20 @@
[package]
name = "custos-local"
description = "The app side of Custos' local API on Windows: keep a subkey seed in Custos and ask Custos to certify the subkey (docs/TESSERA.md §10)"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
[lints]
workspace = true
[dependencies]
tessera = { path = "../tessera" }
serde_json = "1"
getrandom = "0.3"
sha2.workspace = true
data-encoding.workspace = true
zeroize.workspace = true
thiserror.workspace = true
@@ -0,0 +1,29 @@
//! Asks the running Custos for a subkey cert, as a Domi app would.
//!
//! `cargo run -p custos-local --example request_subkey -- <app_id> [purpose] [app name]`
use tessera::{Id, match_code};
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
let app_id = Id::new(args.first().map(String::as_str).unwrap_or("demo")).expect("an app id: a-z, 0-9, '-'");
let purpose = Id::new(args.get(1).map(String::as_str).unwrap_or("sync")).expect("a purpose: a-z, 0-9, '-'");
let app = args.get(2).cloned().unwrap_or_else(|| format!("{app_id} (request_subkey example)"));
let run = || -> Result<(), custos_local::LocalError> {
let mut custos = custos_local::Custos::connect()?;
let subkey = custos.subkey(&app, &app_id)?;
println!("subkey {}", subkey.public());
println!("match {} <- Custos shows the same code", match_code(&subkey.public()));
let cert = custos.request_cert(&app, &app_id, &purpose, &subkey)?;
println!("root {}", cert.root());
println!("app {} / {}", cert.app_id(), cert.purpose());
println!("valid {} .. {} (Unix seconds)", cert.not_before(), cert.not_after());
println!("cert {}", cert.to_text());
Ok(())
};
if let Err(e) = run() {
eprintln!("error: {e}");
std::process::exit(1);
}
}
+319
View File
@@ -0,0 +1,319 @@
//! The app side of Custos' local API (docs/TESSERA.md §10): a Domi app on the same Windows machine keeps its
//! subkey seed in Custos and asks Custos to certify the subkey with the person's root.
//!
//! ```no_run
//! # use tessera::Id;
//! let mut custos = custos_local::Custos::connect().unwrap();
//! let app_id = Id::new("fiscus").unwrap();
//! let subkey = custos.subkey("Fiscus Domi", &app_id).unwrap();
//! println!("Custos will show {}", tessera::match_code(&subkey.public()));
//! let cert = custos.request_cert("Fiscus Domi", &app_id, &Id::new("sync").unwrap(), &subkey).unwrap();
//! ```
//!
//! The seed lives in Custos under `domi://<app_id>/tessera-subkey`; the root never leaves Custos, and no
//! answer contains private key material other than the app's own secrets, in its own namespace: the subkey
//! seed, the state keys and the backup secret.
//!
//! v1.1 (docs/TESSERA.md §12): on every sync an app applies the revocations the person started in Custos and
//! backs up its self group:
//!
//! ```ignore
//! for statements in custos.revocations_to_apply("Fiscus Domi", &app_id, |k| client.events_by_all(k))? {
//! client.apply_revocation(&statements)?;
//! }
//! client.backup(&custos.backup_secret("Fiscus Domi", &app_id)?)?;
//! ```
use data_encoding::BASE64URL_NOPAD;
use serde_json::{Value, json};
use sha2::Digest;
use std::io::{Read, Write};
use tessera::{BackupSecret, Id, PublicKey, Revocation, Subkey, SubkeyCert};
use zeroize::Zeroizing;
/// The pipe Custos listens on; `CUSTOS_PIPE` overrides it (tests, a second Custos).
pub const PIPE: &str = r"\\.\pipe\custos-domi";
const SEED_NAME: &str = "tessera-subkey";
#[derive(Debug, thiserror::Error)]
pub enum LocalError {
#[error("Custos is not running (or this is not Windows): {0}")]
NotRunning(std::io::Error),
#[error("talking to Custos failed: {0}")]
Io(std::io::Error),
#[error("Custos refused: {error} ({message})")]
Refused { error: String, message: String },
#[error("Custos sent an answer this app does not understand")]
BadAnswer,
#[error("the certificate Custos sent does not match the request: {0}")]
WrongCert(&'static str),
#[error("no random numbers from the OS")]
Random,
#[error("the revocation Custos sent does not match the request")]
WrongRevocation,
}
/// A revocation the person started in Custos (Domi identity → a key → Revoke).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PendingRevocation {
pub subkey: PublicKey,
/// Unix seconds, as Custos chose it.
pub revoked_at: u64,
/// `None` until a device of this app sent the list of events to keep.
pub statements: Option<Vec<Revocation>>,
}
/// A connection to Custos.
pub struct Custos {
pipe: std::fs::File,
}
impl Custos {
pub fn connect() -> Result<Custos, LocalError> {
let name = std::env::var("CUSTOS_PIPE").unwrap_or_else(|_| PIPE.to_owned());
let pipe = std::fs::OpenOptions::new().read(true).write(true).open(name).map_err(LocalError::NotRunning)?;
Ok(Custos { pipe })
}
/// One request, one answer. Answers with `"ok": false` become [`LocalError::Refused`].
fn call(&mut self, req: &Value) -> Result<Value, LocalError> {
let out = Zeroizing::new(serde_json::to_vec(req).map_err(|_| LocalError::BadAnswer)?);
self.pipe.write_all(&out).map_err(LocalError::Io)?;
let mut buf = Zeroizing::new(Vec::new());
let mut chunk = Zeroizing::new(vec![0u8; 64 * 1024]);
let v: Value = loop {
let n = self.pipe.read(&mut chunk).map_err(LocalError::Io)?;
if n == 0 {
return Err(LocalError::BadAnswer);
}
buf.extend_from_slice(&chunk[..n]);
match serde_json::from_slice(&buf) {
Ok(v) => break v,
Err(e) if e.is_eof() => continue,
Err(_) => return Err(LocalError::BadAnswer),
}
};
if v["ok"] == true {
return Ok(v);
}
Err(LocalError::Refused {
error: v["error"].as_str().unwrap_or("unknown").to_owned(),
message: v["message"].as_str().unwrap_or("").to_owned(),
})
}
/// This app's subkey: the seed kept in Custos, or a new one from the OS CSPRNG stored there first.
/// Custos asks the person once whether `app` may use the namespace `app_id`.
pub fn subkey(&mut self, app: &str, app_id: &Id) -> Result<Subkey, LocalError> {
let seed = self.random_secret(app, &format!("domi://{app_id}/{SEED_NAME}"), "Domi subkey")?;
Ok(Subkey::from_seed(&seed))
}
/// The key that encrypts this app's Tabellarius state file at `state_path` (one per file), kept in Custos.
pub fn state_key(&mut self, app: &str, app_id: &Id, state_path: &str) -> Result<Zeroizing<[u8; 32]>, LocalError> {
let id: String =
sha2::Sha256::digest(state_path.as_bytes()).iter().take(6).map(|b| format!("{b:02x}")).collect();
self.random_secret(app, &format!("domi://{app_id}/tabellarius-state-{id}"), "Tabellarius state key")
}
/// 32 bytes kept in Custos under `r`: read, or made from the OS CSPRNG and stored first.
fn random_secret(&mut self, app: &str, r: &str, what: &str) -> Result<Zeroizing<[u8; 32]>, LocalError> {
match self.call(&json!({ "op": "get", "ref": r, "app": app })) {
Ok(v) => {
let text = Zeroizing::new(v["value"].as_str().ok_or(LocalError::BadAnswer)?.to_owned());
let seed = Zeroizing::new(BASE64URL_NOPAD.decode(text.as_bytes()).map_err(|_| LocalError::BadAnswer)?);
Ok(Zeroizing::new(seed.as_slice().try_into().map_err(|_| LocalError::BadAnswer)?))
}
Err(LocalError::Refused { error, .. }) if error == "not_found" => {
let mut seed = Zeroizing::new([0u8; 32]);
getrandom::fill(seed.as_mut()).map_err(|_| LocalError::Random)?;
let text = Zeroizing::new(BASE64URL_NOPAD.encode(seed.as_ref()));
let label = format!("{app}: {what}");
self.call(&json!({ "op": "set", "ref": r, "value": text.as_str(), "label": label, "app": app }))?;
Ok(seed)
}
Err(e) => Err(e),
}
}
/// Asks Custos to certify `subkey` for `app_id` and `purpose`. Custos shows the subkey's match code
/// (`tessera::match_code`); show the same code in the app while this waits. Blocks until the person
/// answers. The cert is checked before it is returned.
pub fn request_cert(
&mut self,
app: &str,
app_id: &Id,
purpose: &Id,
subkey: &Subkey,
) -> Result<SubkeyCert, LocalError> {
self.request_cert_for(app, app_id, purpose, &subkey.public())
}
/// [`Custos::request_cert`] for a key this app does not hold: another device of the same person (an app's
/// server-side device, paired through this desktop). Custos shows the key's match code; the other device
/// shows the same code, so the person approves only the key they see there.
pub fn request_cert_for(
&mut self,
app: &str,
app_id: &Id,
purpose: &Id,
key: &PublicKey,
) -> Result<SubkeyCert, LocalError> {
let v = self.call(&json!({
"op": "subkey",
"app": app,
"app_id": app_id.as_str(),
"purpose": purpose.as_str(),
"subkey": key.to_string(),
}))?;
let cert = SubkeyCert::from_text(v["cert"].as_str().ok_or(LocalError::BadAnswer)?)
.map_err(|_| LocalError::BadAnswer)?;
check(&cert, app_id, purpose, key, now())?;
Ok(cert)
}
}
impl Custos {
/// The revocations the person started for this app's subkeys and for device keys.
pub fn revocations(&mut self, app: &str, app_id: &Id) -> Result<Vec<PendingRevocation>, LocalError> {
let v = self.call(&json!({ "op": "revocations", "app": app, "app_id": app_id.as_str() }))?;
let list = v["revocations"].as_array().ok_or(LocalError::BadAnswer)?;
list.iter()
.map(|r| {
let subkey = r["subkey"].as_str().and_then(PublicKey::from_text).ok_or(LocalError::BadAnswer)?;
let revoked_at = r["revoked_at"].as_u64().ok_or(LocalError::BadAnswer)?;
let statements = match &r["statements"] {
Value::Null => None,
s => Some(statements(s, &subkey, revoked_at)?),
};
Ok(PendingRevocation { subkey, revoked_at, statements })
})
.collect()
}
/// Sends the hashes of the events `pending`'s key wrote that stay valid (`Client::events_by_all`); Custos
/// signs the revocation with the root. If another device of this app answered first, Custos returns
/// what it signed then.
pub fn revoke(
&mut self,
app: &str,
app_id: &Id,
pending: &PendingRevocation,
accepted: &[[u8; 32]],
) -> Result<Vec<Revocation>, LocalError> {
let v = self.call(&json!({
"op": "revoke",
"app": app,
"app_id": app_id.as_str(),
"subkey": pending.subkey.to_string(),
"revoked_at": pending.revoked_at,
"accepted": BASE64URL_NOPAD.encode(&accepted.concat()),
}))?;
statements(&v["statements"], &pending.subkey, pending.revoked_at)
}
/// Every revocation this app has to apply, signed: answers the ones still waiting with `accepted_of`
/// (`|k| client.events_by_all(k)`). Hand each to `Client::apply_revocation`.
pub fn revocations_to_apply(
&mut self,
app: &str,
app_id: &Id,
accepted_of: impl Fn(&PublicKey) -> Vec<[u8; 32]>,
) -> Result<Vec<Vec<Revocation>>, LocalError> {
let mut out = Vec::new();
for p in self.revocations(app, app_id)? {
out.push(match &p.statements {
Some(s) => s.clone(),
None => self.revoke(app, app_id, &p, &accepted_of(&p.subkey))?,
});
}
Ok(out)
}
/// This app's backup secret (docs/TESSERA.md §12), derived by Custos from the root. Nothing reads it back
/// out of [`BackupSecret`].
pub fn backup_secret(&mut self, app: &str, app_id: &Id) -> Result<BackupSecret, LocalError> {
let v = self.call(&json!({ "op": "backup_key", "app": app, "app_id": app_id.as_str() }))?;
let text = Zeroizing::new(v["secret"].as_str().ok_or(LocalError::BadAnswer)?.to_owned());
let bytes = Zeroizing::new(BASE64URL_NOPAD.decode(text.as_bytes()).map_err(|_| LocalError::BadAnswer)?);
let secret: [u8; 32] = bytes.as_slice().try_into().map_err(|_| LocalError::BadAnswer)?;
Ok(BackupSecret::from_bytes(secret))
}
}
/// Signed statements from an answer: one root, the asked-for key and time, each signature valid.
fn statements(v: &Value, subkey: &PublicKey, revoked_at: u64) -> Result<Vec<Revocation>, LocalError> {
let list: Vec<Revocation> = v
.as_array()
.ok_or(LocalError::BadAnswer)?
.iter()
.map(|t| t.as_str().and_then(|t| Revocation::from_text(t).ok()).ok_or(LocalError::BadAnswer))
.collect::<Result<_, _>>()?;
let root = list.first().ok_or(LocalError::WrongRevocation)?.root();
let ok = list
.iter()
.all(|r| r.root() == root && r.subkey() == *subkey && r.revoked_at() == revoked_at && r.verify(&root).is_ok());
if !ok {
return Err(LocalError::WrongRevocation);
}
Ok(list)
}
fn now() -> u64 {
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
}
/// Whether `cert` is what was asked for, and valid now under the root it names.
fn check(cert: &SubkeyCert, app_id: &Id, purpose: &Id, key: &PublicKey, now: u64) -> Result<(), LocalError> {
if cert.subkey() != *key {
return Err(LocalError::WrongCert("another subkey"));
}
if cert.app_id() != app_id || cert.purpose() != purpose {
return Err(LocalError::WrongCert("another app id or purpose"));
}
cert.verify(&cert.root(), now).map_err(|_| LocalError::WrongCert("not valid now"))
}
#[cfg(test)]
mod tests {
use super::*;
use tessera::{CertRequest, RootKey, certify};
#[test]
fn a_cert_is_checked_against_the_request() {
let root = RootKey::from_mnemonic(
"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon \
abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art",
)
.unwrap();
let sub = Subkey::from_seed(&[1; 32]);
let (fiscus, sync) = (Id::new("fiscus").unwrap(), Id::new("sync").unwrap());
let cert = certify(&root, &CertRequest::standard(sub.public(), fiscus.clone(), sync.clone(), 1000)).unwrap();
let key = sub.public();
assert!(check(&cert, &fiscus, &sync, &key, 1000).is_ok());
assert!(check(&cert, &Id::new("calenda").unwrap(), &sync, &key, 1000).is_err());
assert!(check(&cert, &fiscus, &sync, &Subkey::from_seed(&[2; 32]).public(), 1000).is_err());
assert!(check(&cert, &fiscus, &sync, &key, 1000 + 366 * 86_400).is_err());
}
#[test]
fn statements_are_checked_against_the_request() {
let root = RootKey::from_mnemonic(
"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art",
)
.unwrap();
let lost = Subkey::from_seed(&[1; 32]).public();
let signed = tessera::revoke(&root, lost, 1000, vec![[7; 32]]).unwrap();
let answer = json!(signed.iter().map(|r| r.to_text()).collect::<Vec<_>>());
assert_eq!(statements(&answer, &lost, 1000).unwrap(), signed);
assert!(matches!(statements(&answer, &lost, 999), Err(LocalError::WrongRevocation)));
let other = Subkey::from_seed(&[2; 32]).public();
assert!(matches!(statements(&answer, &other, 1000), Err(LocalError::WrongRevocation)));
assert!(matches!(statements(&json!([]), &lost, 1000), Err(LocalError::WrongRevocation)));
let mut forged = signed[0].to_bytes();
let n = forged.len();
forged[n - 1] ^= 1;
let forged = json!([data_encoding::BASE64URL_NOPAD.encode(&forged)]);
assert!(matches!(statements(&forged, &lost, 1000), Err(LocalError::WrongRevocation)));
}
}
+18
View File
@@ -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"
+296
View File
@@ -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()
}
}
+349
View File
@@ -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());
}
+19
View File
@@ -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"
+201
View File
@@ -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"));
}
}
+25
View File
@@ -0,0 +1,25 @@
[package]
name = "tessera"
description = "Domi identity: root key from a mnemonic, subkey certificates, match code, hybrid logical clock, deterministic merge (docs/TESSERA.md)"
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
hkdf.workspace = true
bip39.workspace = true
zeroize.workspace = true
thiserror.workspace = true
data-encoding.workspace = true
chacha20poly1305 = "0.10"
[dev-dependencies]
proptest = "1"
static_assertions = "1"
+76
View File
@@ -0,0 +1,76 @@
//! The backup secret (docs/TESSERA.md §12, docs/V1_1.md §3): per app, derived from the root secret, so the
//! 24 words bring it back with every device lost. It seals the app's backup and names its relay mailbox.
//!
//! Custos derives it and hands an app only its own; the app keeps it as an opaque value. Nothing reads the
//! secret back out: it seals, opens, and gives the backup mailbox's access-key seed (a relay credential of
//! the kind invite tokens carry; it lets its holder fetch ciphertext, nothing more).
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
use chacha20poly1305::{XChaCha20Poly1305, XNonce};
use hkdf::Hkdf;
use sha2::Sha256;
use std::fmt;
use zeroize::Zeroizing;
const BACKUP_SALT: &[u8] = b"tessera backup v1";
const SEAL_INFO: &[u8] = b"seal";
const MAILBOX_INFO: &[u8] = b"mailbox";
/// An app's backup secret: 32 bytes from `HKDF-SHA256(salt "tessera backup v1", ikm = root secret,
/// info = app id)`.
pub struct BackupSecret(Zeroizing<[u8; 32]>);
pub(crate) fn derive(root_secret: &[u8; 32], app_id: &crate::Id) -> BackupSecret {
let mut out = Zeroizing::new([0u8; 32]);
Hkdf::<Sha256>::new(Some(BACKUP_SALT), root_secret)
.expand(app_id.as_str().as_bytes(), out.as_mut())
.expect("32 bytes is a valid HKDF length");
BackupSecret(out)
}
impl BackupSecret {
/// The 32 bytes Custos hands the app.
pub fn from_bytes(b: [u8; 32]) -> BackupSecret {
BackupSecret(Zeroizing::new(b))
}
fn expand(&self, info: &[u8]) -> Zeroizing<[u8; 32]> {
let mut out = Zeroizing::new([0u8; 32]);
Hkdf::<Sha256>::from_prk(self.0.as_ref())
.expect("32 bytes is a valid PRK")
.expand(info, out.as_mut())
.expect("32 bytes is a valid HKDF length");
out
}
/// `nonce ‖ XChaCha20-Poly1305(seal key, plain, aad)`. The caller supplies a fresh random nonce.
pub fn seal(&self, nonce: &[u8; 24], aad: &[u8], plain: &[u8]) -> Vec<u8> {
let key = self.expand(SEAL_INFO);
let ct = XChaCha20Poly1305::new(key.as_ref().into())
.encrypt(XNonce::from_slice(nonce), Payload { msg: plain, aad })
.expect("encryption does not fail");
[nonce.as_slice(), &ct].concat()
}
/// The plaintext, or `None` if `sealed` was not sealed with this secret and `aad`.
pub fn open(&self, aad: &[u8], sealed: &[u8]) -> Option<Vec<u8>> {
if sealed.len() < 24 {
return None;
}
let key = self.expand(SEAL_INFO);
XChaCha20Poly1305::new(key.as_ref().into())
.decrypt(XNonce::from_slice(&sealed[..24]), Payload { msg: &sealed[24..], aad })
.ok()
}
/// The seed of the backup mailbox's access key (a Tabellarius `MailboxKey`).
pub fn mailbox_seed(&self) -> Zeroizing<[u8; 32]> {
self.expand(MAILBOX_INFO)
}
}
impl fmt::Debug for BackupSecret {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("BackupSecret([redacted])")
}
}
+175
View File
@@ -0,0 +1,175 @@
//! Subkey certificates (`TSC1`) and the match code (docs/TESSERA.md §4, §5).
use crate::keys::{RootSigner, SignError, verify_cert_sig};
use crate::{Id, PublicKey, Reader, Signature};
use data_encoding::BASE64URL_NOPAD;
use sha2::{Digest, Sha256};
pub const CERT_MAGIC: &[u8; 4] = b"TSC1";
const SKEW: u64 = 5 * 60;
const YEAR: u64 = 365 * 86_400;
/// What a cert will say, before the root signs it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CertRequest {
pub subkey: PublicKey,
pub app_id: Id,
pub purpose: Id,
/// Unix seconds, inclusive.
pub not_before: u64,
/// Unix seconds, exclusive.
pub not_after: u64,
}
impl CertRequest {
/// The validity Custos issues: from five minutes ago (clock skew) for 365 days.
pub fn standard(subkey: PublicKey, app_id: Id, purpose: Id, now: u64) -> CertRequest {
CertRequest {
subkey,
app_id,
purpose,
not_before: now.saturating_sub(SKEW),
not_after: now.saturating_add(YEAR),
}
}
/// The bytes the root signs (after `CERT_DOMAIN`): everything in the cert before `sig`.
pub fn tbs(&self, root: &PublicKey) -> Vec<u8> {
let mut out = Vec::with_capacity(4 + 32 + 32 + 66 + 16);
out.extend_from_slice(CERT_MAGIC);
out.extend_from_slice(root.as_bytes());
out.extend_from_slice(self.subkey.as_bytes());
self.app_id.encode(&mut out);
self.purpose.encode(&mut out);
out.extend_from_slice(&self.not_before.to_be_bytes());
out.extend_from_slice(&self.not_after.to_be_bytes());
out
}
}
/// A subkey certified by a root.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SubkeyCert {
root: PublicKey,
req: CertRequest,
sig: Signature,
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum CertError {
#[error("malformed certificate: {0}")]
Malformed(&'static str),
#[error("the certificate belongs to another identity")]
WrongRoot,
#[error("the certificate's signature is not valid (tampered)")]
BadSignature,
#[error("the certificate is not valid yet")]
NotYetValid,
#[error("the certificate has expired")]
Expired,
#[error("the root did not sign: {0}")]
Sign(SignError),
}
/// Has `signer` certify `req`, and checks the signature it got back.
pub fn certify(signer: &impl RootSigner, req: &CertRequest) -> Result<SubkeyCert, CertError> {
if req.not_after <= req.not_before {
return Err(CertError::Malformed("not_after must be later than not_before"));
}
let root = signer.root_public();
let tbs = req.tbs(&root);
let sig = signer.sign_cert_tbs(&tbs).map_err(CertError::Sign)?;
if !verify_cert_sig(&root, &tbs, &sig) {
return Err(CertError::BadSignature);
}
Ok(SubkeyCert { root, req: req.clone(), sig })
}
impl SubkeyCert {
pub fn root(&self) -> PublicKey {
self.root
}
pub fn subkey(&self) -> PublicKey {
self.req.subkey
}
pub fn app_id(&self) -> &Id {
&self.req.app_id
}
pub fn purpose(&self) -> &Id {
&self.req.purpose
}
pub fn not_before(&self) -> u64 {
self.req.not_before
}
pub fn not_after(&self) -> u64 {
self.req.not_after
}
/// Checks the cert against the root the caller trusts, at `now` (Unix seconds).
pub fn verify(&self, root: &PublicKey, now: u64) -> Result<(), CertError> {
if self.root != *root {
return Err(CertError::WrongRoot);
}
if !verify_cert_sig(&self.root, &self.req.tbs(&self.root), &self.sig) {
return Err(CertError::BadSignature);
}
if now < self.req.not_before {
return Err(CertError::NotYetValid);
}
if now >= self.req.not_after {
return Err(CertError::Expired);
}
Ok(())
}
pub fn to_bytes(&self) -> Vec<u8> {
let mut out = self.req.tbs(&self.root);
out.extend_from_slice(self.sig.as_bytes());
out
}
pub fn from_bytes(b: &[u8]) -> Result<SubkeyCert, CertError> {
let mut r = Reader::new(b);
let m = CertError::Malformed;
if r.take(4) != Some(CERT_MAGIC.as_slice()) {
return Err(m("not a TSC1 certificate"));
}
let root = PublicKey::from_bytes(r.array().ok_or(m("too short"))?);
let subkey = PublicKey::from_bytes(r.array().ok_or(m("too short"))?);
let app_id = Id::decode(&mut r).ok_or(m("invalid app id"))?;
let purpose = Id::decode(&mut r).ok_or(m("invalid purpose"))?;
let not_before = r.u64().ok_or(m("too short"))?;
let not_after = r.u64().ok_or(m("too short"))?;
let sig = Signature::from_bytes(r.array().ok_or(m("too short"))?);
if !r.is_empty() {
return Err(m("trailing bytes"));
}
if not_after <= not_before {
return Err(m("not_after must be later than not_before"));
}
Ok(SubkeyCert { root, req: CertRequest { subkey, app_id, purpose, not_before, not_after }, sig })
}
/// base64url without padding, for JSON and QR codes.
pub fn to_text(&self) -> String {
BASE64URL_NOPAD.encode(&self.to_bytes())
}
pub fn from_text(s: &str) -> Result<SubkeyCert, CertError> {
let b = BASE64URL_NOPAD.decode(s.as_bytes()).map_err(|_| CertError::Malformed("not base64url"))?;
SubkeyCert::from_bytes(&b)
}
}
/// Six digits for `subkey`, shown by the app and by Custos: `u32_be(SHA-256("tessera match v1" ‖ subkey)[0..4])
/// mod 1 000 000`.
pub fn match_code(subkey: &PublicKey) -> String {
let h = Sha256::new().chain_update(b"tessera match v1").chain_update(subkey.as_bytes()).finalize();
let n = u32::from_be_bytes([h[0], h[1], h[2], h[3]]) % 1_000_000;
format!("{n:06}")
}
+90
View File
@@ -0,0 +1,90 @@
//! The hybrid logical clock (docs/TESSERA.md §6). Time is a parameter: Unix milliseconds.
/// A timestamp, ordered by `wall` then `logical`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Hlc {
/// Unix milliseconds.
pub wall: u64,
pub logical: u32,
}
impl Hlc {
pub fn to_bytes(&self) -> [u8; 12] {
let mut b = [0u8; 12];
b[..8].copy_from_slice(&self.wall.to_be_bytes());
b[8..].copy_from_slice(&self.logical.to_be_bytes());
b
}
pub fn from_bytes(b: &[u8; 12]) -> Hlc {
let (w, l) = b.split_at(8);
Hlc {
wall: u64::from_be_bytes(w.try_into().unwrap_or_default()),
logical: u32::from_be_bytes(l.try_into().unwrap_or_default()),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum ClockError {
#[error("the other clock is too far ahead of this one")]
TooFarAhead,
#[error("the logical counter would overflow")]
Overflow,
}
/// One device's clock.
#[derive(Clone, Debug)]
pub struct Clock {
last: Hlc,
max_drift_ms: u64,
}
impl Default for Clock {
/// A clock that accepts remote clocks up to five minutes ahead.
fn default() -> Clock {
Clock::with_max_drift(5 * 60 * 1000)
}
}
impl Clock {
pub fn with_max_drift(max_drift_ms: u64) -> Clock {
Clock { last: Hlc::default(), max_drift_ms }
}
/// The last timestamp this clock produced.
pub fn last(&self) -> Hlc {
self.last
}
/// A timestamp for a local event.
pub fn tick(&mut self, now: u64) -> Result<Hlc, ClockError> {
let wall = self.last.wall.max(now);
let logical =
if wall == self.last.wall { self.last.logical.checked_add(1).ok_or(ClockError::Overflow)? } else { 0 };
self.last = Hlc { wall, logical };
Ok(self.last)
}
/// Moves the clock past a remote timestamp. Refuses one more than `max_drift` ahead of `now`, without
/// changing the clock.
pub fn observe(&mut self, remote: Hlc, now: u64) -> Result<Hlc, ClockError> {
if remote.wall > now.saturating_add(self.max_drift_ms) {
return Err(ClockError::TooFarAhead);
}
let last = self.last;
let wall = last.wall.max(remote.wall).max(now);
let base = match (wall == last.wall, wall == remote.wall) {
(true, true) => Some(last.logical.max(remote.logical)),
(true, false) => Some(last.logical),
(false, true) => Some(remote.logical),
(false, false) => None,
};
let logical = match base {
Some(l) => l.checked_add(1).ok_or(ClockError::Overflow)?,
None => 0,
};
self.last = Hlc { wall, logical };
Ok(self.last)
}
}
+49
View File
@@ -0,0 +1,49 @@
//! Ids: app ids, purposes and the envelope's `app` (docs/TESSERA.md §2).
use std::fmt;
/// 1–32 bytes of `[a-z0-9-]`, not starting or ending with `-`: exactly one encoding per value.
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Id(String);
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[error("an id is 1-32 characters of a-z, 0-9 and '-', not starting or ending with '-'")]
pub struct IdError;
impl Id {
pub fn new(s: &str) -> Result<Id, IdError> {
let ok = (1..=32).contains(&s.len())
&& s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
&& !s.starts_with('-')
&& !s.ends_with('-');
if ok { Ok(Id(s.to_owned())) } else { Err(IdError) }
}
pub fn as_str(&self) -> &str {
&self.0
}
/// `str8`: one length byte, then the bytes.
pub(crate) fn encode(&self, out: &mut Vec<u8>) {
out.push(self.0.len() as u8);
out.extend_from_slice(self.0.as_bytes());
}
pub(crate) fn decode(r: &mut crate::Reader) -> Option<Id> {
let n = r.u8()? as usize;
let s = std::str::from_utf8(r.take(n)?).ok()?;
Id::new(s).ok()
}
}
impl fmt::Display for Id {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl fmt::Debug for Id {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Id({})", self.0)
}
}
+232
View File
@@ -0,0 +1,232 @@
//! Keys: the root key and its derivation, subkeys, public keys and signatures (docs/TESSERA.md §3).
//!
//! The secret types ([`RootKey`], [`Subkey`]) have no method that returns their bytes, are not `Clone`,
//! and print `[redacted]`. `tests/surface.rs` locks this.
use crate::cert::CERT_MAGIC;
use data_encoding::BASE64URL_NOPAD;
use ed25519_dalek::{Signer, SigningKey, VerifyingKey};
use hkdf::Hkdf;
use sha2::Sha256;
use std::fmt;
use zeroize::Zeroizing;
/// Prefix of every message a root signs: it can only ever sign certs.
pub const CERT_DOMAIN: &[u8] = b"tessera cert v1\0";
/// Prefix of every message a subkey signs as an event author.
pub const EVENT_DOMAIN: &[u8] = b"tessera event v1\0";
/// Prefix of what a subkey signs to vouch for a device's keys in a group (docs/TABELLARIUS.md §2).
pub const CREDENTIAL_DOMAIN: &[u8] = b"tessera credential v1\0";
/// Prefix of every revocation a root signs (docs/TESSERA.md §12): its second and only other statement.
pub const REVOKE_DOMAIN: &[u8] = b"tessera revoke v1\0";
const ROOT_SALT: &[u8] = b"tessera root v1";
const ROOT_INFO: &[u8] = b"ed25519";
const MNEMONIC_WORDS: usize = 24;
/// An Ed25519 public key: a root or a subkey.
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct PublicKey([u8; 32]);
impl PublicKey {
pub fn from_bytes(b: [u8; 32]) -> PublicKey {
PublicKey(b)
}
pub fn as_bytes(&self) -> &[u8; 32] {
&self.0
}
/// Parses the base64url form that `Display` prints.
pub fn from_text(s: &str) -> Option<PublicKey> {
let b = BASE64URL_NOPAD.decode(s.as_bytes()).ok()?;
Some(PublicKey(b.try_into().ok()?))
}
}
/// base64url without padding.
impl fmt::Display for PublicKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&BASE64URL_NOPAD.encode(&self.0))
}
}
impl fmt::Debug for PublicKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "PublicKey({self})")
}
}
/// An Ed25519 signature.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Signature([u8; 64]);
impl Signature {
pub fn from_bytes(b: [u8; 64]) -> Signature {
Signature(b)
}
pub fn as_bytes(&self) -> &[u8; 64] {
&self.0
}
}
impl fmt::Debug for Signature {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Signature({}…)", BASE64URL_NOPAD.encode(&self.0[..6]))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum MnemonicError {
#[error("a Domi recovery phrase has 24 words")]
WordCount,
#[error("the recovery phrase has a word that is not in the list, or a wrong checksum")]
Invalid,
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum SignError {
#[error("the root signs only certificates that name it")]
NotACert,
#[error("{0}")]
Other(String),
}
/// What can sign certs with a root: [`RootKey`] here, the Custos vault in practice.
pub trait RootSigner {
fn root_public(&self) -> PublicKey;
/// Signs `CERT_DOMAIN ‖ tbs`. Refuses a `tbs` that does not start with `TSC1` and this root's key.
fn sign_cert_tbs(&self, tbs: &[u8]) -> Result<Signature, SignError>;
}
/// What can sign revocations with a root (v1.1): [`RootKey`] here, the Custos vault in practice.
pub trait RevokeSigner: RootSigner {
/// Signs `REVOKE_DOMAIN ‖ tbs`. Refuses a `tbs` that does not start with `TRV1` and this root's key.
fn sign_revocation_tbs(&self, tbs: &[u8]) -> Result<Signature, SignError>;
}
/// The root key, derived from a mnemonic (docs/TESSERA.md §3). For recovery and tests: the real one stays
/// in Custos.
pub struct RootKey(SigningKey);
impl RootKey {
/// Words are separated by any whitespace; case does not matter. Exactly 24 BIP39 English words.
pub fn from_mnemonic(phrase: &str) -> Result<RootKey, MnemonicError> {
let words: Vec<String> = phrase.split_whitespace().map(|w| w.to_lowercase()).collect();
let normalized = Zeroizing::new(words.join(" "));
drop(Zeroizing::new(words));
if normalized.split(' ').count() != MNEMONIC_WORDS {
return Err(MnemonicError::WordCount);
}
let m = bip39::Mnemonic::parse_in_normalized(bip39::Language::English, &normalized)
.map_err(|_| MnemonicError::Invalid)?;
let seed = Zeroizing::new(m.to_seed_normalized(""));
let mut secret = Zeroizing::new([0u8; 32]);
Hkdf::<Sha256>::new(Some(ROOT_SALT), seed.as_ref())
.expand(ROOT_INFO, secret.as_mut())
.map_err(|_| MnemonicError::Invalid)?;
Ok(RootKey(SigningKey::from_bytes(&secret)))
}
pub fn public(&self) -> PublicKey {
PublicKey(self.0.verifying_key().to_bytes())
}
/// The app's backup secret (docs/TESSERA.md §12): from the root secret, so the 24 words bring it back.
pub fn backup_secret(&self, app_id: &crate::Id) -> crate::BackupSecret {
crate::backup::derive(&Zeroizing::new(self.0.to_bytes()), app_id)
}
}
impl RevokeSigner for RootKey {
fn sign_revocation_tbs(&self, tbs: &[u8]) -> Result<Signature, SignError> {
if !names_root_as(tbs, crate::revoke::REVOCATION_MAGIC, &self.public()) {
return Err(SignError::NotACert);
}
Ok(Signature(self.0.sign(&[REVOKE_DOMAIN, tbs].concat()).to_bytes()))
}
}
impl RootSigner for RootKey {
fn root_public(&self) -> PublicKey {
self.public()
}
fn sign_cert_tbs(&self, tbs: &[u8]) -> Result<Signature, SignError> {
if !names_root(tbs, &self.public()) {
return Err(SignError::NotACert);
}
Ok(Signature(self.0.sign(&[CERT_DOMAIN, tbs].concat()).to_bytes()))
}
}
impl fmt::Debug for RootKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("RootKey([redacted])")
}
}
/// Whether `tbs` starts like a cert for `root`: `TSC1 ‖ root`. Custos' vault applies the same check.
pub(crate) fn names_root(tbs: &[u8], root: &PublicKey) -> bool {
names_root_as(tbs, CERT_MAGIC, root)
}
/// Whether `tbs` starts `magic ‖ root`.
fn names_root_as(tbs: &[u8], magic: &[u8; 4], root: &PublicKey) -> bool {
tbs.len() > 36 && &tbs[..4] == magic && tbs[4..36] == root.0
}
/// An app's subkey. The app makes the 32-byte seed from the OS CSPRNG and keeps it in Custos.
pub struct Subkey(SigningKey);
impl Subkey {
pub fn from_seed(seed: &[u8; 32]) -> Subkey {
Subkey(SigningKey::from_bytes(seed))
}
pub fn public(&self) -> PublicKey {
PublicKey(self.0.verifying_key().to_bytes())
}
/// Signs `EVENT_DOMAIN ‖ tbs`.
pub fn sign_event_tbs(&self, tbs: &[u8]) -> Signature {
Signature(self.0.sign(&[EVENT_DOMAIN, tbs].concat()).to_bytes())
}
/// Signs `CREDENTIAL_DOMAIN ‖ tbs`: vouches for keys this device uses in a group.
pub fn sign_credential_tbs(&self, tbs: &[u8]) -> Signature {
Signature(self.0.sign(&[CREDENTIAL_DOMAIN, tbs].concat()).to_bytes())
}
}
impl fmt::Debug for Subkey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Subkey([redacted])")
}
}
fn verify(key: &PublicKey, domain: &[u8], tbs: &[u8], sig: &Signature) -> bool {
let Ok(vk) = VerifyingKey::from_bytes(&key.0) else { return false };
let sig = ed25519_dalek::Signature::from_bytes(&sig.0);
vk.verify_strict(&[domain, tbs].concat(), &sig).is_ok()
}
/// Whether `sig` is `author`'s signature over `EVENT_DOMAIN ‖ tbs` (strict: no malleable signatures, no
/// weak keys).
pub fn verify_event_sig(author: &PublicKey, tbs: &[u8], sig: &Signature) -> bool {
verify(author, EVENT_DOMAIN, tbs, sig)
}
/// Whether `sig` is `subkey`'s signature over `CREDENTIAL_DOMAIN ‖ tbs`.
pub fn verify_credential_sig(subkey: &PublicKey, tbs: &[u8], sig: &Signature) -> bool {
verify(subkey, CREDENTIAL_DOMAIN, tbs, sig)
}
pub(crate) fn verify_revocation_sig(root: &PublicKey, tbs: &[u8], sig: &Signature) -> bool {
verify(root, REVOKE_DOMAIN, tbs, sig)
}
pub(crate) fn verify_cert_sig(root: &PublicKey, tbs: &[u8], sig: &Signature) -> bool {
verify(root, CERT_DOMAIN, tbs, sig)
}
+74
View File
@@ -0,0 +1,74 @@
//! Tessera: the Domi identity (docs/TESSERA.md).
//!
//! - [`RootKey`]: the root Ed25519 key, derived from a 24-word BIP39 mnemonic. In practice it lives in the
//! Custos vault, which implements [`RootSigner`]; this type is for recovery and tests.
//! - [`SubkeyCert`]: a subkey for one app, certified by the root; [`certify`] makes one, `verify` checks it.
//! - [`match_code`]: six digits the app and Custos both show.
//! - [`Clock`] / [`Hlc`]: a hybrid logical clock; [`merge`]: the deterministic union of event logs.
//! - [`revoke`] / [`RevocationSet`]: withdrawing a subkey (v1.1); [`BackupSecret`]: sealing an app's backup.
//!
//! Pure: no I/O, no network, no clock. Time is always a parameter (Unix seconds for certs, milliseconds for
//! the clock).
mod backup;
mod cert;
mod hlc;
mod id;
mod keys;
mod merge;
mod revoke;
pub use backup::BackupSecret;
pub use cert::{CERT_MAGIC, CertError, CertRequest, SubkeyCert, certify, match_code};
pub use hlc::{Clock, ClockError, Hlc};
pub use id::{Id, IdError};
pub use keys::{
CERT_DOMAIN, CREDENTIAL_DOMAIN, EVENT_DOMAIN, MnemonicError, PublicKey, REVOKE_DOMAIN, RevokeSigner, RootKey,
RootSigner, SignError, Signature, Subkey, verify_credential_sig, verify_event_sig,
};
pub use merge::{Log, LogEvent, Merged, OrderKey, merge};
pub use revoke::{
REVOCATION_MAGIC, REVOCATION_PART_MAX, REVOCATION_PARTS_MAX, Revocation, RevocationError, RevocationSet, revoke,
};
use sha2::{Digest, Sha256};
/// SHA-256 of `bytes`: the hash in an event's order key.
pub fn hash(bytes: &[u8]) -> [u8; 32] {
Sha256::digest(bytes).into()
}
/// A cursor over bytes being decoded. Every read checks the length; nothing panics.
pub(crate) struct Reader<'a> {
bytes: &'a [u8],
pos: usize,
}
impl<'a> Reader<'a> {
pub(crate) fn new(bytes: &'a [u8]) -> Self {
Reader { bytes, pos: 0 }
}
pub(crate) fn take(&mut self, n: usize) -> Option<&'a [u8]> {
let end = self.pos.checked_add(n)?;
let s = self.bytes.get(self.pos..end)?;
self.pos = end;
Some(s)
}
pub(crate) fn array<const N: usize>(&mut self) -> Option<[u8; N]> {
self.take(N)?.try_into().ok()
}
pub(crate) fn u8(&mut self) -> Option<u8> {
Some(self.take(1)?[0])
}
pub(crate) fn u64(&mut self) -> Option<u64> {
Some(u64::from_be_bytes(self.array()?))
}
pub(crate) fn is_empty(&self) -> bool {
self.pos == self.bytes.len()
}
}
+108
View File
@@ -0,0 +1,108 @@
//! The deterministic merge of event logs (docs/TESSERA.md §7).
use crate::{Hlc, PublicKey};
use std::collections::BTreeMap;
/// Where an event sits in every log: by clock, then author, then the hash of its bytes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct OrderKey {
pub hlc: Hlc,
pub author: PublicKey,
/// SHA-256 of the encoded event ([`crate::hash`]).
pub hash: [u8; 32],
}
/// An event a log can hold. `order_key` must be derived from `encoded`, so equal bytes give equal keys.
pub trait LogEvent {
fn order_key(&self) -> OrderKey;
fn encoded(&self) -> &[u8];
}
/// Verified events, each once, sorted by order key.
#[derive(Clone, Debug)]
pub struct Log<E> {
events: Vec<E>,
}
impl<E> Default for Log<E> {
fn default() -> Self {
Log { events: Vec::new() }
}
}
impl<E: LogEvent + Clone> Log<E> {
pub fn new() -> Log<E> {
Log::default()
}
/// A log read back from the app's own storage, whose events were verified when they arrived.
/// Sorts and de-duplicates them.
pub fn from_stored(events: Vec<E>) -> Log<E> {
let map: BTreeMap<OrderKey, E> = events.into_iter().map(|e| (e.order_key(), e)).collect();
Log { events: map.into_values().collect() }
}
pub fn events(&self) -> &[E] {
&self.events
}
pub fn len(&self) -> usize {
self.events.len()
}
pub fn is_empty(&self) -> bool {
self.events.is_empty()
}
pub fn contains(&self, hash: &[u8; 32]) -> bool {
self.events.iter().any(|e| e.order_key().hash == *hash)
}
/// `u32 length ‖ encoded event` for each event, in order.
pub fn to_bytes(&self) -> Vec<u8> {
let mut out = Vec::new();
for e in &self.events {
let b = e.encoded();
out.extend_from_slice(&(b.len() as u32).to_be_bytes());
out.extend_from_slice(b);
}
out
}
}
/// The result of [`merge`].
#[derive(Debug)]
pub struct Merged<E, R> {
pub log: Log<E>,
/// How many events were new.
pub added: usize,
/// Events that failed `verify`, each with its reason. None of them is in `log`.
pub rejected: Vec<(E, R)>,
}
/// The union of `log` and the events of `batch` that pass `verify`, de-duplicated and ordered. Events
/// already in `log` are not verified again. Any order and any repetition of the same batches gives the same
/// log.
pub fn merge<E: LogEvent + Clone, R>(
log: &Log<E>,
batch: impl IntoIterator<Item = E>,
mut verify: impl FnMut(&E) -> Result<(), R>,
) -> Merged<E, R> {
let mut map: BTreeMap<OrderKey, E> = log.events.iter().map(|e| (e.order_key(), e.clone())).collect();
let mut added = 0;
let mut rejected = Vec::new();
for e in batch {
let key = e.order_key();
if map.contains_key(&key) {
continue;
}
match verify(&e) {
Ok(()) => {
map.insert(key, e);
added += 1;
}
Err(why) => rejected.push((e, why)),
}
}
Merged { log: Log { events: map.into_values().collect() }, added, rejected }
}
+227
View File
@@ -0,0 +1,227 @@
//! Revocation (`TRV1`, docs/TESSERA.md §12, docs/V1_1.md §1): the root withdraws a subkey and names exactly
//! which of its events stay valid. Every other event by that subkey is rejected, whatever time it claims, so
//! a stolen subkey cannot backdate into its cert's validity.
use crate::keys::{RevokeSigner, SignError, verify_revocation_sig};
use crate::{PublicKey, Reader, Signature};
use data_encoding::BASE64URL_NOPAD;
use std::collections::{BTreeMap, BTreeSet};
pub const REVOCATION_MAGIC: &[u8; 4] = b"TRV1";
/// Hashes per statement: one statement fits in one event (256 KiB payload) with room to spare.
pub const REVOCATION_PART_MAX: usize = 7_000;
/// At most this many parts: 1.8 million events per revoked subkey per group.
pub const REVOCATION_PARTS_MAX: usize = 256;
/// One root-signed revocation statement (one part of it, if the list is long).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Revocation {
root: PublicKey,
subkey: PublicKey,
revoked_at: u64,
part: u16,
parts: u16,
accepted: Vec<[u8; 32]>,
sig: Signature,
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum RevocationError {
#[error("malformed revocation: {0}")]
Malformed(&'static str),
#[error("the revocation belongs to another identity")]
WrongRoot,
#[error("the revocation's root is not a member of this group")]
UnknownRoot,
#[error("the revocation's signature is not valid (tampered)")]
BadSignature,
#[error("the root did not sign: {0}")]
Sign(SignError),
#[error("too many events to keep in one revocation")]
TooLarge,
#[error("written by a revoked key, and not among the events its revocation kept")]
Revoked,
}
fn tbs(root: &PublicKey, subkey: &PublicKey, revoked_at: u64, part: u16, parts: u16, accepted: &[[u8; 32]]) -> Vec<u8> {
let mut out = Vec::with_capacity(4 + 64 + 8 + 4 + 4 + accepted.len() * 32);
out.extend_from_slice(REVOCATION_MAGIC);
out.extend_from_slice(root.as_bytes());
out.extend_from_slice(subkey.as_bytes());
out.extend_from_slice(&revoked_at.to_be_bytes());
out.extend_from_slice(&part.to_be_bytes());
out.extend_from_slice(&parts.to_be_bytes());
out.extend_from_slice(&(accepted.len() as u32).to_be_bytes());
for h in accepted {
out.extend_from_slice(h);
}
out
}
/// Has `signer` revoke `subkey` at `revoked_at` (Unix seconds), keeping the events whose hashes are in
/// `accepted` (deduplicated and sorted here). A long list comes back as several parts, each signed.
pub fn revoke(
signer: &impl RevokeSigner,
subkey: PublicKey,
revoked_at: u64,
accepted: Vec<[u8; 32]>,
) -> Result<Vec<Revocation>, RevocationError> {
let sorted: Vec<[u8; 32]> = accepted.into_iter().collect::<BTreeSet<_>>().into_iter().collect();
let chunks: Vec<&[[u8; 32]]> =
if sorted.is_empty() { vec![&[][..]] } else { sorted.chunks(REVOCATION_PART_MAX).collect() };
if chunks.len() > REVOCATION_PARTS_MAX {
return Err(RevocationError::TooLarge);
}
let root = signer.root_public();
let parts = chunks.len() as u16;
chunks
.into_iter()
.enumerate()
.map(|(i, chunk)| {
let t = tbs(&root, &subkey, revoked_at, i as u16, parts, chunk);
let sig = signer.sign_revocation_tbs(&t).map_err(RevocationError::Sign)?;
let r = Revocation { root, subkey, revoked_at, part: i as u16, parts, accepted: chunk.to_vec(), sig };
r.verify(&root)?;
Ok(r)
})
.collect()
}
impl Revocation {
pub fn root(&self) -> PublicKey {
self.root
}
pub fn subkey(&self) -> PublicKey {
self.subkey
}
pub fn revoked_at(&self) -> u64 {
self.revoked_at
}
/// This part's hashes, sorted.
pub fn accepted(&self) -> &[[u8; 32]] {
&self.accepted
}
/// The bytes the root signs (after `REVOKE_DOMAIN`).
pub fn tbs(&self) -> Vec<u8> {
tbs(&self.root, &self.subkey, self.revoked_at, self.part, self.parts, &self.accepted)
}
/// Checks the statement against the root the caller trusts.
pub fn verify(&self, root: &PublicKey) -> Result<(), RevocationError> {
if self.root != *root {
return Err(RevocationError::WrongRoot);
}
if !verify_revocation_sig(&self.root, &self.tbs(), &self.sig) {
return Err(RevocationError::BadSignature);
}
Ok(())
}
pub fn to_bytes(&self) -> Vec<u8> {
let mut out = self.tbs();
out.extend_from_slice(self.sig.as_bytes());
out
}
/// base64url without padding, for JSON (the Custos pipe).
pub fn to_text(&self) -> String {
BASE64URL_NOPAD.encode(&self.to_bytes())
}
pub fn from_text(s: &str) -> Result<Revocation, RevocationError> {
let b = BASE64URL_NOPAD.decode(s.as_bytes()).map_err(|_| RevocationError::Malformed("not base64url"))?;
Revocation::from_bytes(&b)
}
/// Strict: the magic, every length, sorted unique hashes, a part inside its count, no trailing bytes.
pub fn from_bytes(b: &[u8]) -> Result<Revocation, RevocationError> {
let m = RevocationError::Malformed;
let mut r = Reader::new(b);
if r.take(4) != Some(REVOCATION_MAGIC.as_slice()) {
return Err(m("not a TRV1 revocation"));
}
let root = PublicKey::from_bytes(r.array().ok_or(m("truncated"))?);
let subkey = PublicKey::from_bytes(r.array().ok_or(m("truncated"))?);
let revoked_at = r.u64().ok_or(m("truncated"))?;
let part = u16::from_be_bytes(r.array().ok_or(m("truncated"))?);
let parts = u16::from_be_bytes(r.array().ok_or(m("truncated"))?);
if parts == 0 || part >= parts || parts as usize > REVOCATION_PARTS_MAX {
return Err(m("a part outside its count"));
}
let count = u32::from_be_bytes(r.array().ok_or(m("truncated"))?) as usize;
if count > REVOCATION_PART_MAX {
return Err(m("too many hashes in one part"));
}
let mut accepted = Vec::with_capacity(count);
for _ in 0..count {
let h: [u8; 32] = r.array().ok_or(m("truncated"))?;
if accepted.last().is_some_and(|prev: &[u8; 32]| *prev >= h) {
return Err(m("hashes not sorted and unique"));
}
accepted.push(h);
}
let sig = Signature::from_bytes(r.array().ok_or(m("truncated"))?);
if !r.is_empty() {
return Err(m("trailing bytes"));
}
Ok(Revocation { root, subkey, revoked_at, part, parts, accepted, sig })
}
}
/// One statement being collected: its parts so far.
#[derive(Default)]
struct Statement {
parts: u16,
have: BTreeSet<u16>,
accepted: BTreeSet<[u8; 32]>,
}
/// The revocations a group's log holds, applied to its events. The same statements give the same answers in
/// any order: parts of one statement add up, separate statements for one subkey keep only what all keep.
#[derive(Default)]
pub struct RevocationSet {
/// (subkey, revoked_at, parts) → the statement's parts.
statements: BTreeMap<(PublicKey, u64, u16), Statement>,
}
impl RevocationSet {
/// Adds one part, after checking it is signed by its root and that the root is one of the group's.
pub fn add(&mut self, r: Revocation, group_roots: &[PublicKey]) -> Result<(), RevocationError> {
if !group_roots.contains(&r.root) {
return Err(RevocationError::UnknownRoot);
}
r.verify(&r.root)?;
let s = self.statements.entry((r.subkey, r.revoked_at, r.parts)).or_default();
s.parts = r.parts;
s.have.insert(r.part);
s.accepted.extend(r.accepted);
Ok(())
}
fn complete(&self, subkey: &PublicKey) -> impl Iterator<Item = &Statement> {
self.statements
.iter()
.filter(move |((k, _, _), s)| k == subkey && s.have.len() == s.parts as usize)
.map(|(_, s)| s)
}
/// Whether a complete revocation of `subkey` is in force.
pub fn is_revoked(&self, subkey: &PublicKey) -> bool {
self.complete(subkey).next().is_some()
}
/// Whether the event `hash` by `author` stays valid: yes unless a complete revocation of `author` is in
/// force and does not list it (every one in force must list it).
pub fn check(&self, author: &PublicKey, hash: &[u8; 32]) -> Result<(), RevocationError> {
for s in self.complete(author) {
if !s.accepted.contains(hash) {
return Err(RevocationError::Revoked);
}
}
Ok(())
}
}
+332
View File
@@ -0,0 +1,332 @@
//! The mandatory tests for tessera (docs/TESSERA.md). Written before the code.
use proptest::prelude::*;
use tessera::{
CertError, CertRequest, Clock, ClockError, Hlc, Id, Log, LogEvent, OrderKey, PublicKey, RootKey, RootSigner,
Subkey, SubkeyCert, certify, match_code, merge,
};
/// `abandon` × 23 + `art`: the BIP39 mnemonic of 32 zero bytes.
const ZERO_MNEMONIC: &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";
/// Its root public key (docs/TESSERA.md §9). CustosPublic pins the same value.
const ROOT_PUB_ZERO: &str = "vCrwX9p44un1ftQLgJtuaVQ0qPWbFfzNjgrlDkL4TKs";
/// The match code of the subkey `07` × 32.
const MATCH_SEVENS: &str = "016810";
const DAY: u64 = 86_400;
const NOW: u64 = 1_793_000_000;
fn root() -> RootKey {
RootKey::from_mnemonic(ZERO_MNEMONIC).unwrap()
}
fn other_root() -> RootKey {
RootKey::from_mnemonic(
"legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful \
legal winner thank year wave sausage worth title",
)
.unwrap()
}
fn request(sub: &Subkey) -> CertRequest {
CertRequest {
subkey: sub.public(),
app_id: Id::new("fiscus").unwrap(),
purpose: Id::new("sync").unwrap(),
not_before: NOW - DAY,
not_after: NOW + 365 * DAY,
}
}
// ---------- mnemonic round trip ----------
#[test]
fn the_same_mnemonic_gives_the_same_root_every_time() {
let a = root().public();
for _ in 0..3 {
assert_eq!(root().public(), a);
}
assert_eq!(a.to_string(), ROOT_PUB_ZERO, "the pinned vector");
// Spacing and case do not change the words.
let messy = format!(" {} ", ZERO_MNEMONIC.to_uppercase().replace(' ', " "));
assert_eq!(RootKey::from_mnemonic(&messy).unwrap().public(), a);
assert_ne!(other_root().public(), a);
}
#[test]
fn a_wrong_mnemonic_is_refused() {
let bad_checksum = ZERO_MNEMONIC.replace(" art", " abandon");
assert!(RootKey::from_mnemonic(&bad_checksum).is_err());
assert!(RootKey::from_mnemonic("abandon abandon").is_err());
assert!(RootKey::from_mnemonic(&ZERO_MNEMONIC.replace(" art", " notaword")).is_err());
// 12 words is a valid BIP39 mnemonic, but a Domi root is always 24.
let twelve = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
assert!(RootKey::from_mnemonic(twelve).is_err());
}
// ---------- certificates ----------
#[test]
fn a_valid_cert_passes_and_round_trips() {
let sub = Subkey::from_seed(&[1; 32]);
let cert = certify(&root(), &request(&sub)).unwrap();
assert_eq!(cert.verify(&root().public(), NOW), Ok(()));
let back = SubkeyCert::from_bytes(&cert.to_bytes()).unwrap();
assert_eq!(back, cert);
assert_eq!(back.subkey(), sub.public());
assert_eq!(back.app_id().as_str(), "fiscus");
assert_eq!(back.purpose().as_str(), "sync");
assert_eq!(SubkeyCert::from_text(&cert.to_text()).unwrap(), cert);
}
#[test]
fn expired_and_not_yet_valid_certs_are_rejected() {
let sub = Subkey::from_seed(&[1; 32]);
let cert = certify(&root(), &request(&sub)).unwrap();
let r = root().public();
assert_eq!(cert.verify(&r, NOW - DAY - 1), Err(CertError::NotYetValid));
assert_eq!(cert.verify(&r, NOW - DAY), Ok(()), "not_before is inclusive");
assert_eq!(cert.verify(&r, NOW + 365 * DAY - 1), Ok(()));
assert_eq!(cert.verify(&r, NOW + 365 * DAY), Err(CertError::Expired), "not_after is exclusive");
}
#[test]
fn a_cert_from_another_root_is_rejected() {
let sub = Subkey::from_seed(&[1; 32]);
let cert = certify(&other_root(), &request(&sub)).unwrap();
assert_eq!(cert.verify(&root().public(), NOW), Err(CertError::WrongRoot));
}
#[test]
fn every_tampered_byte_is_rejected() {
let sub = Subkey::from_seed(&[1; 32]);
let cert = certify(&root(), &request(&sub)).unwrap();
let bytes = cert.to_bytes();
for i in 0..bytes.len() {
for bit in 0..8 {
let mut b = bytes.clone();
b[i] ^= 1 << bit;
if let Ok(c) = SubkeyCert::from_bytes(&b) {
assert!(c.verify(&root().public(), NOW).is_err(), "byte {i} bit {bit} accepted");
}
}
}
}
#[test]
fn a_signer_claiming_another_root_cannot_make_a_valid_cert() {
// A RootSigner whose public key does not match its signatures.
struct Liar(RootKey, PublicKey);
impl RootSigner for Liar {
fn root_public(&self) -> PublicKey {
self.1
}
fn sign_cert_tbs(&self, tbs: &[u8]) -> Result<tessera::Signature, tessera::SignError> {
self.0.sign_cert_tbs(tbs)
}
}
let sub = Subkey::from_seed(&[1; 32]);
let liar = Liar(other_root(), root().public());
assert!(certify(&liar, &request(&sub)).is_err(), "certify checks the signature it got back");
}
#[test]
fn a_root_key_signs_only_cert_shaped_messages() {
assert!(root().sign_cert_tbs(b"pay 100 CZK to mallory").is_err());
let sub = Subkey::from_seed(&[1; 32]);
// A tbs naming another root is refused too.
let tbs = request(&sub).tbs(&other_root().public());
assert!(root().sign_cert_tbs(&tbs).is_err());
}
#[test]
fn malformed_certs_are_rejected_on_decoding() {
let sub = Subkey::from_seed(&[1; 32]);
let good = certify(&root(), &request(&sub)).unwrap().to_bytes();
assert!(SubkeyCert::from_bytes(&good[..good.len() - 1]).is_err());
let mut long = good.clone();
long.push(0);
assert!(SubkeyCert::from_bytes(&long).is_err(), "trailing bytes");
let mut magic = good.clone();
magic[0] = b'X';
assert!(SubkeyCert::from_bytes(&magic).is_err());
let mut empty_validity = request(&sub);
empty_validity.not_after = empty_validity.not_before;
assert!(certify(&root(), &empty_validity).is_err());
for bad in ["", "Fiscus", "-fiscus", "fiscus-", "fis cus", "fiscus/x", &"a".repeat(33)] {
assert!(Id::new(bad).is_err(), "{bad:?}");
}
assert!(Id::new(&"a".repeat(32)).is_ok());
}
// ---------- match code ----------
#[test]
fn match_code_vector() {
let code = match_code(&PublicKey::from_bytes([7; 32]));
assert_eq!(code.len(), 6);
assert!(code.bytes().all(|b| b.is_ascii_digit()));
assert_eq!(code, MATCH_SEVENS);
assert_ne!(match_code(&PublicKey::from_bytes([8; 32])), code);
}
// ---------- secrets stay secret ----------
#[test]
fn event_and_credential_signatures_do_not_cross() {
let sub = Subkey::from_seed(&[1; 32]);
let sig = sub.sign_credential_tbs(b"keys");
assert!(tessera::verify_credential_sig(&sub.public(), b"keys", &sig));
assert!(!tessera::verify_event_sig(&sub.public(), b"keys", &sig), "a credential signature is never an event");
let ev = sub.sign_event_tbs(b"keys");
assert!(!tessera::verify_credential_sig(&sub.public(), b"keys", &ev));
}
#[test]
fn secret_types_print_redacted() {
let s = format!("{:?} {:?}", root(), Subkey::from_seed(&[1; 32]));
assert_eq!(s, "RootKey([redacted]) Subkey([redacted])");
}
// ---------- hybrid logical clock ----------
#[test]
fn the_clock_never_goes_backwards() {
let mut c = Clock::default();
let a = c.tick(1000).unwrap();
let b = c.tick(1000).unwrap();
let d = c.tick(500).unwrap(); // the wall clock jumped back
let e = c.tick(2000).unwrap();
assert!(a < b && b < d && d < e);
assert_eq!(e, Hlc { wall: 2000, logical: 0 });
assert_eq!(Hlc::from_bytes(&e.to_bytes()), e);
}
#[test]
fn the_clock_follows_a_remote_clock_within_the_drift() {
let mut c = Clock::with_max_drift(60_000);
c.tick(1000).unwrap();
let remote = Hlc { wall: 5000, logical: 7 };
let seen = c.observe(remote, 1000).unwrap();
assert!(seen > remote);
assert!(c.tick(1000).unwrap() > seen);
assert_eq!(c.observe(Hlc { wall: 1000 + 60_001, logical: 0 }, 1000), Err(ClockError::TooFarAhead));
}
#[test]
fn the_logical_counter_does_not_wrap() {
let mut c = Clock::default();
c.observe(Hlc { wall: 10, logical: u32::MAX - 1 }, 10).unwrap();
assert_eq!(c.tick(10), Err(ClockError::Overflow));
// A later wall clock resets the counter.
assert_eq!(c.tick(11), Ok(Hlc { wall: 11, logical: 0 }));
}
// ---------- merge ----------
/// A minimal event: its bytes, an author and a clock. Valid unless `bad`.
#[derive(Clone, Debug)]
struct Ev {
bytes: Vec<u8>,
key: OrderKey,
bad: bool,
}
impl Ev {
fn new(author: u8, wall: u64, logical: u32, body: u8, bad: bool) -> Ev {
let bytes = vec![author, (wall % 256) as u8, logical as u8, body, bad as u8];
let key = OrderKey {
hlc: Hlc { wall, logical },
author: PublicKey::from_bytes([author; 32]),
hash: tessera::hash(&bytes),
};
Ev { bytes, key, bad }
}
}
impl LogEvent for Ev {
fn order_key(&self) -> OrderKey {
self.key
}
fn encoded(&self) -> &[u8] {
&self.bytes
}
}
fn check(e: &Ev) -> Result<(), &'static str> {
if e.bad { Err("bad signature") } else { Ok(()) }
}
fn arb_events() -> impl Strategy<Value = Vec<Ev>> {
// Few authors and clocks, so ties on (hlc, author) happen and the hash decides.
prop::collection::vec((0u8..3, 0u64..4, 0u32..2, any::<u8>(), prop::bool::weighted(0.15)), 1..40)
.prop_map(|v| v.into_iter().map(|(a, w, l, b, bad)| Ev::new(a, w, l, b, bad)).collect())
}
/// Merges `batches` into an empty log one after another.
fn merge_all(batches: &[Vec<Ev>]) -> Log<Ev> {
let mut log = Log::new();
for b in batches {
log = merge(&log, b.iter().cloned(), check).log;
}
log
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(256))]
#[test]
fn merge_is_order_independent_and_idempotent(
events in arb_events(),
split in prop::collection::vec(0usize..4, 40),
perm_seed in any::<u64>(),
dups in prop::collection::vec(any::<prop::sample::Index>(), 0..10),
) {
// Split into up to 4 batches, then shuffle the batches and the events in them, and duplicate some.
let mut batches: Vec<Vec<Ev>> = vec![Vec::new(); 4];
for (i, e) in events.iter().enumerate() {
batches[split[i % split.len()]].push(e.clone());
}
for d in &dups {
let e = d.get(&events).clone();
batches[d.index(4)].push(e);
}
let reference = merge_all(std::slice::from_ref(&events));
let mut shuffled = batches.clone();
let mut s = perm_seed;
for b in shuffled.iter_mut() {
for i in (1..b.len()).rev() {
s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
b.swap(i, (s >> 33) as usize % (i + 1));
}
}
shuffled.rotate_left((perm_seed % 4) as usize);
let merged = merge_all(&shuffled);
prop_assert_eq!(merged.to_bytes(), reference.to_bytes());
// Merging everything again changes nothing.
let again = merge(&merged, batches.concat(), check);
prop_assert_eq!(again.added, 0);
prop_assert_eq!(again.log.to_bytes(), reference.to_bytes());
// Only valid events, each once, in order-key order.
let keys: Vec<OrderKey> = merged.events().iter().map(|e| e.order_key()).collect();
prop_assert!(keys.windows(2).all(|w| w[0] < w[1]));
prop_assert!(merged.events().iter().all(|e| !e.bad));
let valid: std::collections::BTreeSet<_> = events.iter().filter(|e| !e.bad).map(|e| e.key.hash).collect();
prop_assert_eq!(merged.len(), valid.len());
}
}
#[test]
fn rejected_events_come_back_with_their_reason() {
let good = Ev::new(1, 1, 0, 1, false);
let bad = Ev::new(1, 2, 0, 2, true);
let m = merge(&Log::new(), vec![good.clone(), bad.clone(), bad.clone()], check);
assert_eq!(m.added, 1);
assert_eq!(m.log.len(), 1);
assert_eq!(m.rejected.len(), 2);
assert!(m.rejected.iter().all(|(e, why)| e.key == bad.key && *why == "bad signature"));
}
+204
View File
@@ -0,0 +1,204 @@
//! v1.1a: revocation (`TRV1`, docs/V1_1.md §1) and the backup secret (§3).
//!
//! - A revocation is root-signed in its own domain; the root's signer refuses to sign it as a cert and the
//! other way round.
//! - It keeps exactly the listed events of the revoked subkey; every other event by that subkey is
//! rejected, whatever time it claims. Unrelated authors are untouched.
//! - Split statements count only when complete; the result does not depend on the order they arrive in;
//! two statements for one subkey keep only what both keep.
//! - The backup secret is the same from the 24 words every time, differs per app, and seals so that only
//! the same secret opens.
use proptest::prelude::*;
use tessera::{
BackupSecret, CertRequest, Id, PublicKey, Revocation, RevocationError, RevocationSet, RevokeSigner, RootKey,
RootSigner, Subkey, hash, revoke,
};
fn root(n: u8) -> RootKey {
let m = bip39::Mnemonic::from_entropy(&[n; 32]).unwrap();
RootKey::from_mnemonic(&m.to_string()).unwrap()
}
fn h(n: u32) -> [u8; 32] {
hash(&n.to_be_bytes())
}
const T: u64 = 1_793_700_000;
#[test]
fn a_revocation_round_trips_and_verifies_under_its_root() {
let r = root(1);
let sub = Subkey::from_seed(&[5; 32]).public();
let parts = revoke(&r, sub, T, vec![h(3), h(1), h(2), h(1)]).unwrap();
assert_eq!(parts.len(), 1);
let p = &parts[0];
assert_eq!((p.root(), p.subkey(), p.revoked_at()), (r.public(), sub, T));
assert_eq!(
p.accepted(),
&[h(1), h(2), h(3)].iter().copied().collect::<std::collections::BTreeSet<_>>().into_iter().collect::<Vec<_>>()
);
let back = Revocation::from_bytes(&p.to_bytes()).unwrap();
assert_eq!(&back, p);
assert!(back.verify(&r.public()).is_ok());
assert_eq!(back.verify(&root(2).public()), Err(RevocationError::WrongRoot));
}
#[test]
fn a_tampered_or_malformed_revocation_is_refused() {
let r = root(1);
let bytes = revoke(&r, Subkey::from_seed(&[5; 32]).public(), T, vec![h(1)]).unwrap()[0].to_bytes();
for i in [5, 40, 70, 80, bytes.len() - 1] {
let mut b = bytes.clone();
b[i] ^= 1;
let bad = Revocation::from_bytes(&b).map(|x| x.verify(&r.public()));
assert!(!matches!(bad, Ok(Ok(()))), "flip at {i} still verifies");
}
for cut in 0..bytes.len() {
assert!(Revocation::from_bytes(&bytes[..cut]).is_err(), "a truncation at {cut} decoded");
}
let mut extra = bytes.clone();
extra.push(0);
assert!(Revocation::from_bytes(&extra).is_err(), "trailing bytes");
let mut as_cert = bytes;
as_cert[..4].copy_from_slice(b"TSC1");
assert!(Revocation::from_bytes(&as_cert).is_err(), "a cert is not a revocation");
}
#[test]
fn a_root_signs_a_revocation_and_a_cert_only_in_their_own_domains() {
let r = root(1);
let sub = Subkey::from_seed(&[5; 32]).public();
let req = CertRequest::standard(sub, Id::new("fiscus").unwrap(), Id::new("sync").unwrap(), T);
let cert_tbs = req.tbs(&r.public());
assert!(r.sign_revocation_tbs(&cert_tbs).is_err(), "a cert's tbs is not signed as a revocation");
let rev_tbs = revoke(&r, sub, T, vec![]).unwrap()[0].tbs();
assert!(r.sign_cert_tbs(&rev_tbs).is_err(), "a revocation's tbs is not signed as a cert");
let other = revoke(&root(2), sub, T, vec![]).unwrap()[0].tbs();
assert!(r.sign_revocation_tbs(&other).is_err(), "a root signs only revocations that name it");
}
#[test]
fn only_the_listed_events_of_a_revoked_subkey_stay_valid() {
let r = root(1);
let lost = Subkey::from_seed(&[5; 32]).public();
let other = Subkey::from_seed(&[6; 32]).public();
let mut set = RevocationSet::default();
for p in revoke(&r, lost, T, vec![h(1), h(2)]).unwrap() {
set.add(p, &[r.public()]).unwrap();
}
assert!(set.check(&lost, &h(1)).is_ok());
assert!(set.check(&lost, &h(2)).is_ok());
assert!(set.check(&lost, &h(3)).is_err(), "written after, or backdated: rejected either way");
assert!(set.check(&other, &h(3)).is_ok(), "other authors are untouched");
assert!(set.is_revoked(&lost) && !set.is_revoked(&other));
}
#[test]
fn a_revocation_from_a_root_outside_the_group_is_refused() {
let lost = Subkey::from_seed(&[5; 32]).public();
let mut set = RevocationSet::default();
let p = revoke(&root(9), lost, T, vec![]).unwrap().remove(0);
assert_eq!(set.add(p, &[root(1).public()]), Err(RevocationError::UnknownRoot));
assert!(set.check(&lost, &h(1)).is_ok());
}
#[test]
fn a_long_list_is_split_and_counts_only_when_complete() {
let r = root(1);
let lost = Subkey::from_seed(&[5; 32]).public();
let kept: Vec<[u8; 32]> = (0..tessera::REVOCATION_PART_MAX as u32 * 2 + 10).map(h).collect();
let parts = revoke(&r, lost, T, kept.clone()).unwrap();
assert_eq!(parts.len(), 3);
for p in &parts {
assert!(p.to_bytes().len() < 240 * 1024, "a part fits in one event");
}
let mut set = RevocationSet::default();
set.add(parts[0].clone(), &[r.public()]).unwrap();
set.add(parts[2].clone(), &[r.public()]).unwrap();
assert!(set.check(&lost, &h(u32::MAX)).is_ok(), "incomplete: not in force yet");
set.add(parts[1].clone(), &[r.public()]).unwrap();
assert!(set.check(&lost, &h(u32::MAX)).is_err(), "complete: in force");
assert!(kept.iter().all(|k| set.check(&lost, k).is_ok()));
}
#[test]
fn two_revocations_of_one_subkey_keep_only_what_both_keep() {
let r = root(1);
let lost = Subkey::from_seed(&[5; 32]).public();
let mut set = RevocationSet::default();
for p in revoke(&r, lost, T, vec![h(1), h(2), h(3)]).unwrap() {
set.add(p, &[r.public()]).unwrap();
}
for p in revoke(&r, lost, T + 60, vec![h(2), h(3), h(4)]).unwrap() {
set.add(p, &[r.public()]).unwrap();
}
let kept: Vec<u32> = (1..=4).filter(|n| set.check(&lost, &h(*n)).is_ok()).collect();
assert_eq!(kept, vec![2, 3], "a later statement never widens what is kept");
}
proptest! {
#[test]
fn the_result_does_not_depend_on_arrival_order(seed in any::<u64>(), keep in proptest::collection::vec(0u32..40, 0..30)) {
let r = root(1);
let lost = Subkey::from_seed(&[5; 32]).public();
let mut parts = revoke(&r, lost, T, keep.iter().map(|n| h(*n)).collect()).unwrap();
parts.extend(revoke(&r, lost, T + 1, (0..40).filter(|n| n % 3 != 0).map(h).collect()).unwrap());
let build = |order: &[Revocation]| {
let mut set = RevocationSet::default();
for p in order {
set.add(p.clone(), &[r.public()]).unwrap();
}
(0..40).map(|n| set.check(&lost, &h(n)).is_ok()).collect::<Vec<_>>()
};
let a = build(&parts);
let mut shuffled = parts.clone();
let mut s = seed;
for i in (1..shuffled.len()).rev() {
s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
shuffled.swap(i, (s >> 33) as usize % (i + 1));
}
prop_assert_eq!(a, build(&shuffled));
}
}
#[test]
fn the_backup_secret_comes_back_from_the_words_and_differs_per_app() {
let fiscus = Id::new("fiscus").unwrap();
let a = root(1).backup_secret(&fiscus);
let b = root(1).backup_secret(&fiscus);
let other_app = root(1).backup_secret(&Id::new("calenda").unwrap());
let other_person = root(2).backup_secret(&fiscus);
let nonce = [7u8; 24];
let sealed = a.seal(&nonce, b"aad", b"the self group's log");
assert_eq!(b.open(b"aad", &sealed).as_deref(), Some(b"the self group's log".as_slice()));
assert_eq!(b.open(b"other aad", &sealed), None);
assert_eq!(other_app.open(b"aad", &sealed), None);
assert_eq!(other_person.open(b"aad", &sealed), None);
assert!(!sealed.windows(4).any(|w| w == b"self"), "sealed, not readable");
assert_ne!(*a.mailbox_seed(), *other_app.mailbox_seed());
assert_eq!(*a.mailbox_seed(), *b.mailbox_seed());
// An app gets the 32 bytes from Custos; nothing reads them back out.
let from_custos = BackupSecret::from_bytes([1u8; 32]);
assert_eq!(from_custos.open(b"", &from_custos.seal(&nonce, b"", b"x")).as_deref(), Some(b"x".as_slice()));
assert_eq!(format!("{from_custos:?}"), "BackupSecret([redacted])");
}
#[test]
fn the_backup_secret_test_vector() {
// docs/TESSERA.md §12: the zero-entropy mnemonic, app "fiscus". Custos derives the same.
let s = root(0).backup_secret(&Id::new("fiscus").unwrap());
let mailbox = data_encoding::BASE64URL_NOPAD.encode(s.mailbox_seed().as_ref());
let sealed = data_encoding::BASE64URL_NOPAD.encode(&s.seal(&[0u8; 24], b"", b""));
assert_eq!((mailbox.as_str(), sealed.as_str()), (VECTOR_MAILBOX, VECTOR_SEALED_EMPTY));
}
const VECTOR_MAILBOX: &str = "IygCOrh-ibO6-KY5AXQ9Prl2SyPWQIyZZ-anffcbMCU";
const VECTOR_SEALED_EMPTY: &str = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAci_JRbtsx5prR83KT9Y7LA";
#[allow(dead_code)]
fn _signer_bound(_: &impl RevokeSigner) {}
#[allow(dead_code)]
fn _root_signer(_: &impl RootSigner) {}
#[allow(dead_code)]
fn _key(_: PublicKey) {}
+150
View File
@@ -0,0 +1,150 @@
//! No key export: no public API of tessera returns private key bytes.
//!
//! - Compile time: the secret types implement none of the traits that would hand out their bytes.
//! - The API surface is locked: every `pub fn` in `src/` is listed here. A new public function fails this
//! test until someone has checked that it returns no secret and added it to the list.
use static_assertions::assert_not_impl_any;
use tessera::{RootKey, Subkey};
assert_not_impl_any!(RootKey: Clone, AsRef<[u8]>, std::ops::Deref, Into<[u8; 32]>, Into<Vec<u8>>, std::fmt::Display);
assert_not_impl_any!(Subkey: Clone, AsRef<[u8]>, std::ops::Deref, Into<[u8; 32]>, Into<Vec<u8>>, std::fmt::Display);
/// Every public function, as `file: signature` with whitespace collapsed. Each returns only public data.
const SURFACE: &[&str] = &[
"backup.rs: pub fn from_bytes(b: [u8; 32]) -> BackupSecret",
"backup.rs: pub fn mailbox_seed(&self) -> Zeroizing<[u8; 32]>",
"backup.rs: pub fn open(&self, aad: &[u8], sealed: &[u8]) -> Option<Vec<u8>>",
"backup.rs: pub fn seal(&self, nonce: &[u8; 24], aad: &[u8], plain: &[u8]) -> Vec<u8>",
"cert.rs: pub fn app_id(&self) -> &Id",
"cert.rs: pub fn certify(signer: &impl RootSigner, req: &CertRequest) -> Result<SubkeyCert, CertError>",
"cert.rs: pub fn from_bytes(b: &[u8]) -> Result<SubkeyCert, CertError>",
"cert.rs: pub fn from_text(s: &str) -> Result<SubkeyCert, CertError>",
"cert.rs: pub fn match_code(subkey: &PublicKey) -> String",
"cert.rs: pub fn not_after(&self) -> u64",
"cert.rs: pub fn not_before(&self) -> u64",
"cert.rs: pub fn purpose(&self) -> &Id",
"cert.rs: pub fn root(&self) -> PublicKey",
"cert.rs: pub fn standard(subkey: PublicKey, app_id: Id, purpose: Id, now: u64) -> CertRequest",
"cert.rs: pub fn subkey(&self) -> PublicKey",
"cert.rs: pub fn tbs(&self, root: &PublicKey) -> Vec<u8>",
"cert.rs: pub fn to_bytes(&self) -> Vec<u8>",
"cert.rs: pub fn to_text(&self) -> String",
"cert.rs: pub fn verify(&self, root: &PublicKey, now: u64) -> Result<(), CertError>",
"hlc.rs: pub fn from_bytes(b: &[u8; 12]) -> Hlc",
"hlc.rs: pub fn last(&self) -> Hlc",
"hlc.rs: pub fn observe(&mut self, remote: Hlc, now: u64) -> Result<Hlc, ClockError>",
"hlc.rs: pub fn tick(&mut self, now: u64) -> Result<Hlc, ClockError>",
"hlc.rs: pub fn to_bytes(&self) -> [u8; 12]",
"hlc.rs: pub fn with_max_drift(max_drift_ms: u64) -> Clock",
"id.rs: pub fn as_str(&self) -> &str",
"id.rs: pub fn new(s: &str) -> Result<Id, IdError>",
"keys.rs: pub fn as_bytes(&self) -> &[u8; 32]",
"keys.rs: pub fn backup_secret(&self, app_id: &crate::Id) -> crate::BackupSecret",
"keys.rs: pub fn as_bytes(&self) -> &[u8; 64]",
"keys.rs: pub fn from_bytes(b: [u8; 32]) -> PublicKey",
"keys.rs: pub fn from_bytes(b: [u8; 64]) -> Signature",
"keys.rs: pub fn from_mnemonic(phrase: &str) -> Result<RootKey, MnemonicError>",
"keys.rs: pub fn from_seed(seed: &[u8; 32]) -> Subkey",
"keys.rs: pub fn from_text(s: &str) -> Option<PublicKey>",
"keys.rs: pub fn public(&self) -> PublicKey",
"keys.rs: pub fn public(&self) -> PublicKey",
"keys.rs: pub fn sign_credential_tbs(&self, tbs: &[u8]) -> Signature",
"keys.rs: pub fn sign_event_tbs(&self, tbs: &[u8]) -> Signature",
"keys.rs: pub fn verify_credential_sig(subkey: &PublicKey, tbs: &[u8], sig: &Signature) -> bool",
"keys.rs: pub fn verify_event_sig(author: &PublicKey, tbs: &[u8], sig: &Signature) -> bool",
"lib.rs: pub fn hash(bytes: &[u8]) -> [u8; 32]",
"merge.rs: pub fn contains(&self, hash: &[u8; 32]) -> bool",
"merge.rs: pub fn events(&self) -> &[E]",
"merge.rs: pub fn from_stored(events: Vec<E>) -> Log<E>",
"merge.rs: pub fn is_empty(&self) -> bool",
"merge.rs: pub fn len(&self) -> usize",
"merge.rs: pub fn merge<E: LogEvent + Clone, R>( log: &Log<E>, batch: impl IntoIterator<Item = E>, mut verify: impl FnMut(&E) -> Result<(), R>, ) -> Merged<E, R>",
"merge.rs: pub fn new() -> Log<E>",
"merge.rs: pub fn to_bytes(&self) -> Vec<u8>",
"revoke.rs: pub fn accepted(&self) -> &[[u8; 32]]",
"revoke.rs: pub fn add(&mut self, r: Revocation, group_roots: &[PublicKey]) -> Result<(), RevocationError>",
"revoke.rs: pub fn check(&self, author: &PublicKey, hash: &[u8; 32]) -> Result<(), RevocationError>",
"revoke.rs: pub fn from_bytes(b: &[u8]) -> Result<Revocation, RevocationError>",
"revoke.rs: pub fn from_text(s: &str) -> Result<Revocation, RevocationError>",
"revoke.rs: pub fn is_revoked(&self, subkey: &PublicKey) -> bool",
"revoke.rs: pub fn revoke( signer: &impl RevokeSigner, subkey: PublicKey, revoked_at: u64, accepted: Vec<[u8; 32]>, ) -> Result<Vec<Revocation>, RevocationError>",
"revoke.rs: pub fn revoked_at(&self) -> u64",
"revoke.rs: pub fn root(&self) -> PublicKey",
"revoke.rs: pub fn subkey(&self) -> PublicKey",
"revoke.rs: pub fn tbs(&self) -> Vec<u8>",
"revoke.rs: pub fn to_bytes(&self) -> Vec<u8>",
"revoke.rs: pub fn to_text(&self) -> String",
"revoke.rs: pub fn verify(&self, root: &PublicKey) -> Result<(), RevocationError>",
];
/// `pub fn` signatures in `src/`, up to the opening brace, whitespace collapsed.
fn public_fns() -> Vec<String> {
let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
let mut out = Vec::new();
for entry in std::fs::read_dir(&src).unwrap() {
let path = entry.unwrap().path();
let name = path.file_name().unwrap().to_string_lossy().into_owned();
let text = std::fs::read_to_string(&path).unwrap();
let mut rest = text.as_str();
while let Some(at) = rest.find("pub fn ") {
let sig_and_more = &rest[at..];
// The first `{` or `;` outside brackets (`[u8; 32]` has a `;` inside).
let mut depth = 0i32;
let end = sig_and_more
.char_indices()
.find(|&(_, c)| {
match c {
'[' | '(' => depth += 1,
']' | ')' => depth -= 1,
_ => {}
}
depth == 0 && (c == '{' || c == ';')
})
.unwrap()
.0;
let sig: String = sig_and_more[..end].split_whitespace().collect::<Vec<_>>().join(" ");
out.push(format!("{name}: {sig}"));
rest = &sig_and_more[end..];
}
}
out.sort();
out
}
#[test]
fn the_public_surface_is_locked() {
let mut want: Vec<String> = SURFACE.iter().map(|s| s.to_string()).collect();
want.sort();
let got = public_fns();
let new: Vec<_> = got.iter().filter(|s| !want.contains(s)).collect();
let gone: Vec<_> = want.iter().filter(|s| !got.contains(s)).collect();
assert!(new.is_empty() && gone.is_empty(), "review the surface.\nnew: {new:#?}\ngone: {gone:#?}");
}
#[test]
fn only_public_data_comes_back_as_bytes() {
// The few functions that return raw bytes, and why each is public data.
let allowed = [
"pub fn as_bytes(&self) -> &[u8; 32]", // PublicKey
"pub fn as_bytes(&self) -> &[u8; 64]", // Signature
"pub fn hash(bytes: &[u8]) -> [u8; 32]", // SHA-256
"pub fn tbs(&self, root: &PublicKey) -> Vec<u8>", // the unsigned cert
"pub fn to_bytes(&self) -> Vec<u8>", // cert, log
"pub fn to_bytes(&self) -> [u8; 12]", // Hlc
"pub fn tbs(&self) -> Vec<u8>", // the unsigned revocation
"pub fn seal(&self, nonce: &[u8; 24], aad: &[u8], plain: &[u8]) -> Vec<u8>", // ciphertext
];
// The one secret that comes out, and why: the backup mailbox's access-key seed is a relay credential (it
// lets its holder fetch ciphertext, as an invite token's access key does), never an identity key.
let secret_ok = ["pub fn mailbox_seed(&self) -> Zeroizing<[u8; 32]>"];
for f in public_fns() {
let sig = f.split_once(": ").unwrap().1;
let returns_bytes = sig.contains("-> [u8") || sig.contains("-> &[u8") || sig.contains("-> Vec<u8>");
assert!(!returns_bytes || allowed.contains(&sig), "returns bytes: {f}");
assert!(
secret_ok.contains(&sig) || (!sig.contains("SigningKey") && !sig.contains("Zeroizing")),
"exposes a secret type: {f}"
);
}
}