chadtmiller.com/monolith
An atproto PDS
0
0
Sessions, blobs, identity and what a relay reads, built in parallel
crates/pds-cli/src/lib.rs+68−12
| @@ -7,6 +7,7 @@ | ||
use pds_lexicon::{Arg, JSON, Kind, Method, Type}; | ||
use serde_json::{Map, Value as Json, json}; | ||
use std::io::{Read, Write}; | ||
use std::sync::LazyLock; | ||
| ||
const USAGE: u8 = 2; | ||
const UNREACHABLE: u8 = 3; | ||
| @@ -101,17 +102,33 @@ fn group_help(group: &str) -> String { | ||
out | ||
} | ||
| ||
/// `--encoding`, the `Content-Type` of a command whose method takes its body | ||
/// as it is (`uploadBlob`), which it reads from standard input. | ||
static ENCODING: LazyLock<Arg> = LazyLock::new(|| Arg { | ||
name: "encoding".into(), | ||
ty: Type::String, | ||
required: true, | ||
description: Some("The Content-Type of the body, which is standard input.".into()), | ||
schema: json!({ "type": "string" }), | ||
def: json!({ "type": "string" }), | ||
}); | ||
| ||
/// A command's flags: its method's arguments, and `--encoding` for one whose body is standard input. | ||
fn flags_of(m: &Method) -> impl Iterator<Item = &Arg> { | ||
m.args.iter().chain(m.raw_input().then(|| &*ENCODING)) | ||
} | ||
| ||
fn command_help(m: &Method) -> String { | ||
let mut out = format!("Usage: pds {} {} [flags]\n", m.group, m.command().unwrap_or_default()); | ||
if let Some(d) = &m.description { | ||
out.push_str(&format!("\n{d}\n")); | ||
} | ||
if m.args.is_empty() { | ||
if flags_of(m).next().is_none() { | ||
out.push_str("\nIt takes no flags.\n"); | ||
return out; | ||
} | ||
out.push_str("\nFlags:\n"); | ||
for a in &m.args { | ||
for a in flags_of(m) { | ||
let flag = format!("--{} {}", a.flag(), a.ty.placeholder()); | ||
let mut about = String::new(); | ||
if a.needed() { | ||
| @@ -144,7 +161,7 @@ fn parse(m: &Method, flags: &[String]) -> Result<Option<Map<String, Json>>, Stop | ||
Some((n, v)) => (n, Some(v.to_string())), | ||
None => (flag, None), | ||
}; | ||
let Some(arg) = m.args.iter().find(|x| x.flag() == name) else { | ||
let Some(arg) = flags_of(m).find(|x| x.flag() == name) else { | ||
return usage(format!("pds {} {} takes no flag --{name}", m.group, m.command().unwrap_or_default())); | ||
}; | ||
if values.contains_key(&arg.name) { | ||
| @@ -170,7 +187,7 @@ fn parse(m: &Method, flags: &[String]) -> Result<Option<Map<String, Json>>, Stop | ||
let value = value(arg, text, &mut stdin_read)?; | ||
values.insert(arg.name.clone(), value); | ||
} | ||
let missing: Vec<String> = m.args.iter().filter(|a| a.needed() && !values.contains_key(&a.name)).map(|a| format!("--{}", a.flag())).collect(); | ||
let missing: Vec<String> = flags_of(m).filter(|a| a.needed() && !values.contains_key(&a.name)).map(|a| format!("--{}", a.flag())).collect(); | ||
if !missing.is_empty() { | ||
return usage(format!("pds {} {} needs {}", m.group, m.command().unwrap_or_default(), missing.join(", "))); | ||
} | ||
| @@ -230,10 +247,15 @@ struct Server { | ||
} | ||
| ||
impl Server { | ||
fn send(&self, nsid: &str, kind: Kind, args: &Map<String, Json>) -> Result<reqwest::blocking::Response, Stop> { | ||
let url = format!("{}/xrpc/{nsid}", self.url); | ||
let mut req = match kind { | ||
Kind::Procedure => self.http.post(&url).header("content-type", JSON).body(Json::Object(args.clone()).to_string()), | ||
/// Call a method: a query with `args` as its parameters, a procedure with | ||
/// them as its JSON input, or with `raw`, a type and bytes, as its body. | ||
fn send(&self, m: &Method, args: &Map<String, Json>, raw: Option<(String, Vec<u8>)>) -> Result<reqwest::blocking::Response, Stop> { | ||
let url = format!("{}/xrpc/{}", self.url, m.nsid); | ||
let mut req = match (m.kind, raw) { | ||
(Kind::Procedure, Some((encoding, body))) => self.http.post(&url).header("content-type", encoding).body(body), | ||
// A procedure that takes no input is sent none. | ||
(Kind::Procedure, None) if m.input.is_none() && args.is_empty() => self.http.post(&url), | ||
(Kind::Procedure, None) => self.http.post(&url).header("content-type", JSON).body(Json::Object(args.clone()).to_string()), | ||
_ => { | ||
let mut params = Vec::new(); | ||
for (k, v) in args { | ||
| @@ -254,7 +276,8 @@ impl Server { | ||
/// 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)?; | ||
let get_session = pds_lexicon::method("com.atproto.server.getSession").expect("getSession's lexicon"); | ||
let (status, body) = answer(self.send(get_session, &Map::new(), None)?, &self.url)?; | ||
Ok(body["did"].as_str().filter(|_| status == 200).map(str::to_string)) | ||
} | ||
} | ||
| @@ -304,7 +327,25 @@ fn call(m: &Method, mut args: Map<String, Json>) -> Result<u8, Stop> { | ||
} | ||
} | ||
} | ||
let res = server.send(&m.nsid, m.kind, &args)?; | ||
// A body of any type is standard input, sent as `--encoding` says. | ||
let raw = match (m.raw_input(), args.get("encoding")) { | ||
(true, Some(Json::String(encoding))) => { | ||
let encoding = encoding.clone(); | ||
args.remove("encoding"); | ||
let mut body = Vec::new(); | ||
if let Err(e) = std::io::stdin().read_to_end(&mut body) { | ||
return usage(format!("cannot read standard input: {e}")); | ||
} | ||
Some((encoding, body)) | ||
} | ||
_ => None, | ||
}; | ||
let mut res = server.send(m, &args, raw)?; | ||
// A method that answers nothing prints `{}`. | ||
if res.status().is_success() && m.output.is_none() { | ||
print_line(&json!({})); | ||
return Ok(0); | ||
} | ||
if !res.status().is_success() || m.output.as_deref() == Some(JSON) { | ||
let (status, body) = answer(res, &server.url)?; | ||
if !(200..300).contains(&status) { | ||
| @@ -313,9 +354,9 @@ fn call(m: &Method, mut args: Map<String, Json>) -> Result<u8, Stop> { | ||
print_line(&body); | ||
return Ok(0); | ||
} | ||
let bytes = res.bytes().map_err(|e| Stop::Unreachable(format!("cannot read the answer of {}: {e}", server.url)))?; | ||
// Bytes, as getRepo's and getBlob's: written as they come. | ||
let mut out = std::io::stdout().lock(); | ||
let _ = out.write_all(&bytes); | ||
res.copy_to(&mut out).map_err(|e| Stop::Unreachable(format!("cannot read the answer of {}: {e}", server.url)))?; | ||
let _ = out.flush(); | ||
Ok(0) | ||
} | ||
| @@ -362,4 +403,19 @@ mod tests { | ||
assert!(flags(create, &["--collection", "a.b.c", "--record", "null"]).is_err()); | ||
assert!(flags(create, &["--collection", "a.b.c", "--record", "{"]).is_err()); | ||
} | ||
| ||
/// `upload-blob` takes its body from standard input, its type from | ||
/// `--encoding`, which it needs; `get-blob` takes its parameters. | ||
#[test] | ||
fn blob_commands() { | ||
let upload = "com.atproto.repo.uploadBlob"; | ||
assert_eq!(Json::Object(flags(upload, &["--encoding", "image/png"]).unwrap().unwrap()), json!({ "encoding": "image/png" })); | ||
assert!(flags(upload, &[]).is_err()); | ||
assert!(flags(upload, &["--encoding", "a/b", "--repo", "x"]).is_err()); | ||
let help = command_help(pds_lexicon::method(upload).unwrap()); | ||
assert!(help.contains("--encoding <string>"), "{help}"); | ||
let got = flags("com.atproto.sync.getBlob", &["--did", "did:plc:x", "--cid", "bafy"]).unwrap().unwrap(); | ||
assert_eq!(Json::Object(got), json!({ "did": "did:plc:x", "cid": "bafy" })); | ||
assert!(flags("com.atproto.sync.getBlob", &["--encoding", "a/b"]).is_err()); | ||
} | ||
} | ||
crates/pds-lexicon/src/lib.rs+30−6
| @@ -93,6 +93,8 @@ pub struct Method { | ||
/// Its parameters (a query's or a subscription's) or its input's properties | ||
/// (a procedure's), by name. | ||
pub args: Vec<Arg>, | ||
/// The encoding of its input, if it is a procedure that takes one. | ||
pub input: Option<String>, | ||
/// The encoding of its answer, if it has one. | ||
pub output: Option<String>, | ||
/// The `params` or input schema the arguments are the properties of. | ||
| @@ -100,12 +102,19 @@ pub struct Method { | ||
} | ||
| ||
impl Method { | ||
/// Its MCP tool's name, if it has a tool: every method whose answer is JSON. | ||
/// Its MCP tool's name, if it has a tool: every method whose answer is | ||
/// JSON, or that answers nothing, and whose input, if it has one, is JSON too. | ||
pub fn tool(&self) -> Option<String> { | ||
(self.kind != Kind::Subscription && self.output.as_deref() == Some(JSON)) | ||
(self.kind != Kind::Subscription && self.output.as_deref().is_none_or(|o| o == JSON) && self.input.as_deref().is_none_or(|i| i == JSON)) | ||
.then(|| format!("{}_{}", self.group, split_case(&self.name, '_'))) | ||
} | ||
| ||
/// Whether its input is the request's body as it is, of any type, rather | ||
/// than JSON: its command sends standard input, with `--encoding` as its type. | ||
pub fn raw_input(&self) -> bool { | ||
self.input.as_deref().is_some_and(|i| i != JSON) | ||
} | ||
| ||
/// Its CLI command's name within its group, if it has one: every method but a subscription. | ||
pub fn command(&self) -> Option<String> { | ||
(self.kind != Kind::Subscription).then(|| split_case(&self.name, '-')) | ||
| @@ -249,6 +258,7 @@ fn read_method(doc: &Json) -> Option<Method> { | ||
kind, | ||
description: main["description"].as_str().map(str::to_string), | ||
args, | ||
input: main["input"]["encoding"].as_str().map(str::to_string), | ||
output: main["output"]["encoding"].as_str().map(str::to_string), | ||
schema: object, | ||
}) | ||
| @@ -495,13 +505,27 @@ mod tests { | ||
| ||
#[test] | ||
fn which_methods() { | ||
let get_repo = method("com.atproto.sync.getRepo").unwrap(); | ||
assert_eq!((get_repo.tool(), get_repo.command().as_deref()), (None, Some("get-repo"))); | ||
// A method whose answer is a CAR file is a command and no tool. | ||
for (nsid, command) in [("com.atproto.sync.getRepo", "get-repo"), ("com.atproto.sync.getBlocks", "get-blocks"), ("com.atproto.sync.getRecord", "get-record")] { | ||
let m = method(nsid).unwrap(); | ||
assert_eq!((m.tool(), m.command().as_deref()), (None, Some(command)), "{nsid}"); | ||
} | ||
let sub = method("com.atproto.sync.subscribeRepos").unwrap(); | ||
assert_eq!((sub.tool(), sub.command()), (None, None)); | ||
// A method that answers nothing has a tool too. | ||
let delete = method("com.atproto.server.deleteSession").unwrap(); | ||
assert_eq!((delete.tool().as_deref(), delete.output.as_deref(), delete.input.as_deref()), (Some("server_delete_session"), None, None)); | ||
let tools: Vec<String> = methods().iter().filter_map(Method::tool).collect(); | ||
assert_eq!(tools.len(), 12, "{tools:?}"); | ||
assert_eq!(groups(), ["repo", "server", "sync"]); | ||
assert_eq!(tools.len(), 23, "{tools:?}"); | ||
assert!(tools.contains(&"sync_list_repos".to_string()) && tools.contains(&"sync_get_repo_status".to_string())); | ||
// uploadBlob's input and getBlob's answer are bytes: neither has a tool, both a command. | ||
for nsid in ["com.atproto.repo.uploadBlob", "com.atproto.sync.getBlob"] { | ||
let m = method(nsid).unwrap(); | ||
assert_eq!((m.tool(), m.command().is_some()), (None, true), "{nsid}"); | ||
} | ||
assert!(method("com.atproto.repo.uploadBlob").unwrap().raw_input()); | ||
assert!(!method("com.atproto.repo.createRecord").unwrap().raw_input()); | ||
assert_eq!(groups(), ["identity", "repo", "server", "sync"]); | ||
assert!(method("com.atproto.repo.defs").is_none()); | ||
} | ||
| ||
crates/pds-repo/src/data.rs+24−20
| @@ -252,10 +252,9 @@ pub fn from_json(j: &Json) -> Result<V, String> { | ||
Json::String(s) => V::Str(s.clone()), | ||
Json::Array(a) => V::Arr(a.iter().map(from_json).collect::<Result<_, _>>()?), | ||
Json::Object(o) => { | ||
if let Some(l) = o.get("$link") { | ||
if o.len() != 1 { | ||
return Err("$link object with other fields".into()); | ||
} | ||
// A `$link` beside other keys is no link but a map, kept as it is | ||
// (`spec/BLOBS.md`), as is any map of `$type` blob. | ||
if let Some(l) = o.get("$link").filter(|_| o.len() == 1) { | ||
let cid = l.as_str().and_then(parse_cid).ok_or("invalid $link")?; | ||
return Ok(V::Link(cid)); | ||
} | ||
| @@ -267,17 +266,8 @@ pub fn from_json(j: &Json) -> Result<V, String> { | ||
return Ok(V::Bytes(bytes)); | ||
} | ||
if let Some(t) = o.get("$type") { | ||
match t.as_str() { | ||
Some("") | None => return Err("$type must be a non-empty string".into()), | ||
Some("blob") => { | ||
let ok = o.get("ref").is_some_and(|r| r.get("$link").is_some()) | ||
&& o.get("mimeType").and_then(Json::as_str).is_some_and(|m| !m.is_empty()) | ||
&& o.get("size").is_some_and(|s| s.is_i64()); | ||
if !ok { | ||
return Err("invalid blob".into()); | ||
} | ||
} | ||
_ => {} | ||
if t.as_str().is_none_or(str::is_empty) { | ||
return Err("$type must be a non-empty string".into()); | ||
} | ||
} | ||
let mut m = Vec::new(); | ||
| @@ -398,18 +388,32 @@ mod tests { | ||
assert!(!valid_cid_string(&cid[..cid.len() - 2]) && !valid_cid_string("bafy") && !valid_cid_string("not a cid")); | ||
} | ||
| ||
/// The data model's invalid values are refused, but for the maps that | ||
/// look like a blob or a link and are kept as they are (`spec/BLOBS.md`). | ||
#[test] | ||
fn invalid() { | ||
let text = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../spec/interop/data-model/data-model-invalid.json")).unwrap(); | ||
let cases: Vec<Json> = serde_json::from_str(&text).unwrap(); | ||
let kept = ["blob with string size", "blob with missing key", "link with extra fields"]; | ||
for c in cases { | ||
let j = &c["json"]; | ||
let bad = match j.get("rcrd").or(j.get("blb")).or(j.get("lnk")) { | ||
Some(x) => from_json(x).is_err(), | ||
None => true, | ||
}; | ||
assert!(bad, "{}", c["note"]); | ||
let Some(x) = j.get("rcrd").or(j.get("blb")).or(j.get("lnk")) else { continue }; | ||
let note = c["note"].as_str().unwrap(); | ||
if kept.contains(¬e) { | ||
let v = from_json(x).unwrap(); | ||
assert!(matches!(v, V::Map(_)), "{note}"); | ||
assert_eq!(&to_json(&v), x, "{note}"); | ||
} else { | ||
assert!(from_json(x).is_err(), "{note}"); | ||
} | ||
} | ||
for kept in [ | ||
serde_json::json!({ "$type": "blob", "ref": "bafkrei", "mimeType": "", "size": null }), | ||
serde_json::json!({ "$type": "blob", "ref": { "a": 1 }, "mimeType": 5, "size": -2, "x": 1 }), | ||
] { | ||
assert_eq!(to_json(&from_json(&kept).unwrap()), kept); | ||
} | ||
assert!(from_json(&serde_json::json!({ "$type": "blob", "size": 1.5 })).is_err()); | ||
} | ||
| ||
#[test] | ||
crates/pds-repo/src/lib.rs+75−9
| @@ -136,6 +136,11 @@ impl Repo { | ||
self.commit(vec![]) | ||
} | ||
| ||
/// The public key of the key that signs its commits. | ||
pub fn verifying_key(&self) -> &k256::ecdsa::VerifyingKey { | ||
self.key.verifying_key() | ||
} | ||
| ||
pub fn head_string(&self) -> String { | ||
cid_string(&self.head) | ||
} | ||
| @@ -257,26 +262,43 @@ impl Repo { | ||
| ||
/// Apply writes as one commit, all or nothing. | ||
pub fn apply(&mut self, ops: Vec<Op>, swap_commit: Option<&str>) -> Result<Vec<OpResult>, Refused> { | ||
self.apply_checked(ops, swap_commit, || Ok(())) | ||
} | ||
| ||
/// Apply writes as one commit, all or nothing, once `check` passes: it | ||
/// runs only once the writes are found possible, and its refusal makes no | ||
/// commit and changes nothing. | ||
pub fn apply_checked<E: From<Refused>>( | ||
&mut self, | ||
ops: Vec<Op>, | ||
swap_commit: Option<&str>, | ||
check: impl FnOnce() -> Result<(), E>, | ||
) -> Result<Vec<OpResult>, E> { | ||
if swap_commit.is_some_and(|s| s != self.head_string()) { | ||
return Err(Refused::StaleCommit); | ||
return Err(Refused::StaleCommit.into()); | ||
} | ||
let mut originals: BTreeMap<String, Option<Record>> = BTreeMap::new(); | ||
let mut results = Vec::new(); | ||
let mut evops = Vec::new(); | ||
let mut refused = None; | ||
for op in ops { | ||
match self.apply_one(op, &mut originals, &mut evops) { | ||
Ok(x) => results.push(x), | ||
Err(e) => { | ||
for (k, old) in originals { | ||
match old { | ||
Some(r) => self.records.insert(k, r), | ||
None => self.records.remove(&k), | ||
}; | ||
} | ||
return Err(e); | ||
refused = Some(E::from(e)); | ||
break; | ||
} | ||
} | ||
} | ||
if let Some(e) = refused.map_or_else(|| check().err(), Some) { | ||
for (k, old) in originals { | ||
match old { | ||
Some(r) => self.records.insert(k, r), | ||
None => self.records.remove(&k), | ||
}; | ||
} | ||
return Err(e); | ||
} | ||
let mut change = self.commit(evops); | ||
change.puts = originals.keys().filter_map(|k| self.records.get(k).map(|r| (k.clone(), to_json(&r.value)))).collect(); | ||
change.dels = originals.keys().filter(|k| !self.records.contains_key(*k)).cloned().collect(); | ||
| @@ -358,6 +380,45 @@ impl Repo { | ||
); | ||
car_file(&self.head, blocks) | ||
} | ||
| ||
/// The blocks with these CIDs, each once, as a CAR file with no roots: | ||
/// None if the repository does not hold one of them, its latest commit or | ||
/// a node or record of its current tree. | ||
pub fn blocks_car(&self, cids: &[Vec<u8>]) -> Option<Vec<u8>> { | ||
let mut left: HashSet<&[u8]> = cids.iter().map(Vec::as_slice).collect(); | ||
let mut found: Vec<(&[u8], &[u8])> = Vec::with_capacity(left.len()); | ||
if left.remove(self.head.as_slice()) { | ||
found.push((&self.head, &self.head_bytes)); | ||
} | ||
for r in self.records.values() { | ||
if left.is_empty() { | ||
break; | ||
} | ||
if left.remove(r.cid.as_slice()) { | ||
found.push((&r.cid, &r.bytes)); | ||
} | ||
} | ||
if !left.is_empty() { | ||
for n in self.tree.nodes() { | ||
if left.remove(n.cid.as_slice()) { | ||
found.push((&n.cid, &n.bytes)); | ||
} | ||
} | ||
} | ||
left.is_empty().then(|| car_with_roots(&[], found)) | ||
} | ||
| ||
/// A CAR file rooted at the latest commit that proves the record at | ||
/// `path`, or that there is none: the commit, the tree nodes a search for | ||
/// the key passes through, and the record if the tree holds it. | ||
pub fn proof_car(&self, path: &str) -> Vec<u8> { | ||
let mut blocks: Vec<(&[u8], &[u8])> = vec![(&self.head, &self.head_bytes)]; | ||
blocks.extend(self.tree.path(path.as_bytes()).into_iter().map(|n| (n.cid.as_slice(), n.bytes.as_slice()))); | ||
if let Some(r) = self.records.get(path) { | ||
blocks.push((&r.cid, &r.bytes)); | ||
} | ||
car_file(&self.head, blocks) | ||
} | ||
} | ||
| ||
/// Whether `s` is a TID: 13 characters of base32-sortable, the first of them | ||
| @@ -369,8 +430,13 @@ pub fn valid_tid(s: &str) -> bool { | ||
| ||
/// A CAR file with one root and these blocks, in order. | ||
pub fn car_file<'a>(root: &[u8], blocks: impl IntoIterator<Item = (&'a [u8], &'a [u8])>) -> Vec<u8> { | ||
car_with_roots(&[root], blocks) | ||
} | ||
| ||
/// A CAR file with these roots, if any, and these blocks, in order. | ||
pub fn car_with_roots<'a>(roots: &[&[u8]], blocks: impl IntoIterator<Item = (&'a [u8], &'a [u8])>) -> Vec<u8> { | ||
let header = encode(&V::Map(vec![ | ||
("roots".into(), V::Arr(vec![V::Link(root.to_vec())])), | ||
("roots".into(), V::Arr(roots.iter().map(|r| V::Link(r.to_vec())).collect())), | ||
("version".into(), V::Int(1)), | ||
])); | ||
let mut out = Vec::new(); | ||
crates/pds-repo/src/mst.rs+18−0
| @@ -89,6 +89,24 @@ impl Node { | ||
n = x.gap(at); | ||
} | ||
} | ||
| ||
/// The nodes a search for `key` passes through, from this one: in each, | ||
/// it ends at the entry whose key it is, or else goes on into the subtree | ||
/// just before the first entry that sorts after the key, and ends where | ||
/// there is no such subtree. They prove the key's value, or its absence. | ||
pub fn path<'a>(&'a self, key: &[u8]) -> Vec<&'a Node> { | ||
let mut out = Vec::new(); | ||
let mut n = Some(self); | ||
while let Some(x) = n { | ||
out.push(x); | ||
let at = x.entries.partition_point(|e| e.key.as_slice() < key); | ||
if x.entries.get(at).is_some_and(|e| e.key == key) { | ||
break; | ||
} | ||
n = x.gap(at); | ||
} | ||
out | ||
} | ||
} | ||
| ||
/// The tree nodes a commit's `#commit` event carries, in CID order: those of | ||
crates/pds-server/src/blobs.rsnew+1216−0
1216 lines changed: not loaded until asked for.
crates/pds-server/src/events.rs+6−1
| @@ -196,6 +196,11 @@ pub fn commit_event(did: &str, seq: u64, c: &Change) -> Vec<u8> { | ||
message("#commit", body) | ||
} | ||
| ||
/// The `#identity` event of an account's handle. | ||
pub fn identity_event(did: &str, handle: &str, seq: u64, time: &str) -> Vec<u8> { | ||
message("#identity", vec![("seq", V::Int(seq as i64)), ("did", s(did)), ("time", s(time)), ("handle", s(handle))]) | ||
} | ||
| ||
/// 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>> { | ||
| @@ -203,7 +208,7 @@ pub fn initial_events(did: &str, handle: &str, seq: u64, c: &Change) -> Vec<Vec< | ||
let time = timestamp(); | ||
let n = |i: u64| V::Int((seq + i) as i64); | ||
vec![ | ||
message("#identity", vec![("seq", n(0)), ("did", s(did)), ("time", s(&time)), ("handle", s(handle))]), | ||
identity_event(did, handle, seq, &time), | ||
message("#account", vec![("seq", n(1)), ("did", s(did)), ("time", s(&time)), ("active", V::Bool(true))]), | ||
commit_event(did, seq + 2, c), | ||
message( | ||
crates/pds-server/src/federation.rsnew+537−0
537 lines changed: not loaded until asked for.
crates/pds-server/src/identity.rsnew+910−0
910 lines changed: not loaded until asked for.
crates/pds-server/src/lib.rs+130−45
| @@ -3,16 +3,23 @@ | ||
//! This module is the router, the state every request shares, and the | ||
//! dispatch of a call to its method. Each area's methods are in a module of | ||
//! their own, named in `AREAS`: `server` (the server, its accounts and their | ||
//! sessions), `repo` (records) and `sync` (the repository whole); the firehose | ||
//! is `events`, the MCP endpoint `mcp`, the PLC directory `plc`, and what the | ||
//! server keeps, and how it starts again from it, `log`. | ||
| ||
//! sessions), `sessions` (tokens, refreshing and ending sessions, and app | ||
//! passwords), `repo` (records), `sync` (the repository whole), | ||
//! `federation` (what a relay reads, and the crawlers the server tells), | ||
//! `identity` (handles) and `blobs`; the firehose is `events`, the MCP | ||
//! endpoint `mcp`, the PLC directory `plc`, and what the server keeps, and | ||
//! how it starts again from it, `log`. | ||
| ||
mod blobs; | ||
mod events; | ||
mod federation; | ||
mod identity; | ||
mod log; | ||
mod mcp; | ||
mod plc; | ||
mod repo; | ||
mod server; | ||
mod sessions; | ||
mod sync; | ||
| ||
use axum::{ | ||
| @@ -45,6 +52,8 @@ pub(crate) struct Config { | ||
pub rotation_key: k256::ecdsa::SigningKey, | ||
/// A `did:key` listed before the server's own as a rotation key. | ||
pub recovery_did_key: Option<String>, | ||
/// The base URLs of the crawlers to tell of new events (`spec/FEDERATION.md`). | ||
pub crawlers: Vec<String>, | ||
} | ||
| ||
impl Config { | ||
| @@ -62,6 +71,7 @@ impl Config { | ||
plc_url: var("PDS_PLC_URL")?, | ||
rotation_key, | ||
recovery_did_key: std::env::var("PDS_RECOVERY_DID_KEY").ok().filter(|k| !k.is_empty()), | ||
crawlers: std::env::var("PDS_CRAWLERS").unwrap_or_default().split(',').map(str::trim).filter(|u| !u.is_empty()).map(str::to_string).collect(), | ||
}) | ||
} | ||
} | ||
| @@ -69,32 +79,41 @@ impl Config { | ||
/// An account, with its repository. | ||
pub(crate) struct Account { | ||
pub did: String, | ||
/// In lower case. | ||
pub handle: String, | ||
/// In lower case. Changed only with the directory's lock held, as its | ||
/// `handles` are. | ||
pub handle: RwLock<String>, | ||
/// In lower case; an account without a password keeps none. | ||
pub email: Option<String>, | ||
/// Its password's hash; an account without one cannot log in. | ||
pub password: Option<String>, | ||
/// Its DID document, as the PLC directory served it. | ||
pub did_doc: Json, | ||
/// 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. | ||
pub store: RwLock<Store>, | ||
} | ||
| ||
impl Account { | ||
pub fn handle(&self) -> String { | ||
read(&self.handle).clone() | ||
} | ||
} | ||
| ||
/// An account's repository and the log it is kept in, apart from every other account's. | ||
pub(crate) struct Store { | ||
pub repo: Repo, | ||
pub wal: Arc<Wal>, | ||
pub blobs: blobs::Blobs, | ||
} | ||
| ||
/// Every account, by DID, handle and email, and the sessions given out. | ||
/// Every account, by DID, handle and email. | ||
#[derive(Default)] | ||
pub(crate) struct Directory { | ||
pub by_did: HashMap<String, Arc<Account>>, | ||
/// Every account's DID, in the order `accounts.log` has them: from when it | ||
/// is logged, so that `listRepos` lists none made after one being made. | ||
pub order: Vec<String>, | ||
pub handles: HashMap<String, String>, | ||
pub emails: HashMap<String, String>, | ||
/// Access tokens, each to its account's DID. | ||
pub sessions: HashMap<String, String>, | ||
/// The handles and emails of accounts being created. | ||
pub claimed_handles: HashSet<String>, | ||
pub claimed_emails: HashSet<String>, | ||
| @@ -102,7 +121,7 @@ pub(crate) struct Directory { | ||
| ||
impl Directory { | ||
pub fn insert(&mut self, a: Arc<Account>) { | ||
self.handles.insert(a.handle.clone(), a.did.clone()); | ||
self.handles.insert(a.handle(), a.did.clone()); | ||
if let Some(e) = &a.email { | ||
self.emails.insert(e.clone(), a.did.clone()); | ||
} | ||
| @@ -114,12 +133,16 @@ impl Directory { | ||
pub(crate) struct Service { | ||
config: Config, | ||
dir: PathBuf, | ||
/// The service-wide log: accounts and sessions. | ||
/// The service-wide log: accounts, sessions and app passwords. | ||
log: Arc<Wal>, | ||
directory: RwLock<Directory>, | ||
/// The sessions given out, and app passwords. | ||
sessions: sessions::Sessions, | ||
/// The firehose: one sequence across all accounts. | ||
events: events::Firehose, | ||
http: reqwest::Client, | ||
/// Each account's handle changes, one at a time, and any not yet settled. | ||
changes: identity::Changes, | ||
} | ||
| ||
type Shared = Arc<Service>; | ||
| @@ -139,20 +162,37 @@ async fn durable(wal: Arc<Wal>, n: u64) { | ||
} | ||
} | ||
| ||
/// Who a request's bearer token says it is. | ||
/// Who a request's access token says it is. | ||
enum Auth { | ||
None, | ||
/// An account's session, by its DID. | ||
Account(String), | ||
/// A token the server did not give out. | ||
/// A token the server did not give out, or not an access token, or a | ||
/// header not of the `Bearer` scheme. | ||
Invalid, | ||
/// An access token past its `exp`. | ||
Expired, | ||
} | ||
| ||
impl Auth { | ||
/// The account's DID, or the error a method that needs one answers. | ||
fn did(self) -> Result<String, XrpcError> { | ||
match self { | ||
Auth::Account(did) => Ok(did), | ||
Auth::None => err(401, "AuthMissing", "Authentication Required"), | ||
Auth::Invalid => invalid_token(), | ||
Auth::Expired => sessions::expired(), | ||
} | ||
} | ||
} | ||
| ||
impl Service { | ||
fn auth(&self, bearer: Option<&str>) -> Auth { | ||
match bearer { | ||
None => Auth::None, | ||
Some(t) => read(&self.directory).sessions.get(t).map_or(Auth::Invalid, |did| Auth::Account(did.clone())), | ||
fn auth(&self, bearer: sessions::Bearer) -> Auth { | ||
match sessions::access_token(self, bearer) { | ||
Ok(t) => Auth::Account(t.did), | ||
Err(e) if e.name == "AuthMissing" => Auth::None, | ||
Err(e) if e.name == "ExpiredToken" => Auth::Expired, | ||
Err(_) => Auth::Invalid, | ||
} | ||
} | ||
| ||
| @@ -194,6 +234,9 @@ impl Shown { | ||
enum Resp { | ||
Json(Json), | ||
Car(Vec<u8>), | ||
/// No answer, as a method with no output gives: `200` with an empty body. | ||
Nothing, | ||
Blob(blobs::Served), | ||
} | ||
| ||
/// An error as XRPC answers it: an HTTP status, a name and a message. | ||
| @@ -236,7 +279,8 @@ struct Call<'a> { | ||
method: &'a Method, | ||
params: &'a [(String, String)], | ||
body: &'a [u8], | ||
bearer: Option<&'a str>, | ||
/// What the `Authorization` header holds. | ||
bearer: sessions::Bearer<'a>, | ||
} | ||
| ||
/// A query's answer, given the call and its parameters; it notes in `Shown` | ||
| @@ -244,7 +288,7 @@ struct Call<'a> { | ||
type QueryFn = fn(&Service, &Call, &mut Shown, &Map<String, Json>) -> Result<Resp, XrpcError>; | ||
| ||
/// A repository write, once its input is checked, to apply to the repository its `repo` names. | ||
type Apply = Box<dyn FnOnce(&mut Repo) -> Result<Resp, XrpcError> + Send>; | ||
type Apply = Box<dyn FnOnce(&mut Store) -> Result<Resp, XrpcError> + Send>; | ||
| ||
/// A repository write: its input checked, the write to apply. | ||
type WriteFn = fn(&Map<String, Json>) -> Result<Apply, XrpcError>; | ||
| @@ -254,18 +298,31 @@ type Answer = Pin<Box<dyn Future<Output = Result<Resp, XrpcError>> + Send>>; | ||
/// Any other procedure, given its input. It runs to its end even if its caller goes away. | ||
type ProcedureFn = fn(Shared, Map<String, Json>) -> Answer; | ||
| ||
/// The token a procedure takes, checked: the session it is of, or the error to answer. | ||
type CheckFn = fn(&Service, sessions::Bearer) -> Result<sessions::Token, XrpcError>; | ||
| ||
/// A procedure that takes a token, given the token checked and its input. | ||
type AuthedFn = fn(Shared, sessions::Token, Map<String, Json>) -> Answer; | ||
| ||
/// A query that asks outside the server, given its parameters. | ||
type LookupFn = fn(Shared, Map<String, Json>) -> Answer; | ||
| ||
/// What answers a method. | ||
enum Handler { | ||
/// A query, which reads and changes nothing. | ||
Query(QueryFn), | ||
/// A query that waits on something outside the server, such as the PLC directory. | ||
Lookup(LookupFn), | ||
/// A write to the repository its `repo` names: only that account may make | ||
/// it, and its token is checked before its input, its `repo` after. | ||
Write(WriteFn), | ||
Procedure(ProcedureFn), | ||
/// A procedure that takes a token, checked before its input. | ||
Authed(CheckFn, AuthedFn), | ||
} | ||
| ||
/// Each area's methods: what answers a method, by its NSID, if the area has it. | ||
const AREAS: &[fn(&str) -> Option<Handler>] = &[server::handler, repo::handler, sync::handler]; | ||
const AREAS: &[fn(&str) -> Option<Handler>] = &[server::handler, sessions::handler, repo::handler, sync::handler, federation::handler, identity::handler, blobs::handler]; | ||
| ||
fn handler(nsid: &str) -> Option<Handler> { | ||
AREAS.iter().find_map(|area| area(nsid)) | ||
| @@ -281,25 +338,26 @@ pub fn run() { | ||
let port = var("PDS_PORT").parse::<u16>().unwrap_or_else(|_| fail("PDS_PORT is not a port".into())); | ||
let dir = var("PDS_DATA_DIR"); | ||
let config = Config::from_env().unwrap_or_else(|e| fail(e)); | ||
let svc = Service::open(FsPath::new(&dir), config).unwrap_or_else(|e| fail(format!("cannot recover {dir}: {e}"))); | ||
let svc = Arc::new(Service::open(FsPath::new(&dir), config).unwrap_or_else(|e| fail(format!("cannot recover {dir}: {e}")))); | ||
let app = Router::new() | ||
.route("/xrpc/com.atproto.sync.subscribeRepos", get(events::subscribe)) | ||
.route("/xrpc/com.atproto.repo.uploadBlob", any(blobs::upload)) | ||
.route("/xrpc/{nsid}", any(handle)) | ||
.route("/mcp", any(mcp::endpoint)) | ||
.with_state(Arc::new(svc)); | ||
.route("/.well-known/atproto-did", get(identity::well_known)) | ||
.with_state(svc.clone()); | ||
tokio::runtime::Runtime::new().unwrap().block_on(async { | ||
federation::tell_crawlers(&svc); | ||
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await.unwrap(); | ||
// Handle changes in flight when the server stopped are settled while it serves. | ||
identity::settle_unfinished(&svc); | ||
axum::serve(listener, app).await.unwrap(); | ||
}); | ||
} | ||
| ||
/// The bearer token a request's `Authorization` header carries. | ||
fn bearer(headers: &HeaderMap) -> Option<String> { | ||
headers | ||
.get(header::AUTHORIZATION) | ||
.and_then(|v| v.to_str().ok()) | ||
.and_then(|v| v.strip_prefix("Bearer ")) | ||
.map(str::to_string) | ||
/// A request's `Authorization` header, as text; one that is not is empty, which no scheme is. | ||
fn authorization(headers: &HeaderMap) -> Option<String> { | ||
headers.get(header::AUTHORIZATION).map(|v| v.to_str().unwrap_or_default().to_string()) | ||
} | ||
| ||
async fn handle( | ||
| @@ -310,11 +368,19 @@ async fn handle( | ||
Query(params): Query<Vec<(String, String)>>, | ||
body: Bytes, | ||
) -> Response { | ||
let bearer = bearer(&headers); | ||
let call = Call { nsid: &nsid, method: &method, params: ¶ms, body: &body, bearer: bearer.as_deref() }; | ||
match answer(&st, &call).await { | ||
let authorization = authorization(&headers); | ||
let bearer = sessions::Bearer::of(authorization.as_deref()); | ||
let call = Call { nsid: &nsid, method: &method, params: ¶ms, body: &body, bearer }; | ||
respond(answer(&st, &call).await) | ||
} | ||
| ||
/// An answer as XRPC sends it. | ||
fn respond(answer: Result<Resp, XrpcError>) -> Response { | ||
match answer { | ||
Ok(Resp::Json(j)) => (StatusCode::OK, [(header::CONTENT_TYPE, "application/json")], j.to_string()).into_response(), | ||
Ok(Resp::Car(b)) => (StatusCode::OK, [(header::CONTENT_TYPE, "application/vnd.ipld.car")], b).into_response(), | ||
Ok(Resp::Nothing) => StatusCode::OK.into_response(), | ||
Ok(Resp::Blob(b)) => blobs::response(b), | ||
Err(e) => ( | ||
StatusCode::from_u16(e.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR), | ||
[(header::CONTENT_TYPE, "application/json")], | ||
| @@ -339,11 +405,20 @@ async fn answer(svc: &Shared, call: &Call<'_>) -> Result<Resp, XrpcError> { | ||
shown.durable().await; | ||
out | ||
} | ||
Some(Handler::Lookup(f)) => { | ||
let p = m.parse_params(call.params.iter().map(|(k, v)| (k.as_str(), v.as_str()))).or_else(|e| invalid(e.0))?; | ||
tokio::spawn(f(svc.clone(), p)).await.unwrap_or_else(|_| internal()) | ||
} | ||
Some(Handler::Write(f)) => write_repo(svc, call, m, f).await, | ||
Some(Handler::Procedure(f)) => { | ||
let b = input(call, m)?; | ||
tokio::spawn(f(svc.clone(), b)).await.unwrap_or_else(|_| internal()) | ||
} | ||
Some(Handler::Authed(check, f)) => { | ||
let token = check(svc, call.bearer)?; | ||
let b = input(call, m)?; | ||
tokio::spawn(f(svc.clone(), token, b)).await.unwrap_or_else(|_| internal()) | ||
} | ||
None => err(501, "MethodNotImplemented", "Method not implemented"), | ||
} | ||
} | ||
| @@ -351,27 +426,23 @@ async fn answer(svc: &Shared, call: &Call<'_>) -> Result<Resp, XrpcError> { | ||
/// A write checks, in this order, its token, its input, its `repo`, then its | ||
/// records' `$type`. | ||
async fn write_repo(svc: &Shared, call: &Call<'_>, m: &pds_lexicon::Method, f: WriteFn) -> Result<Resp, XrpcError> { | ||
let did = match svc.auth(call.bearer) { | ||
Auth::Account(did) => did, | ||
Auth::None => return err(401, "AuthMissing", "Authentication Required"), | ||
Auth::Invalid => return invalid_token(), | ||
}; | ||
let did = svc.auth(call.bearer).did()?; | ||
let b = input(call, m)?; | ||
let apply = f(&b)?; | ||
let Some(account) = svc.account(required(&b, "repo")?) else { return err(403, "AccountNotFound", "Could not find account") }; | ||
if account.did != did { | ||
return err(401, "AuthenticationRequired", "Bad token scope"); | ||
} | ||
let (out, shown, landing) = { | ||
let (out, shown, landing, doomed) = { | ||
let mut st = write(&account.store); | ||
let st = &mut *st; | ||
st.repo.change = None; | ||
let out = apply(&mut st.repo); | ||
let out = apply(st); | ||
let landing = match (&out, st.repo.change.take()) { | ||
(Ok(_), Some(c)) => Some(log::log_commit(&svc.events, &account.did, st, &c)), | ||
_ => None, | ||
}; | ||
(out, Shown(vec![(st.wal.clone(), st.wal.written())]), landing) | ||
(out, Shown(vec![(st.wal.clone(), st.wal.written())]), landing, st.blobs.take_doomed()) | ||
}; | ||
// The write is in the log: the rest must happen even if the caller goes away, | ||
// or its event would never reach the firehose. | ||
| @@ -381,6 +452,7 @@ async fn write_repo(svc: &Shared, call: &Call<'_>, m: &pds_lexicon::Method, f: W | ||
if let Some(l) = landing { | ||
svc.events.land(l); | ||
} | ||
blobs::forget(&svc, &account, doomed); | ||
}); | ||
finish.await.expect("finishing a write, which aborts rather than fail"); | ||
out | ||
| @@ -402,8 +474,12 @@ fn method_of(call: &Call) -> Result<&'static pds_lexicon::Method, XrpcError> { | ||
Ok(m) | ||
} | ||
| ||
/// A procedure's input, checked against its lexicon. | ||
/// A procedure's input, checked against its lexicon. A procedure that takes | ||
/// none takes no body either. | ||
fn input(call: &Call, m: &pds_lexicon::Method) -> Result<Map<String, Json>, XrpcError> { | ||
if m.input.is_none() { | ||
return if call.body.is_empty() { Ok(Map::new()) } else { invalid("Request body is not allowed") }; | ||
} | ||
let Ok(input) = serde_json::from_slice::<Json>(call.body) else { return invalid("Invalid request body") }; | ||
m.check_input(&input).or_else(|e| invalid(e.0))?; | ||
let Json::Object(b) = input else { return invalid("Invalid request body") }; | ||
| @@ -471,6 +547,7 @@ mod testing { | ||
plc_url: plc_url.into(), | ||
rotation_key: k256::ecdsa::SigningKey::from_slice(&[9u8; 32]).unwrap(), | ||
recovery_did_key: Some("did:key:zQ3shokFTS3brHcDQrn82RUDfCZESWL1ZdCEJwekUDPQiYBme".into()), | ||
crawlers: vec![], | ||
} | ||
} | ||
| ||
| @@ -483,12 +560,20 @@ mod testing { | ||
Service::open(dir, config(plc_url)) | ||
} | ||
| ||
/// A call with a bearer token; a `null` body is none. | ||
pub async fn call_with(s: &Shared, nsid: &str, token: Option<&str>, params: &[(String, String)], body: Json) -> Result<Json, String> { | ||
let bearer = token.map_or(sessions::Bearer::None, sessions::Bearer::Token); | ||
call_raw(s, nsid, bearer, params, &if body.is_null() { String::new() } else { body.to_string() }).await | ||
} | ||
| ||
/// A call as sent: its `Authorization` header and body. A method's empty answer is `null`. | ||
pub async fn call_raw(s: &Shared, nsid: &str, bearer: sessions::Bearer<'_>, params: &[(String, String)], body: &str) -> Result<Json, String> { | ||
let method = if pds_lexicon::method(nsid).is_some_and(|m| m.kind == Kind::Query) { Method::GET } else { Method::POST }; | ||
let body = body.to_string(); | ||
match answer(s, &Call { nsid, method: &method, params, body: body.as_bytes(), bearer: token }).await { | ||
match answer(s, &Call { nsid, method: &method, params, body: body.as_bytes(), bearer }).await { | ||
Ok(Resp::Json(j)) => Ok(j), | ||
Ok(Resp::Car(_)) => Err("a CAR file".into()), | ||
Ok(Resp::Nothing) => Ok(Json::Null), | ||
Ok(Resp::Blob(_)) => Err("a blob".into()), | ||
Err(e) => Err(e.name.to_string()), | ||
} | ||
} | ||
crates/pds-server/src/log.rs+339−23
| @@ -2,16 +2,24 @@ | ||
//! `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 session given out; | ||
//! password hash, signing 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 | ||
//! one frame with its firehose events. | ||
//! one frame with its firehose events, the blobs it stored, and its handle | ||
//! changes: each recorded before its operation goes to the PLC directory, | ||
//! then settled, in one frame with its `#identity` event if it landed; | ||
//! - `repos/<did>/blobs/<cid>`, the bytes of each blob it holds (`blobs`). | ||
//! | ||
//! An account is in `accounts.log` before its repository's log exists: if | ||
//! the server stops between the two, it makes the repository's first commit | ||
//! when it starts again. Events are numbered in one sequence across all the | ||
//! accounts' logs (`events::Firehose`). | ||
//! accounts' logs (`events::Firehose`). An account's handle is the one its | ||
//! last landed change gave it, or else the one `accounts.log` has. | ||
| ||
use crate::blobs::{Blobs, blob_dir}; | ||
use crate::events::{self, Firehose, Landing}; | ||
use crate::sessions::{self, Sessions}; | ||
use crate::{Account, Config, Directory, Service, Store}; | ||
use axum::body::Bytes; | ||
use k256::ecdsa::SigningKey; | ||
| @@ -67,14 +75,17 @@ impl AccountEntry { | ||
| ||
/// The account, with its repository. | ||
pub fn account(self, store: Store) -> Account { | ||
Account { did: self.did, handle: self.handle, email: self.email, password: self.password, did_doc: self.did_doc, store: RwLock::new(store) } | ||
Account { | ||
did: self.did, | ||
handle: RwLock::new(self.handle), | ||
email: self.email, | ||
password: self.password, | ||
did_doc: RwLock::new(self.did_doc), | ||
store: RwLock::new(store), | ||
} | ||
} | ||
} | ||
| ||
pub(crate) fn session_entry(token: &str, did: &str) -> Json { | ||
json!({ "t": "session", "token": token, "did": did }) | ||
} | ||
| ||
pub(crate) fn commit_entry(c: &Change) -> Json { | ||
json!({ | ||
"t": "commit", "rev": c.rev, "head": hex::encode(&c.head_bytes), | ||
| @@ -87,6 +98,26 @@ fn event_entry(seq: u64, ord: u64, frame: &[u8]) -> Json { | ||
json!({ "t": "event", "seq": seq, "ord": ord, "frame": hex::encode(frame) }) | ||
} | ||
| ||
/// A handle change, recorded before its operation, by its CID, goes to the directory. | ||
pub(crate) fn handle_entry(handle: &str, cid: &str) -> Json { | ||
json!({ "t": "handle", "handle": handle, "cid": cid }) | ||
} | ||
| ||
/// Settle the account's handle change in flight, under its account's lock: | ||
/// it landed, with its `#identity` event in the same frame, or it was | ||
/// dropped. Answers the event to land once the log is on disk. | ||
pub(crate) fn log_settled(events: &Firehose, did: &str, st: &mut Store, cid: &str, landed: Option<&str>) -> Option<Landing> { | ||
let settled = json!({ "t": "handled", "cid": cid, "landed": landed.is_some() }); | ||
let Some(handle) = landed else { | ||
st.wal.append(&[settled]); | ||
return None; | ||
}; | ||
let (seq, ord) = events.reserve(1); | ||
let frame = events::identity_event(did, handle, seq, &events::timestamp()); | ||
st.wal.append(&[settled, event_entry(seq, ord, &frame)]); | ||
Some(Landing { seq, frames: vec![Bytes::from(frame)] }) | ||
} | ||
| ||
/// Log a commit made under its account's lock, with its event; land the | ||
/// event once the log is on disk. | ||
pub(crate) fn log_commit(events: &Firehose, did: &str, st: &mut Store, c: &Change) -> Landing { | ||
| @@ -121,6 +152,10 @@ struct Recovered { | ||
events: Vec<Event>, | ||
/// Whether it has no commit yet. | ||
fresh: bool, | ||
/// The handle its last landed change gave it. | ||
handle: Option<String>, | ||
/// A handle change recorded and not settled. | ||
pending: Option<crate::identity::Pending>, | ||
} | ||
| ||
/// Replay an account's log, or begin it. | ||
| @@ -129,7 +164,10 @@ fn open_repo(dir: &FsPath, a: &AccountEntry) -> Result<Recovered, String> { | ||
let (wal, frames) = Wal::open(&path).map_err(|e| format!("{}: {e}", path.display()))?; | ||
let mut repo = Repo::new(a.did.clone(), a.key.clone()); | ||
let mut events: Vec<Event> = Vec::new(); | ||
let mut blobs = Blobs::default(); | ||
let mut have_commit = false; | ||
let mut handle = None; | ||
let mut pending: Option<crate::identity::Pending> = None; | ||
let at = |why: String| format!("{}: {why}", path.display()); | ||
for e in frames.iter().flatten() { | ||
let text = |k: &str| e[k].as_str().map(str::to_string).ok_or_else(|| at(format!("a log entry with no {k}: {e}"))); | ||
| @@ -159,15 +197,35 @@ fn open_repo(dir: &FsPath, a: &AccountEntry) -> Result<Recovered, String> { | ||
..Default::default() | ||
}; | ||
repo.load(&c).map_err(at)?; | ||
blobs.committed(&repo, &c); | ||
have_commit = true; | ||
} | ||
Some("handle") => { | ||
if pending.is_some() || !have_commit { | ||
return Err(at(format!("a handle change while none could be made: {e}"))); | ||
} | ||
pending = Some(crate::identity::Pending { handle: text("handle")?, cid: text("cid")? }); | ||
} | ||
Some("handled") => { | ||
let (Some(p), Some(landed)) = (pending.take(), e["landed"].as_bool()) else { | ||
return Err(at(format!("a handle change settled that was not made: {e}"))); | ||
}; | ||
if e["cid"] != p.cid { | ||
return Err(at(format!("a handle change settled that was not the one made: {e}"))); | ||
} | ||
if landed { | ||
handle = Some(p.handle); | ||
} | ||
} | ||
Some("blob") => blobs.replay(e).map_err(at)?, | ||
t => return Err(at(format!("a log entry of no known type: {t:?}"))), | ||
} | ||
} | ||
if have_commit { | ||
repo.finish_load().map_err(at)?; | ||
} | ||
Ok(Recovered { store: Store { repo, wal: Arc::new(wal) }, events, fresh: !have_commit }) | ||
blobs.recover(&blob_dir(dir, &a.did))?; | ||
Ok(Recovered { store: Store { repo, wal: Arc::new(wal), blobs }, events, fresh: !have_commit, handle, pending }) | ||
} | ||
| ||
impl Service { | ||
| @@ -175,25 +233,24 @@ impl Service { | ||
pub(crate) fn open(dir: &FsPath, config: Config) -> Result<Service, String> { | ||
let (log, frames) = Wal::open(&dir.join(ACCOUNTS_LOG)).map_err(|e| format!("{ACCOUNTS_LOG}: {e}"))?; | ||
let mut accounts: Vec<AccountEntry> = Vec::new(); | ||
let mut directory = Directory::default(); | ||
let sessions = Sessions::open(dir, &config.hostname, frames.is_empty())?; | ||
for e in frames.iter().flatten() { | ||
let at = |why: String| format!("{ACCOUNTS_LOG}: {why}"); | ||
match e["t"].as_str() { | ||
Some("account") => { | ||
let a = AccountEntry::parse(e).map_err(at)?; | ||
if accounts.iter().any(|b| b.did == a.did || b.handle == a.handle || (a.email.is_some() && b.email == a.email)) { | ||
return Err(at(format!("a second account with the DID, handle or email of {}", a.did))); | ||
// Handles are checked once each account's own log has said what its handle is. | ||
if accounts.iter().any(|b| b.did == a.did || (a.email.is_some() && b.email == a.email)) { | ||
return Err(at(format!("a second account with the DID or email of {}", a.did))); | ||
} | ||
accounts.push(a); | ||
} | ||
Some("session") => { | ||
let (Some(token), Some(did)) = (e["token"].as_str(), e["did"].as_str()) else { | ||
return Err(at(format!("a session with no token or did: {e}"))); | ||
}; | ||
Some(t) if sessions::ENTRIES.contains(&t) => { | ||
let did = e["did"].as_str().unwrap_or_default(); | ||
if !accounts.iter().any(|a| a.did == did) { | ||
return Err(at(format!("a session of {did}, which no account has"))); | ||
return Err(at(format!("a {t} entry of {did:?}, which no account has"))); | ||
} | ||
directory.sessions.insert(token.to_string(), did.to_string()); | ||
sessions.replay(e).map_err(at)?; | ||
} | ||
t => return Err(at(format!("a log entry of no known type: {t:?}"))), | ||
} | ||
| @@ -204,6 +261,21 @@ impl Service { | ||
opening.into_iter().map(|h| h.join().unwrap_or_else(|_| Err("replaying a log panicked".into()))).collect() | ||
}); | ||
let mut recovered = recovered.into_iter().collect::<Result<Vec<_>, _>>()?; | ||
for (a, r) in accounts.iter_mut().zip(&mut recovered) { | ||
if let Some(h) = r.handle.take() { | ||
a.handle = h; | ||
} | ||
} | ||
// Each handle, an account's or one a change in flight holds, is one account's. | ||
let mut held: std::collections::HashMap<&str, &str> = std::collections::HashMap::new(); | ||
for (a, r) in accounts.iter().zip(&recovered) { | ||
let changing = r.pending.as_ref().map(|p| p.handle.as_str()).filter(|h| *h != a.handle); | ||
for h in std::iter::once(a.handle.as_str()).chain(changing) { | ||
if let Some(other) = held.insert(h, &a.did) { | ||
return Err(format!("{h} is the handle of both {other} and {}", a.did)); | ||
} | ||
} | ||
} | ||
// Number every event in `ord` order. | ||
let mut all: Vec<(&str, Event)> = | ||
accounts.iter().zip(&mut recovered).flat_map(|(a, r)| std::mem::take(&mut r.events).into_iter().map(|e| (a.did.as_str(), e))).collect(); | ||
| @@ -221,9 +293,11 @@ impl Service { | ||
config, | ||
dir: dir.to_path_buf(), | ||
log: Arc::new(log), | ||
directory: RwLock::new(directory), | ||
directory: RwLock::new(Directory::default()), | ||
sessions, | ||
events: Firehose::new(frames, offset), | ||
http: crate::plc::client().map_err(|e| format!("an HTTP client: {e}"))?, | ||
changes: crate::identity::Changes::default(), | ||
}; | ||
// An account whose repository has no commit yet gets its first. | ||
let mut d = crate::write(&svc.directory); | ||
| @@ -233,6 +307,14 @@ impl Service { | ||
r.store.wal.wait(r.store.wal.written()); | ||
svc.events.land(landing); | ||
} | ||
d.order.push(a.did.clone()); | ||
if let Some(p) = r.pending { | ||
// The handle stays taken until the change is settled. | ||
if p.handle != a.handle { | ||
d.claimed_handles.insert(p.handle.clone()); | ||
} | ||
svc.changes.unsettled(&a.did, p); | ||
} | ||
d.insert(Arc::new(a.account(r.store))); | ||
} | ||
drop(d); | ||
| @@ -250,13 +332,13 @@ mod tests { | ||
| ||
/// 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, String>, Vec<Vec<u8>>); | ||
type State = (BTreeMap<String, (Vec<u8>, 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 sessions = d.sessions.iter().map(|(t, did)| (t.clone(), did.clone())).collect(); | ||
drop(d); | ||
let sessions = s.sessions.snapshot(); | ||
let n = s.events.len(); | ||
(repos, sessions, s.events.get(0, n).iter().map(|e| e.to_vec()).collect()) | ||
} | ||
| @@ -394,17 +476,38 @@ mod tests { | ||
broken[at].push(bad.clone()); | ||
assert!(reopen(&alice, &broken).is_some(), "{bad}"); | ||
} | ||
for bad in [json!({ "t": "nonsense" }), json!({ "t": "session", "token": "t" }), json!({ "t": "session", "token": "t", "did": "did:plc:nobody" })] { | ||
let a = accounts[0].0.as_str(); | ||
let session = |did: &str, app: Json, scope: &str| json!({ "t": "session", "did": did, "id": "s", "app": app, "scope": scope, "exp": 1 }); | ||
for bad in [ | ||
json!({ "t": "nonsense" }), | ||
json!({ "t": "session", "did": a }), | ||
session("did:plc:nobody", Json::Null, "com.atproto.access"), | ||
session(a, Json::Null, "com.atproto.appPass"), | ||
session(a, json!("no such app password"), "com.atproto.appPass"), | ||
json!({ "t": "refresh", "did": a, "id": "not kept", "next": "n", "exp": 1, "nextExp": 2 }), | ||
json!({ "t": "endSession", "did": a, "id": "not kept" }), | ||
json!({ "t": "appPassword", "did": a, "name": "x", "hash": "h", "createdAt": "c" }), | ||
json!({ "t": "revokeAppPassword", "did": a, "name": "not had" }), | ||
] { | ||
let mut broken = frames(&accounts_log); | ||
broken[1].push(bad.clone()); | ||
assert!(reopen(&accounts_log, &broken).is_some(), "{bad}"); | ||
} | ||
// The same session twice. | ||
let mut twice = frames(&accounts_log); | ||
let first = twice[0].iter().find(|e| e["t"] == "session").unwrap().clone(); | ||
twice.push(vec![first]); | ||
assert!(reopen(&accounts_log, &twice).unwrap().contains("a second session")); | ||
// A second account with the first's handle. | ||
// A second account with the first's email, or its handle. | ||
let mut twice = frames(&accounts_log); | ||
let mut copy = twice[0][0].clone(); | ||
copy["did"] = json!("did:plc:another"); | ||
twice.push(vec![copy]); | ||
twice.push(vec![copy.clone()]); | ||
assert!(reopen(&accounts_log, &twice).unwrap().contains("a second account")); | ||
copy["email"] = json!("another@mail.com"); | ||
*twice.last_mut().unwrap() = vec![copy]; | ||
assert!(reopen(&accounts_log, &twice).unwrap().contains("is the handle of both")); | ||
let _ = std::fs::remove_dir_all(&dir); | ||
let _ = std::fs::remove_dir_all(&work); | ||
} | ||
| @@ -463,6 +566,134 @@ mod tests { | ||
let _ = std::fs::remove_dir_all(&work); | ||
} | ||
| ||
/// Cut `accounts.log` at every byte of each frame a change to sessions or | ||
/// app passwords wrote (and flip a byte in it): recovery must give the | ||
/// state before that change or after it. Each kind of entry is cut. | ||
#[tokio::test] | ||
async fn torn_session_writes() { | ||
let plc = plc().await; | ||
let dir = scratch("torn-sessions"); | ||
let s = open(&dir, &plc); | ||
let (alice, _) = create(&s, "alice").await; | ||
let mut steps = vec![Step { files: files(&dir), state: state(&s) }]; | ||
let snap = |s: &Service, steps: &mut Vec<Step>| steps.push(Step { files: files(&dir), state: state(s) }); | ||
let tokens = |got: Json| (got["accessJwt"].as_str().unwrap().to_string(), got["refreshJwt"].as_str().unwrap().to_string()); | ||
let login = |pw: &str| json!({ "identifier": "alice.test", "password": pw }); | ||
let (access, r0) = tokens(call(&s, "com.atproto.server.createSession", None, login("alice-pw")).await.unwrap()); | ||
snap(&s, &mut steps); | ||
let app = call(&s, "com.atproto.server.createAppPassword", Some(&access), json!({ "name": "phone", "privileged": true })).await.unwrap(); | ||
snap(&s, &mut steps); | ||
let (_, app_r0) = tokens(call(&s, "com.atproto.server.createSession", None, login(app["password"].as_str().unwrap())).await.unwrap()); | ||
snap(&s, &mut steps); | ||
let (_, r1) = tokens(call(&s, "com.atproto.server.refreshSession", Some(&r0), Json::Null).await.unwrap()); | ||
snap(&s, &mut steps); | ||
call(&s, "com.atproto.server.refreshSession", Some(&app_r0), Json::Null).await.unwrap(); | ||
snap(&s, &mut steps); | ||
call(&s, "com.atproto.server.deleteSession", Some(&r1), Json::Null).await.unwrap(); | ||
snap(&s, &mut steps); | ||
call(&s, "com.atproto.server.revokeAppPassword", Some(&access), json!({ "name": "phone" })).await.unwrap(); | ||
snap(&s, &mut steps); | ||
drop(s); | ||
let accounts_log = PathBuf::from(ACCOUNTS_LOG); | ||
let work = scratch("torn-sessions-work"); | ||
let mut kinds = Vec::new(); | ||
for w in steps.windows(2) { | ||
let changed: Vec<&PathBuf> = w[1].files.keys().filter(|p| w[0].files.get(*p) != w[1].files.get(*p)).collect(); | ||
assert_eq!(changed, [&accounts_log]); | ||
assert_ne!(w[0].state, w[1].state); | ||
let whole = &w[1].files[&accounts_log]; | ||
let (from, to) = (w[0].files[&accounts_log].len(), whole.len()); | ||
let (frames, _) = store::scan(&whole[from..]); | ||
kinds.extend(frames.iter().flatten().map(|e| e["t"].as_str().unwrap().to_string())); | ||
for cut in from..=to { | ||
let mut files = w[1].files.clone(); | ||
files.insert(accounts_log.clone(), whole[..cut].to_vec()); | ||
put_files(&work, &files); | ||
let want = if cut == to { &w[1].state } else { &w[0].state }; | ||
assert_eq!(&state(&open(&work, &plc)), want, "cut at {cut} of {from}..{to}"); | ||
} | ||
for at in (from..to).step_by(3) { | ||
let mut files = w[1].files.clone(); | ||
files.get_mut(&accounts_log).unwrap()[at] ^= 0x55; | ||
put_files(&work, &files); | ||
assert_eq!(&state(&open(&work, &plc)), &w[0].state, "flip at {at} of {from}..{to}"); | ||
} | ||
} | ||
kinds.sort(); | ||
kinds.dedup(); | ||
let mut want: Vec<&str> = crate::sessions::ENTRIES.to_vec(); | ||
want.sort(); | ||
assert_eq!(kinds, want); | ||
// After recovery from the last cut, the log takes changes, and replays them. | ||
put_files(&work, &steps.last().unwrap().files); | ||
let s = open(&work, &plc); | ||
call(&s, "com.atproto.server.createSession", None, login("alice-pw")).await.unwrap(); | ||
assert_eq!(state(&open(&work, &plc)), state(&s)); | ||
assert_ne!(state(&s).1[&alice], steps.last().unwrap().state.1[&alice]); | ||
let _ = std::fs::remove_dir_all(&dir); | ||
let _ = std::fs::remove_dir_all(&work); | ||
} | ||
| ||
/// An account's blobs, and the files of its blob directory. | ||
fn blob_state(s: &Service, dir: &Path, did: &str) -> (String, Vec<String>) { | ||
let held = crate::read(&s.account(did).unwrap().store).blobs.snapshot(); | ||
let mut names: Vec<String> = | ||
std::fs::read_dir(blob_dir(dir, did)).map(|d| d.map(|e| e.unwrap().file_name().into_string().unwrap()).collect()).unwrap_or_default(); | ||
names.sort(); | ||
(held, names) | ||
} | ||
| ||
/// Cut the account's log at every byte of each blob write: an upload, a | ||
/// commit referencing it, and one dropping it, with the files as they | ||
/// are while that frame is on its way. An upload's file is in place | ||
/// before its entry is written, and a dropped blob's file goes only once | ||
/// the commit is on disk, so through each write the blob's file is | ||
/// there. Recovery gives the blobs as before the write or after, and | ||
/// leaves no file no entry holds: a kill between a commit dropping a blob | ||
/// and the removal of its file loses no blob still held, and leaks none. | ||
#[tokio::test] | ||
async fn torn_blob_writes_recover_to_before_or_after() { | ||
let plc = plc().await; | ||
let dir = scratch("torn-blob-src"); | ||
let s = open(&dir, &plc); | ||
let (did, token) = create(&s, "alice").await; | ||
let log = repo_log(Path::new(""), &did); | ||
let blob = b"spec-pds blob torn".to_vec(); | ||
let cid = pds_repo::data::cid_string(&pds_repo::data::cid_of(0x55, &blob)); | ||
let snap = |s: &Service| (files(&dir), blob_state(s, &dir, &did)); | ||
let mut steps = vec![snap(&s)]; | ||
crate::blobs::test_upload(&s, Some(&token), Some("text/plain"), blob.clone(), false).await.unwrap(); | ||
steps.push(snap(&s)); | ||
let r = json!({ "f": { "$type": "blob", "ref": { "$link": cid }, "mimeType": "text/plain", "size": blob.len() } }); | ||
call(&s, "com.atproto.repo.putRecord", Some(&token), json!({ "repo": did, "collection": "a.b.c", "rkey": "a", "record": r })).await.unwrap(); | ||
steps.push(snap(&s)); | ||
call(&s, "com.atproto.repo.deleteRecord", Some(&token), json!({ "repo": did, "collection": "a.b.c", "rkey": "a" })).await.unwrap(); | ||
steps.push(snap(&s)); | ||
drop(s); | ||
assert_eq!(steps[1].1.1, vec![cid.clone()]); | ||
assert_eq!(steps[3].1.1, Vec::<String>::new()); | ||
let work = scratch("torn-blob-work"); | ||
let mut cuts = 0; | ||
for w in steps.windows(2) { | ||
let ((before_files, before), (after_files, after)) = (&w[0], &w[1]); | ||
let (from, to) = (before_files[&log].len(), after_files[&log].len()); | ||
assert!(to > from); | ||
let mut files = before_files.clone(); | ||
files.extend(after_files.clone()); | ||
for cut in from..=to { | ||
files.insert(log.clone(), after_files[&log][..cut].to_vec()); | ||
put_files(&work, &files); | ||
let s = open(&work, &plc); | ||
let want = if cut == to { after } else { before }; | ||
assert_eq!(&blob_state(&s, &work, &did), want, "cut at {cut} of {from}..{to}"); | ||
cuts += 1; | ||
} | ||
} | ||
assert!(cuts > 100, "{cuts}"); | ||
let _ = std::fs::remove_dir_all(&dir); | ||
let _ = std::fs::remove_dir_all(&work); | ||
} | ||
| ||
/// An account whose entry is cut short is not there; one whose entry is | ||
/// whole but whose repository's first frame is not starts with a fresh | ||
/// first commit, once. | ||
| @@ -499,6 +730,91 @@ mod tests { | ||
let _ = std::fs::remove_dir_all(&work); | ||
} | ||
| ||
/// A handle change writes two frames to its account's log: the change | ||
/// recorded, then settled with its `#identity` event. Cut at every byte | ||
/// of them (or with a byte of the second flipped), recovery gives the | ||
/// account before the change, with it recorded and not settled, or with | ||
/// it landed; and one recorded is settled, landing whole, once the | ||
/// server serves. | ||
#[tokio::test] | ||
async fn torn_handle_changes() { | ||
let plc = crate::identity::stub::Plc::start().await; | ||
let dir = scratch("torn-handle"); | ||
let s = open(&dir, &plc.url); | ||
let (alice, ta) = create(&s, "alice").await; | ||
create(&s, "bob").await; | ||
let before = files(&dir); | ||
let body = json!({ "handle": "carol.test" }); | ||
call(&s, "com.atproto.identity.updateHandle", Some(&ta), body).await.unwrap(); | ||
let after = files(&dir); | ||
let after_state = state(&s); | ||
drop(s); | ||
let path = repo_log(Path::new(""), &alice); | ||
let changed: Vec<&PathBuf> = after.keys().filter(|p| before.get(*p) != after.get(*p)).collect(); | ||
assert_eq!(changed, [&path]); | ||
let (from, to) = (before[&path].len(), after[&path].len()); | ||
let frames = store::scan(&after[&path]).0; | ||
let recorded = from + store::frame(&frames[frames.len() - 2]).len(); | ||
// What recovery gives: alice's handle, the handles held, and how many events. | ||
let identity = |s: &Service| { | ||
let d = crate::read(&s.directory); | ||
let mut held: Vec<String> = d.claimed_handles.iter().cloned().collect(); | ||
held.sort(); | ||
(d.by_did[&alice].handle(), held, s.events.len()) | ||
}; | ||
let n = after_state.2.len(); | ||
let work = scratch("torn-handle-work"); | ||
let mut unsettled = 0; | ||
let check = |files: BTreeMap<PathBuf, Vec<u8>>, at: String, cut: usize| { | ||
put_files(&work, &files); | ||
let s = open(&work, &plc.url); | ||
// Repositories and sessions are as they were throughout. | ||
let got = state(&s); | ||
assert_eq!((&got.0, &got.1), (&after_state.0, &after_state.1), "{at}"); | ||
let want = if cut < recorded { | ||
("alice.test".to_string(), vec![], n - 1) | ||
} else if cut < to { | ||
("alice.test".to_string(), vec!["carol.test".to_string()], n - 1) | ||
} else { | ||
("carol.test".to_string(), vec![], n) | ||
}; | ||
assert_eq!(identity(&s), want, "{at}"); | ||
if want.1.is_empty() { | ||
assert_eq!(state(&open(&work, &plc.url)), got, "{at}"); | ||
} | ||
s | ||
}; | ||
for cut in from..=to { | ||
let mut files = after.clone(); | ||
files.insert(path.clone(), after[&path][..cut].to_vec()); | ||
let s = check(files, format!("cut at {cut} of {from}..{to}"), cut); | ||
// One recorded and not settled lands whole once the server serves. | ||
if (recorded..to).contains(&cut) && (cut == recorded || cut % 23 == 0) { | ||
crate::identity::settle_unfinished(&s); | ||
for _ in 0..100 { | ||
if identity(&s).0 == "carol.test" { | ||
break; | ||
} | ||
tokio::time::sleep(std::time::Duration::from_millis(20)).await; | ||
} | ||
assert_eq!(identity(&s), ("carol.test".to_string(), vec![], n), "settling after a cut at {cut}"); | ||
drop(s); | ||
let s = open(&work, &plc.url); | ||
assert_eq!(identity(&s), ("carol.test".to_string(), vec![], n), "after settling a cut at {cut}"); | ||
unsettled += 1; | ||
} | ||
} | ||
for at in (recorded..to).step_by(3) { | ||
let mut files = after.clone(); | ||
files.get_mut(&path).unwrap()[at] ^= 0x55; | ||
check(files, format!("flip at {at} of {recorded}..{to}"), recorded); | ||
} | ||
assert!(unsettled > 3, "{unsettled}"); | ||
assert_eq!(plc.log(&alice).len(), 2); | ||
let _ = std::fs::remove_dir_all(&dir); | ||
let _ = std::fs::remove_dir_all(&work); | ||
} | ||
| ||
/// An event that never reached the disk, while a later one of another | ||
/// account's did: a restart numbers the events with no gap, the same | ||
/// way every time, and the next event follows on. | ||
crates/pds-server/src/mcp.rs+46−10
| @@ -1,9 +1,10 @@ | ||
//! The MCP endpoint, `POST /mcp`: Streamable HTTP for protocol version | ||
//! 2026-07-28, stateless, serving `server/discover`, `tools/list` and | ||
//! `tools/call`. Each method with a JSON answer is a tool (`spec/COMMANDS.md`), | ||
//! `tools/call`. Each method with a JSON answer, or none, is a tool (`spec/COMMANDS.md`), | ||
//! called through the same handling as XRPC. | ||
| ||
use crate::{Auth, Call, Resp, Shared, answer, bearer}; | ||
use crate::sessions::Bearer; | ||
use crate::{Auth, Call, Resp, Shared, answer, authorization}; | ||
use axum::body::Bytes; | ||
use axum::extract::State; | ||
use axum::http::{HeaderMap, HeaderValue, Method, StatusCode, header}; | ||
| @@ -181,7 +182,7 @@ async fn request(st: &Shared, headers: &HeaderMap, method: &str, params: Option< | ||
if header_name != name { | ||
return Err(mismatch("Mcp-Name", &header_name, name)); | ||
} | ||
call_tool(st, name, params.get("arguments"), bearer(headers)).await | ||
call_tool(st, name, params.get("arguments"), authorization(headers)).await | ||
} | ||
} | ||
} | ||
| @@ -228,8 +229,10 @@ fn param_text(v: &Json) -> String { | ||
} | ||
} | ||
| ||
/// Call a tool's method, with its arguments as the query's parameters or the procedure's input. | ||
async fn call_tool(st: &Shared, name: &str, arguments: Option<&Json>, token: Option<String>) -> Result<Json, RpcError> { | ||
/// Call a tool's method, with its arguments as the query's parameters or the | ||
/// procedure's input, and the request's `Authorization` header. | ||
async fn call_tool(st: &Shared, name: &str, arguments: Option<&Json>, authorization: Option<String>) -> Result<Json, RpcError> { | ||
let bearer = Bearer::of(authorization.as_deref()); | ||
let Some(m): Option<&'static Lexicon> = pds_lexicon::by_tool(name) else { | ||
return Err(rpc_err(StatusCode::OK, INVALID_PARAMS, format!("Unknown tool: {name}"))); | ||
}; | ||
| @@ -240,7 +243,7 @@ async fn call_tool(st: &Shared, name: &str, arguments: Option<&Json>, token: Opt | ||
}; | ||
// 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()) { | ||
if let Auth::Account(did) = st.auth(bearer) { | ||
for a in m.args.iter().filter(|a| a.names_account()) { | ||
args.entry(a.name.clone()).or_insert_with(|| json!(did)); | ||
} | ||
| @@ -254,14 +257,17 @@ async fn call_tool(st: &Shared, name: &str, arguments: Option<&Json>, token: Opt | ||
v => params.push((k.clone(), param_text(v))), | ||
} | ||
} | ||
} else { | ||
} else if m.input.is_some() || !args.is_empty() { | ||
// A procedure that takes no input is sent none, unless given arguments, which it refuses. | ||
body = Json::Object(args).to_string(); | ||
} | ||
let call = Call { nsid: &m.nsid, method: &method, params: ¶ms, body: body.as_bytes(), bearer: token.as_deref() }; | ||
let call = Call { nsid: &m.nsid, method: &method, params: ¶ms, body: body.as_bytes(), bearer }; | ||
let (content, is_error) = match answer(st, &call).await { | ||
// A method that answers nothing answers `{}`. | ||
Ok(_) if m.output.is_none() => (json!({}), false), | ||
Ok(Resp::Json(j)) => (j, false), | ||
// No method with a tool answers anything but JSON. | ||
Ok(Resp::Car(_)) => (json!({ "error": "InternalServerError", "message": "a tool's method answered a CAR file" }), true), | ||
// No other method with a tool answers anything but JSON. | ||
Ok(Resp::Car(_) | Resp::Blob(_) | Resp::Nothing) => (json!({ "error": "InternalServerError", "message": "a tool's method answered no JSON" }), true), | ||
Err(e) => (json!({ "error": e.name, "message": e.message }), true), | ||
}; | ||
Ok(json!({ | ||
| @@ -287,6 +293,36 @@ mod tests { | ||
} | ||
} | ||
| ||
/// A method that answers nothing is a tool answering `{}`; given | ||
/// arguments it takes none of, it refuses them as XRPC refuses a body. | ||
#[tokio::test] | ||
async fn no_answer_is_empty_object() { | ||
use crate::testing::*; | ||
let plc = plc().await; | ||
let dir = scratch("mcp-nothing"); | ||
let s = open(&dir, &plc); | ||
create(&s, "alice").await; | ||
let got = call(&s, "com.atproto.server.createSession", None, json!({ "identifier": "alice.test", "password": "alice-pw" })).await.unwrap(); | ||
let refresh = format!("Bearer {}", got["refreshJwt"].as_str().unwrap()); | ||
let tool = |name: &'static str, args: Option<Json>| { | ||
let (s, refresh) = (s.clone(), refresh.clone()); | ||
async move { | ||
match call_tool(&s, name, args.as_ref(), Some(refresh)).await { | ||
Ok(r) => r, | ||
Err(e) => panic!("{name}: {}", e.message), | ||
} | ||
} | ||
}; | ||
let refused = tool("server_delete_session", Some(json!({ "x": 1 }))).await; | ||
assert_eq!((&refused["isError"], &refused["structuredContent"]["error"]), (&json!(true), &json!("InvalidRequest"))); | ||
for args in [None, Some(json!({}))] { | ||
let r = tool("server_delete_session", args).await; | ||
assert_eq!((&r["isError"], &r["structuredContent"]), (&json!(false), &json!({}))); | ||
assert_eq!(r["content"], json!([{ "type": "text", "text": "{}" }])); | ||
} | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
| ||
#[test] | ||
fn header_values() { | ||
assert_eq!(decoded("repo_get_record").as_deref(), Some("repo_get_record")); | ||
crates/pds-server/src/plc.rs+199−22
| @@ -1,6 +1,7 @@ | ||
//! 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`). | ||
//! `PDS_PLC_URL` (`spec/ACCOUNTS.md`); and the update operations that change | ||
//! an account's handle (`spec/IDENTITY.md`). | ||
| ||
use crate::Config; | ||
use base64::Engine; | ||
| @@ -28,16 +29,32 @@ pub struct Genesis { | ||
pub op: Json, | ||
} | ||
| ||
/// The rotation keys of the DIDs the server creates: `PDS_RECOVERY_DID_KEY` | ||
/// if set, then its own rotation key, each a `did:key`. | ||
pub fn rotation_keys(config: &Config) -> Vec<String> { | ||
let rotation = did_key(config.rotation_key.verifying_key()); | ||
let mut keys: Vec<String> = config.recovery_did_key.iter().filter(|k| **k != rotation).cloned().collect(); | ||
keys.push(rotation); | ||
keys | ||
} | ||
| ||
/// Sign an operation's fields with the server's rotation key: the DAG-CBOR | ||
/// of the operation without `sig`, signed in low-S form, as base64url. | ||
fn sign(config: &Config, mut fields: Vec<(String, V)>) -> V { | ||
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(), V::Str(URL_SAFE_NO_PAD.encode(sig.to_bytes())))); | ||
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 { | ||
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![ | ||
let fields = vec![ | ||
("type".to_string(), s("plc_operation")), | ||
("rotationKeys".to_string(), V::Arr(rotation_keys)), | ||
("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)))])), | ||
("alsoKnownAs".to_string(), V::Arr(vec![s(&format!("at://{handle}"))])), | ||
( | ||
| @@ -49,14 +66,52 @@ pub fn genesis(config: &Config, signing: &VerifyingKey, handle: &str) -> Genesis | ||
), | ||
("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); | ||
let signed = sign(config, fields); | ||
Genesis { did: did_of(&encode(&signed)), op: to_json(&signed) } | ||
} | ||
| ||
/// The CID of an operation as the directory has it: of its DAG-CBOR, as | ||
/// `atproto/did-plc.md` makes `prev`. | ||
pub fn cid(op: &Json) -> Result<String, String> { | ||
Ok(cid_string(&cid_of(0x71, &encode(&from_json(op)?)))) | ||
} | ||
| ||
/// The update operation that gives a DID `handle`, built on `last`, the | ||
/// DID's last operation: its fields, with `prev` its CID and `alsoKnownAs` | ||
/// changed and nothing else, its first `at://` entry `at://<handle>` (or, | ||
/// with none, `at://<handle>` first); signed with the server's rotation key. | ||
pub fn update(config: &Config, last: &Json, handle: &str) -> Result<Json, String> { | ||
if last["type"] != "plc_operation" { | ||
return Err(format!("the DID's last operation is not a plc_operation: {last}")); | ||
} | ||
let prev = cid(last)?; | ||
let V::Map(fields) = from_json(last)? else { return Err("an operation that is not an object".into()) }; | ||
let at = V::Str(format!("at://{handle}")); | ||
let mut out = Vec::with_capacity(fields.len()); | ||
for (k, v) in fields { | ||
match (k.as_str(), v) { | ||
("sig", _) => {} | ||
("prev", _) => out.push((k, V::Str(prev.clone()))), | ||
("alsoKnownAs", V::Arr(mut aka)) => { | ||
match aka.iter().position(|u| matches!(u, V::Str(u) if u.starts_with("at://"))) { | ||
Some(i) => aka[i] = at.clone(), | ||
None => aka.insert(0, at.clone()), | ||
} | ||
out.push((k, V::Arr(aka))); | ||
} | ||
("alsoKnownAs", _) => return Err(format!("an operation whose alsoKnownAs is not a list: {last}")), | ||
(_, v) => out.push((k, v)), | ||
} | ||
} | ||
if !out.iter().any(|(k, _)| k == "alsoKnownAs") { | ||
out.push(("alsoKnownAs".to_string(), V::Arr(vec![at]))); | ||
} | ||
if !out.iter().any(|(k, _)| k == "prev") { | ||
out.push(("prev".to_string(), V::Str(prev))); | ||
} | ||
Ok(to_json(&sign(config, out))) | ||
} | ||
| ||
/// 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]) | ||
| @@ -76,9 +131,9 @@ pub fn client() -> reqwest::Result<reqwest::Client> { | ||
.build() | ||
} | ||
| ||
/// The DID document the directory serves at `url`, or None if it serves none. | ||
/// The JSON the directory serves at `url`, or None if it serves none (404). | ||
/// 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> { | ||
pub(crate) 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}"))?, | ||
| @@ -88,10 +143,57 @@ async fn document(http: &reqwest::Client, url: &str) -> Result<Option<Json>, Str | ||
return Ok(None); | ||
} | ||
if !res.status().is_success() { | ||
return Err(format!("{url} answered {} for the DID document", res.status())); | ||
return Err(format!("{url} answered {}", 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}")) | ||
serde_json::from_slice(&bytes).map(Some).map_err(|e| format!("the JSON at {url}: {e}")) | ||
} | ||
| ||
/// Why the directory did not take an update operation. | ||
pub enum Upstream { | ||
/// It answered, refusing it, with this message. | ||
Refused(String), | ||
/// It could not be reached; `sent` if the request may have reached it. | ||
Unreachable { why: String, sent: bool }, | ||
} | ||
| ||
fn url_of(plc_url: &str, did: &str) -> String { | ||
format!("{}/{did}", plc_url.trim_end_matches('/')) | ||
} | ||
| ||
/// The DID's last operation, as `GET <PLC>/<did>/log/last` answers it. | ||
pub async fn last_operation(http: &reqwest::Client, plc_url: &str, did: &str) -> Result<Json, Upstream> { | ||
let url = format!("{}/log/last", url_of(plc_url, did)); | ||
match document(http, &url).await { | ||
Ok(Some(op)) => Ok(op), | ||
Ok(None) => Err(Upstream::Refused(format!("the directory has no operation for {did}"))), | ||
Err(why) => Err(Upstream::Unreachable { why, sent: false }), | ||
} | ||
} | ||
| ||
/// Post an update operation for `did`. | ||
pub async fn post(http: &reqwest::Client, plc_url: &str, did: &str, op: &Json) -> Result<(), Upstream> { | ||
let url = url_of(plc_url, did); | ||
match http.post(&url).header(reqwest::header::CONTENT_TYPE, "application/json").body(op.to_string()).send().await { | ||
Ok(res) if res.status().is_success() => Ok(()), | ||
Ok(res) => { | ||
let status = res.status(); | ||
let text = res.text().await.unwrap_or_default(); | ||
// The directory says why as `{message}`. | ||
let message = serde_json::from_str::<Json>(&text).ok().and_then(|j| j["message"].as_str().map(str::to_string)); | ||
Err(Upstream::Refused(message.unwrap_or_else(|| format!("{status} {text}")))) | ||
} | ||
Err(e) => Err(Upstream::Unreachable { why: format!("posting to {url}: {e}"), sent: !e.is_connect() }), | ||
} | ||
} | ||
| ||
/// Whether the directory's log of `did` holds the operation with this CID, | ||
/// as `GET <PLC>/<did>/log/audit` lists them. | ||
pub async fn holds(http: &reqwest::Client, plc_url: &str, did: &str, cid: &str) -> Result<bool, String> { | ||
let url = format!("{}/log/audit", url_of(plc_url, did)); | ||
let log = document(http, &url).await?.unwrap_or_default(); | ||
let entries = log.as_array().ok_or_else(|| format!("{url} is not a list: {log}"))?; | ||
Ok(entries.iter().any(|e| e["cid"] == cid)) | ||
} | ||
| ||
/// Register a genesis operation with the directory, and answer the DID | ||
| @@ -137,11 +239,37 @@ pub fn parse_did_key(k: &str) -> Option<VerifyingKey> { | ||
/// 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 { | ||
if did_of(&encode(&from_json(op)?)) != did { | ||
return Err(format!("the operation does not make {did}")); | ||
} | ||
signer(op, &op["rotationKeys"]).map(|_| ()) | ||
} | ||
| ||
/// Check an update operation as a directory would: its `prev` the CID of | ||
/// `last`, and signed, in low-S form, by one of `last`'s rotation keys. | ||
/// Answers the `did:key` that signed it. | ||
#[cfg(test)] | ||
pub fn verify_update(last: &Json, op: &Json) -> Result<String, String> { | ||
if op["prev"] != cid(last)? { | ||
return Err(format!("prev is {}, not the CID of the last operation", op["prev"])); | ||
} | ||
signer(op, &last["rotationKeys"]) | ||
} | ||
| ||
/// An operation signed again with the server's rotation key, as a test | ||
/// posts one of its own. | ||
#[cfg(test)] | ||
pub fn signed(config: &Config, op: &Json) -> Json { | ||
let V::Map(fields) = from_json(op).expect("an operation in the data model") else { panic!("an operation that is not an object") }; | ||
to_json(&sign(config, fields.into_iter().filter(|(k, _)| k != "sig").collect())) | ||
} | ||
| ||
/// Which of `keys` signed `op`, as `atproto/did-plc.md` asks: the DAG-CBOR | ||
/// of the operation without `sig`, and a low-S signature in base64url. | ||
#[cfg(test)] | ||
fn signer(op: &Json, keys: &Json) -> Result<String, String> { | ||
use k256::ecdsa::signature::hazmat::PrehashVerifier; | ||
let V::Map(mut fields) = from_json(op)? else { return Err("not an object".into()) }; | ||
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())?; | ||
| @@ -150,11 +278,11 @@ pub fn verify(did: &str, op: &Json) -> Result<(), String> { | ||
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")?; | ||
let keys = keys.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(()) | ||
.filter_map(Json::as_str) | ||
.find(|k| parse_did_key(k).is_some_and(|key| key.verify_prehash(&hash, &sig).is_ok())) | ||
.map(str::to_string) | ||
.ok_or_else(|| "no rotation key signed it".into()) | ||
} | ||
| ||
| @@ -218,6 +346,55 @@ mod tests { | ||
assert_eq!(genesis(&alone, signing.verifying_key(), "alice.test").op["rotationKeys"], json!([rotation])); | ||
} | ||
| ||
/// An update operation as `atproto/did-plc.md` says: the last | ||
/// operation's fields, `prev` its CID, `alsoKnownAs` changed and nothing | ||
/// else, signed by the server's rotation key. | ||
#[test] | ||
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 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(); | ||
let bytes = parse_cid(prev).unwrap(); | ||
assert_eq!(bytes[..4], [1, 0x71, 0x12, 0x20]); | ||
assert_eq!(bytes[4..], Sha256::digest(encode(&from_json(&g.op).unwrap()))[..]); | ||
let mut want = g.op.clone(); | ||
want["prev"] = json!(prev); | ||
want["alsoKnownAs"] = json!(["at://carol.test"]); | ||
want["sig"] = op["sig"].clone(); | ||
assert_eq!(op, want); | ||
assert_eq!(verify_update(&g.op, &op).unwrap(), did_key(config.rotation_key.verifying_key())); | ||
// Built on it again, `prev` is its CID; a change to any field breaks the signature. | ||
let next = update(&config, &op, "dave.test").unwrap(); | ||
assert_eq!(next["prev"], json!(cid(&op).unwrap())); | ||
verify_update(&op, &next).unwrap(); | ||
assert!(verify_update(&g.op, &next).is_err()); | ||
let mut tampered = op.clone(); | ||
tampered["services"]["atproto_pds"]["endpoint"] = json!("https://elsewhere.test"); | ||
assert!(verify_update(&g.op, &tampered).is_err()); | ||
// The first `at://` entry changes, wherever it is; with none, one goes first. | ||
for (aka, after) in [ | ||
(json!(["at://alice.test", "https://alice.example.com"]), json!(["at://carol.test", "https://alice.example.com"])), | ||
(json!(["https://alice.example.com", "at://alice.test", "at://old.test"]), json!(["https://alice.example.com", "at://carol.test", "at://old.test"])), | ||
(json!(["https://alice.example.com"]), json!(["at://carol.test", "https://alice.example.com"])), | ||
(json!([]), json!(["at://carol.test"])), | ||
] { | ||
let mut last = g.op.clone(); | ||
last["alsoKnownAs"] = aka; | ||
last["prev"] = json!(cid(&g.op).unwrap()); | ||
let op = update(&config, &last, "carol.test").unwrap(); | ||
assert_eq!(op["alsoKnownAs"], after); | ||
assert_eq!(op["rotationKeys"], last["rotationKeys"]); | ||
assert_eq!(op["verificationMethods"], last["verificationMethods"]); | ||
assert_eq!(op["services"], last["services"]); | ||
assert_eq!(op["prev"], json!(cid(&last).unwrap())); | ||
} | ||
// A tombstone cannot be built on. | ||
assert!(update(&config, &json!({ "type": "plc_tombstone", "prev": prev, "sig": "x" }), "carol.test").is_err()); | ||
} | ||
| ||
/// How the stub directory loses the first operation posted to it. | ||
#[derive(Clone, Copy, PartialEq)] | ||
enum Lose { | ||
crates/pds-server/src/repo.rs+32−23
crates/pds-server/src/server.rs+37−43
crates/pds-server/src/sessions.rsnew+970−0
970 lines changed: not loaded until asked for.
crates/pds-server/src/sync.rs+1−1
crates/pds-server/Cargo.toml+2−0
harness/checks/accounts.mjs+7−7
harness/checks/blobs.mjsnew+589−0
589 lines changed: not loaded until asked for.
harness/checks/commands.mjs+1−1
harness/checks/crashes.mjs+16−5
harness/checks/federation.mjsnew+309−0
harness/checks/firehose.mjs+16−5
harness/checks/identity.mjsnew+362−0
harness/checks/sessions.mjsnew+450−0
450 lines changed: not loaded until asked for.