~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0

Hardening: limits, quotas, invite codes and rate limits, from a security review

Merged chadtmiller.com asked to merge into main from chadtmiller.com/monolith:harden-h
crates/pds-cli/src/lib.rs+6−1
@@ -243,6 +243,8 @@ fn param_text(v: &Json) -> String {
struct Server {
url: String,
token: Option<String>,
/// The admin's password, sent as `Basic` auth when there is no token.
admin: Option<String>,
http: reqwest::blocking::Client,
}
@@ -269,6 +271,8 @@ impl Server {
};
if let Some(t) = &self.token {
req = req.bearer_auth(t);
} else if let Some(password) = &self.admin {
req = req.basic_auth("admin", Some(password));
}
req.send().map_err(|e| Stop::Unreachable(format!("cannot reach {}: {e}", self.url)))
}
@@ -318,7 +322,8 @@ fn call(m: &Method, mut args: Map<String, Json>) -> Result<u8, Stop> {
}
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, http };
let admin = std::env::var("PDS_ADMIN_PASSWORD").ok();
let server = Server { url: url.trim_end_matches('/').to_string(), token, admin, 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()? {
crates/pds-lexicon/src/lib.rs+1−1
@@ -516,7 +516,7 @@ mod tests {
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(), 23, "{tools:?}");
assert_eq!(tools.len(), 26, "{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"] {
crates/pds-repo/src/lib.rs+251−55
@@ -21,8 +21,15 @@ pub enum Refused {
Exists(String),
/// An update or delete of a record that does not exist, by path.
Missing(String),
/// A commit whose `#commit` event would carry more than
/// `MAX_EVENT_BLOCKS` bytes of blocks.
TooBig,
}
/// The most bytes of blocks a commit's `#commit` event may carry, as
/// `subscribeRepos`'s lexicon says.
pub const MAX_EVENT_BLOCKS: usize = 2_000_000;
const TID_CHARS: &[u8; 32] = b"234567abcdefghijklmnopqrstuvwxyz";
pub struct Tids {
@@ -95,6 +102,44 @@ pub struct Change {
/// The CIDs of the blocks, records and tree nodes, that the repository
/// holds after this commit and did not before.
pub added: Vec<Vec<u8>>,
/// The repository as it was before the commit, to put back should the
/// commit not reach its log.
pub undo: Option<Undo>,
}
/// Where a block the repository holds is: a record, by its path, or a tree
/// node, with its bytes.
enum At {
Record(String),
Node(Vec<u8>),
}
/// A block the repository holds but its commit: the rev of the commit that
/// added it, and where it is.
struct Held {
rev: String,
at: At,
}
/// A repository as it was before a commit.
pub struct Undo {
/// Each record the commit wrote or deleted, as it was.
records: BTreeMap<String, Option<Record>>,
rev: String,
head: Vec<u8>,
head_bytes: Vec<u8>,
tree: mst::Node,
held: HashMap<Vec<u8>, Held>,
}
/// A commit made and not yet put in place.
struct Made {
rev: String,
tree: mst::Node,
held: HashMap<Vec<u8>, Held>,
head: Vec<u8>,
head_bytes: Vec<u8>,
change: Change,
}
pub struct Repo {
@@ -108,9 +153,12 @@ pub struct Repo {
tree: mst::Node,
pub tids: Tids,
pub change: Option<Change>,
/// Every block the repository holds but its commit, by CID, with the rev
/// of the commit that added it.
held: HashMap<Vec<u8>, String>,
/// Every block the repository holds but its commit, by CID: the index
/// `blocks_car` reads, and when each was added.
held: HashMap<Vec<u8>, Held>,
/// The rev of the commit that added each block, as a log replays it,
/// until `finish_load` makes `held` of it.
loaded: HashMap<Vec<u8>, String>,
}
impl Repo {
@@ -128,12 +176,14 @@ impl Repo {
tids: Tids::new(),
change: None,
held: HashMap::new(),
loaded: HashMap::new(),
}
}
/// The first commit of a new repository: the empty tree.
pub fn init(&mut self) -> Change {
self.commit(vec![])
let made = self.make(vec![]);
self.install(made, BTreeMap::new())
}
/// The public key of the key that signs its commits.
@@ -150,27 +200,38 @@ impl Repo {
self.records.iter().map(|(k, r)| (k.as_bytes().to_vec(), r.cid.clone())).collect()
}
/// Rebuild the tree and sign a new commit over it, for these ops.
fn commit(&mut self, ops: Vec<EvOp>) -> Change {
/// Every block of `tree` and of the records, each once, where it is,
/// with the rev `rev_of` gives it.
fn index(&self, tree: &mst::Node, mut rev_of: impl FnMut(&[u8]) -> String) -> HashMap<Vec<u8>, Held> {
let nodes = tree.nodes();
let mut held = HashMap::with_capacity(nodes.len() + self.records.len());
for n in nodes {
if !held.contains_key(&n.cid) {
held.insert(n.cid.clone(), Held { rev: rev_of(&n.cid), at: At::Node(n.bytes.clone()) });
}
}
for (path, r) in &self.records {
if !held.contains_key(&r.cid) {
held.insert(r.cid.clone(), Held { rev: rev_of(&r.cid), at: At::Record(path.clone()) });
}
}
held
}
/// Rebuild the tree and sign a new commit over it, for these ops,
/// changing nothing but the TIDs given out.
fn make(&mut self, ops: Vec<EvOp>) -> Made {
let tree = mst::build_tree(&self.entries());
let first = self.rev.is_empty();
let rev = self.tids.next();
let nodes = tree.nodes();
let mut held = HashMap::with_capacity(nodes.len() + self.records.len());
let mut added = Vec::new();
for cid in nodes.iter().map(|n| &n.cid).chain(self.records.values().map(|r| &r.cid)) {
if held.contains_key(cid) {
continue;
let held = self.index(&tree, |cid| match self.held.get(cid) {
Some(h) => h.rev.clone(),
None => {
added.push(cid.to_vec());
rev.clone()
}
let since = match self.held.remove(cid) {
Some(r) => r,
None => {
added.push(cid.clone());
rev.clone()
}
};
held.insert(cid.clone(), since);
}
});
let before = (!first).then_some(&self.tree);
let mut blocks: Vec<Block> = mst::event_nodes(before, &tree, ops.iter().map(|o| o.path.as_bytes()))
.into_iter()
@@ -197,7 +258,6 @@ impl Repo {
let sig: k256::ecdsa::Signature = self.key.sign_prehash(&hash).expect("signing a 32-byte digest");
let sig = sig.normalize_s().unwrap_or(sig);
let bytes = encode(&unsigned(Some(sig.to_bytes().to_vec())));
drop(nodes);
let change = Change {
rev: rev.clone(),
head_bytes: bytes.clone(),
@@ -208,14 +268,39 @@ impl Repo {
added,
..Default::default()
};
self.head = cid_of(0x71, &bytes);
self.held = held;
self.head_bytes = bytes;
self.tree = tree;
self.rev = rev;
Made { rev, tree, held, head: cid_of(0x71, &bytes), head_bytes: bytes, change }
}
/// Put a commit made in place; its change keeps what it replaced.
fn install(&mut self, m: Made, records: BTreeMap<String, Option<Record>>) -> Change {
let mut change = m.change;
change.undo = Some(Undo {
records,
rev: std::mem::replace(&mut self.rev, m.rev),
head: std::mem::replace(&mut self.head, m.head),
head_bytes: std::mem::replace(&mut self.head_bytes, m.head_bytes),
tree: std::mem::replace(&mut self.tree, m.tree),
held: std::mem::replace(&mut self.held, m.held),
});
change
}
/// Put the repository back as it was before the commit `undo` came with.
pub fn undo(&mut self, u: Undo) {
for (k, old) in u.records {
match old {
Some(r) => self.records.insert(k, r),
None => self.records.remove(&k),
};
}
self.rev = u.rev;
self.head = u.head;
self.head_bytes = u.head_bytes;
self.tree = u.tree;
self.held = u.held;
self.change = None;
}
/// Replay a logged change to the records; `finish_load` then rebuilds the tree.
pub fn load(&mut self, c: &Change) -> Result<(), String> {
for (path, j) in &c.puts {
@@ -226,7 +311,7 @@ impl Repo {
}
self.rev = c.rev.clone();
for cid in &c.added {
self.held.insert(cid.clone(), c.rev.clone());
self.loaded.insert(cid.clone(), c.rev.clone());
}
self.head_bytes = c.head_bytes.clone();
Ok(())
@@ -247,9 +332,9 @@ impl Repo {
if field("rev") != Some(&V::Str(self.rev.clone())) {
return Err(format!("the latest commit is not rev {}", self.rev));
}
let current: HashSet<&[u8]> =
self.tree.nodes().into_iter().map(|n| n.cid.as_slice()).chain(self.records.values().map(|r| r.cid.as_slice())).collect();
self.held.retain(|cid, _| current.contains(cid.as_slice()));
let loaded = std::mem::take(&mut self.loaded);
// A block whose adding no entry names was added before any `since` asks after.
self.held = self.index(&self.tree, |cid| loaded.get(cid).cloned().unwrap_or_default());
self.head = cid_of(0x71, &self.head_bytes);
self.tids.after(&self.rev);
self.change = None;
@@ -267,7 +352,8 @@ impl Repo {
/// 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.
/// commit and changes nothing. A commit whose event would carry more than
/// `MAX_EVENT_BLOCKS` bytes of blocks is refused too.
pub fn apply_checked<E: From<Refused>>(
&mut self,
ops: Vec<Op>,
@@ -290,7 +376,12 @@ impl Repo {
}
}
}
if let Some(e) = refused.map_or_else(|| check().err(), Some) {
let mut refused = refused.map_or_else(|| check().err(), Some);
let made = refused.is_none().then(|| self.make(evops));
if made.as_ref().is_some_and(|m| event_blocks_len(&m.head, &m.head_bytes, &m.change.blocks) > MAX_EVENT_BLOCKS) {
refused = Some(Refused::TooBig.into());
}
if let Some(e) = refused {
for (k, old) in originals {
match old {
Some(r) => self.records.insert(k, r),
@@ -299,9 +390,11 @@ impl Repo {
}
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();
let puts = originals.keys().filter_map(|k| self.records.get(k).map(|r| (k.clone(), to_json(&r.value)))).collect();
let dels = originals.keys().filter(|k| !self.records.contains_key(*k)).cloned().collect();
let mut change = self.install(made.expect("a commit made"), originals);
change.puts = puts;
change.dels = dels;
self.change = Some(change);
Ok(results)
}
@@ -365,7 +458,7 @@ impl Repo {
/// only the blocks it holds now that commits after rev `since` added: none
/// when `since` is the latest rev.
pub fn car_since(&self, since: &str) -> Vec<u8> {
let after = |cid: &[u8]| self.held.get(cid).is_some_and(|rev| rev.as_str() > since);
let after = |cid: &[u8]| self.held.get(cid).is_some_and(|h| h.rev.as_str() > since);
let mut blocks: Vec<(&[u8], &[u8])> = Vec::new();
if self.rev.as_str() > since {
blocks.push((&self.head, &self.head_bytes));
@@ -383,29 +476,27 @@ impl Repo {
/// 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.
/// a node or record of its current tree. Each CID is looked up in the
/// index of the blocks it holds, so what this reads is what is asked for,
/// however large the repository.
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));
let mut seen: HashSet<&[u8]> = HashSet::with_capacity(cids.len());
let mut found: Vec<(&[u8], &[u8])> = Vec::with_capacity(cids.len());
for cid in cids {
if !seen.insert(cid.as_slice()) {
continue;
}
}
if !left.is_empty() {
for n in self.tree.nodes() {
if left.remove(n.cid.as_slice()) {
found.push((&n.cid, &n.bytes));
}
if *cid == self.head {
found.push((&self.head, &self.head_bytes));
continue;
}
let bytes = match &self.held.get(cid)?.at {
At::Node(bytes) => bytes.as_slice(),
At::Record(path) => self.records.get(path).filter(|r| r.cid == *cid)?.bytes.as_slice(),
};
found.push((cid, bytes));
}
left.is_empty().then(|| car_with_roots(&[], found))
Some(car_with_roots(&[], found))
}
/// A CAR file rooted at the latest commit that proves the record at
@@ -462,3 +553,108 @@ fn varint(out: &mut Vec<u8>, mut n: usize) {
}
out.push(n as u8);
}
fn varint_len(n: usize) -> usize {
(usize::BITS - n.max(1).leading_zeros()).div_ceil(7) as usize
}
/// The length of the CAR file a commit's `#commit` event carries as its
/// `blocks`: rooted at the commit, holding it and then `blocks`.
pub fn event_blocks_len(head: &[u8], head_bytes: &[u8], blocks: &[Block]) -> usize {
let header = encode(&V::Map(vec![("roots".into(), V::Arr(vec![V::Link(head.to_vec())])), ("version".into(), V::Int(1))])).len();
let block = |cid: &[u8], data: &[u8]| varint_len(cid.len() + data.len()) + cid.len() + data.len();
varint_len(header) + header + block(head, head_bytes) + blocks.iter().map(|(c, d)| block(c, d)).sum::<usize>()
}
#[cfg(test)]
mod tests {
use super::*;
fn repo() -> Repo {
let mut r = Repo::new("did:plc:aaaaaaaaaaaaaaaaaaaaaaaa".into(), SigningKey::from_slice(&[7u8; 32]).unwrap());
r.init();
r
}
fn create(r: &mut Repo, rkey: &str, value: V) -> Result<Change, Refused> {
let op = Op::Create { collection: "a.b.c".into(), rkey: Some(rkey.into()), value };
r.apply(vec![op], None)?;
Ok(r.change.take().unwrap())
}
fn text(n: usize) -> V {
V::Map(vec![("$type".into(), V::Str("a.b.c".into())), ("b".into(), V::Bytes(vec![1; n]))])
}
#[test]
fn varint_lengths() {
for n in [0usize, 1, 127, 128, 16383, 16384, 2_000_000, usize::MAX >> 1] {
let mut out = Vec::new();
varint(&mut out, n);
assert_eq!(out.len(), varint_len(n), "{n}");
}
}
/// A commit whose event would carry more than `MAX_EVENT_BLOCKS` bytes is
/// refused and changes nothing; one of exactly as many is made, and its
/// event's blocks are that long.
#[test]
fn commits_too_big_are_refused() {
let mut r = repo();
let (head, rev) = (r.head.clone(), r.rev.clone());
assert_eq!(create(&mut r, "big", text(MAX_EVENT_BLOCKS)).err(), Some(Refused::TooBig));
assert_eq!((&r.head, &r.rev, r.records.len()), (&head, &rev, 0));
// The largest record that fits, found by halving.
let (mut lo, mut hi) = (MAX_EVENT_BLOCKS / 2, MAX_EVENT_BLOCKS);
while hi - lo > 1 {
let mid = (lo + hi) / 2;
let mut trial = repo();
if create(&mut trial, "big", text(mid)).is_ok() { lo = mid } else { hi = mid }
}
let c = create(&mut r, "big", text(lo)).unwrap();
let len = event_blocks_len(&r.head, &r.head_bytes, &c.blocks);
let mut blocks: Vec<(&[u8], &[u8])> = vec![(&r.head, &r.head_bytes)];
blocks.extend(c.blocks.iter().map(|(k, d)| (k.as_slice(), d.as_slice())));
assert_eq!(car_file(&r.head, blocks).len(), len);
assert!(len <= MAX_EVENT_BLOCKS && len > MAX_EVENT_BLOCKS - 8, "{len}");
assert_eq!(create(&mut r, "big2", text(lo + 1)).err(), Some(Refused::TooBig));
}
/// A commit undone leaves the repository as it was, and the next commit
/// goes on from there.
#[test]
fn undo_puts_it_back() {
let mut r = repo();
create(&mut r, "one", text(1)).unwrap();
let before = (r.head.clone(), r.rev.clone(), r.car());
let c = create(&mut r, "two", text(2)).unwrap();
r.undo(c.undo.unwrap());
assert_eq!((r.head.clone(), r.rev.clone(), r.car()), before);
assert!(r.blocks_car(&[make_record(text(2)).cid]).is_none());
let c = create(&mut r, "two", text(2)).unwrap();
assert_eq!(c.since.as_deref(), Some(before.1.as_str()));
assert!(r.blocks_car(&[make_record(text(2)).cid]).is_some());
}
/// `getBlocks` reads what it asks for: no walk of the tree, in a large
/// repository or a small one, whether the blocks are held or not.
#[test]
fn blocks_by_index() {
for size in [3usize, 3000] {
let mut r = repo();
let ops = (0..size).map(|i| Op::Create { collection: "a.b.c".into(), rkey: Some(format!("k{i}")), value: text(i % 7 + 1) }).collect();
r.apply(ops, None).unwrap();
r.change = None;
let some_record = r.records.values().next().unwrap().cid.clone();
let root = r.tree.cid.clone();
mst::VISITS.with(|v| v.set(0));
let missing = cid_of(0x71, b"not held");
assert_eq!(r.blocks_car(&[some_record.clone(), missing]), None);
let car = r.blocks_car(&[root.clone(), some_record.clone(), r.head.clone(), root.clone()]).unwrap();
assert_eq!(mst::VISITS.with(|v| v.get()), 0, "{size} records");
let want: Vec<(&[u8], &[u8])> =
vec![(&root, &r.tree.bytes), (&some_record, &r.records.values().next().unwrap().bytes), (&r.head, &r.head_bytes)];
assert_eq!(car, car_with_roots(&[], want));
}
}
}
crates/pds-repo/src/mst.rs+8−0
@@ -33,8 +33,16 @@ pub struct Entry {
pub sub: Option<Box<Node>>,
}
#[cfg(test)]
thread_local! {
/// How many nodes walks of a tree have visited, on this thread.
pub(crate) static VISITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
impl Node {
fn collect<'a>(&'a self, out: &mut Vec<&'a Node>) {
#[cfg(test)]
VISITS.with(|v| v.set(v.get() + 1));
if let Some(l) = &self.left {
l.collect(out);
}
crates/pds-server/src/blobs.rs+395−78
473 lines changed: not loaded until asked for.
crates/pds-server/src/compact.rsnew+161−0
@@ -0,0 +1,161 @@
//! Compacting `accounts.log` (`spec/LIMITS.md`): once the log has grown past
//! twice what it was after it was last compacted, and a constant's slack, it
//! is folded into what it holds now, with appends held off meanwhile: each
//! account's entry, the invite codes and their uses, and each account's app
//! passwords and the sessions it keeps. So however often sessions are
//! refreshed, the log holds no more than the sessions and app passwords kept,
//! and a constant factor of slack.
//!
//! The fold reads the log, not memory, so that it is exactly what replay
//! would make of it. It leaves out sessions that expired more than `MARGIN`
//! ago: none of those can be named by an entry still to come.
use crate::sessions::{self, Keep};
use crate::{Service, Shared};
use serde_json::Value as Json;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
/// How long past its expiry a session is kept on disk.
const MARGIN: u64 = 60 * 60;
/// How many entries go in one frame of a compacted log.
const FRAME_ENTRIES: usize = 1000;
/// When `accounts.log` is next compacted.
pub(crate) struct Compaction {
/// The log's length after it was last compacted, none at start.
base: AtomicU64,
/// The bytes it may grow by besides doubling.
pub slack: AtomicU64,
running: AtomicBool,
}
impl Default for Compaction {
fn default() -> Compaction {
Compaction { base: AtomicU64::new(0), slack: AtomicU64::new(1 << 20), running: AtomicBool::new(false) }
}
}
/// After an append to `accounts.log`: compact it in the background if it is
/// due and no compaction is running.
pub(crate) fn after_append(s: &Shared) {
let c = &s.compaction;
if s.log.len() <= 2 * c.base.load(Ordering::SeqCst) + c.slack.load(Ordering::SeqCst) || c.running.swap(true, Ordering::SeqCst) {
return;
}
let s = s.clone();
tokio::task::spawn_blocking(move || {
if let Err(why) = run(&s) {
eprintln!("pds: compacting {}: {why}", crate::log::ACCOUNTS_LOG);
}
s.compaction.running.store(false, Ordering::SeqCst);
});
}
/// Compact `accounts.log` now.
pub(crate) fn run(s: &Service) -> Result<(), String> {
let before = s.sessions.now().saturating_sub(MARGIN);
s.log.rewrite(|frames| fold(frames, before))?;
s.compaction.base.store(s.log.len(), Ordering::SeqCst);
Ok(())
}
/// What `frames` hold now, as entries, without sessions that expired before `before`.
fn fold(frames: Vec<Vec<Json>>, before: u64) -> Result<Vec<Vec<Json>>, String> {
let mut accounts = Vec::new();
let mut keeps: Vec<(String, Keep)> = Vec::new();
let mut by_did: HashMap<String, usize> = HashMap::new();
let invites = crate::invites::Invites::default();
for e in frames.into_iter().flatten() {
match e["t"].as_str() {
Some("account") => accounts.push(e),
Some(t) if sessions::ENTRIES.contains(&t) => {
let did = e["did"].as_str().ok_or_else(|| format!("an entry with no did: {e}"))?.to_string();
let at = *by_did.entry(did.clone()).or_insert_with(|| {
keeps.push((did, Keep::default()));
keeps.len() - 1
});
keeps[at].1.apply(&e)?;
}
Some(t) if crate::invites::ENTRIES.contains(&t) => invites.replay(&e)?,
t => return Err(format!("a log entry of no known type: {t:?}")),
}
}
let mut entries = accounts;
entries.extend(invites.entries());
for (did, k) in &keeps {
entries.extend(k.entries(did, before));
}
Ok(entries.chunks(FRAME_ENTRIES).map(<[Json]>::to_vec).collect())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::*;
use serde_json::json;
/// Refreshing a session again and again leaves `accounts.log` no larger
/// than what it keeps and a constant factor of slack, and a restart
/// finds every account, session, app password and invite code as before.
#[tokio::test]
async fn refreshing_leaves_the_log_bounded() {
let plc = plc().await;
let dir = scratch("compact");
let s = open(&dir, &plc);
s.compaction.slack.store(16 * 1024, Ordering::SeqCst);
let (did, token) = create(&s, "alice").await;
create(&s, "bob").await;
let admin = format!("Basic {}", base64::Engine::encode(&base64::engine::general_purpose::STANDARD, format!("admin:{ADMIN_PASSWORD}")));
let code = call_raw(&s, "com.atproto.server.createInviteCode", crate::sessions::Bearer::of(Some(&admin)), &[], r#"{"useCount":2}"#).await.unwrap();
let app = call(&s, "com.atproto.server.createAppPassword", Some(&token), json!({ "name": "phone" })).await.unwrap();
let login = json!({ "identifier": "alice.test", "password": app["password"] });
let mut refresh = call(&s, "com.atproto.server.createSession", None, login).await.unwrap()["refreshJwt"].as_str().unwrap().to_string();
let path = dir.join(crate::log::ACCOUNTS_LOG);
let mut largest = 0;
for _ in 0..1500 {
let got = call(&s, "com.atproto.server.refreshSession", Some(&refresh), Json::Null).await.unwrap();
refresh = got["refreshJwt"].as_str().unwrap().to_string();
// Let a compaction begun run.
while s.compaction.running.load(Ordering::SeqCst) {
tokio::time::sleep(std::time::Duration::from_millis(1)).await;
}
largest = largest.max(std::fs::metadata(&path).unwrap().len());
}
let base = s.compaction.base.load(Ordering::SeqCst);
assert!(base > 0, "never compacted");
assert!(largest <= 2 * base + 16 * 1024 + 4096, "{largest} bytes, {base} after compacting");
// The account keeps at most its sessions' limit, so the log stays small.
assert!(s.sessions.count(&did) <= crate::sessions::MAX_SESSIONS);
assert!(base < 200 * 1024, "{base}");
let before = (s.sessions.snapshot(), s.invites.snapshot());
drop(s);
let s = open(&dir, &plc);
assert_eq!((s.sessions.snapshot(), s.invites.snapshot()), before);
// The latest token works, and the code can still be used.
call(&s, "com.atproto.server.refreshSession", Some(&refresh), Json::Null).await.unwrap();
let body = json!({ "handle": "carol.test", "email": "carol@mail.com", "password": "pw", "inviteCode": code["code"] });
call(&s, "com.atproto.server.createAccount", None, body).await.unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
/// Sessions long expired are left out of a compacted log; those within
/// the margin, and every other, are kept.
#[test]
fn fold_leaves_out_long_expired_sessions() {
let did = "did:plc:a";
let session = |id: &str, exp: u64| json!({ "t": "session", "did": did, "id": id, "app": null, "scope": "com.atproto.access", "exp": exp });
let frames = vec![
vec![json!({ "t": "account", "did": did })],
vec![session("old", 10), session("recent", 100), session("live", 1000)],
vec![json!({ "t": "refresh", "did": did, "id": "live", "next": "after", "exp": 1000, "nextExp": 2000 })],
];
let folded = fold(frames, 50).unwrap();
let ids: Vec<&str> = folded.iter().flatten().filter(|e| e["t"] == "session").map(|e| e["id"].as_str().unwrap()).collect();
// In the order they were made, so that a replay orders them alike.
assert_eq!(ids, ["recent", "live", "after"]);
let live = folded.iter().flatten().find(|e| e["id"] == "live").unwrap();
assert_eq!(live["next"], json!("after"));
}
}
crates/pds-server/src/events.rs+167−27
@@ -2,15 +2,16 @@
//! they are numbered in across all accounts, and the WebSocket that serves
//! them, as `spec/SYNC.md` says.
use crate::Shared;
use crate::{Shared, limits};
use axum::body::Bytes;
use axum::extract::ws::rejection::WebSocketUpgradeRejection;
use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
use axum::extract::{Query, State};
use axum::http::StatusCode;
use axum::extract::ws::{CloseFrame, Message, WebSocket, WebSocketUpgrade, close_code};
use axum::extract::{Extension, Query, State};
use axum::http::{HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use pds_repo::data::*;
use pds_repo::{Change, car_file};
use std::collections::HashMap;
use std::sync::{Mutex, PoisonError};
use std::time::{SystemTime, UNIX_EPOCH};
@@ -21,37 +22,56 @@ use std::time::{SystemTime, UNIX_EPOCH};
/// 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.
/// from every account's, and is never given twice. 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. So too while the server runs: events whose
/// write failed are taken out, and those after them, none of them sent yet,
/// numbered again as a restart would number them.
pub(crate) struct Firehose {
seq: Mutex<Seq>,
/// How many events subscribers may be sent.
published: tokio::sync::watch::Sender<usize>,
/// The subscriptions held, by client address, and in all.
subscribers: Mutex<(HashMap<String, usize>, usize)>,
}
/// An event: its `ord`, and its frame once it is on disk.
struct Slot {
ord: u64,
frame: Option<Bytes>,
}
struct Seq {
/// Event `n` has seq `n + 1`; `None` until it is on disk.
events: Vec<Option<Bytes>>,
offset: u64,
/// Event `n` has seq `n + 1`, in `ord` order.
events: Vec<Slot>,
next_ord: 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.
/// Events on their way to the disk, numbered from `seq` and ordered from
/// `ord`, to `land` once they are there or `fail` if they never will be.
pub(crate) struct Landing {
pub seq: u64,
pub ord: u64,
pub frames: Vec<Bytes>,
}
impl Seq {
/// Where the event with this `ord` is.
fn at(&self, ord: u64) -> usize {
self.events.partition_point(|s| s.ord < ord)
}
}
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 {
/// The events recovered, all on disk, each with its `ord`, in order.
pub fn new(events: Vec<(u64, Bytes)>) -> 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 }
let next_ord = events.last().map_or(1, |(ord, _)| ord + 1);
let seq = Seq { events: events.into_iter().map(|(ord, f)| Slot { ord, frame: Some(f) }).collect(), next_ord, published: n };
Firehose { seq: Mutex::new(seq), published: tokio::sync::watch::channel(n).0, subscribers: Mutex::default() }
}
fn lock(&self) -> std::sync::MutexGuard<'_, Seq> {
@@ -61,20 +81,24 @@ impl Firehose {
/// 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)
let (seq, ord) = (s.events.len() as u64 + 1, s.next_ord);
s.events.extend((0..n as u64).map(|i| Slot { ord: ord + i, frame: None }));
s.next_ord += n as u64;
(seq, ord)
}
/// 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();
let at = s.at(l.ord);
for (i, f) in l.frames.into_iter().enumerate() {
s.events[(l.seq - 1) as usize + i] = Some(f);
// Numbered again if events before it failed meanwhile.
let seq = (at + i) as u64 + 1;
let f = if seq == l.seq + i as u64 { f } else { renumber(&f, seq).map(Bytes::from).unwrap_or(f) };
s.events[at + i].frame = Some(f);
}
while s.published < s.events.len() && s.events[s.published].is_some() {
while s.published < s.events.len() && s.events[s.published].frame.is_some() {
s.published += 1;
}
s.published
@@ -86,10 +110,25 @@ impl Firehose {
});
}
/// The `n` events from `ord` on will never reach the disk: they are taken
/// out, and the events after them, none of which has been sent, numbered again.
pub fn fail(&self, ord: u64, n: usize) {
let mut s = self.lock();
let at = s.at(ord);
let end = (at + n).min(s.events.len());
s.events.drain(at..end);
for i in at..s.events.len() {
if let Some(f) = &s.events[i].frame {
let f = renumber(f, i as u64 + 1).map(Bytes::from).unwrap_or_else(|_| f.clone());
s.events[i].frame = Some(f);
}
}
}
/// 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())
self.lock().events.get(from..to).map_or_else(Vec::new, |e| e.iter().filter_map(|s| s.frame.clone()).collect())
}
pub fn subscribe(&self) -> tokio::sync::watch::Receiver<usize> {
@@ -224,20 +263,72 @@ pub fn initial_events(did: &str, handle: &str, seq: u64, c: &Change) -> Vec<Vec<
]
}
/// A subscription held, by its client: let go when its connection ends.
struct Subscription {
st: Shared,
client: String,
}
impl Subscription {
/// Hold one for `client`, unless it holds `MAX_SUBSCRIPTIONS_PER_CLIENT`
/// already, or the server `MAX_SUBSCRIPTIONS`.
fn hold(st: &Shared, client: String) -> Option<Subscription> {
let mut subs = st.events.subscribers.lock().unwrap_or_else(PoisonError::into_inner);
let (by_client, all) = &mut *subs;
let held = by_client.entry(client.clone()).or_default();
if *held >= limits::MAX_SUBSCRIPTIONS_PER_CLIENT || *all >= limits::MAX_SUBSCRIPTIONS {
if *held == 0 {
by_client.remove(&client);
}
return None;
}
*held += 1;
*all += 1;
Some(Subscription { st: st.clone(), client })
}
}
impl Drop for Subscription {
fn drop(&mut self) {
let mut subs = self.st.events.subscribers.lock().unwrap_or_else(PoisonError::into_inner);
let (by_client, all) = &mut *subs;
*all -= 1;
if let Some(n) = by_client.get_mut(&self.client) {
*n -= 1;
if *n == 0 {
by_client.remove(&self.client);
}
}
}
}
/// `subscribeRepos`: refused as XRPC refuses a call past its rate limits for
/// a client, or a server, holding all the subscriptions it may, and taking
/// no message from the client longer than `MAX_CLIENT_MESSAGE`.
pub async fn subscribe(
State(st): State<Shared>,
Query(params): Query<Vec<(String, String)>>,
headers: HeaderMap,
peer: Option<Extension<limits::Peer>>,
ws: Result<WebSocketUpgrade, WebSocketUpgradeRejection>,
) -> Response {
let Ok(ws) = ws else {
return (StatusCode::UPGRADE_REQUIRED, "Upgrade Required").into_response();
};
let client = limits::client(&headers, peer.map(|Extension(p)| p.0));
let Some(held) = Subscription::hold(&st, client) else {
return crate::respond(crate::err(429, "RateLimitExceeded", "Too many subscriptions"), None);
};
let cursor = params.iter().find(|(k, _)| k == "cursor").map(|(_, v)| v.parse::<u64>());
ws.on_upgrade(move |socket| stream(st, cursor, socket))
ws.max_message_size(limits::MAX_CLIENT_MESSAGE).max_frame_size(limits::MAX_CLIENT_MESSAGE).on_upgrade(move |socket| async move {
stream(st, cursor, socket).await;
drop(held);
})
}
/// Send the events after `cursor` (or none, without one), then each new event
/// as it reaches the disk.
/// as it reaches the disk. What the client sends is read and thrown away; a
/// message too long closes the connection with `1009`.
async fn stream(st: Shared, cursor: Option<Result<u64, std::num::ParseIntError>>, mut socket: WebSocket) {
let start = {
let rx = st.events.subscribe();
@@ -265,7 +356,14 @@ async fn stream(st: Shared, cursor: Option<Result<u64, std::num::ParseIntError>>
tokio::select! {
changed = rx.changed() => if changed.is_err() { return },
incoming = socket.recv() => match incoming {
None | Some(Err(_)) | Some(Ok(Message::Close(_))) => return,
None | Some(Ok(Message::Close(_))) => return,
Some(Err(_)) => {
// Most likely a message past the limit: the connection
// ends, saying so if it still can.
let close = CloseFrame { code: close_code::SIZE, reason: "Message too big".into() };
let _ = socket.send(Message::Close(Some(close))).await;
return;
}
Some(Ok(_)) => {}
},
}
@@ -277,3 +375,45 @@ async fn refuse(mut socket: WebSocket, name: &str, text: &str) {
let _ = socket.send(Message::Close(None)).await;
}
#[cfg(test)]
mod tests {
use super::*;
fn seq_of(frame: &[u8]) -> i64 {
let (_, at) = decode_prefix(frame).unwrap();
match decode(&frame[at..]).unwrap() {
V::Map(m) => match m.iter().find(|(k, _)| k == "seq") {
Some((_, V::Int(n))) => *n,
_ => panic!("no seq"),
},
_ => panic!("not a map"),
}
}
fn landing(seq: u64, ord: u64) -> Landing {
Landing { seq, ord, frames: vec![Bytes::from(identity_event("did:plc:a", "a.test", seq, "t"))] }
}
/// Events whose write failed are taken out: those after them, landed or
/// not, are numbered again with no gap, as a restart would number them,
/// and are sent once the events before them are on disk.
#[test]
fn failed_events_are_taken_out() {
let f = Firehose::new(vec![]);
let rx = f.subscribe();
let (a, b, c) = (f.reserve(1), f.reserve(1), f.reserve(1));
assert_eq!((a, b, c), ((1, 1), (2, 2), (3, 3)));
f.land(landing(c.0, c.1));
assert_eq!(*rx.borrow(), 0);
f.fail(a.1, 1);
assert_eq!(*rx.borrow(), 0);
let d = f.reserve(1);
assert_eq!(d, (3, 4));
f.land(landing(b.0, b.1));
f.land(landing(d.0, d.1));
assert_eq!(*rx.borrow(), 3);
let seqs: Vec<i64> = f.get(0, 3).iter().map(|e| seq_of(e)).collect();
assert_eq!(seqs, [1, 2, 3]);
}
}
crates/pds-server/src/federation.rs+2−1
@@ -130,7 +130,8 @@ mod tests {
/// A query whose answer is a CAR file: its bytes, or the error's name.
async fn car(s: &Shared, nsid: &str, p: &[(&str, &str)]) -> Result<Vec<u8>, String> {
let p = params(p);
match answer(s, &Call { nsid, method: &Method::GET, params: &p, body: b"", bearer: crate::sessions::Bearer::None }).await {
let call = Call { nsid, method: &Method::GET, params: &p, body: b"", bearer: crate::sessions::Bearer::None, client: String::new(), charged: std::sync::OnceLock::new() };
match answer(s, &call).await {
Ok(Resp::Car(b)) => Ok(b),
Ok(Resp::Json(j)) => panic!("{nsid} answered JSON: {j}"),
Ok(Resp::Nothing) => panic!("{nsid} answered nothing"),
crates/pds-server/src/identity.rs+115−29
@@ -64,27 +64,57 @@ fn recommended_credentials(s: &Service, call: &Call, _: &mut Shown, _: &Map<Stri
})))
}
/// The DID document the directory serves for an account's DID now; the one
/// it last served, should it not answer.
/// An account's DID document, as the directory last served it, if it was
/// fetched within `PDS_DID_CACHE_SECS`.
fn kept_doc(s: &Service, a: &Account) -> Option<Json> {
let (doc, at) = &*read(&a.did_doc);
at.filter(|t| s.limits.clock.now() < t.saturating_add(s.config.did_cache)).map(|_| doc.clone())
}
/// The DID document of an account's DID: the one kept, if it was fetched
/// within `PDS_DID_CACHE_SECS`, or else the one the directory serves now,
/// fetched once at a time; the one it last served, should it not answer.
pub(crate) async fn did_doc(s: &Service, did: &str) -> Json {
let Some(a) = s.account(did) else { return Json::Null };
let url = format!("{}/{did}", s.config.plc_url.trim_end_matches('/'));
if let Some(doc) = kept_doc(s, &a) {
return doc;
}
let _fetching = a.fetching.lock().await;
// Another call may have fetched it meanwhile.
if let Some(doc) = kept_doc(s, &a) {
return doc;
}
fetch_doc(s, &a).await
}
/// Fetch an account's DID document from the directory, and keep it; with the
/// account's fetch held.
async fn fetch_doc(s: &Service, a: &Account) -> Json {
let url = format!("{}/{}", s.config.plc_url.trim_end_matches('/'), a.did);
match plc::document(&s.http, &url).await {
Ok(Some(doc)) => {
*write(&a.did_doc) = doc.clone();
*write(&a.did_doc) = (doc.clone(), Some(s.limits.clock.now()));
doc
}
Ok(None) => {
eprintln!("pds: {url} serves no DID document");
read(&a.did_doc).clone()
read(&a.did_doc).0.clone()
}
Err(why) => {
eprintln!("pds: {why}");
read(&a.did_doc).clone()
read(&a.did_doc).0.clone()
}
}
}
/// After an operation the server posted for the account: its document,
/// fetched now, is the one served from then on; out of date if it cannot be.
async fn refetch_doc(s: &Service, a: &Account) {
let _fetching = a.fetching.lock().await;
write(&a.did_doc).1 = None;
fetch_doc(s, a).await;
}
/// Whether a DID document's first `at://` name is `at://<handle>`.
pub(crate) fn names_handle(doc: &Json, handle: &str) -> bool {
let first = doc["alsoKnownAs"].as_array().and_then(|aka| aka.iter().filter_map(Json::as_str).find(|u| u.starts_with("at://")));
@@ -172,21 +202,33 @@ async fn settle_later(s: Weak<Service>, did: String) {
async fn settle(s: &Service, a: &Account, change: &mut Option<Pending>) -> Result<(), String> {
let Some(p) = change.as_ref() else { return Ok(()) };
let landed = plc::holds(&s.http, &s.config.plc_url, &a.did, &p.cid).await?;
finish(s, a, change, landed).await;
if !finish(s, a, change, landed).await {
return Err("its settling could not be logged".into());
}
Ok(())
}
/// Settle the change in flight: in the log, on disk, then, if it landed, the
/// account's handle, freeing the old one, and its `#identity` event. Its
/// handle is no longer held for it either way.
async fn finish(s: &Service, a: &Account, change: &mut Option<Pending>, landed: bool) {
let Some(p) = change.take() else { return };
let (wal, n, landing) = {
/// account's handle, freeing the old one, its `#identity` event, and its DID
/// document fetched again. Its handle is no longer held for it either way.
/// False, with the change still in flight, if it could not be logged.
async fn finish(s: &Service, a: &Account, change: &mut Option<Pending>, landed: bool) -> bool {
let Some(p) = change.take() else { return true };
let logged = {
let mut st = write(&a.store);
let landing = log::log_settled(&s.events, &a.did, &mut st, &p.cid, landed.then_some(p.handle.as_str()));
(st.wal.clone(), st.wal.written(), landing)
landing.map(|l| (st.wal.clone(), st.wal.written(), l))
};
let (wal, n, landing) = match logged {
Ok(x) => x,
Err(e) => {
eprintln!("pds: settling the handle change of {}: {e}", a.did);
*change = Some(p);
return false;
}
};
durable(wal, n).await;
// A sync that fails is said; the change is made in memory as it is in the log.
let _ = durable(wal, n).await;
{
let mut d = write(&s.directory);
d.claimed_handles.remove(&p.handle);
@@ -202,6 +244,10 @@ async fn finish(s: &Service, a: &Account, change: &mut Option<Pending>, landed:
if let Some(l) = landing {
s.events.land(l);
}
if landed {
refetch_doc(s, a).await;
}
true
}
/// A handle held for a change before it is recorded, so that no other
@@ -276,27 +322,31 @@ async fn update_handle(s: Shared, did: String, b: Map<String, Json>) -> Result<R
// holds the handle until it is settled.
let (wal, n) = {
let st = write(&a.store);
(st.wal.clone(), st.wal.append(&[log::handle_entry(&handle, &cid)]))
match st.wal.append(&[log::handle_entry(&handle, &cid)]) {
Ok(n) => (st.wal.clone(), n),
Err(e) => {
eprintln!("pds: updateHandle {handle}: {e}");
return internal();
}
}
};
durable(wal, n).await;
held.keep();
*change = Some(Pending { handle: handle.clone(), cid: cid.clone() });
let landed = match plc::post(&s.http, &s.config.plc_url, &did, &op).await {
Ok(()) => true,
Err(Upstream::Refused(why)) => {
finish(&s, &a, &mut change, false).await;
return invalid(why);
}
if durable(wal, n).await.is_err() {
drop(change);
tokio::spawn(settle_later(Arc::downgrade(&s), did));
return internal();
}
let (landed, refused) = match plc::post(&s.http, &s.config.plc_url, &did, &op).await {
Ok(()) => (true, None),
Err(Upstream::Refused(why)) => (false, Some(invalid(why))),
Err(Upstream::Unreachable { why, sent }) => {
eprintln!("pds: updateHandle {handle}: {why}");
// A post that may have reached the directory: whether it took it is in its log.
let found = if sent { plc::holds(&s.http, &s.config.plc_url, &did, &cid).await } else { Ok(false) };
match found {
Ok(true) => true,
Ok(false) => {
finish(&s, &a, &mut change, false).await;
return upstream();
}
Ok(true) => (true, None),
Ok(false) => (false, Some(upstream())),
Err(why) => {
eprintln!("pds: updateHandle {handle}: {why}; settling it later");
drop(change);
@@ -306,8 +356,13 @@ async fn update_handle(s: Shared, did: String, b: Map<String, Json>) -> Result<R
}
}
};
finish(&s, &a, &mut change, landed).await;
Ok(Resp::Nothing)
if !finish(&s, &a, &mut change, landed).await {
// Settled in the background, once its settling can be logged.
drop(change);
tokio::spawn(settle_later(Arc::downgrade(&s), did));
return internal();
}
refused.unwrap_or(Ok(Resp::Nothing))
}
/// A PLC directory for tests, keeping each DID's log of operations as
@@ -921,4 +976,35 @@ mod tests {
assert_eq!((handle_of(&s, &alice), claimed(&s), events(&s)), ("alice.test".to_string(), vec![], evs));
let _ = std::fs::remove_dir_all(&dir);
}
/// With `PDS_DID_CACHE_SECS`, `describeRepo` serves the document kept, not
/// one changed behind the server's back, until it is that old; after the
/// server's own handle change, the new document at once.
#[tokio::test]
async fn documents_are_kept() {
let plc = Plc::start().await;
let dir = scratch("did-cache");
let s = open_with(&dir, &plc.url, |c| c.did_cache = 60);
s.limits.clock.freeze();
let (alice, ta) = create(&s, "alice").await;
let genesis = plc.log(&alice).pop().unwrap();
let mut theirs = genesis.clone();
theirs["alsoKnownAs"] = json!(["at://elsewhere.test"]);
theirs["prev"] = json!(plc::cid(&genesis).unwrap());
assert_eq!(plc.post(&alice, &plc::signed(&s.config, &theirs)).await, 200);
let aka = |d: Json| d["didDoc"]["alsoKnownAs"].clone();
assert_eq!(aka(describe(&s, &alice).await.unwrap()), json!(["at://alice.test"]));
// Older than the cache's time: fetched again.
s.limits.clock.skew.store(61, std::sync::atomic::Ordering::SeqCst);
assert_eq!(aka(describe(&s, &alice).await.unwrap()), json!(["at://elsewhere.test"]));
// The server's own change: at once.
update(&s, &ta, "carol.test").await.unwrap();
let got = describe(&s, "carol.test").await.unwrap();
assert_eq!((aka(got.clone()), &got["handleIsCorrect"]), (json!(["at://carol.test"]), &json!(true)));
// Down, the directory is not asked while the document is young.
plc.down().await;
assert_eq!(aka(describe(&s, &alice).await.unwrap()), json!(["at://carol.test"]));
plc.up().await;
let _ = std::fs::remove_dir_all(&dir);
}
}
crates/pds-server/src/invites.rsnew+442−0
442 lines changed: not loaded until asked for.
crates/pds-server/src/lib.rs+186−50
@@ -6,14 +6,18 @@
//! 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`.
//! `identity` (handles), `blobs` and `invites`; the firehose is `events`, the
//! MCP endpoint `mcp`, the PLC directory `plc`, what keeps the server up when
//! anyone may call it `limits`, and what the server keeps, how it starts
//! again from it, and how it compacts it, `log` and `compact`.
mod blobs;
mod compact;
mod events;
mod federation;
mod identity;
mod invites;
mod limits;
mod log;
mod mcp;
mod plc;
@@ -24,8 +28,8 @@ mod sync;
use axum::{
Router,
body::Bytes,
extract::{Path, Query, State as AxState},
body::Body,
extract::{Extension, Path, Query, State as AxState},
http::{HeaderMap, Method, StatusCode, header},
response::{IntoResponse, Response},
routing::{any, get},
@@ -37,9 +41,10 @@ use serde_json::{Map, Value as Json, json};
use std::collections::{HashMap, HashSet};
use std::path::{Path as FsPath, PathBuf};
use std::pin::Pin;
use std::sync::{Arc, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::sync::{Arc, OnceLock, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard};
/// The server's configuration, from its environment (`spec/ACCOUNTS.md`).
/// The server's configuration, from its environment (`spec/ACCOUNTS.md`,
/// `spec/FEDERATION.md`, `spec/LIMITS.md`).
pub(crate) struct Config {
/// Its DID is `did:web:<hostname>`.
pub hostname: String,
@@ -54,6 +59,22 @@ pub(crate) struct Config {
pub recovery_did_key: Option<String>,
/// The base URLs of the crawlers to tell of new events (`spec/FEDERATION.md`).
pub crawlers: Vec<String>,
/// Whether `createAccount` needs an invite code.
pub invite_required: bool,
/// The password of the admin's `Basic` auth; with none, no request is the admin.
pub admin_password: Option<String>,
/// Whether the rate limits apply.
pub rate_limits: bool,
/// The bytes of blobs an account may hold.
pub blob_quota: u64,
/// How long, in seconds, an upload no record references is held.
pub blob_ttl: u64,
/// The free space below which writes are refused.
pub min_free: u64,
/// How long, in seconds, a DID document fetched from the directory is served.
pub did_cache: u64,
/// How long after its input is checked `createSession` answers, at the soonest.
pub login_floor: std::time::Duration,
}
impl Config {
@@ -72,6 +93,14 @@ impl Config {
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(),
invite_required: limits::env_bool("PDS_INVITE_REQUIRED", false)?,
admin_password: std::env::var("PDS_ADMIN_PASSWORD").ok(),
rate_limits: limits::env_bool("PDS_RATE_LIMITS_ENABLED", true)?,
blob_quota: limits::env_u64("PDS_BLOB_QUOTA_BYTES", 1 << 30)?,
blob_ttl: limits::env_u64("PDS_BLOB_TTL_SECS", 3600)?,
min_free: limits::env_u64("PDS_MIN_FREE_BYTES", 256 << 20)?,
did_cache: limits::env_u64("PDS_DID_CACHE_SECS", 3600)?,
login_floor: std::time::Duration::from_millis(350),
})
}
}
@@ -89,8 +118,11 @@ pub(crate) struct Account {
/// Its KEM key (`spec/SPACES.md`); None for an account made before
/// accounts had one.
pub kem: Option<pds_space::KemKey>,
/// Its DID document, as the PLC directory last served it.
pub did_doc: RwLock<Json>,
/// Its DID document, as the PLC directory last served it, and when, in
/// seconds since the epoch: none if it may be out of date.
pub did_doc: RwLock<(Json, Option<u64>)>,
/// Held by the one fetch of its DID document at a time.
pub fetching: tokio::sync::Mutex<()>,
/// Queries read it side by side; a write has it alone.
pub store: RwLock<Store>,
}
@@ -136,16 +168,24 @@ impl Directory {
pub(crate) struct Service {
config: Config,
dir: PathBuf,
/// The service-wide log: accounts, sessions and app passwords.
/// The service-wide log: accounts, sessions, app passwords and invite codes.
log: Arc<Wal>,
/// The accounts' logs, of which only so many are open at once.
files: Arc<pds_store::Files>,
directory: RwLock<Directory>,
/// The sessions given out, and app passwords.
sessions: sessions::Sessions,
/// The invite codes, and their uses.
invites: invites::Invites,
/// 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,
/// Rate limits, the free space, the clock, and the password hashes' threads.
limits: limits::Limits,
/// When `accounts.log` is next compacted.
compaction: compact::Compaction,
}
type Shared = Arc<Service>;
@@ -158,10 +198,19 @@ fn write<T>(l: &RwLock<T>) -> RwLockWriteGuard<'_, T> {
l.write().unwrap_or_else(PoisonError::into_inner)
}
/// Return once frame `n` of `wal` is on disk, sharing an fsync with whoever else waits.
async fn durable(wal: Arc<Wal>, n: u64) {
if !wal.is_durable(n) {
tokio::task::spawn_blocking(move || wal.wait(n)).await.expect("waiting for a log, which aborts rather than fail");
/// Return once frame `n` of `wal` is on disk, sharing an fsync with whoever
/// else waits: an error, said on standard error, if it cannot be made so.
async fn durable(wal: Arc<Wal>, n: u64) -> Result<(), XrpcError> {
if wal.is_durable(n) {
return Ok(());
}
match tokio::task::spawn_blocking(move || wal.wait(n)).await {
Ok(Ok(())) => Ok(()),
Ok(Err(e)) => {
eprintln!("pds: syncing a log: {e}");
internal()
}
Err(_) => internal(),
}
}
@@ -227,10 +276,11 @@ impl Service {
struct Shown(Vec<(Arc<Wal>, u64)>);
impl Shown {
async fn durable(self) {
async fn durable(self) -> Result<(), XrpcError> {
for (wal, n) in self.0 {
durable(wal, n).await;
durable(wal, n).await?;
}
Ok(())
}
}
@@ -271,6 +321,7 @@ impl From<Refused> for XrpcError {
let (status, name, message) = match r {
Refused::StaleCommit => (400, "InvalidSwap", "Commit was at a different CID"),
Refused::Exists(_) | Refused::Missing(_) => (500, "InternalServerError", "Internal Server Error"),
Refused::TooBig => (400, "InvalidRequest", "Commit is too large"),
};
XrpcError { status, name, message: message.into() }
}
@@ -284,6 +335,10 @@ struct Call<'a> {
body: &'a [u8],
/// What the `Authorization` header holds.
bearer: sessions::Bearer<'a>,
/// The client it is from, as the rate limits key on it.
client: String,
/// What it cost of the rate limits, for its answer's headers.
charged: OnceLock<limits::Charged>,
}
/// A query's answer, given the call and its parameters; it notes in `Shown`
@@ -325,7 +380,8 @@ enum Handler {
}
/// Each area's methods: what answers a method, by its NSID, if the area has it.
const AREAS: &[fn(&str) -> Option<Handler>] = &[server::handler, sessions::handler, repo::handler, sync::handler, federation::handler, identity::handler, blobs::handler];
const AREAS: &[fn(&str) -> Option<Handler>] =
&[server::handler, sessions::handler, repo::handler, sync::handler, federation::handler, identity::handler, blobs::handler, invites::handler];
fn handler(nsid: &str) -> Option<Handler> {
AREAS.iter().find_map(|area| area(nsid))
@@ -342,22 +398,28 @@ pub fn run() {
let dir = var("PDS_DATA_DIR");
let config = Config::from_env().unwrap_or_else(|e| fail(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))
.route("/.well-known/atproto-did", get(identity::well_known))
.with_state(svc.clone());
let app = router(&svc);
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();
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await.unwrap_or_else(|e| fail(format!("listening on port {port}: {e}")));
// Handle changes in flight when the server stopped are settled while it serves.
identity::settle_unfinished(&svc);
axum::serve(listener, app).await.unwrap();
blobs::sweep_every(&svc);
limits::serve(listener, app).await;
});
}
/// Every path the server serves.
fn router(svc: &Shared) -> Router {
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))
.route("/.well-known/atproto-did", get(identity::well_known))
.with_state(svc.clone())
}
/// 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())
@@ -368,18 +430,25 @@ async fn handle(
Path(nsid): Path<String>,
method: Method,
headers: HeaderMap,
peer: Option<Extension<limits::Peer>>,
Query(params): Query<Vec<(String, String)>>,
body: Bytes,
body: Body,
) -> Response {
// Read only so far past the method's limit: `input` refuses a body longer than it.
let Some(body) = limits::read_body(body, limits::body_limit(&nsid)).await else {
return respond(invalid("The body could not be read"), None);
};
let authorization = authorization(&headers);
let bearer = sessions::Bearer::of(authorization.as_deref());
let call = Call { nsid: &nsid, method: &method, params: &params, body: &body, bearer };
respond(answer(&st, &call).await)
let client = limits::client(&headers, peer.map(|Extension(p)| p.0));
let call = Call { nsid: &nsid, method: &method, params: &params, body: &body, bearer, client, charged: OnceLock::new() };
let answer = answer(&st, &call).await;
respond(answer, call.charged.get())
}
/// An answer as XRPC sends it.
fn respond(answer: Result<Resp, XrpcError>) -> Response {
match answer {
/// An answer as XRPC sends it, with what it cost of the rate limits.
fn respond(answer: Result<Resp, XrpcError>, charged: Option<&limits::Charged>) -> Response {
let mut res = 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(),
@@ -390,59 +459,98 @@ fn respond(answer: Result<Resp, XrpcError>) -> Response {
json!({ "error": e.name, "message": e.message }).to_string(),
)
.into_response(),
};
if let Some(c) = charged {
c.apply(res.headers_mut());
}
res
}
/// Whether an error is a token's, which costs a call nothing of the rate limits.
fn token_error(e: &XrpcError) -> bool {
matches!(e.name, "AuthMissing" | "InvalidToken" | "ExpiredToken")
}
/// Answer a call. A query reads the repositories it needs side by side with
/// other calls; a write has its account's repository alone, only to apply
/// it and hand its log frame to the operating system. Either is answered
/// only once what it read or wrote is on disk, waited for with no lock held,
/// so that calls meanwhile share the fsync.
/// so that calls meanwhile share the fsync. Each pays the rate limits once
/// its parameters, token and input are checked (`limits::guard`).
async fn answer(svc: &Shared, call: &Call<'_>) -> Result<Resp, XrpcError> {
let Some(h) = handler(call.nsid) else {
// A method not served costs its point first.
limits::charge(svc, call, None, None)?;
return err(501, "MethodNotImplemented", "Method not implemented");
};
let m = method_of(call)?;
match handler(call.nsid) {
Some(Handler::Query(f)) => {
match h {
Handler::Query(f) => {
let p = m.parse_params(call.params.iter().map(|(k, v)| (k.as_str(), v.as_str()))).or_else(|e| invalid(e.0))?;
let mut shown = Shown::default();
// A query changes nothing, so it may pay once it has run: its
// token, checked within it, costs nothing if it is refused.
let out = f(svc, call, &mut shown, &p);
shown.durable().await;
if !out.as_ref().is_err_and(token_error) {
limits::charge(svc, call, None, None)?;
}
shown.durable().await?;
out
}
Some(Handler::Lookup(f)) => {
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))?;
limits::guard(svc, call, None, None)?;
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)) => {
Handler::Write(f) => write_repo(svc, call, m, f).await,
Handler::Procedure(f) => {
let b = input(call, m)?;
limits::guard(svc, call, None, Some(&b))?;
tokio::spawn(f(svc.clone(), b)).await.unwrap_or_else(|_| internal())
}
Some(Handler::Authed(check, f)) => {
Handler::Authed(check, f) => {
let token = check(svc, call.bearer)?;
let b = input(call, m)?;
limits::guard(svc, call, Some(&token.did), Some(&b))?;
tokio::spawn(f(svc.clone(), token, b)).await.unwrap_or_else(|_| internal())
}
None => err(501, "MethodNotImplemented", "Method not implemented"),
}
}
/// A write checks, in this order, its token, its input, its `repo`, then its
/// records' `$type`.
/// A write checks, in this order, its token, its input, its `repo`, the
/// number of its writes, then its records' `$type`.
async fn write_repo(svc: &Shared, call: &Call<'_>, m: &pds_lexicon::Method, f: WriteFn) -> Result<Resp, XrpcError> {
let did = svc.auth(call.bearer).did()?;
let b = input(call, m)?;
let apply = f(&b)?;
limits::guard(svc, call, Some(&did), Some(&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");
}
if b.get("writes").and_then(Json::as_array).is_some_and(|w| w.len() > limits::MAX_WRITES) {
return invalid(format!("Too many writes. Max: {}", limits::MAX_WRITES));
}
let (out, shown, landing, doomed) = {
let mut st = write(&account.store);
let st = &mut *st;
st.repo.change = None;
let out = apply(st);
st.blobs.time(svc.limits.clock.now(), svc.config.blob_ttl);
let mut out = apply(st);
let landing = match (&out, st.repo.change.take()) {
(Ok(_), Some(c)) => Some(log::log_commit(&svc.events, &account.did, st, &c)),
(Ok(_), Some(mut c)) => match log::log_commit(&svc.events, &account.did, st, &c) {
Ok(l) => Some(l),
Err(e) => {
// Nothing of it reached the log: nothing of it stays.
eprintln!("pds: a write to {}: {e}", account.did);
if let Some(u) = c.undo.take() {
st.repo.undo(u);
}
st.blobs.undo();
out = internal();
None
}
},
_ => None,
};
(out, Shown(vec![(st.wal.clone(), st.wal.written())]), landing, st.blobs.take_doomed())
@@ -451,13 +559,14 @@ async fn write_repo(svc: &Shared, call: &Call<'_>, m: &pds_lexicon::Method, f: W
// or its event would never reach the firehose.
let svc = svc.clone();
let finish = tokio::spawn(async move {
shown.durable().await;
let synced = shown.durable().await;
if let Some(l) = landing {
svc.events.land(l);
}
blobs::forget(&svc, &account, doomed);
synced
});
finish.await.expect("finishing a write, which aborts rather than fail");
finish.await.unwrap_or_else(|_| internal())?;
out
}
@@ -477,12 +586,16 @@ fn method_of(call: &Call) -> Result<&'static pds_lexicon::Method, XrpcError> {
Ok(m)
}
/// A procedure's input, checked against its lexicon. A procedure that takes
/// none takes no body either.
/// A procedure's input, checked against its lexicon, once its length is: a
/// body longer than its method takes is `413 PayloadTooLargeError`. 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") };
}
if call.body.len() > limits::body_limit(call.nsid) {
return limits::too_large();
}
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") };
@@ -508,6 +621,7 @@ fn commit_meta(r: &Repo) -> Json {
#[cfg(test)]
mod testing {
use super::*;
use axum::body::Bytes;
/// A PLC directory, at the URL answered, which takes a genesis operation
/// only if its signature and DID are as `atproto/did-plc.md` says, and
@@ -558,6 +672,9 @@ mod testing {
})
}
/// The configuration the tests run with: no rate limits, no floor of
/// free space or of `createSession`'s time, and every DID document
/// fetched again, so that each test sees what it changes at once.
pub fn config(plc_url: &str) -> Config {
Config {
hostname: "localhost".into(),
@@ -567,9 +684,20 @@ mod testing {
rotation_key: k256::ecdsa::SigningKey::from_slice(&[9u8; 32]).unwrap(),
recovery_did_key: Some("did:key:zQ3shokFTS3brHcDQrn82RUDfCZESWL1ZdCEJwekUDPQiYBme".into()),
crawlers: vec![],
invite_required: false,
admin_password: Some(ADMIN_PASSWORD.into()),
rate_limits: false,
blob_quota: 1 << 30,
blob_ttl: 3600,
min_free: 0,
did_cache: 0,
login_floor: std::time::Duration::ZERO,
}
}
/// The admin's password in `config`.
pub const ADMIN_PASSWORD: &str = "admin-pw";
/// The server on `dir`, registering DIDs at `plc_url`.
pub fn open(dir: &FsPath, plc_url: &str) -> Shared {
Arc::new(try_open(dir, plc_url).unwrap())
@@ -579,6 +707,13 @@ mod testing {
Service::open(dir, config(plc_url))
}
/// The server on `dir`, configured as `config` and then `change` says.
pub fn open_with(dir: &FsPath, plc_url: &str, change: impl FnOnce(&mut Config)) -> Shared {
let mut c = config(plc_url);
change(&mut c);
Arc::new(Service::open(dir, c).unwrap())
}
/// 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);
@@ -588,7 +723,8 @@ mod testing {
/// 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 };
match answer(s, &Call { nsid, method: &method, params, body: body.as_bytes(), bearer }).await {
let call = Call { nsid, method: &method, params, body: body.as_bytes(), bearer, client: "127.0.0.1".into(), charged: OnceLock::new() };
match answer(s, &call).await {
Ok(Resp::Json(j)) => Ok(j),
Ok(Resp::Car(_)) => Err("a CAR file".into()),
Ok(Resp::Nothing) => Ok(Json::Null),
crates/pds-server/src/limits.rsnew+1011−0
1011 lines changed: not loaded until asked for.
crates/pds-server/src/log.rs+413−58
471 lines changed: not loaded until asked for.
crates/pds-server/src/mcp.rs+18−11
@@ -4,14 +4,15 @@
//! called through the same handling as XRPC.
use crate::sessions::Bearer;
use crate::{Auth, Call, Resp, Shared, answer, authorization};
use axum::body::Bytes;
use axum::extract::State;
use crate::{Auth, Call, Resp, Shared, answer, authorization, limits};
use axum::body::Body;
use axum::extract::{Extension, State};
use axum::http::{HeaderMap, HeaderValue, Method, StatusCode, header};
use axum::response::{IntoResponse, Response};
use base64::Engine;
use pds_lexicon::{Kind, Method as Lexicon};
use serde_json::{Map, Value as Json, json};
use std::sync::OnceLock;
/// The one protocol version served.
const VERSION: &str = "2026-07-28";
@@ -35,7 +36,7 @@ fn rpc_err(status: StatusCode, code: i64, message: impl Into<String>) -> RpcErro
RpcError { status, code, message: message.into(), data: None }
}
pub async fn endpoint(State(st): State<Shared>, method: Method, headers: HeaderMap, body: Bytes) -> Response {
pub async fn endpoint(State(st): State<Shared>, method: Method, headers: HeaderMap, peer: Option<Extension<limits::Peer>>, body: Body) -> Response {
if let Some(origin) = headers.get(header::ORIGIN) {
if !local_origin(origin) {
return error_response(None, rpc_err(StatusCode::FORBIDDEN, INVALID_REQUEST, "Origin not allowed"), false);
@@ -45,6 +46,12 @@ pub async fn endpoint(State(st): State<Shared>, method: Method, headers: HeaderM
return (StatusCode::METHOD_NOT_ALLOWED, [(header::ALLOW, "POST")]).into_response();
}
let sse = wants_sse(&headers);
let body = match limits::read_body(body, limits::MAX_MCP_BODY).await {
Some(b) if b.len() <= limits::MAX_MCP_BODY => b,
Some(_) => return error_response(None, rpc_err(StatusCode::PAYLOAD_TOO_LARGE, INVALID_REQUEST, "Request body too large"), sse),
None => return error_response(None, rpc_err(StatusCode::BAD_REQUEST, PARSE_ERROR, "The body could not be read"), sse),
};
let client = limits::client(&headers, peer.map(|Extension(p)| p.0));
let Ok(message) = serde_json::from_slice::<Json>(&body) else {
return error_response(None, rpc_err(StatusCode::BAD_REQUEST, PARSE_ERROR, "Parse error"), sse);
};
@@ -64,7 +71,7 @@ pub async fn endpoint(State(st): State<Shared>, method: Method, headers: HeaderM
}
(Some(_), Some(id)) => {
let params = message.get("params");
let answer = match request(&st, &headers, rpc_method, params).await {
let answer = match request(&st, &headers, rpc_method, params, client).await {
Ok(result) => json!({ "jsonrpc": "2.0", "id": id, "result": result }),
Err(e) => return error_response(Some(id), e, sse),
};
@@ -134,7 +141,7 @@ fn mismatch(name: &str, header: &str, body: &str) -> RpcError {
}
/// Check a request's headers and `_meta`, then answer it with its result.
async fn request(st: &Shared, headers: &HeaderMap, method: &str, params: Option<&Json>) -> Result<Json, RpcError> {
async fn request(st: &Shared, headers: &HeaderMap, method: &str, params: Option<&Json>, client: String) -> Result<Json, RpcError> {
let version = required_header(headers, "mcp-protocol-version").map_err(|mut e| {
e.message = format!("{}; this server supports protocol version {VERSION}", e.message);
e
@@ -182,7 +189,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"), authorization(headers)).await
call_tool(st, name, params.get("arguments"), authorization(headers), client).await
}
}
}
@@ -230,8 +237,8 @@ fn param_text(v: &Json) -> String {
}
/// 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> {
/// procedure's input, and the request's `Authorization` header, from `client`.
async fn call_tool(st: &Shared, name: &str, arguments: Option<&Json>, authorization: Option<String>, client: 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}")));
@@ -261,7 +268,7 @@ async fn call_tool(st: &Shared, name: &str, arguments: Option<&Json>, authorizat
// 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: &params, body: body.as_bytes(), bearer };
let call = Call { nsid: &m.nsid, method: &method, params: &params, body: body.as_bytes(), bearer, client, charged: OnceLock::new() };
let (content, is_error) = match answer(st, &call).await {
// A method that answers nothing answers `{}`.
Ok(_) if m.output.is_none() => (json!({}), false),
@@ -307,7 +314,7 @@ mod tests {
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 {
match call_tool(&s, name, args.as_ref(), Some(refresh), "127.0.0.1".into()).await {
Ok(r) => r,
Err(e) => panic!("{name}: {}", e.message),
}
crates/pds-server/src/plc.rs+59−3
crates/pds-server/src/repo.rs+43−1
crates/pds-server/src/server.rs+112−37
crates/pds-server/src/sessions.rs+344−73
417 lines changed: not loaded until asked for.
crates/pds-server/Cargo.toml+4−0
crates/pds-store/src/lib.rs+364−47
411 lines changed: not loaded until asked for.
harness/checks/accounts.mjs+12−6
harness/checks/blobs.mjs+1−1
harness/checks/crashes.mjs+2−0
harness/checks/limits.mjsnew+1022−0
1022 lines changed: not loaded until asked for.
harness/lib/args.mjs+13−1
harness/lib/env.mjs+13−2
harness/lib/plc-proxy.mjsnew+41−0
harness/lib/processes.mjs+18−9
harness/compare.mjs+19−3
harness/gates.mjs+6−1
spec/lexicons/com/atproto/server/createInviteCode.jsonnew+31−0
spec/lexicons/com/atproto/server/createInviteCodes.jsonnew+49−0
spec/lexicons/com/atproto/server/defs.jsonnew+38−0
spec/lexicons/com/atproto/server/getAccountInviteCodes.jsonnew+38−0
spec/ACCOUNTS.md+12−8
spec/BLOBS.md+10−5
spec/COMMANDS.md+6−2
spec/DURABILITY.md+5−0
spec/FEDERATION.md+3−0
spec/IDENTITY.md+12−3
spec/LIMITS.mdnew+435−0
435 lines changed: not loaded until asked for.
spec/PDS.md+8−2
spec/REPO.md+4−0
spec/SESSIONS.md+9−4
spec/SYNC.md+6−1
Cargo.lock+4−0
Cargo.toml+4−0
README.md+15−4