chadtmiller.com/monolith
An atproto PDS
0
0
Any number of accounts, each with a did:plc and its own storage
crates/pds/src/main.rs+3−2
| @@ -1,8 +1,9 @@ | ||
//! `pds`: `pds serve` runs the server; anything else is the CLI, calling a running one. | ||
| ||
const SERVE_HELP: &str = "Usage: pds serve\n\n\ | ||
Run the server, configured by its environment: PDS_PORT, PDS_DID, PDS_HANDLE,\n\ | ||
PDS_PASSWORD, PDS_SIGNING_KEY_HEX and PDS_DATA_DIR.\n"; | ||
Run the server, configured by its environment: PDS_PORT, PDS_DATA_DIR, PDS_HOSTNAME,\n\ | ||
PDS_PUBLIC_URL, PDS_HANDLE_DOMAINS, PDS_PLC_URL, PDS_PLC_ROTATION_KEY_HEX and,\n\ | ||
if set, PDS_RECOVERY_DID_KEY.\n"; | ||
| ||
fn main() { | ||
let args: Vec<String> = std::env::args().skip(1).collect(); | ||
crates/pds-cli/src/lib.rs+22−22
| @@ -119,7 +119,8 @@ fn command_help(m: &Method) -> String { | ||
} | ||
about.push_str(a.description.as_deref().unwrap_or("")); | ||
if a.names_account() { | ||
about.push_str(if about.is_empty() { "Left out, the account's DID." } else { " Left out, the account's DID." }); | ||
let left_out = "Left out with PDS_TOKEN set, the token's account's DID."; | ||
about.push_str(&if about.is_empty() { left_out.to_string() } else { format!(" {left_out}") }); | ||
} | ||
out.push_str(&format!(" {flag:<32} {}\n", about.trim_end())); | ||
} | ||
| @@ -250,19 +251,11 @@ impl Server { | ||
req.send().map_err(|e| Stop::Unreachable(format!("cannot reach {}: {e}", self.url))) | ||
} | ||
| ||
/// The account's DID: the token's, else the one the server describes itself with. | ||
fn account(&self) -> Result<Result<String, (u16, Json)>, Stop> { | ||
if self.token.is_some() { | ||
let (status, body) = answer(self.send("com.atproto.server.getSession", Kind::Query, &Map::new())?, &self.url)?; | ||
if let (200, Some(did)) = (status, body["did"].as_str()) { | ||
return Ok(Ok(did.to_string())); | ||
} | ||
} | ||
let (status, body) = answer(self.send("com.atproto.server.describeServer", Kind::Query, &Map::new())?, &self.url)?; | ||
match (status, body["did"].as_str()) { | ||
(200, Some(did)) => Ok(Ok(did.to_string())), | ||
_ => Ok(Err((status, body))), | ||
} | ||
/// The token's account's DID, as `getSession` answers it; None for a | ||
/// token it does not answer for. | ||
fn account(&self) -> Result<Option<String>, Stop> { | ||
let (status, body) = answer(self.send("com.atproto.server.getSession", Kind::Query, &Map::new())?, &self.url)?; | ||
Ok(body["did"].as_str().filter(|_| status == 200).map(str::to_string)) | ||
} | ||
} | ||
| ||
| @@ -292,16 +285,23 @@ fn print_error(status: u16, body: &Json) -> u8 { | ||
} | ||
| ||
fn call(m: &Method, mut args: Map<String, Json>) -> Result<u8, Stop> { | ||
let token = std::env::var("PDS_TOKEN").ok().filter(|t| !t.is_empty()); | ||
// A `repo` or `did` left out is the token's account's; with no token, it | ||
// is as required as the lexicon says. | ||
let left_out: Vec<&Arg> = m.args.iter().filter(|a| a.names_account() && !args.contains_key(&a.name)).collect(); | ||
if token.is_none() && !left_out.is_empty() { | ||
let missing: Vec<String> = left_out.iter().map(|a| format!("--{}", a.flag())).collect(); | ||
return usage(format!("pds {} {} needs {}, or PDS_TOKEN for its account's", m.group, m.command().unwrap_or_default(), missing.join(", "))); | ||
} | ||
let Ok(url) = std::env::var("PDS_URL") else { return Err(Stop::Unreachable("PDS_URL is not set: it is the server's URL".into())) }; | ||
let http = reqwest::blocking::Client::builder().no_proxy().build().map_err(|e| Stop::Unreachable(e.to_string()))?; | ||
let server = Server { url: url.trim_end_matches('/').to_string(), token: std::env::var("PDS_TOKEN").ok().filter(|t| !t.is_empty()), http }; | ||
if m.args.iter().any(|a| a.names_account() && !args.contains_key(&a.name)) { | ||
let did = match server.account()? { | ||
Ok(did) => did, | ||
Err((status, body)) => return Ok(print_error(status, &body)), | ||
}; | ||
for a in m.args.iter().filter(|a| a.names_account()) { | ||
args.entry(a.name.clone()).or_insert_with(|| json!(did)); | ||
let server = Server { url: url.trim_end_matches('/').to_string(), token, http }; | ||
// A token getSession does not answer for leaves them out, for the method to answer it. | ||
if server.token.is_some() && !left_out.is_empty() { | ||
if let Some(did) = server.account()? { | ||
for a in left_out { | ||
args.insert(a.name.clone(), json!(did)); | ||
} | ||
} | ||
} | ||
let res = server.send(&m.nsid, m.kind, &args)?; | ||
crates/pds-lexicon/src/lib.rs+13−3
| @@ -61,9 +61,12 @@ pub struct Arg { | ||
} | ||
| ||
impl Arg { | ||
/// Whether it names the account, and so may be left out for the account's DID. | ||
/// Whether it names the account the method is about, and so may be left | ||
/// out, with a token, for the token's account's DID: a `repo` or `did` the | ||
/// lexicon requires. `createAccount`'s optional `did`, an account to | ||
/// import, names none here. | ||
pub fn names_account(&self) -> bool { | ||
self.name == "repo" || self.name == "did" | ||
self.required && (self.name == "repo" || self.name == "did") | ||
} | ||
| ||
/// Whether the method's MCP tool and CLI command require it. | ||
| @@ -497,7 +500,7 @@ mod tests { | ||
let sub = method("com.atproto.sync.subscribeRepos").unwrap(); | ||
assert_eq!((sub.tool(), sub.command()), (None, None)); | ||
let tools: Vec<String> = methods().iter().filter_map(Method::tool).collect(); | ||
assert_eq!(tools.len(), 11, "{tools:?}"); | ||
assert_eq!(tools.len(), 12, "{tools:?}"); | ||
assert_eq!(groups(), ["repo", "server", "sync"]); | ||
assert!(method("com.atproto.repo.defs").is_none()); | ||
} | ||
| @@ -521,6 +524,13 @@ mod tests { | ||
let p = method("com.atproto.repo.putRecord").unwrap().input_schema(); | ||
assert_eq!(p["properties"]["swapRecord"]["type"], json!(["string", "null"])); | ||
assert_eq!(p["properties"]["swapCommit"]["type"], "string"); | ||
// A required `repo` or `did` names the account, which a token may give; | ||
// `createAccount`'s optional `did` does not. | ||
assert_eq!(p["required"], json!(["collection", "record", "rkey"])); | ||
assert_eq!(method("com.atproto.sync.getRepo").unwrap().input_schema()["required"], json!([])); | ||
let create = method("com.atproto.server.createAccount").unwrap(); | ||
assert!(!create.arg("did").unwrap().names_account()); | ||
assert_eq!(create.input_schema()["required"], json!(["handle"])); | ||
let hints = |nsid: &str| method(nsid).unwrap().annotations(); | ||
for nsid in ["com.atproto.repo.deleteRecord", "com.atproto.repo.putRecord", "com.atproto.repo.applyWrites"] { | ||
assert_eq!(hints(nsid), Some(json!({ "readOnlyHint": false, "destructiveHint": true })), "{nsid}"); | ||
crates/pds-repo/src/data.rs+7−0
| @@ -190,6 +190,13 @@ pub fn decode(data: &[u8]) -> Result<V, String> { | ||
if pos == data.len() { Ok(v) } else { Err("bytes after the value".into()) } | ||
} | ||
| ||
/// Decode the DAG-CBOR value at the start of `data`; answers it and how many bytes it took. | ||
pub fn decode_prefix(data: &[u8]) -> Result<(V, usize), String> { | ||
let mut pos = 0; | ||
let v = dec(data, &mut pos, 0)?; | ||
Ok((v, pos)) | ||
} | ||
| ||
fn take<'a>(data: &'a [u8], pos: &mut usize, n: usize) -> Result<&'a [u8], String> { | ||
let s = data.get(*pos..pos.saturating_add(n)).ok_or("the value is cut short")?; | ||
*pos += n; | ||
crates/pds-server/src/events.rs+115−12
| @@ -1,4 +1,6 @@ | ||
//! The firehose: `com.atproto.sync.subscribeRepos` events and the WebSocket that serves them, as `spec/SYNC.md` says. | ||
//! The firehose: `com.atproto.sync.subscribeRepos` events, the one sequence | ||
//! they are numbered in across all accounts, and the WebSocket that serves | ||
//! them, as `spec/SYNC.md` says. | ||
| ||
use crate::Shared; | ||
use axum::body::Bytes; | ||
| @@ -9,8 +11,110 @@ use axum::http::StatusCode; | ||
use axum::response::{IntoResponse, Response}; | ||
use pds_repo::data::*; | ||
use pds_repo::{Change, car_file}; | ||
use std::sync::{Mutex, PoisonError}; | ||
use std::time::{SystemTime, UNIX_EPOCH}; | ||
| ||
/// The firehose's events, numbered across all accounts. A write takes its | ||
/// events' numbers under its account's lock, so each account's events are in | ||
/// the order of its commits; writes to different accounts take them side by | ||
/// side and reach the disk in any order. Subscribers are sent an event only | ||
/// once it and every event before it are on disk. | ||
/// | ||
/// Each event also has an `ord`, which orders the events in the logs, apart | ||
/// from every account's: its seq plus an offset fixed when the server starts. | ||
/// A restart numbers the events it recovers 1, 2, ... in `ord` order; the | ||
/// events past one that never reached the disk were never sent, so they may | ||
/// take numbers other than those they were written with, and the offset | ||
/// keeps every later `ord` above those already written. | ||
pub(crate) struct Firehose { | ||
seq: Mutex<Seq>, | ||
/// How many events subscribers may be sent. | ||
published: tokio::sync::watch::Sender<usize>, | ||
} | ||
| ||
struct Seq { | ||
/// Event `n` has seq `n + 1`; `None` until it is on disk. | ||
events: Vec<Option<Bytes>>, | ||
offset: u64, | ||
/// How many events from the first are on disk. | ||
published: usize, | ||
} | ||
| ||
/// Events on their way to the disk, from seq `seq` on, to `land` once they are there. | ||
pub(crate) struct Landing { | ||
pub seq: u64, | ||
pub frames: Vec<Bytes>, | ||
} | ||
| ||
impl Firehose { | ||
/// The events recovered, all on disk, and the offset of new events' `ord` from their seq. | ||
pub fn new(events: Vec<Bytes>, offset: u64) -> Firehose { | ||
let n = events.len(); | ||
let seq = Seq { events: events.into_iter().map(Some).collect(), offset, published: n }; | ||
Firehose { seq: Mutex::new(seq), published: tokio::sync::watch::channel(n).0 } | ||
} | ||
| ||
fn lock(&self) -> std::sync::MutexGuard<'_, Seq> { | ||
self.seq.lock().unwrap_or_else(PoisonError::into_inner) | ||
} | ||
| ||
/// Number `n` new events: answers the first one's seq and `ord`. | ||
pub fn reserve(&self, n: usize) -> (u64, u64) { | ||
let mut s = self.lock(); | ||
let seq = s.events.len() as u64 + 1; | ||
let len = s.events.len() + n; | ||
s.events.resize(len, None); | ||
(seq, seq + s.offset) | ||
} | ||
| ||
/// Events are on disk: send them, and any after them already there, to subscribers. | ||
pub fn land(&self, l: Landing) { | ||
let published = { | ||
let mut s = self.lock(); | ||
for (i, f) in l.frames.into_iter().enumerate() { | ||
s.events[(l.seq - 1) as usize + i] = Some(f); | ||
} | ||
while s.published < s.events.len() && s.events[s.published].is_some() { | ||
s.published += 1; | ||
} | ||
s.published | ||
}; | ||
self.published.send_if_modified(|n| { | ||
let more = *n < published; | ||
*n = (*n).max(published); | ||
more | ||
}); | ||
} | ||
| ||
/// The events from seq `from + 1` to `to`, all of which are on disk. | ||
pub fn get(&self, from: usize, to: usize) -> Vec<Bytes> { | ||
// Shared with the firehose's copy: a send copies no frame. | ||
self.lock().events.get(from..to).map_or_else(Vec::new, |e| e.iter().flatten().cloned().collect()) | ||
} | ||
| ||
pub fn subscribe(&self) -> tokio::sync::watch::Receiver<usize> { | ||
self.published.subscribe() | ||
} | ||
| ||
/// How many events there are, on disk or not. | ||
#[cfg(test)] | ||
pub fn len(&self) -> usize { | ||
self.lock().events.len() | ||
} | ||
} | ||
| ||
/// An event's frame with its seq changed. | ||
pub fn renumber(frame: &[u8], seq: u64) -> Result<Vec<u8>, String> { | ||
let (header, n) = decode_prefix(frame)?; | ||
let mut body = decode(&frame[n..])?; | ||
let V::Map(fields) = &mut body else { return Err("an event whose body is not a map".into()) }; | ||
let Some((_, at)) = fields.iter_mut().find(|(k, _)| k == "seq") else { return Err("an event with no seq".into()) }; | ||
*at = V::Int(seq as i64); | ||
let mut out = encode(&header); | ||
out.extend(encode(&body)); | ||
Ok(out) | ||
} | ||
| ||
/// The current time as an atproto datetime, in UTC to the millisecond. | ||
pub fn timestamp() -> String { | ||
let ms = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_millis() as i64; | ||
| @@ -92,19 +196,20 @@ pub fn commit_event(did: &str, seq: u64, c: &Change) -> Vec<u8> { | ||
message("#commit", body) | ||
} | ||
| ||
/// What a new account's stream starts with, from `#identity` to `#sync`; seqs | ||
/// are the caller's to give. | ||
pub fn initial_events(did: &str, handle: &str, c: &Change) -> Vec<Vec<u8>> { | ||
/// What a new account's stream starts with, from `#identity` to `#sync`, | ||
/// numbered from `seq`. | ||
pub fn initial_events(did: &str, handle: &str, seq: u64, c: &Change) -> Vec<Vec<u8>> { | ||
let head = cid_of(0x71, &c.head_bytes); | ||
let time = timestamp(); | ||
let n = |i: u64| V::Int((seq + i) as i64); | ||
vec![ | ||
message("#identity", vec![("seq", V::Int(1)), ("did", s(did)), ("time", s(&time)), ("handle", s(handle))]), | ||
message("#account", vec![("seq", V::Int(2)), ("did", s(did)), ("time", s(&time)), ("active", V::Bool(true))]), | ||
commit_event(did, 3, c), | ||
message("#identity", vec![("seq", n(0)), ("did", s(did)), ("time", s(&time)), ("handle", s(handle))]), | ||
message("#account", vec![("seq", n(1)), ("did", s(did)), ("time", s(&time)), ("active", V::Bool(true))]), | ||
commit_event(did, seq + 2, c), | ||
message( | ||
"#sync", | ||
vec![ | ||
("seq", V::Int(4)), | ||
("seq", n(3)), | ||
("did", s(did)), | ||
("blocks", V::Bytes(car_file(&head, [(head.as_slice(), c.head_bytes.as_slice())]))), | ||
("rev", s(&c.rev)), | ||
| @@ -130,8 +235,7 @@ pub async fn subscribe( | ||
/// as it reaches the disk. | ||
async fn stream(st: Shared, cursor: Option<Result<u64, std::num::ParseIntError>>, mut socket: WebSocket) { | ||
let start = { | ||
let s = st.read().await; | ||
let rx = s.published.subscribe(); | ||
let rx = st.events.subscribe(); | ||
let last = *rx.borrow(); | ||
match cursor { | ||
None => Ok((rx, last)), | ||
| @@ -146,8 +250,7 @@ async fn stream(st: Shared, cursor: Option<Result<u64, std::num::ParseIntError>> | ||
}; | ||
loop { | ||
let upto = *rx.borrow_and_update(); | ||
// Shared with the server's copy: a send copies no frame. | ||
let batch: Vec<Bytes> = st.read().await.events.get(pos..upto).map_or_else(Vec::new, <[Bytes]>::to_vec); | ||
let batch = st.events.get(pos, upto); | ||
pos = upto; | ||
for frame in batch { | ||
if socket.send(Message::Binary(frame)).await.is_err() { | ||
crates/pds-server/src/lib.rs+330−143
473 lines changed: not loaded until asked for.
crates/pds-server/src/log.rs+473−187
660 lines changed: not loaded until asked for.
crates/pds-server/src/mcp.rs+8−5
| @@ -3,7 +3,7 @@ | ||
//! `tools/call`. Each method with a JSON answer is a tool (`spec/COMMANDS.md`), | ||
//! called through the same handling as XRPC. | ||
| ||
use crate::{Call, Resp, Shared, answer, bearer}; | ||
use crate::{Auth, Call, Resp, Shared, answer, bearer}; | ||
use axum::body::Bytes; | ||
use axum::extract::State; | ||
use axum::http::{HeaderMap, HeaderValue, Method, StatusCode, header}; | ||
| @@ -195,7 +195,7 @@ fn discover() -> Json { | ||
"resultType": "complete", | ||
"supportedVersions": [VERSION], | ||
"capabilities": { "tools": {} }, | ||
"instructions": "An atproto PDS holding one account. Each tool is an XRPC method of the server, with its arguments and answer; a `repo` or `did` left out is the account's DID.", | ||
"instructions": "An atproto PDS holding any number of accounts. Each tool is an XRPC method of the server, with its arguments and answer; a `repo` or `did` left out, with a token, is the token's account's DID.", | ||
"_meta": server_meta(), | ||
"ttlMs": 0, | ||
"cacheScope": "public", | ||
| @@ -238,9 +238,12 @@ async fn call_tool(st: &Shared, name: &str, arguments: Option<&Json>, token: Opt | ||
Some(Json::Object(a)) => a.clone(), | ||
Some(_) => return Err(rpc_err(StatusCode::OK, INVALID_PARAMS, "arguments must be an object")), | ||
}; | ||
let did = st.read().await.did.clone(); | ||
for a in m.args.iter().filter(|a| a.names_account()) { | ||
args.entry(a.name.clone()).or_insert_with(|| json!(did)); | ||
// A `repo` or `did` left out is the token's account's; with no token, or | ||
// one the server did not give out, it stays out, for the method to answer. | ||
if let Auth::Account(did) = st.auth(token.as_deref()) { | ||
for a in m.args.iter().filter(|a| a.names_account()) { | ||
args.entry(a.name.clone()).or_insert_with(|| json!(did)); | ||
} | ||
} | ||
let (method, mut params, mut body) = (if m.kind == Kind::Query { Method::GET } else { Method::POST }, Vec::new(), String::new()); | ||
if m.kind == Kind::Query { | ||
crates/pds-server/src/plc.rsnew+335−0
| @@ -0,0 +1,335 @@ | ||
//! The PLC directory: a new account's `did:plc`, by the genesis operation | ||
//! `atproto/did-plc.md` describes, registered with the directory at | ||
//! `PDS_PLC_URL` (`spec/ACCOUNTS.md`). | ||
| ||
use crate::Config; | ||
use base64::Engine; | ||
use base64::engine::general_purpose::URL_SAFE_NO_PAD; | ||
use k256::ecdsa::signature::hazmat::PrehashSigner; | ||
use k256::ecdsa::{Signature, VerifyingKey}; | ||
use pds_repo::data::*; | ||
use serde_json::Value as Json; | ||
use sha2::{Digest, Sha256}; | ||
| ||
/// The multicodec of a secp256k1 public key, as a varint. | ||
const SECP256K1_PUB: [u8; 2] = [0xe7, 0x01]; | ||
| ||
/// A secp256k1 public key as a `did:key`: its multicodec and compressed point, in base58btc. | ||
pub fn did_key(key: &VerifyingKey) -> String { | ||
let mut bytes = SECP256K1_PUB.to_vec(); | ||
bytes.extend_from_slice(key.to_encoded_point(true).as_bytes()); | ||
format!("did:key:z{}", bs58::encode(bytes).into_string()) | ||
} | ||
| ||
/// A signed genesis operation and the DID it makes. | ||
pub struct Genesis { | ||
pub did: String, | ||
/// The signed operation, as JSON, as it is posted. | ||
pub op: Json, | ||
} | ||
| ||
/// 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 { | ||
let s = |x: &str| V::Str(x.to_string()); | ||
let rotation = did_key(config.rotation_key.verifying_key()); | ||
let mut rotation_keys: Vec<V> = config.recovery_did_key.iter().filter(|k| **k != rotation).map(|k| s(k)).collect(); | ||
rotation_keys.push(s(&rotation)); | ||
let mut fields = vec![ | ||
("type".to_string(), s("plc_operation")), | ||
("rotationKeys".to_string(), V::Arr(rotation_keys)), | ||
("verificationMethods".to_string(), V::Map(vec![("atproto".to_string(), s(&did_key(signing)))])), | ||
("alsoKnownAs".to_string(), V::Arr(vec![s(&format!("at://{handle}"))])), | ||
( | ||
"services".to_string(), | ||
V::Map(vec![( | ||
"atproto_pds".to_string(), | ||
V::Map(vec![("type".to_string(), s("AtprotoPersonalDataServer")), ("endpoint".to_string(), s(&config.public_url))]), | ||
)]), | ||
), | ||
("prev".to_string(), V::Null), | ||
]; | ||
let unsigned = encode(&V::Map(fields.clone())); | ||
let sig: Signature = config.rotation_key.sign_prehash(&Sha256::digest(&unsigned)).expect("signing a 32-byte digest"); | ||
let sig = sig.normalize_s().unwrap_or(sig); | ||
fields.push(("sig".to_string(), s(&URL_SAFE_NO_PAD.encode(sig.to_bytes())))); | ||
let signed = V::Map(fields); | ||
Genesis { did: did_of(&encode(&signed)), op: to_json(&signed) } | ||
} | ||
| ||
/// The DID a signed genesis operation, as DAG-CBOR, makes. | ||
fn did_of(signed: &[u8]) -> String { | ||
format!("did:plc:{}", &base32_encode(&Sha256::digest(signed))[..24]) | ||
} | ||
| ||
/// The HTTP client the server reaches the PLC directory with. It keeps no | ||
/// idle connection: a server may close one it holds idle (Node's HTTP server | ||
/// does after 5 seconds) just as the next request goes out on it, which then | ||
/// fails, perhaps after the server has read it. Each request takes a | ||
/// connection of its own, and none waits for ever. | ||
pub fn client() -> reqwest::Result<reqwest::Client> { | ||
reqwest::Client::builder() | ||
.no_proxy() | ||
.pool_max_idle_per_host(0) | ||
.connect_timeout(std::time::Duration::from_secs(5)) | ||
.timeout(std::time::Duration::from_secs(15)) | ||
.build() | ||
} | ||
| ||
/// The DID document the directory serves at `url`, or None if it serves none. | ||
/// Reading changes nothing, so a read that failed on its way is tried once more. | ||
async fn document(http: &reqwest::Client, url: &str) -> Result<Option<Json>, String> { | ||
let res = match http.get(url).send().await { | ||
Ok(res) => res, | ||
Err(e) if !e.is_timeout() => http.get(url).send().await.map_err(|e| format!("reading {url}: {e}"))?, | ||
Err(e) => return Err(format!("reading {url}: {e}")), | ||
}; | ||
if res.status() == reqwest::StatusCode::NOT_FOUND { | ||
return Ok(None); | ||
} | ||
if !res.status().is_success() { | ||
return Err(format!("{url} answered {} for the DID document", res.status())); | ||
} | ||
let bytes = res.bytes().await.map_err(|e| format!("reading {url}: {e}"))?; | ||
serde_json::from_slice(&bytes).map(Some).map_err(|e| format!("the DID document at {url}: {e}")) | ||
} | ||
| ||
/// Register a genesis operation with the directory, and answer the DID | ||
/// document it then serves for the DID. | ||
/// | ||
/// A post that fails on its way may or may not have reached the directory. | ||
/// The DID is the hash of this very operation, so no other operation can | ||
/// have made it: a document served for it means the directory took this | ||
/// one, and none means it has no operation for the DID, so posting this one | ||
/// again is its first genesis, not a second. | ||
pub async fn register(http: &reqwest::Client, plc_url: &str, g: &Genesis) -> Result<Json, String> { | ||
async fn refused(url: &str, res: reqwest::Response) -> Result<Json, String> { | ||
let status = res.status(); | ||
Err(format!("{url} refused the operation: {status} {}", res.text().await.unwrap_or_default())) | ||
} | ||
let url = format!("{}/{}", plc_url.trim_end_matches('/'), g.did); | ||
let post = || http.post(&url).header(reqwest::header::CONTENT_TYPE, "application/json").body(g.op.to_string()).send(); | ||
match post().await { | ||
Ok(res) if res.status().is_success() => {} | ||
Ok(res) => return refused(&url, res).await, | ||
Err(e) => { | ||
eprintln!("pds: posting to {url}: {e}; asking whether it was taken"); | ||
if document(http, &url).await?.is_none() { | ||
match post().await { | ||
Ok(res) if res.status().is_success() => {} | ||
Ok(res) => return refused(&url, res).await, | ||
Err(e) => return Err(format!("posting to {url}: {e}")), | ||
} | ||
} | ||
} | ||
} | ||
document(http, &url).await?.ok_or_else(|| format!("{url} serves no DID document for the operation it took")) | ||
} | ||
| ||
/// The public key of a secp256k1 `did:key`. | ||
#[cfg(test)] | ||
pub fn parse_did_key(k: &str) -> Option<VerifyingKey> { | ||
let bytes = bs58::decode(k.strip_prefix("did:key:z")?).into_vec().ok()?; | ||
VerifyingKey::from_sec1_bytes(bytes.strip_prefix(&SECP256K1_PUB[..])?).ok() | ||
} | ||
| ||
/// Check a genesis operation as a directory would: signed, in low-S form, | ||
/// by one of its rotation keys, and making `did`. | ||
#[cfg(test)] | ||
pub fn verify(did: &str, op: &Json) -> Result<(), String> { | ||
use k256::ecdsa::signature::hazmat::PrehashVerifier; | ||
let V::Map(mut fields) = from_json(op)? else { return Err("not an object".into()) }; | ||
if did_of(&encode(&V::Map(fields.clone()))) != did { | ||
return Err(format!("the operation does not make {did}")); | ||
} | ||
let at = fields.iter().position(|(k, _)| k == "sig").ok_or("no sig")?; | ||
let V::Str(sig) = fields.remove(at).1 else { return Err("sig is not a string".into()) }; | ||
let sig = URL_SAFE_NO_PAD.decode(&sig).map_err(|e| e.to_string())?; | ||
let sig = Signature::from_slice(&sig).map_err(|e| e.to_string())?; | ||
if sig.normalize_s().is_some() { | ||
return Err("a high-S signature".into()); | ||
} | ||
let hash = Sha256::digest(encode(&V::Map(fields))); | ||
let keys = op["rotationKeys"].as_array().ok_or("no rotationKeys")?; | ||
keys.iter() | ||
.filter_map(|k| parse_did_key(k.as_str()?)) | ||
.any(|k| k.verify_prehash(&hash, &sig).is_ok()) | ||
.then_some(()) | ||
.ok_or_else(|| "no rotation key signed it".into()) | ||
} | ||
| ||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
use crate::testing::config; | ||
use k256::ecdsa::SigningKey; | ||
use serde_json::json; | ||
| ||
/// `did:key`s as the interop vectors have them. | ||
#[test] | ||
fn did_keys() { | ||
let text = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../spec/interop/crypto/w3c_didkey_K256.json")).unwrap(); | ||
let vectors: Vec<Json> = serde_json::from_str(&text).unwrap(); | ||
assert!(!vectors.is_empty()); | ||
for v in vectors { | ||
let key = SigningKey::from_slice(&hex::decode(v["privateKeyBytesHex"].as_str().unwrap()).unwrap()).unwrap(); | ||
assert_eq!(did_key(key.verifying_key()), v["publicDidKey"].as_str().unwrap()); | ||
} | ||
} | ||
| ||
/// A genesis operation as `atproto/did-plc.md` says, with fixed keys. | ||
#[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 rotation = did_key(config.rotation_key.verifying_key()); | ||
let sig = g.op["sig"].as_str().unwrap().to_string(); | ||
assert_eq!( | ||
g.op, | ||
json!({ | ||
"type": "plc_operation", | ||
"rotationKeys": [config.recovery_did_key.clone().unwrap(), rotation], | ||
"verificationMethods": { "atproto": did_key(signing.verifying_key()) }, | ||
"alsoKnownAs": ["at://alice.test"], | ||
"services": { "atproto_pds": { "type": "AtprotoPersonalDataServer", "endpoint": "http://127.0.0.1:2583" } }, | ||
"prev": null, | ||
"sig": sig, | ||
}) | ||
); | ||
// The signature: 64 bytes, base64url without padding. | ||
assert_eq!(sig.len(), 86); | ||
assert!(sig.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_')); | ||
// The DID: 24 characters of base32, lower case, without 0, 1, 8 or 9. | ||
let id = g.did.strip_prefix("did:plc:").unwrap(); | ||
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(); | ||
// 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); | ||
// Changing any field breaks it. | ||
let mut tampered = g.op.clone(); | ||
tampered["alsoKnownAs"] = json!(["at://mallory.test"]); | ||
assert!(verify(&g.did, &tampered).is_err()); | ||
// 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])); | ||
} | ||
| ||
/// How the stub directory loses the first operation posted to it. | ||
#[derive(Clone, Copy, PartialEq)] | ||
enum Lose { | ||
Nothing, | ||
/// It closes the connection having read the post, before taking it. | ||
Request, | ||
/// It takes the operation, then closes the connection unanswered. | ||
Answer, | ||
} | ||
| ||
/// A directory that, like a server closing a connection it held idle just | ||
/// as a request arrives on it, answers only the first request on each | ||
/// connection and closes it on reading the next. It takes any operation, | ||
/// serving `{id}` as its DID's document. Answers its URL. | ||
async fn closing_plc(lose: Lose) -> String { | ||
use std::collections::HashMap; | ||
use std::sync::{Arc, Mutex}; | ||
use tokio::io::{AsyncReadExt, AsyncWriteExt}; | ||
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap(); | ||
let url = format!("http://{}", listener.local_addr().unwrap()); | ||
let ops: Arc<Mutex<(HashMap<String, Json>, bool)>> = Arc::default(); | ||
tokio::spawn(async move { | ||
loop { | ||
let (mut conn, _) = listener.accept().await.unwrap(); | ||
let ops = ops.clone(); | ||
tokio::spawn(async move { | ||
let mut buf = Vec::new(); | ||
for served in 0.. { | ||
// Read one request: its head, then a body as long as it says. | ||
let head_end = loop { | ||
if let Some(i) = buf.windows(4).position(|w| w == b"\r\n\r\n") { | ||
break i + 4; | ||
} | ||
let mut chunk = [0u8; 4096]; | ||
match conn.read(&mut chunk).await { | ||
Ok(0) | Err(_) => return, | ||
Ok(n) => buf.extend_from_slice(&chunk[..n]), | ||
} | ||
}; | ||
let head = String::from_utf8_lossy(&buf[..head_end]).to_lowercase(); | ||
let len = head.lines().find_map(|l| l.strip_prefix("content-length:")).map_or(0, |n| n.trim().parse().unwrap()); | ||
while buf.len() < head_end + len { | ||
let mut chunk = [0u8; 4096]; | ||
match conn.read(&mut chunk).await { | ||
Ok(0) | Err(_) => return, | ||
Ok(n) => buf.extend_from_slice(&chunk[..n]), | ||
} | ||
} | ||
let body: Vec<u8> = buf.drain(..head_end + len).skip(head_end).collect(); | ||
if served > 0 { | ||
return; | ||
} | ||
let did = head.split_whitespace().nth(1).unwrap().trim_start_matches('/').to_string(); | ||
let answer = if head.starts_with("post") { | ||
let mut ops = ops.lock().unwrap(); | ||
let first = !std::mem::replace(&mut ops.1, true); | ||
if first && lose == Lose::Request { | ||
return; | ||
} | ||
ops.0.insert(did, serde_json::from_slice(&body).unwrap()); | ||
if first && lose == Lose::Answer { | ||
return; | ||
} | ||
"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n".to_string() | ||
} else if ops.lock().unwrap().0.contains_key(&did) { | ||
let doc = json!({ "id": did }).to_string(); | ||
format!("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: keep-alive\r\n\r\n{doc}", doc.len()) | ||
} else { | ||
"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n".to_string() | ||
}; | ||
if conn.write_all(answer.as_bytes()).await.is_err() { | ||
return; | ||
} | ||
} | ||
}); | ||
} | ||
}); | ||
url | ||
} | ||
| ||
fn op(handle: &str) -> Genesis { | ||
genesis(&config("http://plc.invalid"), SigningKey::from_slice(&[3u8; 32]).unwrap().verifying_key(), handle) | ||
} | ||
| ||
/// A pooled connection the directory closes as the next request arrives | ||
/// fails that request; the server's client keeps none, so requests and | ||
/// registrations one after another each succeed. | ||
#[tokio::test] | ||
async fn no_idle_connection_is_reused() { | ||
let plc = closing_plc(Lose::Nothing).await; | ||
let url = format!("{plc}/did:plc:nobody"); | ||
let pooled = reqwest::Client::builder().no_proxy().build().unwrap(); | ||
assert_eq!(pooled.get(&url).send().await.unwrap().status(), 404); | ||
let e = pooled.get(&url).send().await.unwrap_err(); | ||
assert!(!e.is_timeout() && !e.is_connect(), "{e:?}"); | ||
let http = client().unwrap(); | ||
for _ in 0..3 { | ||
assert_eq!(http.get(&url).send().await.unwrap().status(), 404); | ||
} | ||
for h in ["a.test", "b.test", "c.test"] { | ||
let g = op(h); | ||
assert_eq!(register(&http, &plc, &g).await.unwrap(), json!({ "id": g.did })); | ||
} | ||
} | ||
| ||
/// A post lost on its way is found taken, or posted again if it was not. | ||
#[tokio::test] | ||
async fn a_lost_post_is_settled() { | ||
for lose in [Lose::Request, Lose::Answer] { | ||
let plc = closing_plc(lose).await; | ||
let g = op("lost.test"); | ||
assert_eq!(register(&client().unwrap(), &plc, &g).await.unwrap(), json!({ "id": g.did })); | ||
} | ||
} | ||
} | ||
crates/pds-server/src/repo.rs+184−126
| @@ -1,7 +1,7 @@ | ||
//! The repository's records: the `com.atproto.repo` methods, as | ||
//! `spec/REPO.md` says. | ||
//! `spec/REPO.md` says, of any account's repository. | ||
| ||
use crate::{Call, Handler, Resp, Server, XrpcError, commit_meta, err, internal, invalid, opt, required}; | ||
use crate::{Apply, Call, Handler, Resp, Service, Shown, XrpcError, commit_meta, err, internal, invalid, opt, required}; | ||
use pds_repo::data::*; | ||
use pds_repo::*; | ||
use serde_json::{Map, Value as Json, json}; | ||
| @@ -11,36 +11,34 @@ pub(crate) fn handler(nsid: &str) -> Option<Handler> { | ||
"com.atproto.repo.getRecord" => Handler::Query(get_record), | ||
"com.atproto.repo.listRecords" => Handler::Query(list_records), | ||
"com.atproto.repo.describeRepo" => Handler::Query(describe_repo), | ||
"com.atproto.repo.createRecord" => Handler::Procedure { owner: true, f: create_record }, | ||
"com.atproto.repo.putRecord" => Handler::Procedure { owner: true, f: put_record }, | ||
"com.atproto.repo.deleteRecord" => Handler::Procedure { owner: true, f: delete_record }, | ||
"com.atproto.repo.applyWrites" => Handler::Procedure { owner: true, f: apply_writes }, | ||
"com.atproto.repo.createRecord" => Handler::Write(create_record), | ||
"com.atproto.repo.putRecord" => Handler::Write(put_record), | ||
"com.atproto.repo.deleteRecord" => Handler::Write(delete_record), | ||
"com.atproto.repo.applyWrites" => Handler::Write(apply_writes), | ||
_ => return None, | ||
}) | ||
} | ||
| ||
fn check_repo(s: &Server, repo: &str) -> Result<(), XrpcError> { | ||
if repo == s.handle || repo == s.did { Ok(()) } else { invalid("Could not find repo") } | ||
fn not_found() -> XrpcError { | ||
XrpcError { status: 400, name: "InvalidRequest", message: "Could not find repo".into() } | ||
} | ||
| ||
fn record_json(s: &Server, collection: &str, rkey: &str, r: &Record) -> Json { | ||
json!({ "uri": s.repo.uri(collection, rkey), "cid": cid_string(&r.cid), "value": to_json(&r.value) }) | ||
fn record_json(r: &Repo, collection: &str, rkey: &str, rec: &Record) -> Json { | ||
json!({ "uri": r.uri(collection, rkey), "cid": cid_string(&rec.cid), "value": to_json(&rec.value) }) | ||
} | ||
| ||
fn get_record(s: &Server, _: &Call, p: &Map<String, Json>) -> Result<Resp, XrpcError> { | ||
check_repo(s, required(p, "repo")?)?; | ||
fn get_record(s: &Service, _: &Call, shown: &mut Shown, p: &Map<String, Json>) -> Result<Resp, XrpcError> { | ||
let (collection, rkey) = (required(p, "collection")?, required(p, "rkey")?); | ||
match s.repo.records.get(&format!("{collection}/{rkey}")) { | ||
Some(r) if opt(p, "cid").is_none_or(|c| c == cid_string(&r.cid)) => Ok(Resp::Json(record_json(s, collection, rkey, r))), | ||
_ => err(400, "RecordNotFound", format!("Could not locate record: {}", s.repo.uri(collection, rkey))), | ||
} | ||
s.with_repo(shown, required(p, "repo")?, not_found, |_, r| match r.records.get(&format!("{collection}/{rkey}")) { | ||
Some(rec) if opt(p, "cid").is_none_or(|c| c == cid_string(&rec.cid)) => Ok(Resp::Json(record_json(r, collection, rkey, rec))), | ||
_ => err(400, "RecordNotFound", format!("Could not locate record: {}", r.uri(collection, rkey))), | ||
}) | ||
} | ||
| ||
/// A page of a collection: newest (greatest key) first unless `reverse`, read | ||
/// from the range of the collection's keys after the cursor. | ||
fn list_records(s: &Server, _: &Call, p: &Map<String, Json>) -> Result<Resp, XrpcError> { | ||
fn list_records(s: &Service, _: &Call, shown: &mut Shown, p: &Map<String, Json>) -> Result<Resp, XrpcError> { | ||
use std::ops::Bound::{Excluded, Included}; | ||
check_repo(s, required(p, "repo")?)?; | ||
let collection = required(p, "collection")?; | ||
let limit = p.get("limit").and_then(Json::as_u64).unwrap_or(50) as usize; | ||
let reverse = p.get("reverse").and_then(Json::as_bool) == Some(true); | ||
| @@ -52,28 +50,28 @@ fn list_records(s: &Server, _: &Call, p: &Map<String, Json>) -> Result<Resp, Xrp | ||
(Some(c), false) => (Included(lo.clone()), Excluded(format!("{lo}{c}"))), | ||
(Some(c), true) => (Excluded(format!("{lo}{c}")), Excluded(hi)), | ||
}; | ||
let keyed = s.repo.records.range(range).map(|(k, r)| (&k[lo.len()..], r)); | ||
let page: Vec<(&str, &Record)> = if reverse { keyed.take(limit).collect() } else { keyed.rev().take(limit).collect() }; | ||
let records: Vec<Json> = page.iter().map(|(rk, r)| record_json(s, collection, rk, r)).collect(); | ||
let mut out = json!({ "records": records }); | ||
if let Some((rk, _)) = page.last() { | ||
out["cursor"] = json!(rk); | ||
} | ||
Ok(Resp::Json(out)) | ||
s.with_repo(shown, required(p, "repo")?, not_found, |_, r| { | ||
let keyed = r.records.range(range).map(|(k, rec)| (&k[lo.len()..], rec)); | ||
let page: Vec<(&str, &Record)> = if reverse { keyed.take(limit).collect() } else { keyed.rev().take(limit).collect() }; | ||
let records: Vec<Json> = page.iter().map(|(rk, rec)| record_json(r, collection, rk, rec)).collect(); | ||
let mut out = json!({ "records": records }); | ||
if let Some((rk, _)) = page.last() { | ||
out["cursor"] = json!(rk); | ||
} | ||
Ok(Resp::Json(out)) | ||
}) | ||
} | ||
| ||
fn describe_repo(s: &Server, _: &Call, p: &Map<String, Json>) -> Result<Resp, XrpcError> { | ||
fn describe_repo(s: &Service, _: &Call, shown: &mut Shown, p: &Map<String, Json>) -> Result<Resp, XrpcError> { | ||
let repo = required(p, "repo")?; | ||
if repo != s.handle && repo != s.did { | ||
return err(400, "RepoNotFound", format!("Could not find repo: {repo}")); | ||
} | ||
let mut cols: Vec<&str> = s.repo.records.keys().filter_map(|k| k.split('/').next()).collect(); | ||
cols.dedup(); | ||
Ok(Resp::Json(json!({ | ||
"handle": s.handle, "did": s.did, | ||
"didDoc": { "id": s.did, "alsoKnownAs": [format!("at://{}", s.handle)] }, | ||
"collections": cols, "handleIsCorrect": true | ||
}))) | ||
let missing = || XrpcError { status: 400, name: "RepoNotFound", message: format!("Could not find repo: {repo}") }; | ||
s.with_repo(shown, repo, missing, |a, r| { | ||
let mut cols: Vec<&str> = r.records.keys().filter_map(|k| k.split('/').next()).collect(); | ||
cols.dedup(); | ||
Ok(Resp::Json(json!({ | ||
"handle": a.handle, "did": a.did, "didDoc": a.did_doc, "collections": cols, "handleIsCorrect": true | ||
}))) | ||
}) | ||
} | ||
| ||
// ---- Writes ----------------------------------------------------------- | ||
| @@ -122,11 +120,6 @@ fn with_status(mut answer: Json, status: Option<&str>) -> Json { | ||
answer | ||
} | ||
| ||
/// A write's `repo`, checked once its input is: `403 AccountNotFound` unless it names the account. | ||
fn check_account(s: &Server, repo: &str) -> Result<(), XrpcError> { | ||
if repo == s.handle || repo == s.did { Ok(()) } else { err(403, "AccountNotFound", "Could not find account") } | ||
} | ||
| ||
/// The record one write created or updated. | ||
fn written(results: Vec<OpResult>) -> Result<(String, String), XrpcError> { | ||
match results.into_iter().next() { | ||
| @@ -135,61 +128,65 @@ fn written(results: Vec<OpResult>) -> Result<(String, String), XrpcError> { | ||
} | ||
} | ||
| ||
fn create_record(s: &mut Server, b: &Map<String, Json>) -> Result<Resp, XrpcError> { | ||
let (repo, collection, rkey) = (required(b, "repo")?, required(b, "collection")?, opt(b, "rkey")); | ||
fn create_record(b: &Map<String, Json>) -> Result<Apply, XrpcError> { | ||
let (collection, rkey) = (required(b, "collection")?.to_string(), opt(b, "rkey").map(String::from)); | ||
let status = validation_status(b)?; | ||
let value = record_value(b, "record")?; | ||
check_account(s, repo)?; | ||
let value = typed(value, collection)?; | ||
let op = Op::Create { collection: collection.into(), rkey: rkey.map(Into::into), value }; | ||
let (uri, cid) = written(s.repo.apply(vec![op], opt(b, "swapCommit"))?)?; | ||
Ok(Resp::Json(with_status(json!({ "uri": uri, "cid": cid, "commit": commit_meta(s) }), status))) | ||
let swap = opt(b, "swapCommit").map(String::from); | ||
Ok(Box::new(move |r: &mut Repo| { | ||
let value = typed(value, &collection)?; | ||
let op = Op::Create { collection, rkey, value }; | ||
let (uri, cid) = written(r.apply(vec![op], swap.as_deref())?)?; | ||
Ok(Resp::Json(with_status(json!({ "uri": uri, "cid": cid, "commit": commit_meta(r) }), status))) | ||
})) | ||
} | ||
| ||
fn put_record(s: &mut Server, b: &Map<String, Json>) -> Result<Resp, XrpcError> { | ||
let (repo, collection, rkey) = (required(b, "repo")?, required(b, "collection")?, required(b, "rkey")?); | ||
fn put_record(b: &Map<String, Json>) -> Result<Apply, XrpcError> { | ||
let (collection, rkey) = (required(b, "collection")?.to_string(), required(b, "rkey")?.to_string()); | ||
let status = validation_status(b)?; | ||
let value = record_value(b, "record")?; | ||
check_account(s, repo)?; | ||
let value = typed(value, collection)?; | ||
let existing = s.repo.records.get(&format!("{collection}/{rkey}")).map(|r| cid_string(&r.cid)); | ||
if existing.is_some() && existing.as_deref() == Some(cid_string(&make_record(value.clone()).cid).as_str()) { | ||
// Writing what is already there makes no commit. | ||
let uri = s.repo.uri(collection, rkey); | ||
return Ok(Resp::Json(with_status(json!({ "uri": uri, "cid": existing }), status))); | ||
} | ||
// `swapRecord: null` asks that there be no record. | ||
match b.get("swapRecord") { | ||
None => {} | ||
Some(Json::Null) if existing.is_none() => {} | ||
Some(Json::String(c)) if existing.as_deref() == Some(c.as_str()) => {} | ||
Some(_) => return err(400, "InvalidSwap", "Record was at a different CID"), | ||
} | ||
let op = if existing.is_some() { | ||
Op::Update { collection: collection.into(), rkey: rkey.into(), value } | ||
} else { | ||
Op::Create { collection: collection.into(), rkey: Some(rkey.into()), value } | ||
}; | ||
let (uri, cid) = written(s.repo.apply(vec![op], opt(b, "swapCommit"))?)?; | ||
Ok(Resp::Json(with_status(json!({ "uri": uri, "cid": cid, "commit": commit_meta(s) }), status))) | ||
let (swap, swap_record) = (opt(b, "swapCommit").map(String::from), b.get("swapRecord").cloned()); | ||
Ok(Box::new(move |r: &mut Repo| { | ||
let value = typed(value, &collection)?; | ||
let existing = r.records.get(&format!("{collection}/{rkey}")).map(|rec| cid_string(&rec.cid)); | ||
if existing.is_some() && existing.as_deref() == Some(cid_string(&make_record(value.clone()).cid).as_str()) { | ||
// Writing what is already there makes no commit. | ||
return Ok(Resp::Json(with_status(json!({ "uri": r.uri(&collection, &rkey), "cid": existing }), status))); | ||
} | ||
// `swapRecord: null` asks that there be no record. | ||
match swap_record { | ||
None => {} | ||
Some(Json::Null) if existing.is_none() => {} | ||
Some(Json::String(c)) if existing.as_deref() == Some(c.as_str()) => {} | ||
Some(_) => return err(400, "InvalidSwap", "Record was at a different CID"), | ||
} | ||
let op = if existing.is_some() { | ||
Op::Update { collection, rkey, value } | ||
} else { | ||
Op::Create { collection, rkey: Some(rkey), value } | ||
}; | ||
let (uri, cid) = written(r.apply(vec![op], swap.as_deref())?)?; | ||
Ok(Resp::Json(with_status(json!({ "uri": uri, "cid": cid, "commit": commit_meta(r) }), status))) | ||
})) | ||
} | ||
| ||
fn delete_record(s: &mut Server, b: &Map<String, Json>) -> Result<Resp, XrpcError> { | ||
let (repo, collection, rkey) = (required(b, "repo")?, required(b, "collection")?, required(b, "rkey")?); | ||
check_account(s, repo)?; | ||
let existing = s.repo.records.get(&format!("{collection}/{rkey}")).map(|r| cid_string(&r.cid)); | ||
if existing.is_none() { | ||
return Ok(Resp::Json(json!({}))); | ||
} | ||
if opt(b, "swapRecord").is_some_and(|c| existing.as_deref() != Some(c)) { | ||
return err(400, "InvalidSwap", "Record was at a different CID"); | ||
} | ||
s.repo.apply(vec![Op::Delete { collection: collection.into(), rkey: rkey.into() }], opt(b, "swapCommit"))?; | ||
Ok(Resp::Json(json!({ "commit": commit_meta(s) }))) | ||
fn delete_record(b: &Map<String, Json>) -> Result<Apply, XrpcError> { | ||
let (collection, rkey) = (required(b, "collection")?.to_string(), required(b, "rkey")?.to_string()); | ||
let (swap, swap_record) = (opt(b, "swapCommit").map(String::from), opt(b, "swapRecord").map(String::from)); | ||
Ok(Box::new(move |r: &mut Repo| { | ||
let existing = r.records.get(&format!("{collection}/{rkey}")).map(|rec| cid_string(&rec.cid)); | ||
if existing.is_none() { | ||
return Ok(Resp::Json(json!({}))); | ||
} | ||
if swap_record.is_some_and(|c| existing.as_deref() != Some(c.as_str())) { | ||
return err(400, "InvalidSwap", "Record was at a different CID"); | ||
} | ||
r.apply(vec![Op::Delete { collection, rkey }], swap.as_deref())?; | ||
Ok(Resp::Json(json!({ "commit": commit_meta(r) }))) | ||
})) | ||
} | ||
| ||
fn apply_writes(s: &mut Server, b: &Map<String, Json>) -> Result<Resp, XrpcError> { | ||
let repo = required(b, "repo")?; | ||
fn apply_writes(b: &Map<String, Json>) -> Result<Apply, XrpcError> { | ||
let status = validation_status(b)?; | ||
let Some(Json::Array(writes)) = b.get("writes") else { return invalid("Input/writes must be an array") }; | ||
let mut ops = Vec::with_capacity(writes.len()); | ||
| @@ -207,27 +204,28 @@ fn apply_writes(s: &mut Server, b: &Map<String, Json>) -> Result<Resp, XrpcError | ||
_ => return invalid("unknown write type"), | ||
}); | ||
} | ||
check_account(s, repo)?; | ||
for op in &mut ops { | ||
if let Op::Create { collection, value, .. } | Op::Update { collection, value, .. } = op { | ||
*value = typed(std::mem::replace(value, V::Null), collection)?; | ||
} | ||
} | ||
let results: Vec<Json> = s | ||
.repo | ||
.apply(ops, opt(b, "swapCommit"))? | ||
.into_iter() | ||
.map(|r| match r { | ||
OpResult::Create { uri, cid } => { | ||
with_status(json!({ "$type": "com.atproto.repo.applyWrites#createResult", "uri": uri, "cid": cid }), status) | ||
let swap = opt(b, "swapCommit").map(String::from); | ||
Ok(Box::new(move |r: &mut Repo| { | ||
for op in &mut ops { | ||
if let Op::Create { collection, value, .. } | Op::Update { collection, value, .. } = op { | ||
*value = typed(std::mem::replace(value, V::Null), collection)?; | ||
} | ||
OpResult::Update { uri, cid } => { | ||
with_status(json!({ "$type": "com.atproto.repo.applyWrites#updateResult", "uri": uri, "cid": cid }), status) | ||
} | ||
OpResult::Delete => json!({ "$type": "com.atproto.repo.applyWrites#deleteResult" }), | ||
}) | ||
.collect(); | ||
Ok(Resp::Json(json!({ "commit": commit_meta(s), "results": results }))) | ||
} | ||
let results: Vec<Json> = r | ||
.apply(ops, swap.as_deref())? | ||
.into_iter() | ||
.map(|res| match res { | ||
OpResult::Create { uri, cid } => { | ||
with_status(json!({ "$type": "com.atproto.repo.applyWrites#createResult", "uri": uri, "cid": cid }), status) | ||
} | ||
OpResult::Update { uri, cid } => { | ||
with_status(json!({ "$type": "com.atproto.repo.applyWrites#updateResult", "uri": uri, "cid": cid }), status) | ||
} | ||
OpResult::Delete => json!({ "$type": "com.atproto.repo.applyWrites#deleteResult" }), | ||
}) | ||
.collect(); | ||
Ok(Resp::Json(json!({ "commit": commit_meta(r), "results": results }))) | ||
})) | ||
} | ||
| ||
#[cfg(test)] | ||
| @@ -236,31 +234,91 @@ mod tests { | ||
use serde_json::json; | ||
| ||
/// listRecords pages through its collection alone, both ways. | ||
#[test] | ||
fn list_records_pages_a_collection() { | ||
#[tokio::test] | ||
async fn list_records_pages_a_collection() { | ||
let plc = plc().await; | ||
let dir = scratch("list"); | ||
let mut s = open(&dir); | ||
let owner = session(&mut s); | ||
let s = open(&dir, &plc); | ||
let (did, owner) = create(&s, "alice").await; | ||
let (_, other) = create(&s, "bob").await; | ||
for c in ["a.b.c", "a.b.cd", "a.b.c.d", "a.b.b"] { | ||
for k in ["-x", "1", "m", "z~"] { | ||
call(&mut s, "com.atproto.repo.putRecord", Some(&owner), json!({ "repo": DID, "collection": c, "rkey": k, "record": {} })).unwrap(); | ||
call(&s, "com.atproto.repo.putRecord", Some(&owner), json!({ "repo": did, "collection": c, "rkey": k, "record": {} })).await.unwrap(); | ||
} | ||
} | ||
let mut list = |reverse: bool, cursor: Option<&str>| { | ||
let mut p = vec![("repo".to_string(), DID.to_string()), ("collection".into(), "a.b.c".into()), ("limit".into(), "3".into())]; | ||
p.extend(reverse.then(|| ("reverse".to_string(), "true".to_string()))); | ||
p.extend(cursor.map(|c| ("cursor".to_string(), c.to_string()))); | ||
let got = call_with(&mut s, "com.atproto.repo.listRecords", None, &p, json!({})).unwrap(); | ||
let keys: Vec<String> = got["records"].as_array().unwrap().iter().map(|r| r["uri"].as_str().unwrap().rsplit('/').next().unwrap().to_string()).collect(); | ||
(keys, got["cursor"].as_str().map(str::to_string)) | ||
// Bob's records are his alone. | ||
call(&s, "com.atproto.repo.putRecord", Some(&other), json!({ "repo": "bob.test", "collection": "a.b.c", "rkey": "n", "record": {} })).await.unwrap(); | ||
let list = |repo: &'static str, reverse: bool, cursor: Option<&'static str>| { | ||
let s = s.clone(); | ||
let repo = if repo == "alice" { did.clone() } else { repo.to_string() }; | ||
async move { | ||
let mut p = vec![("repo".to_string(), repo), ("collection".into(), "a.b.c".into()), ("limit".into(), "3".into())]; | ||
p.extend(reverse.then(|| ("reverse".to_string(), "true".to_string()))); | ||
p.extend(cursor.map(|c| ("cursor".to_string(), c.to_string()))); | ||
let got = call_with(&s, "com.atproto.repo.listRecords", None, &p, json!({})).await.unwrap(); | ||
let keys: Vec<String> = got["records"].as_array().unwrap().iter().map(|r| r["uri"].as_str().unwrap().rsplit('/').next().unwrap().to_string()).collect(); | ||
(keys, got["cursor"].as_str().map(str::to_string)) | ||
} | ||
}; | ||
assert_eq!(list(false, None), (vec!["z~".into(), "m".into(), "1".into()], Some("1".into()))); | ||
assert_eq!(list(false, Some("1")), (vec!["-x".into()], Some("-x".into()))); | ||
assert_eq!(list(false, Some("-x")), (vec![], None)); | ||
assert_eq!(list(true, None), (vec!["-x".into(), "1".into(), "m".into()], Some("m".into()))); | ||
assert_eq!(list(true, Some("m")), (vec!["z~".into()], Some("z~".into()))); | ||
assert_eq!(list(true, Some("")), (vec!["-x".into(), "1".into(), "m".into()], Some("m".into()))); | ||
assert_eq!(list(false, Some("")).0, Vec::<String>::new()); | ||
assert_eq!(list("alice", false, None).await, (vec!["z~".into(), "m".into(), "1".into()], Some("1".into()))); | ||
assert_eq!(list("alice", false, Some("1")).await, (vec!["-x".into()], Some("-x".into()))); | ||
assert_eq!(list("alice", false, Some("-x")).await, (vec![], None)); | ||
assert_eq!(list("alice", true, None).await, (vec!["-x".into(), "1".into(), "m".into()], Some("m".into()))); | ||
assert_eq!(list("alice", true, Some("m")).await, (vec!["z~".into()], Some("z~".into()))); | ||
assert_eq!(list("alice", true, Some("")).await, (vec!["-x".into(), "1".into(), "m".into()], Some("m".into()))); | ||
assert_eq!(list("alice", false, Some("")).await.0, Vec::<String>::new()); | ||
assert_eq!(list("bob.test", false, None).await, (vec!["n".into()], Some("n".into()))); | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
| ||
/// A write to another account's repository, or to one no account has, is | ||
/// refused after its token and input are checked, before its `$type`. | ||
#[tokio::test] | ||
async fn writes_to_another_account() { | ||
let plc = plc().await; | ||
let dir = scratch("other-account"); | ||
let s = open(&dir, &plc); | ||
let (alice, ta) = create(&s, "alice").await; | ||
let (bob, tb) = create(&s, "bob").await; | ||
let put = |repo: &str, record: serde_json::Value| json!({ "repo": repo, "collection": "a.b.c", "rkey": "k", "record": record }); | ||
let nsid = "com.atproto.repo.putRecord"; | ||
// Token first, then input. | ||
assert_eq!(call(&s, nsid, None, put(&bob, json!({}))).await, Err("AuthMissing".into())); | ||
assert_eq!(call(&s, nsid, Some("forged"), put("nobody.test", json!(1.5))).await, Err("InvalidToken".into())); | ||
assert_eq!(call(&s, nsid, Some(&ta), put(&bob, json!({ "f": 1.5 }))).await, Err("InvalidRequest".into())); | ||
assert_eq!(call(&s, nsid, Some(&ta), json!({ "repo": bob, "collection": "a.b.c", "rkey": "k", "record": {}, "validate": true })).await, Err("InvalidRequest".into())); | ||
// Then the repo, before the record's $type. | ||
for repo in [bob.as_str(), "bob.test"] { | ||
assert_eq!(call(&s, nsid, Some(&ta), put(repo, json!({ "$type": "x.y.z" }))).await, Err("AuthenticationRequired".into())); | ||
} | ||
assert_eq!(call(&s, nsid, Some(&ta), put("nobody.test", json!({ "$type": "x.y.z" }))).await, Err("AccountNotFound".into())); | ||
assert_eq!(call(&s, nsid, Some(&ta), put("did:plc:aaaaaaaaaaaaaaaaaaaaaaaa", json!({}))).await, Err("AccountNotFound".into())); | ||
// A handle is matched as given: none here has a capital letter. | ||
assert_eq!(call(&s, nsid, Some(&ta), put("ALICE.test", json!({}))).await, Err("AccountNotFound".into())); | ||
let p = [("repo".to_string(), "Bob.test".to_string())]; | ||
assert_eq!(call_with(&s, "com.atproto.repo.describeRepo", None, &p, json!({})).await, Err("RepoNotFound".into())); | ||
assert_eq!(call(&s, nsid, Some(&ta), put(&alice, json!({ "$type": "x.y.z" }))).await, Err("InvalidRequest".into())); | ||
for (nsid, body) in [ | ||
("com.atproto.repo.createRecord", json!({ "repo": bob, "collection": "a.b.c", "record": {} })), | ||
("com.atproto.repo.deleteRecord", json!({ "repo": bob, "collection": "a.b.c", "rkey": "k" })), | ||
("com.atproto.repo.applyWrites", json!({ "repo": bob, "writes": [] })), | ||
] { | ||
assert_eq!(call(&s, nsid, Some(&ta), body).await, Err("AuthenticationRequired".into()), "{nsid}"); | ||
} | ||
// Each writes its own, and reads anyone's. | ||
call(&s, nsid, Some(&ta), put(&alice, json!({ "n": 1 }))).await.unwrap(); | ||
call(&s, nsid, Some(&tb), put("bob.test", json!({ "n": 2 }))).await.unwrap(); | ||
for (repo, n) in [(alice.as_str(), 1), ("alice.test", 1), (bob.as_str(), 2), ("bob.test", 2)] { | ||
let p = [("repo".to_string(), repo.to_string()), ("collection".into(), "a.b.c".into()), ("rkey".into(), "k".into())]; | ||
let got = call_with(&s, "com.atproto.repo.getRecord", None, &p, json!({})).await.unwrap(); | ||
assert_eq!(got["value"]["n"], json!(n), "{repo}"); | ||
} | ||
let p = [("repo".to_string(), "bob.test".to_string())]; | ||
let got = call_with(&s, "com.atproto.repo.describeRepo", None, &p, json!({})).await.unwrap(); | ||
assert_eq!((got["did"].clone(), got["handle"].clone(), got["collections"].clone()), (json!(bob), json!("bob.test"), json!(["a.b.c"]))); | ||
assert_eq!(got["didDoc"]["id"], json!(bob)); | ||
let p = [("repo".to_string(), "nobody.test".to_string())]; | ||
assert_eq!(call_with(&s, "com.atproto.repo.describeRepo", None, &p, json!({})).await, Err("RepoNotFound".into())); | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
} | ||
crates/pds-server/src/server.rs+495−31
526 lines changed: not loaded until asked for.
crates/pds-server/src/sync.rs+43−28
| @@ -1,7 +1,8 @@ | ||
//! The repository whole: `getRepo` and `getLatestCommit`, as `spec/SYNC.md` | ||
//! says. The firehose, `subscribeRepos`, is in `events`. | ||
//! says, of any account's repository. The firehose, `subscribeRepos`, is in | ||
//! `events`. | ||
| ||
use crate::{Call, Handler, Resp, Server, XrpcError, commit_meta, err, opt, required}; | ||
use crate::{Call, Handler, Resp, Service, Shown, XrpcError, commit_meta, opt, required}; | ||
use serde_json::{Map, Value as Json}; | ||
| ||
pub(crate) fn handler(nsid: &str) -> Option<Handler> { | ||
| @@ -12,21 +13,21 @@ pub(crate) fn handler(nsid: &str) -> Option<Handler> { | ||
}) | ||
} | ||
| ||
fn check_did(s: &Server, did: &str) -> Result<(), XrpcError> { | ||
if did == s.did { Ok(()) } else { err(400, "RepoNotFound", "Could not find repo") } | ||
fn not_found() -> XrpcError { | ||
XrpcError { status: 400, name: "RepoNotFound", message: "Could not find repo".into() } | ||
} | ||
| ||
fn get_repo(s: &Server, _: &Call, p: &Map<String, Json>) -> Result<Resp, XrpcError> { | ||
check_did(s, required(p, "did")?)?; | ||
Ok(Resp::Car(match opt(p, "since") { | ||
None => s.repo.car(), | ||
Some(since) => s.repo.car_since(since), | ||
})) | ||
fn get_repo(s: &Service, _: &Call, shown: &mut Shown, p: &Map<String, Json>) -> Result<Resp, XrpcError> { | ||
s.with_repo(shown, required(p, "did")?, not_found, |_, r| { | ||
Ok(Resp::Car(match opt(p, "since") { | ||
None => r.car(), | ||
Some(since) => r.car_since(since), | ||
})) | ||
}) | ||
} | ||
| ||
fn get_latest_commit(s: &Server, _: &Call, p: &Map<String, Json>) -> Result<Resp, XrpcError> { | ||
check_did(s, required(p, "did")?)?; | ||
Ok(Resp::Json(commit_meta(s))) | ||
fn get_latest_commit(s: &Service, _: &Call, shown: &mut Shown, p: &Map<String, Json>) -> Result<Resp, XrpcError> { | ||
s.with_repo(shown, required(p, "did")?, not_found, |_, r| Ok(Resp::Json(commit_meta(r)))) | ||
} | ||
| ||
#[cfg(test)] | ||
| @@ -38,23 +39,30 @@ mod tests { | ||
| ||
/// `getRepo since` answers the same after a restart, which rebuilds when | ||
/// each block was added from the log. | ||
#[test] | ||
fn since_survives_restart() { | ||
#[tokio::test] | ||
async fn since_survives_restart() { | ||
let plc = plc().await; | ||
let dir = scratch("since"); | ||
let mut s = open(&dir); | ||
let owner = session(&mut s); | ||
let mut revs = vec![s.repo.rev.clone()]; | ||
let s = open(&dir, &plc); | ||
let (did, owner) = create(&s, "alice").await; | ||
let (bob, other) = create(&s, "bob").await; | ||
let rev = |s: &crate::Service| repo_of(s, &did, |r| r.rev.clone()); | ||
let mut revs = vec![rev(&s)]; | ||
for (k, n) in [("one", 1), ("two", 2), ("one", 3), ("three", 1)] { | ||
let body = json!({ "repo": DID, "collection": "a.b.c", "rkey": k, "record": { "n": n } }); | ||
call(&mut s, "com.atproto.repo.putRecord", Some(&owner), body).unwrap(); | ||
revs.push(s.repo.rev.clone()); | ||
let body = json!({ "repo": did, "collection": "a.b.c", "rkey": k, "record": { "n": n } }); | ||
call(&s, "com.atproto.repo.putRecord", Some(&owner), body).await.unwrap(); | ||
// Another account's commits change nothing of this one's. | ||
let body = json!({ "repo": bob, "collection": "a.b.c", "rkey": k, "record": { "n": n + 10 } }); | ||
call(&s, "com.atproto.repo.putRecord", Some(&other), body).await.unwrap(); | ||
revs.push(rev(&s)); | ||
} | ||
call(&mut s, "com.atproto.repo.deleteRecord", Some(&owner), json!({ "repo": DID, "collection": "a.b.c", "rkey": "two" })).unwrap(); | ||
revs.push(s.repo.rev.clone()); | ||
let before: Vec<Vec<u8>> = revs.iter().map(|r| s.repo.car_since(r)).collect(); | ||
call(&s, "com.atproto.repo.deleteRecord", Some(&owner), json!({ "repo": did, "collection": "a.b.c", "rkey": "two" })).await.unwrap(); | ||
revs.push(rev(&s)); | ||
let cars = |s: &crate::Service| -> Vec<Vec<u8>> { revs.iter().map(|r| repo_of(s, &did, |repo| repo.car_since(r))).collect() }; | ||
let before = cars(&s); | ||
// At the latest rev, the CAR is its header alone. | ||
let latest = before.last().unwrap(); | ||
assert_eq!(latest, &car_file(&s.repo.head, std::iter::empty())); | ||
assert_eq!(latest, &repo_of(&s, &did, |r| car_file(&r.head, std::iter::empty()))); | ||
// A record's block is among them from the commit that last made the | ||
// repository hold it: `three` holds again what `one` first held. | ||
let holds = |car: &[u8], n: i64| { | ||
| @@ -64,10 +72,17 @@ mod tests { | ||
assert!(holds(&before[3], 1) && !holds(&before[3], 2) && !holds(&before[3], 3)); | ||
assert!(!holds(&before[4], 1)); | ||
assert!(holds(&before[0], 1) && holds(&before[0], 3) && !holds(&before[0], 2)); | ||
assert!(!before.iter().any(|car| holds(car, 11))); | ||
drop(s); | ||
let s = open(&dir); | ||
let after: Vec<Vec<u8>> = revs.iter().map(|r| s.repo.car_since(r)).collect(); | ||
assert_eq!(before, after); | ||
let s = open(&dir, &plc); | ||
assert_eq!(before, cars(&s)); | ||
// getRepo and getLatestCommit of each, by DID. | ||
let p = |d: &str| [("did".to_string(), d.to_string())]; | ||
let latest = call_with(&s, "com.atproto.sync.getLatestCommit", None, &p(&bob), json!({})).await.unwrap(); | ||
assert_eq!(latest["rev"], json!(repo_of(&s, &bob, |r| r.rev.clone()))); | ||
assert_eq!(call_with(&s, "com.atproto.sync.getRepo", None, &p(&did), json!({})).await, Err("a CAR file".into())); | ||
let nobody = "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa"; | ||
assert_eq!(call_with(&s, "com.atproto.sync.getLatestCommit", None, &p(nobody), json!({})).await, Err("RepoNotFound".into())); | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
} | ||
crates/pds-server/Cargo.toml+4−0
| @@ -10,8 +10,12 @@ pds-repo.workspace = true | ||
pds-store.workspace = true | ||
axum.workspace = true | ||
base64.workspace = true | ||
bs58.workspace = true | ||
hex.workspace = true | ||
k256.workspace = true | ||
rand.workspace = true | ||
reqwest.workspace = true | ||
scrypt.workspace = true | ||
serde_json.workspace = true | ||
sha2.workspace = true | ||
tokio.workspace = true | ||
crates/pds-store/src/lib.rs+43−20
harness/checks/accounts.mjsnew+350−0
harness/checks/commands.mjs+5−3
harness/checks/crashes.mjs+20−16
harness/checks/firehose.mjs+60−43
harness/checks/odd.mjs+29−27
harness/checks/records.mjs+99−87
harness/checks/repository.mjs+42−27
harness/checks/session.mjs+13−42
harness/lib/env.mjsnew+26−0
harness/lib/plc.mjsnew+29−0
harness/lib/processes.mjs+17−33
harness/lib/state.mjs+53−18
harness/lib/via.mjs+31−13
harness/lib/xrpc.mjs+57−19
harness/compare.mjs+30−22
harness/conformance.mjs+9−11
spec/atproto/did-plc.mdnew+453−0
453 lines changed: not loaded until asked for.
spec/data/reserved-handles.txtnew+1029−0
1029 lines changed: not loaded until asked for.