chadtmiller.com/monolith
An atproto PDS
0
0
//! Every case of every vector file in `spec/interop/spaces/`, and STAR's
//! published fixtures in `spec/interop/star/` (`spec/SPACES.md`, "Test vectors").
#![forbid(unsafe_code)]
use pds_repo::data::{cid_of, cid_string, encode, from_json, parse_cid, to_json};
use pds_space::commit::Commit;
use pds_space::key::MAC_INFO;
use pds_space::lthash::{self, LtHash};
use pds_space::mac::{self, MacHeaders, Profile, Received};
use pds_space::signature::{self, Headers};
use pds_space::star::{self, Limits};
use pds_space::{KemKey, PublicKey, SharedSecret};
use serde_json::Value as Json;
use std::collections::BTreeSet;
fn load(path: &str) -> Json {
let p = format!("{}/../../spec/interop/{path}", env!("CARGO_MANIFEST_DIR"));
serde_json::from_str(&std::fs::read_to_string(&p).unwrap_or_else(|e| panic!("{p}: {e}")))
.unwrap()
}
fn cases<'a>(j: &'a Json, k: &str) -> &'a [Json] {
let a = j[k].as_array().unwrap_or_else(|| panic!("no {k}"));
assert!(!a.is_empty(), "no cases in {k}");
a
}
fn s(j: &Json) -> &str {
j.as_str().unwrap_or_else(|| panic!("not a string: {j}"))
}
fn bytes(j: &Json) -> Vec<u8> {
hex::decode(s(j)).unwrap()
}
fn b32(j: &Json) -> [u8; 32] {
bytes(j).try_into().unwrap()
}
fn secret(j: &Json) -> SharedSecret {
SharedSecret(b32(j))
}
fn commit_of(j: &Json) -> Commit {
assert_eq!(j["ver"], 1);
Commit {
repo: s(&j["repo"]).into(),
space: s(&j["space"]).into(),
rev: s(&j["rev"]).into(),
data: b32(&j["data"]),
}
}
/// No vector file goes untested: each one here is one a test below reads.
#[test]
fn every_file_is_tested() {
let dir = format!("{}/../../spec/interop/spaces", env!("CARGO_MANIFEST_DIR"));
let files: BTreeSet<String> = std::fs::read_dir(dir)
.unwrap()
.map(|e| e.unwrap().file_name().into_string().unwrap())
.filter(|n| n.ends_with(".json"))
.collect();
let tested: BTreeSet<String> = [
"http-signature.json",
"kem.json",
"lthash.json",
"mac.json",
"repo-star.json",
]
.map(String::from)
.into();
assert_eq!(files, tested);
}
#[test]
fn kem() {
let v = load("spaces/kem.json");
for c in cases(&v, "valid") {
let at = s(&c["comment"]);
let key = KemKey::from_bytes(&bytes(&c["author_private_key"])).unwrap();
assert_eq!(key.public().did_key(), s(&c["author_kem_key"]), "{at}");
assert_eq!(
KemKey::from_bytes(&key.to_bytes()).unwrap().public(),
key.public(),
"{at}"
);
let share = PublicKey::from_did_key(s(&c["key_share"])).unwrap();
assert_eq!(share.did_key(), s(&c["key_share"]), "{at}");
assert!(share.did_key().starts_with("did:key:zDn"), "{at}");
assert_eq!(key.dh(&share), b32(&c["dh"]), "{at}");
assert_eq!(key.kem_secret(&share), b32(&c["kem_secret"]), "{at}");
let info = bytes(&c["info"]);
let want = secret(&c["shared_secret"]);
assert_eq!(key.decapsulate(&share, &info), want, "{at}");
if info == MAC_INFO {
assert_eq!(key.shared_secret(&share), want, "{at}");
}
// A syncer's fresh key makes with the author's public key the
// secret the author makes with its key share.
let fresh = KemKey::generate();
assert_eq!(
fresh.encapsulate(&key.public()),
key.shared_secret(&fresh.public()),
"{at}"
);
}
for c in cases(&v, "invalid") {
assert!(
PublicKey::from_did_key(s(&c["key_share"])).is_err(),
"{}",
c["comment"]
);
}
}
#[test]
fn lthash() {
let v = load("spaces/lthash.json");
for c in cases(&v, "cases") {
let mut h = LtHash::new();
for e in c["add"].as_array().unwrap() {
h.add(s(e));
}
for e in c["remove"].as_array().unwrap() {
h.remove(s(e));
}
assert_eq!(h.digest(), b32(&c["digest"]), "{}", c["comment"]);
}
let mut a = LtHash::new();
a.add("a");
assert_eq!(a.state().to_vec(), bytes(&v["state_of_a"]));
}
/// The headers of an answer, as a vector holds them, for `profile`.
fn received<'a>(h: &'a Json, profile: Profile) -> Received<'a> {
Received {
covered: h[profile.as_str()].as_str(),
signature_input: h["signature-input"].as_str(),
signature: h["signature"].as_str(),
}
}
/// What a commit or record case shares: the secret its key share makes,
/// its request read, the base, the MAC, the response headers `answer`
/// makes, and `check` of them, which another secret or key share fails.
fn mac_case(
c: &Json,
profile: Profile,
header: &str,
answer: impl Fn(&mac::Request, &SharedSecret) -> MacHeaders,
check: impl Fn(&Received, &str, &SharedSecret) -> Result<(), pds_space::Error>,
) {
let at = s(&c["comment"]);
assert_eq!(header, s(&c["header"]), "{at}");
let key = KemKey::from_bytes(&bytes(&c["author_private_key"])).unwrap();
let share = PublicKey::from_did_key(s(&c["key_share"])).unwrap();
let secret = secret(&c["shared_secret"]);
assert_eq!(key.shared_secret(&share), secret, "{at}");
let request = mac::read_accept_signature(c["accept_signature"].as_str(), profile)
.unwrap_or_else(|e| panic!("{at}: {e}"))
.unwrap_or_else(|| panic!("{at}: no MAC asked for"));
assert_eq!(request.key_share, share, "{at}");
let base = mac::signature_base(profile, header, &request.signature_params);
assert_eq!(base, s(&c["base"]), "{at}");
assert_eq!(mac::mac(&secret, &base), b32(&c["mac"]), "{at}");
let answer = answer(&request, &secret);
let mut got = answer.headers().to_vec();
got.sort();
let mut want: Vec<(&str, &str)> = c["response"]
.as_object()
.unwrap()
.iter()
.map(|(k, v)| (k.as_str(), s(v)))
.collect();
want.sort();
assert_eq!(got, want, "{at}");
let response = received(&c["response"], profile);
let share = s(&c["key_share"]);
assert_eq!(check(&response, share, &secret), Ok(()), "{at}");
let wrong = SharedSecret([1; 32]);
assert!(check(&response, share, &wrong).is_err(), "{at}");
let other_share = KemKey::generate().public().did_key();
assert!(check(&response, &other_share, &secret).is_err(), "{at}");
}
#[test]
fn macs() {
let v = load("spaces/mac.json");
for c in cases(&v, "commit") {
let at = s(&c["comment"]);
let commit = commit_of(&c["commit"]);
mac_case(
c,
Profile::Commit,
&mac::commit_header(&commit),
|r, secret| MacHeaders::commit(r, secret, &commit),
|h, share, secret| mac::check_commit(h, share, secret, &commit),
);
let other = Commit {
rev: "3mzzzzzzzzzzz".into(),
..commit.clone()
};
let response = received(&c["response"], Profile::Commit);
let (share, secret) = (s(&c["key_share"]), secret(&c["shared_secret"]));
assert!(
mac::check_commit(&response, share, &secret, &other).is_err(),
"{at}"
);
}
for c in cases(&v, "record") {
let at = s(&c["comment"]);
let (uri, cid) = (s(&c["uri"]), s(&c["cid"]));
assert!(parse_cid(cid).is_some(), "{at}");
mac_case(
c,
Profile::Record,
&mac::record_header(uri, cid),
|r, secret| MacHeaders::record(r, secret, uri, cid),
|h, share, secret| mac::check_record(h, share, secret, uri, cid),
);
let response = received(&c["response"], Profile::Record);
let (share, secret) = (s(&c["key_share"]), secret(&c["shared_secret"]));
assert!(
mac::check_record(&response, share, &secret, uri, "bafyreianother").is_err(),
"{at}"
);
}
assert_eq!(mac::read_accept_signature(None, Profile::Commit), Ok(None));
for c in cases(&v, "accept_signature") {
let at = s(&c["comment"]);
let profile = match s(&c["profile"]) {
"atproto-space-commit" => Profile::Commit,
"atproto-space-record" => Profile::Record,
other => panic!("{other}"),
};
let got = mac::read_accept_signature(Some(s(&c["header"])), profile);
if c["refused"] == true {
assert!(got.is_err(), "{at}: {got:?}");
continue;
}
let got = got.unwrap_or_else(|e| panic!("{at}: {e}")).map(|r| {
serde_json::json!({
"label": r.label,
"key_share": r.key_share.did_key(),
"signature_params": r.signature_params,
})
});
assert_eq!(got.unwrap_or(Json::Null), c["request"], "{at}");
}
}
#[test]
fn http_signatures() {
let v = load("spaces/http-signature.json");
for c in cases(&v, "cases") {
let at = s(&c["comment"]);
let key = c["key_id"].as_str().unwrap_or_else(|| s(&v["key_id"]));
let h = &c["headers"];
let headers = Headers {
authorization: h["authorization"].as_str(),
audience: h["atproto-space-audience"].as_str(),
signature_input: h["signature-input"].as_str(),
signature: h["signature"].as_str(),
};
let got = signature::verify(&headers, key);
if c["valid"] == true {
assert_eq!(got.as_deref(), Ok(s(&c["signature_base"])), "{at}");
} else {
assert!(got.is_err(), "{at}");
}
}
}
/// Read a repo-star case's archive as its space and repo, asked with its
/// key share, whose secret it gives, and answered with its headers.
fn read_case(c: &Json) -> Result<star::SpaceRepo, pds_space::Error> {
star::read_repo(
&bytes(&c["star"]),
s(&c["space"]),
s(&c["repo"]),
s(&c["key_share"]),
&secret(&c["shared_secret"]),
&received(&c["headers"], Profile::Commit),
)
}
#[test]
fn repo_star() {
let v = load("spaces/repo-star.json");
for c in cases(&v, "valid") {
let at = s(&c["comment"]);
let commit = commit_of(&c["commit"]);
assert_eq!(
(commit.space.as_str(), commit.repo.as_str()),
(s(&c["space"]), s(&c["repo"])),
"{at}"
);
let mut hash = LtHash::new();
let mut records = Vec::new();
for r in c["records"].as_array().unwrap() {
let drisl = bytes(&r["drisl"]);
// The record as JSON is the value its bytes are.
assert_eq!(encode(&from_json(&r["value"]).unwrap()), drisl, "{at}");
let cid = cid_string(&cid_of(0x71, &drisl));
assert_eq!(cid, s(&r["cid"]), "{at}");
hash.add(<hash::element(s(&r["path"]), &cid));
records.push((s(&r["path"]).to_string(), drisl));
}
assert_eq!(hash.digest(), commit.data, "{at}");
assert_eq!(
mac::commit_header(&commit),
s(&c["headers"]["atproto-space-commit"]),
"{at}"
);
let archive = bytes(&c["star"]);
// Written in any order, the records come out in order.
let mut reversed = records.clone();
reversed.reverse();
assert_eq!(star::write_repo(&commit, &reversed), archive, "{at}");
let got = read_case(c).unwrap_or_else(|e| panic!("{at}: {e}"));
assert_eq!(got, star::SpaceRepo { commit, records }, "{at}");
}
for c in cases(&v, "readable") {
let at = s(&c["comment"]);
let got = read_case(c).unwrap_or_else(|e| panic!("{at}: {e}"));
let paths: Vec<(String, String)> = got
.records
.iter()
.map(|(p, b)| (p.clone(), cid_string(&cid_of(0x71, b))))
.collect();
let want: Vec<(String, String)> = c["records"]
.as_array()
.unwrap()
.iter()
.map(|r| (s(&r["path"]).into(), s(&r["cid"]).into()))
.collect();
assert_eq!(paths, want, "{at}");
}
for c in cases(&v, "invalid") {
assert!(read_case(c).is_err(), "{}", c["comment"]);
}
}
#[test]
fn star_fixtures() {
let valid = load("star/valid-star-fixtures.json");
let valid = valid.as_array().unwrap();
assert!(!valid.is_empty());
for c in valid {
let at = s(&c["comment"]);
let archive = bytes(&c["star_hex"]);
let got = star::read(&archive, &Limits::NONE).unwrap_or_else(|e| panic!("{at}: {e}"));
assert_eq!(to_json(&got.meta), c["decoded"]["meta"], "{at}");
let pairs: Vec<(Vec<u8>, Vec<u8>)> = got
.pairs
.iter()
.map(|(k, v)| (k.to_vec(), v.to_vec()))
.collect();
let want: Vec<(Vec<u8>, Vec<u8>)> = c["decoded"]["pairs"]
.as_array()
.unwrap()
.iter()
.map(|p| (bytes(&p["key_hex"]), bytes(&p["value_hex"])))
.collect();
assert_eq!(pairs, want, "{at}");
assert_eq!(
star::write(&got.meta, got.pairs.iter().copied()),
archive,
"{at}"
);
}
let invalid = load("star/invalid-star-fixtures.json");
let invalid = invalid.as_array().unwrap();
assert!(!invalid.is_empty());
for c in invalid {
assert!(
star::read(&bytes(&c["star_hex"]), &Limits::NONE).is_err(),
"{}",
c["comment"]
);
}
}