Fundamentum client v0.5.0
This commit is contained in:
@@ -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