chadtmiller.com/monolith
An atproto PDS
0
0
Spaces foundation: KEM keys, the pds-space crate, and a harness against the spaces alpha
.knotless/workflows/gates.yml+3−1
| @@ -9,12 +9,14 @@ runners: [runner.knotless.dev] | ||
on: | ||
push: {refs: [refs/heads/main]} | ||
pull: {base: [refs/heads/main]} | ||
cache: [target, /usr/local/cargo/registry, /usr/local/rustup, /opt/node, harness/node_modules] | ||
cache: [target, /usr/local/cargo/registry, /usr/local/rustup, /opt/node, harness/node_modules, harness/spaces/node_modules] | ||
steps: | ||
- uses: chadtmiller.com/steps/node@1 | ||
with: {version: 24.22.1} | ||
- uses: chadtmiller.com/steps/npm-ci@1 | ||
with: {dir: harness} | ||
- uses: chadtmiller.com/steps/npm-ci@1 | ||
with: {dir: harness/spaces} | ||
# A step at a time, each under the runner's limit on one. | ||
- name: test | ||
run: cargo test | ||
crates/pds-server/src/identity.rs+25−11
| @@ -52,9 +52,13 @@ fn recommended_credentials(s: &Service, call: &Call, _: &mut Shown, _: &Map<Stri | ||
let did = s.auth(call.bearer).did()?; | ||
let Some(a) = s.account(&did) else { return internal() }; | ||
let signing = plc::did_key(read(&a.store).repo.verifying_key()); | ||
let mut methods = json!({ "atproto": signing }); | ||
if let Some(kem) = &a.kem { | ||
methods["atproto_kem"] = json!(kem.public().did_key()); | ||
} | ||
Ok(Resp::Json(json!({ | ||
"alsoKnownAs": [format!("at://{}", a.handle())], | ||
"verificationMethods": { "atproto": signing }, | ||
"verificationMethods": methods, | ||
"rotationKeys": plc::rotation_keys(&s.config), | ||
"services": { "atproto_pds": { "type": "AtprotoPersonalDataServer", "endpoint": s.config.public_url } }, | ||
}))) | ||
| @@ -366,13 +370,7 @@ pub(crate) mod stub { | ||
| ||
async fn doc(State(logs): State<Logs>, Path(did): Path<String>) -> Response { | ||
let Some(op) = last(&logs, &did) else { return StatusCode::NOT_FOUND.into_response() }; | ||
let key = op["verificationMethods"]["atproto"].as_str().unwrap().trim_start_matches("did:key:").to_string(); | ||
found(json!({ | ||
"@context": ["https://www.w3.org/ns/did/v1"], | ||
"id": did, "alsoKnownAs": op["alsoKnownAs"], | ||
"verificationMethod": [{ "id": format!("{did}#atproto"), "type": "Multikey", "controller": did, "publicKeyMultibase": key }], | ||
"service": [{ "id": "#atproto_pds", "type": "AtprotoPersonalDataServer", "serviceEndpoint": op["services"]["atproto_pds"]["endpoint"] }], | ||
})) | ||
found(crate::testing::did_document(&did, &op)) | ||
} | ||
| ||
async fn log_last(State(logs): State<Logs>, Path(did): Path<String>) -> Response { | ||
| @@ -599,6 +597,9 @@ mod tests { | ||
for k in ["type", "rotationKeys", "verificationMethods", "services"] { | ||
assert_eq!(op[k], last[k], "{k}"); | ||
} | ||
// The KEM key with the signing key, unchanged (`spec/SPACES.md`). | ||
assert_eq!(op["verificationMethods"], genesis["verificationMethods"]); | ||
assert!(op["verificationMethods"]["atproto_kem"].as_str().is_some_and(|k| k.starts_with("did:key:zDn"))); | ||
assert_eq!(op["alsoKnownAs"], json!(["at://carol.test", "https://alice.example.com"])); | ||
| ||
// `#identity`, numbered after every event before it. | ||
| @@ -720,16 +721,29 @@ mod tests { | ||
got, | ||
json!({ | ||
"alsoKnownAs": ["at://alice.test"], | ||
"verificationMethods": { "atproto": genesis["verificationMethods"]["atproto"] }, | ||
"verificationMethods": { "atproto": genesis["verificationMethods"]["atproto"], "atproto_kem": genesis["verificationMethods"]["atproto_kem"] }, | ||
"rotationKeys": [s.config.recovery_did_key.clone().unwrap(), rotation], | ||
"services": { "atproto_pds": { "type": "AtprotoPersonalDataServer", "endpoint": "http://127.0.0.1:2583" } }, | ||
}) | ||
); | ||
assert_eq!(call(&s, CREDENTIALS, None, json!({})).await, Err("AuthMissing".into())); | ||
assert_eq!(call(&s, CREDENTIALS, Some("nope"), json!({})).await, Err("InvalidToken".into())); | ||
// The handle now, whatever the directory's document says. | ||
// The handle now, whatever the directory's document says; the same keys. | ||
update(&s, &ta, "carol.test").await.unwrap(); | ||
assert_eq!(call(&s, CREDENTIALS, Some(&ta), json!({})).await.unwrap()["alsoKnownAs"], json!(["at://carol.test"])); | ||
let after = call(&s, CREDENTIALS, Some(&ta), json!({})).await.unwrap(); | ||
assert_eq!(after["alsoKnownAs"], json!(["at://carol.test"])); | ||
assert_eq!(after["verificationMethods"], got["verificationMethods"]); | ||
assert_eq!(plc.log(&alice)[1]["verificationMethods"], genesis["verificationMethods"]); | ||
// Each account its own KEM key, which a restart keeps, posting nothing. | ||
let (bob, tb) = create(&s, "bob").await; | ||
let bobs = call(&s, CREDENTIALS, Some(&tb), json!({})).await.unwrap(); | ||
assert_eq!(bobs["verificationMethods"]["atproto_kem"], plc.log(&bob)[0]["verificationMethods"]["atproto_kem"]); | ||
assert_ne!(bobs["verificationMethods"]["atproto_kem"], got["verificationMethods"]["atproto_kem"]); | ||
drop(s); | ||
let s = open(&dir, &plc.url); | ||
assert_eq!(call(&s, CREDENTIALS, Some(&ta), json!({})).await.unwrap()["verificationMethods"], got["verificationMethods"]); | ||
assert_eq!(call(&s, CREDENTIALS, Some(&tb), json!({})).await.unwrap()["verificationMethods"], bobs["verificationMethods"]); | ||
assert_eq!((plc.log(&alice).len(), plc.log(&bob).len()), (2, 1)); | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
| ||
crates/pds-server/src/lib.rs+27−8
| @@ -86,6 +86,9 @@ pub(crate) struct Account { | ||
pub email: Option<String>, | ||
/// Its password's hash; an account without one cannot log in. | ||
pub password: Option<String>, | ||
/// Its KEM key (`spec/SPACES.md`); None for an account made before | ||
/// accounts had one. | ||
pub kem: Option<pds_space::KemKey>, | ||
/// Its DID document, as the PLC directory last served it. | ||
pub did_doc: RwLock<Json>, | ||
/// Queries read it side by side; a write has it alone. | ||
| @@ -523,14 +526,7 @@ mod testing { | ||
} | ||
async fn get_doc(State(ops): State<Ops>, Path(did): Path<String>) -> Response { | ||
let Some(op) = ops.lock().unwrap().get(&did).cloned() else { return StatusCode::NOT_FOUND.into_response() }; | ||
let key = op["verificationMethods"]["atproto"].as_str().unwrap().trim_start_matches("did:key:").to_string(); | ||
let doc = json!({ | ||
"@context": ["https://www.w3.org/ns/did/v1"], | ||
"id": did, "alsoKnownAs": op["alsoKnownAs"], | ||
"verificationMethod": [{ "id": format!("{did}#atproto"), "type": "Multikey", "controller": did, "publicKeyMultibase": key }], | ||
"service": [{ "id": "#atproto_pds", "type": "AtprotoPersonalDataServer", "serviceEndpoint": op["services"]["atproto_pds"]["endpoint"] }], | ||
}); | ||
([(header::CONTENT_TYPE, "application/json")], doc.to_string()).into_response() | ||
([(header::CONTENT_TYPE, "application/json")], did_document(&did, &op).to_string()).into_response() | ||
} | ||
let app = Router::new().route("/{did}", get(get_doc).post(post)).with_state(Ops::default()); | ||
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap(); | ||
| @@ -539,6 +535,29 @@ mod testing { | ||
url | ||
} | ||
| ||
/// The DID document a directory renders from a DID's last operation: | ||
/// the signing key as a `Multikey`, and a KEM key in the legacy form | ||
/// `spec/SPACES.md` says the harness's directory renders it in. | ||
pub fn did_document(did: &str, op: &Json) -> Json { | ||
let key = op["verificationMethods"]["atproto"].as_str().unwrap().trim_start_matches("did:key:").to_string(); | ||
let mut context = vec![json!("https://www.w3.org/ns/did/v1")]; | ||
let mut methods = vec![json!({ "id": format!("{did}#atproto"), "type": "Multikey", "controller": did, "publicKeyMultibase": key })]; | ||
if let Some(kem) = op["verificationMethods"]["atproto_kem"].as_str() { | ||
let point = pds_space::PublicKey::from_did_key(kem).unwrap().uncompressed(); | ||
context.push(json!("https://w3id.org/security/suites/ecdsa-2019/v1")); | ||
methods.push(json!({ | ||
"id": "#atproto_kem", "type": "EcdsaSecp256r1VerificationKey2019", "controller": did, | ||
"publicKeyMultibase": format!("z{}", bs58::encode(point).into_string()), | ||
})); | ||
} | ||
json!({ | ||
"@context": context, | ||
"id": did, "alsoKnownAs": op["alsoKnownAs"], | ||
"verificationMethod": methods, | ||
"service": [{ "id": "#atproto_pds", "type": "AtprotoPersonalDataServer", "serviceEndpoint": op["services"]["atproto_pds"]["endpoint"] }], | ||
}) | ||
} | ||
| ||
pub fn config(plc_url: &str) -> Config { | ||
Config { | ||
hostname: "localhost".into(), | ||
crates/pds-server/src/log.rs+58−6
| @@ -2,7 +2,7 @@ | ||
//! `spec/DURABILITY.md` says. In `PDS_DATA_DIR`: | ||
//! | ||
//! - `accounts.log`, the service-wide log: each account (DID, handle, email, | ||
//! password hash, signing key, DID document), and each change to the | ||
//! password hash, signing key, KEM key, DID document), and each change to the | ||
//! sessions it gave out and its app passwords (`sessions::ENTRIES`); | ||
//! - `jwt.key`, the secret its tokens are signed with; | ||
//! - `repos/<did>/repo.log`, each account's own log: its commits, each in | ||
| @@ -44,6 +44,9 @@ pub(crate) struct AccountEntry { | ||
pub email: Option<String>, | ||
pub password: Option<String>, | ||
pub key: SigningKey, | ||
/// Its KEM key (`spec/SPACES.md`); None for an account made before | ||
/// accounts had one, which is given none. | ||
pub kem: Option<pds_space::KemKey>, | ||
pub did_doc: Json, | ||
} | ||
| ||
| @@ -51,7 +54,8 @@ impl AccountEntry { | ||
pub fn entry(&self) -> Json { | ||
json!({ | ||
"t": "account", "did": self.did, "handle": self.handle, "email": self.email, | ||
"password": self.password, "key": hex::encode(self.key.to_bytes()), "didDoc": self.did_doc, | ||
"password": self.password, "key": hex::encode(self.key.to_bytes()), | ||
"kemKey": self.kem.as_ref().map(|k| hex::encode(k.to_bytes())), "didDoc": self.did_doc, | ||
}) | ||
} | ||
| ||
| @@ -64,13 +68,17 @@ impl AccountEntry { | ||
_ => Err(format!("an account with a bad {k}: {e}")), | ||
}; | ||
let (password, email) = (optional("password")?, optional("email")?); | ||
let kem = match optional("kemKey")? { | ||
None => None, | ||
Some(k) => Some(hex::decode(k).ok().and_then(|b| pds_space::KemKey::from_bytes(&b).ok()).ok_or_else(|| format!("an account with a bad kemKey: {e}"))?), | ||
}; | ||
if password.is_some() != email.is_some() { | ||
return Err(format!("an account with a password and no email, or an email and no password: {e}")); | ||
} | ||
if !e["didDoc"].is_object() { | ||
return Err(format!("an account with no didDoc: {e}")); | ||
} | ||
Ok(AccountEntry { did: text("did")?, handle: text("handle")?, email, password, key, did_doc: e["didDoc"].clone() }) | ||
Ok(AccountEntry { did: text("did")?, handle: text("handle")?, email, password, key, kem, did_doc: e["didDoc"].clone() }) | ||
} | ||
| ||
/// The account, with its repository. | ||
| @@ -80,6 +88,7 @@ impl AccountEntry { | ||
handle: RwLock::new(self.handle), | ||
email: self.email, | ||
password: self.password, | ||
kem: self.kem, | ||
did_doc: RwLock::new(self.did_doc), | ||
store: RwLock::new(store), | ||
} | ||
| @@ -331,12 +340,19 @@ mod tests { | ||
use std::path::Path; | ||
| ||
/// Everything a restart must carry over, as one comparable value: each | ||
/// account's repository and rev, the sessions, and the events. | ||
type State = (BTreeMap<String, (Vec<u8>, String)>, BTreeMap<String, sessions::Keep>, Vec<Vec<u8>>); | ||
/// account's repository, rev and KEM key, the sessions, and the events. | ||
type State = (BTreeMap<String, (Vec<u8>, String, Option<String>)>, BTreeMap<String, sessions::Keep>, Vec<Vec<u8>>); | ||
| ||
fn state(s: &Service) -> State { | ||
let d = crate::read(&s.directory); | ||
let repos = d.by_did.iter().map(|(did, a)| (did.clone(), { let st = crate::read(&a.store); (st.repo.car(), st.repo.rev.clone()) })).collect(); | ||
let repos = d | ||
.by_did | ||
.iter() | ||
.map(|(did, a)| { | ||
let st = crate::read(&a.store); | ||
(did.clone(), (st.repo.car(), st.repo.rev.clone(), a.kem.as_ref().map(|k| hex::encode(k.to_bytes())))) | ||
}) | ||
.collect(); | ||
drop(d); | ||
let sessions = s.sessions.snapshot(); | ||
let n = s.events.len(); | ||
| @@ -508,10 +524,42 @@ mod tests { | ||
copy["email"] = json!("another@mail.com"); | ||
*twice.last_mut().unwrap() = vec![copy]; | ||
assert!(reopen(&accounts_log, &twice).unwrap().contains("is the handle of both")); | ||
// A KEM key that is not one. | ||
for bad in [json!("zz"), json!("00"), json!(hex::encode([0u8; 32])), json!(1)] { | ||
let mut broken = frames(&accounts_log); | ||
broken[0][0]["kemKey"] = bad.clone(); | ||
assert!(reopen(&accounts_log, &broken).unwrap().contains("bad kemKey"), "{bad}"); | ||
} | ||
let _ = std::fs::remove_dir_all(&dir); | ||
let _ = std::fs::remove_dir_all(&work); | ||
} | ||
| ||
/// An account from before accounts had a KEM key is given none: it | ||
/// starts without one, its credentials name only its signing key, and | ||
/// its entry stays as it was. | ||
#[tokio::test] | ||
async fn an_account_without_a_kem_key() { | ||
let plc = plc().await; | ||
let dir = scratch("no-kem"); | ||
let s = open(&dir, &plc); | ||
let (alice, token) = create(&s, "alice").await; | ||
drop(s); | ||
let path = dir.join(ACCOUNTS_LOG); | ||
let mut frames = store::scan(&std::fs::read(&path).unwrap()).0; | ||
let entry = frames.iter_mut().flatten().find(|e| e["t"] == "account").unwrap(); | ||
assert!(entry["kemKey"].is_string()); | ||
entry.as_object_mut().unwrap().remove("kemKey"); | ||
let bytes: Vec<u8> = frames.iter().flat_map(|f| store::frame(f)).collect(); | ||
std::fs::write(&path, &bytes).unwrap(); | ||
let s = open(&dir, &plc); | ||
assert!(s.account(&alice).unwrap().kem.is_none()); | ||
let got = call(&s, "com.atproto.identity.getRecommendedDidCredentials", Some(&token), json!({})).await.unwrap(); | ||
assert_eq!(got["verificationMethods"].as_object().unwrap().keys().collect::<Vec<_>>(), ["atproto"]); | ||
drop(s); | ||
assert_eq!(std::fs::read(&path).unwrap(), bytes); | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
| ||
/// Cut each log at every byte of the last frame the script wrote to it | ||
/// (and flip a byte in it): recovery must give the state before that | ||
/// write or after it, and keep working. | ||
| @@ -721,6 +769,10 @@ mod tests { | ||
let s = open(&work, &plc); | ||
assert!(repo_of(&s, bob, |r| r.records.is_empty() && !r.rev.is_empty())); | ||
assert_eq!(s.events.len(), 8); | ||
// Its KEM key is the one its whole entry has. | ||
let kem = state(&s).0[bob.as_str()].2.clone(); | ||
assert!(kem.is_some()); | ||
assert_eq!(kem, after.state.0[bob.as_str()].2); | ||
if cut % 61 == 0 { | ||
let again = open(&work, &plc); | ||
assert_eq!(state(&again), state(&s)); | ||
crates/pds-server/src/plc.rs+23−12
| @@ -48,14 +48,14 @@ fn sign(config: &Config, mut fields: Vec<(String, V)>) -> V { | ||
V::Map(fields) | ||
} | ||
| ||
/// The genesis operation of an account with this handle and signing key, | ||
/// signed with the server's rotation key. | ||
pub fn genesis(config: &Config, signing: &VerifyingKey, handle: &str) -> Genesis { | ||
/// The genesis operation of an account with this handle, signing key and | ||
/// KEM key (`spec/SPACES.md`), signed with the server's rotation key. | ||
pub fn genesis(config: &Config, signing: &VerifyingKey, kem: &pds_space::PublicKey, handle: &str) -> Genesis { | ||
let s = |x: &str| V::Str(x.to_string()); | ||
let fields = vec![ | ||
("type".to_string(), s("plc_operation")), | ||
("rotationKeys".to_string(), V::Arr(rotation_keys(config).iter().map(|k| s(k)).collect())), | ||
("verificationMethods".to_string(), V::Map(vec![("atproto".to_string(), s(&did_key(signing)))])), | ||
("verificationMethods".to_string(), V::Map(vec![("atproto".to_string(), s(&did_key(signing))), ("atproto_kem".to_string(), s(&kem.did_key()))])), | ||
("alsoKnownAs".to_string(), V::Arr(vec![s(&format!("at://{handle}"))])), | ||
( | ||
"services".to_string(), | ||
| @@ -293,6 +293,11 @@ mod tests { | ||
use k256::ecdsa::SigningKey; | ||
use serde_json::json; | ||
| ||
/// A fixed KEM key. | ||
fn kem() -> pds_space::PublicKey { | ||
pds_space::KemKey::from_bytes(&[4u8; 32]).unwrap().public() | ||
} | ||
| ||
/// `did:key`s as the interop vectors have them. | ||
#[test] | ||
fn did_keys() { | ||
| @@ -305,12 +310,13 @@ mod tests { | ||
} | ||
} | ||
| ||
/// A genesis operation as `atproto/did-plc.md` says, with fixed keys. | ||
/// A genesis operation as `atproto/did-plc.md` says, with fixed keys, | ||
/// the KEM key beside the signing key (`spec/SPACES.md`). | ||
#[test] | ||
fn genesis_operation() { | ||
let config = config("http://plc.invalid"); | ||
let signing = SigningKey::from_slice(&[3u8; 32]).unwrap(); | ||
let g = genesis(&config, signing.verifying_key(), "alice.test"); | ||
let g = genesis(&config, signing.verifying_key(), &kem(), "alice.test"); | ||
let rotation = did_key(config.rotation_key.verifying_key()); | ||
let sig = g.op["sig"].as_str().unwrap().to_string(); | ||
assert_eq!( | ||
| @@ -318,7 +324,7 @@ mod tests { | ||
json!({ | ||
"type": "plc_operation", | ||
"rotationKeys": [config.recovery_did_key.clone().unwrap(), rotation], | ||
"verificationMethods": { "atproto": did_key(signing.verifying_key()) }, | ||
"verificationMethods": { "atproto": did_key(signing.verifying_key()), "atproto_kem": kem().did_key() }, | ||
"alsoKnownAs": ["at://alice.test"], | ||
"services": { "atproto_pds": { "type": "AtprotoPersonalDataServer", "endpoint": "http://127.0.0.1:2583" } }, | ||
"prev": null, | ||
| @@ -333,9 +339,14 @@ mod tests { | ||
assert_eq!(id.len(), 24); | ||
assert!(id.bytes().all(|c| c.is_ascii_lowercase() || (b'2'..=b'7').contains(&c))); | ||
verify(&g.did, &g.op).unwrap(); | ||
let kem_key = g.op["verificationMethods"]["atproto_kem"].as_str().unwrap(); | ||
assert!(kem_key.starts_with("did:key:zDn")); | ||
assert_eq!(pds_space::PublicKey::from_did_key(kem_key).unwrap(), kem()); | ||
// The same keys and handle make the same DID; signing is deterministic. | ||
assert_eq!(genesis(&config, signing.verifying_key(), "alice.test").did, g.did); | ||
assert_ne!(genesis(&config, signing.verifying_key(), "bob.test").did, g.did); | ||
assert_eq!(genesis(&config, signing.verifying_key(), &kem(), "alice.test").did, g.did); | ||
assert_ne!(genesis(&config, signing.verifying_key(), &kem(), "bob.test").did, g.did); | ||
let other_kem = pds_space::KemKey::from_bytes(&[5u8; 32]).unwrap().public(); | ||
assert_ne!(genesis(&config, signing.verifying_key(), &other_kem, "alice.test").did, g.did); | ||
// Changing any field breaks it. | ||
let mut tampered = g.op.clone(); | ||
tampered["alsoKnownAs"] = json!(["at://mallory.test"]); | ||
| @@ -343,7 +354,7 @@ mod tests { | ||
// Without a recovery key, the server's own is the only rotation key. | ||
let mut alone = config; | ||
alone.recovery_did_key = None; | ||
assert_eq!(genesis(&alone, signing.verifying_key(), "alice.test").op["rotationKeys"], json!([rotation])); | ||
assert_eq!(genesis(&alone, signing.verifying_key(), &kem(), "alice.test").op["rotationKeys"], json!([rotation])); | ||
} | ||
| ||
/// An update operation as `atproto/did-plc.md` says: the last | ||
| @@ -353,7 +364,7 @@ mod tests { | ||
fn update_operation() { | ||
let config = config("http://plc.invalid"); | ||
let signing = SigningKey::from_slice(&[3u8; 32]).unwrap(); | ||
let g = genesis(&config, signing.verifying_key(), "alice.test"); | ||
let g = genesis(&config, signing.verifying_key(), &kem(), "alice.test"); | ||
let op = update(&config, &g.op, "carol.test").unwrap(); | ||
// `prev`: CIDv1, dag-cbor, sha-256 of the last operation's DAG-CBOR, in base32. | ||
let prev = op["prev"].as_str().unwrap(); | ||
| @@ -476,7 +487,7 @@ mod tests { | ||
} | ||
| ||
fn op(handle: &str) -> Genesis { | ||
genesis(&config("http://plc.invalid"), SigningKey::from_slice(&[3u8; 32]).unwrap().verifying_key(), handle) | ||
genesis(&config("http://plc.invalid"), SigningKey::from_slice(&[3u8; 32]).unwrap().verifying_key(), &kem(), handle) | ||
} | ||
| ||
/// A pooled connection the directory closes as the next request arrives | ||
crates/pds-server/src/server.rs+48−3
| @@ -24,6 +24,7 @@ fn describe_server(s: &Service, _: &Call, _: &mut Shown, _: &Map<String, Json>) | ||
"availableUserDomains": s.config.handle_domains, | ||
"inviteCodeRequired": false, | ||
"blobUploadLimit": crate::blobs::UPLOAD_LIMIT, | ||
"spacesAlpha": true, | ||
}))) | ||
} | ||
| ||
| @@ -199,7 +200,8 @@ async fn create_account(s: Shared, b: Map<String, Json>) -> Result<Resp, XrpcErr | ||
None => None, | ||
}; | ||
let key = k256::ecdsa::SigningKey::random(&mut rand::rngs::OsRng); | ||
let genesis = crate::plc::genesis(&s.config, key.verifying_key(), &handle); | ||
let kem = pds_space::KemKey::generate(&mut rand::rngs::OsRng); | ||
let genesis = crate::plc::genesis(&s.config, key.verifying_key(), &kem.public(), &handle); | ||
let did_doc = match crate::plc::register(&s.http, &s.config.plc_url, &genesis).await { | ||
Ok(doc) => doc, | ||
Err(why) => { | ||
| @@ -208,7 +210,7 @@ async fn create_account(s: Shared, b: Map<String, Json>) -> Result<Resp, XrpcErr | ||
} | ||
}; | ||
let did = genesis.did; | ||
let entry = AccountEntry { did: did.clone(), handle: handle.clone(), email: claim.email.clone(), password, key: key.clone(), did_doc }; | ||
let entry = AccountEntry { did: did.clone(), handle: handle.clone(), email: claim.email.clone(), password, key: key.clone(), kem: Some(kem), did_doc }; | ||
let (access, refresh, n) = { | ||
// Logged under the directory's lock, so that `listRepos` lists the | ||
// accounts in the order `accounts.log` has them. | ||
| @@ -299,7 +301,10 @@ mod tests { | ||
let dir = scratch("describe"); | ||
let s = open(&dir, &plc); | ||
let got = call(&s, "com.atproto.server.describeServer", None, json!({})).await.unwrap(); | ||
assert_eq!(got, json!({ "did": "did:web:localhost", "availableUserDomains": [".test", ".example"], "inviteCodeRequired": false, "blobUploadLimit": 5242880 })); | ||
assert_eq!( | ||
got, | ||
json!({ "did": "did:web:localhost", "availableUserDomains": [".test", ".example"], "inviteCodeRequired": false, "blobUploadLimit": 5242880, "spacesAlpha": true }) | ||
); | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
| ||
| @@ -406,6 +411,46 @@ mod tests { | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
| ||
/// The genesis operation `createAccount` posts names the account's own | ||
/// P-256 KEM key beside its signing key, and the DID document it answers | ||
/// is the directory's, with the KEM key in it (`spec/SPACES.md`). | ||
#[tokio::test] | ||
async fn create_account_makes_a_kem_key() { | ||
let plc = crate::identity::stub::Plc::start().await; | ||
let dir = scratch("create-kem"); | ||
let s = open(&dir, &plc.url); | ||
let got = call(&s, CREATE, None, account("alice.test", "alice@mail.com")).await.unwrap(); | ||
let did = got["did"].as_str().unwrap().to_string(); | ||
let (bob, _) = create(&s, "bob").await; | ||
let ops = plc.log(&did); | ||
assert_eq!(ops.len(), 1); | ||
crate::plc::verify(&did, &ops[0]).unwrap(); | ||
let methods = &ops[0]["verificationMethods"]; | ||
let mut names: Vec<&String> = methods.as_object().unwrap().keys().collect(); | ||
names.sort(); | ||
assert_eq!(names, ["atproto", "atproto_kem"]); | ||
let account = s.account(&did).unwrap(); | ||
let kem = account.kem.as_ref().unwrap().public(); | ||
assert_eq!(methods["atproto_kem"], json!(kem.did_key())); | ||
assert!(kem.did_key().starts_with("did:key:zDn")); | ||
assert_eq!(methods["atproto"], json!(repo_of(&s, &did, |r| crate::plc::did_key(r.verifying_key())))); | ||
assert_ne!(methods["atproto_kem"], methods["atproto"]); | ||
assert_ne!(methods["atproto_kem"], plc.log(&bob)[0]["verificationMethods"]["atproto_kem"]); | ||
// The document the directory serves, the KEM key in it as it renders one. | ||
let doc: Json = serde_json::from_str(&reqwest::get(format!("{}/{did}", plc.url)).await.unwrap().text().await.unwrap()).unwrap(); | ||
assert_eq!(got["didDoc"], doc); | ||
let point = format!("z{}", bs58::encode(kem.uncompressed()).into_string()); | ||
let rendered = doc["verificationMethod"].as_array().unwrap().iter().find(|m| m["id"] == "#atproto_kem").unwrap(); | ||
assert_eq!(rendered["publicKeyMultibase"], json!(point)); | ||
// A restart keeps it, and posts nothing. | ||
drop(account); | ||
drop(s); | ||
let s = open(&dir, &plc.url); | ||
assert_eq!(s.account(&did).unwrap().kem.as_ref().unwrap().public(), kem); | ||
assert_eq!(plc.log(&did).len(), 1); | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
| ||
/// A directory that refuses the operation leaves no account. | ||
#[tokio::test] | ||
async fn refused_by_the_directory() { | ||
crates/pds-server/Cargo.toml+1−0
| @@ -7,6 +7,7 @@ publish.workspace = true | ||
[dependencies] | ||
pds-lexicon.workspace = true | ||
pds-repo.workspace = true | ||
pds-space.workspace = true | ||
pds-store.workspace = true | ||
axum.workspace = true | ||
base64.workspace = true | ||
crates/pds-space/src/commit.rsnew+124−0
| @@ -0,0 +1,124 @@ | ||
//! A space repo's commit (`com.atproto.space.defs#commit`), and the MACs a | ||
//! repo host authenticates a commit or a record with, with their headers | ||
//! (`spec/SPACES.md`, "The set hash, records and commits" and "MACs"). | ||
| ||
use crate::key::{SharedSecret, hmac}; | ||
use crate::sf::{self, Bare, Member}; | ||
use base64::Engine; | ||
use base64::engine::general_purpose::STANDARD; | ||
use pds_repo::data::V; | ||
| ||
/// The commit's `ver`. | ||
pub const VERSION: i64 = 1; | ||
| ||
/// The request header a syncer asks for a MAC with. | ||
pub const WANT_MAC_HEADER: &str = "atproto-space-want-mac"; | ||
| ||
/// The response header the MAC goes back in. | ||
pub const MAC_HEADER: &str = "atproto-space-mac"; | ||
| ||
/// A space repo's commit, `ver` 1. It has no signature. | ||
#[derive(Clone, Debug, PartialEq, Eq)] | ||
pub struct Commit { | ||
/// The author's DID. | ||
pub repo: String, | ||
/// The space's URI. | ||
pub space: String, | ||
/// A TID. | ||
pub rev: String, | ||
/// The LtHash digest of the elements of every record the repo holds. | ||
pub data: [u8; 32], | ||
} | ||
| ||
impl Commit { | ||
/// `{ver: 1, repo, space, rev, data}`, `data` as bytes. | ||
pub fn to_value(&self) -> V { | ||
V::Map(vec![ | ||
("ver".into(), V::Int(VERSION)), | ||
("repo".into(), V::Str(self.repo.clone())), | ||
("space".into(), V::Str(self.space.clone())), | ||
("rev".into(), V::Str(self.rev.clone())), | ||
("data".into(), V::Bytes(self.data.to_vec())), | ||
]) | ||
} | ||
| ||
/// The commit MAC's message: `"atproto-space-repo-v1" ‖ lp(space) ‖ | ||
/// lp(repo) ‖ lp(rev) ‖ data`. | ||
pub fn mac_input(&self) -> Vec<u8> { | ||
let mut out = b"atproto-space-repo-v1".to_vec(); | ||
for s in [&self.space, &self.repo, &self.rev] { | ||
lp(&mut out, s); | ||
} | ||
out.extend_from_slice(&self.data); | ||
out | ||
} | ||
| ||
/// The commit MAC under `secret`. | ||
pub fn mac(&self, secret: &SharedSecret) -> [u8; 32] { | ||
hmac(&secret.0, &[&self.mac_input()]) | ||
} | ||
} | ||
| ||
/// A string prefixed with its length in UTF-8 bytes, two bytes big-endian. | ||
/// Every string a MAC covers is far shorter than 65536 bytes: a space's | ||
/// URI, a DID, a TID, a record's URI. | ||
fn lp(out: &mut Vec<u8>, s: &str) { | ||
let n = u16::try_from(s.len()).expect("a string a MAC covers is under 65536 bytes"); | ||
out.extend_from_slice(&n.to_be_bytes()); | ||
out.extend_from_slice(s.as_bytes()); | ||
} | ||
| ||
/// The record MAC's message: `"atproto-space-record-v1" ‖ lp(uri) ‖ cid`, | ||
/// `uri` the record's full space URI and `cid` its CID in binary. | ||
pub fn record_mac_input(uri: &str, cid: &[u8]) -> Vec<u8> { | ||
let mut out = b"atproto-space-record-v1".to_vec(); | ||
lp(&mut out, uri); | ||
out.extend_from_slice(cid); | ||
out | ||
} | ||
| ||
/// The record MAC under `secret`. | ||
pub fn record_mac(secret: &SharedSecret, uri: &str, cid: &[u8]) -> [u8; 32] { | ||
hmac(&secret.0, &[&record_mac_input(uri, cid)]) | ||
} | ||
| ||
/// What a MAC is of: a method answering a commit, or one answering a record. | ||
#[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
pub enum MacType { | ||
Repo, | ||
Record, | ||
} | ||
| ||
impl MacType { | ||
pub fn as_str(self) -> &'static str { | ||
match self { | ||
MacType::Repo => "atproto-space-repo", | ||
MacType::Record => "atproto-space-record", | ||
} | ||
} | ||
} | ||
| ||
/// The `Atproto-Space-Mac` response header carrying `mac`. | ||
pub fn mac_header(t: MacType, mac: &[u8; 32]) -> String { | ||
format!("type=\"{}\", ver=1, mac=:{}:", t.as_str(), STANDARD.encode(mac)) | ||
} | ||
| ||
/// The key share an `Atproto-Space-Want-Mac` header asks a method answering | ||
/// `t` for a MAC under, as given: None if the header is not a Dictionary, | ||
/// its `type` is not the String `t`, its `ver` not the Integer 1, or it has | ||
/// no String `key_share`. Other members and every parameter are ignored. | ||
/// Whether the key share is a P-256 key is `PublicKey::from_did_key`'s to say. | ||
pub fn want_mac(header: &str, t: MacType) -> Option<String> { | ||
let d = sf::parse_dictionary(header)?; | ||
let item = |k: &str| match sf::member(&d, k)? { | ||
Member::Item((bare, _)) => Some(bare), | ||
Member::InnerList(..) => None, | ||
}; | ||
if item("type")? != &Bare::String(t.as_str().into()) || item("ver")? != &Bare::Integer(1) { | ||
return None; | ||
} | ||
match item("key_share")? { | ||
Bare::String(k) => Some(k.clone()), | ||
_ => None, | ||
} | ||
} | ||
crates/pds-space/src/key.rsnew+125−0
| @@ -0,0 +1,125 @@ | ||
//! P-256 keys (`spec/SPACES.md`, "P-256 did:keys"): a public key as a | ||
//! `did:key`, an account's KEM key, and the shared secret a syncer's key | ||
//! share and the KEM key make ("The shared secret"): DHKEM(P-256, | ||
//! HKDF-SHA256) of RFC 9180 §4.1, the key share its `enc`. | ||
| ||
use crate::Error; | ||
use hmac::{Hmac, Mac}; | ||
use p256::elliptic_curve::rand_core::CryptoRngCore; | ||
use p256::elliptic_curve::sec1::ToEncodedPoint; | ||
use sha2::Sha256; | ||
| ||
/// The multicodec `p256-pub`, as a varint. | ||
const P256_PUB: [u8; 2] = [0x80, 0x24]; | ||
| ||
/// A point on P-256. | ||
#[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
pub struct PublicKey(p256::PublicKey); | ||
| ||
impl PublicKey { | ||
/// The key a P-256 `did:key` names: `did:key:z`, then base58btc of | ||
/// `0x80 0x24` and the 33-byte compressed point. Anything else is no | ||
/// P-256 key: another curve, an uncompressed point, an `x` with no point. | ||
pub fn from_did_key(s: &str) -> Result<PublicKey, Error> { | ||
let b58 = s.strip_prefix("did:key:z").ok_or_else(|| Error::new("not a did:key"))?; | ||
let bytes = bs58::decode(b58).into_vec().map_err(|_| Error::new("a did:key that does not parse"))?; | ||
let point = bytes.strip_prefix(&P256_PUB[..]).ok_or_else(|| Error::new("a did:key that is not P-256"))?; | ||
if point.len() != 33 || !matches!(point[0], 2 | 3) { | ||
return Err(Error::new("a P-256 did:key that is not 33 bytes of compressed point")); | ||
} | ||
p256::PublicKey::from_sec1_bytes(point).map(PublicKey).map_err(|_| Error::new("a P-256 did:key with no point on the curve")) | ||
} | ||
| ||
/// The key as a `did:key`; every one starts `did:key:zDn`. | ||
pub fn did_key(&self) -> String { | ||
let mut bytes = P256_PUB.to_vec(); | ||
bytes.extend_from_slice(self.0.to_encoded_point(true).as_bytes()); | ||
format!("did:key:z{}", bs58::encode(bytes).into_string()) | ||
} | ||
| ||
/// The uncompressed point: `0x04`, `x`, `y`, each 32 bytes big-endian. | ||
pub fn uncompressed(&self) -> [u8; 65] { | ||
self.0.to_encoded_point(false).as_bytes().try_into().expect("an uncompressed P-256 point is 65 bytes") | ||
} | ||
| ||
pub(crate) fn verifying_key(&self) -> p256::ecdsa::VerifyingKey { | ||
p256::ecdsa::VerifyingKey::from(self.0) | ||
} | ||
} | ||
| ||
/// An account's KEM key: a P-256 private key, which signs nothing. | ||
#[derive(Clone)] | ||
pub struct KemKey(p256::SecretKey); | ||
| ||
impl std::fmt::Debug for KemKey { | ||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
write!(f, "KemKey({})", self.public().did_key()) | ||
} | ||
} | ||
| ||
impl KemKey { | ||
/// A new key, from `rng`. | ||
pub fn generate(rng: &mut impl CryptoRngCore) -> KemKey { | ||
KemKey(p256::SecretKey::random(rng)) | ||
} | ||
| ||
/// The key whose scalar is these 32 bytes, big-endian. | ||
pub fn from_bytes(bytes: &[u8]) -> Result<KemKey, Error> { | ||
if bytes.len() != 32 { | ||
return Err(Error::new("a P-256 private key is 32 bytes")); | ||
} | ||
p256::SecretKey::from_slice(bytes).map(KemKey).map_err(|_| Error::new("not a P-256 private key")) | ||
} | ||
| ||
/// The scalar, 32 bytes big-endian, as `from_bytes` takes it. | ||
pub fn to_bytes(&self) -> [u8; 32] { | ||
self.0.to_bytes().into() | ||
} | ||
| ||
pub fn public(&self) -> PublicKey { | ||
PublicKey(self.0.public_key()) | ||
} | ||
| ||
/// ECDH with a key share: the 32-byte big-endian `x` of `d·P`. | ||
pub fn dh(&self, key_share: &PublicKey) -> [u8; 32] { | ||
let shared = p256::ecdh::diffie_hellman(self.0.to_nonzero_scalar(), key_share.0.as_affine()); | ||
(*shared.raw_secret_bytes()).into() | ||
} | ||
| ||
/// The shared secret of a syncer's key share and this key. | ||
pub fn shared_secret(&self, key_share: &PublicKey) -> SharedSecret { | ||
const PREFIX: &[u8] = b"HPKE-v1KEM\x00\x10"; | ||
let dh = self.dh(key_share); | ||
let ikm = [PREFIX, b"eae_prk", &dh].concat(); | ||
let info = [b"\x00\x20", PREFIX, b"shared_secret", &key_share.uncompressed(), &self.public().uncompressed()].concat(); | ||
let prk = hmac(b"", &[&ikm]); | ||
SharedSecret(hmac(&prk, &[&info, &[1]])) | ||
} | ||
} | ||
| ||
/// HMAC-SHA256 of the parts, in order, keyed with `key`. | ||
pub(crate) fn hmac(key: &[u8], parts: &[&[u8]]) -> [u8; 32] { | ||
let mut m = Hmac::<Sha256>::new_from_slice(key).expect("HMAC takes a key of any length"); | ||
for p in parts { | ||
m.update(p); | ||
} | ||
m.finalize().into_bytes().into() | ||
} | ||
| ||
/// Whether `mac` is the HMAC-SHA256 of `message` keyed with `key`, compared | ||
/// in constant time. | ||
pub(crate) fn verify_hmac(key: &[u8], message: &[u8], mac: &[u8]) -> bool { | ||
let mut m = Hmac::<Sha256>::new_from_slice(key).expect("HMAC takes a key of any length"); | ||
m.update(message); | ||
m.verify_slice(mac).is_ok() | ||
} | ||
| ||
/// The secret a syncer and a repo host agree, the key of their MACs. | ||
#[derive(Clone, PartialEq, Eq)] | ||
pub struct SharedSecret(pub [u8; 32]); | ||
| ||
impl std::fmt::Debug for SharedSecret { | ||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
f.write_str("SharedSecret(..)") | ||
} | ||
} | ||
crates/pds-space/src/lib.rsnew+37−0
| @@ -0,0 +1,37 @@ | ||
//! The building blocks of atproto spaces, as `spec/SPACES.md` specifies | ||
//! them: P-256 `did:key`s and the KEM shared secret (`key`), LtHash | ||
//! (`lthash`), the space repo's commit and its MACs (`commit`), a space | ||
//! credential's HTTP Message Signature (`signature`), and STAR archives with | ||
//! the `atproto-space-repo` profile (`star`). Pure: it does no I/O. | ||
//! | ||
//! `sf` reads and writes the RFC 9651 structured fields the headers are. | ||
| ||
pub mod commit; | ||
pub mod key; | ||
pub mod lthash; | ||
pub mod sf; | ||
pub mod signature; | ||
pub mod star; | ||
| ||
pub use commit::{Commit, MacType}; | ||
pub use key::{KemKey, PublicKey, SharedSecret}; | ||
pub use lthash::LtHash; | ||
| ||
/// Why an input was refused: a key that is no P-256 key, a signature that | ||
/// does not verify, an archive with a fault. The text says which. | ||
#[derive(Clone, Debug, PartialEq, Eq)] | ||
pub struct Error(String); | ||
| ||
impl Error { | ||
pub(crate) fn new(why: impl Into<String>) -> Error { | ||
Error(why.into()) | ||
} | ||
} | ||
| ||
impl std::fmt::Display for Error { | ||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
f.write_str(&self.0) | ||
} | ||
} | ||
| ||
impl std::error::Error for Error {} | ||
crates/pds-space/src/lthash.rsnew+71−0
crates/pds-space/src/sf.rsnew+382−0
crates/pds-space/src/signature.rsnew+79−0
crates/pds-space/src/star.rsnew+213−0
crates/pds-space/tests/vectors.rsnew+204−0
crates/pds-space/Cargo.tomlnew+18−0
harness/checks/accounts.mjs+9−2
harness/checks/identity.mjs+6−2
harness/checks/session.mjs+8−3
harness/lib/kem.mjsnew+30−0
harness/lib/xrpc.mjs+11−1
harness/spaces/lib/spec.mjsnew+353−0
harness/spaces/compare.mjsnew+302−0
harness/spaces/package-lock.jsonnew+8785−0
A large diff, not shown.
harness/spaces/package.jsonnew+66−0
harness/spaces/pin-alpha.shnew+38−0
harness/spaces/vectors.mjsnew+448−0
448 lines changed: not loaded until asked for.
harness/gates.mjs+5−1
spec/interop/spaces/http-signature.jsonnew+256−0
spec/interop/spaces/kem.jsonnew+64−0
spec/interop/spaces/lthash.jsonnew+100−0
spec/interop/spaces/mac.jsonnew+173−0
spec/interop/spaces/README.mdnew+23−0
spec/interop/spaces/repo-star.jsonnew+270−0
spec/interop/star/invalid-star-fixtures.jsonnew+150−0
spec/interop/star/LICENSE.Apache-2.0new+190−0
spec/interop/star/LICENSE.MITnew+21−0
spec/interop/star/README.mdnew+58−0
spec/interop/star/valid-star-fixtures.jsonnew+206−0
spec/spaces/lexicons/com/atproto/space/defs.jsonnew+36−0
spec/spaces/LICENSE-DASL.mdnew+49−0
spec/spaces/proposal.mdnew+1017−0
1017 lines changed: not loaded until asked for.
spec/spaces/README.mdnew+23−0
spec/spaces/rfc9180.txtnew+4810−0
A large diff, not shown.
spec/spaces/rfc9421.txtnew+5157−0
A large diff, not shown.