Fundamentum client v0.5.0
This commit is contained in:
@@ -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"
|
||||
@@ -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])")
|
||||
}
|
||||
}
|
||||
@@ -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}")
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
}
|
||||
@@ -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"));
|
||||
}
|
||||
@@ -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) {}
|
||||
@@ -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}"
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user