chadtmiller.com/monolith
An atproto PDS
0
0
Accounts move between servers, with handles of their own domains
crates/pds-cli/src/lib.rs+17−0
| @@ -634,4 +634,21 @@ mod tests { | ||
json!({ "space": "at://did:plc:x/space/a.b.c/k" }) | ||
); | ||
} | ||
| ||
/// `import-repo` sends standard input as its one type, a CAR file | ||
/// (`spec/COMMANDS.md`): no `--encoding`, nor any other flag; and its | ||
/// method has no MCP tool. | ||
#[test] | ||
fn import_repo_command() { | ||
let import = pds_lexicon::method("com.atproto.repo.importRepo").unwrap(); | ||
assert_eq!(import.command().as_deref(), Some("import-repo")); | ||
assert_eq!(fixed_encoding(import), Some("application/vnd.ipld.car")); | ||
assert_eq!(import.tool(), None); | ||
assert_eq!( | ||
flags("com.atproto.repo.importRepo", &[]).unwrap().unwrap(), | ||
Map::new() | ||
); | ||
assert!(flags("com.atproto.repo.importRepo", &["--encoding", "a/b"]).is_err()); | ||
assert!(command_help(import).contains("It takes no flags.")); | ||
} | ||
} | ||
crates/pds-lexicon/src/lib.rs+13−3
| @@ -824,7 +824,16 @@ mod tests { | ||
(Some("server_delete_session"), None, None) | ||
); | ||
let tools: Vec<String> = methods().iter().filter_map(Method::tool).collect(); | ||
assert_eq!(tools.len(), 77, "{tools:?}"); | ||
assert_eq!(tools.len(), 81, "{tools:?}"); | ||
// The methods of a move are tools, but `importRepo`, whose input is a CAR file. | ||
for t in [ | ||
"repo_list_missing_blobs", | ||
"identity_submit_plc_operation", | ||
"identity_request_plc_operation_signature", | ||
"identity_sign_plc_operation", | ||
] { | ||
assert!(tools.contains(&t.to_string()), "{t}"); | ||
} | ||
assert!( | ||
tools.contains(&"server_delete_account".to_string()) | ||
&& tools.contains(&"admin_update_subject_status".to_string()) | ||
| @@ -847,10 +856,11 @@ mod tests { | ||
&& tools.contains(&"memberspace_put_member".to_string()) | ||
); | ||
// uploadBlob's input and getBlob's answer are bytes: neither has a tool, both a command; | ||
// nor have a space meta archive's export and import, a space repo's archive and import, | ||
// or a space blob. | ||
// nor have importRepo's CAR file, a space meta archive's export and import, a space | ||
// repo's archive and import, or a space blob. | ||
for nsid in [ | ||
"com.atproto.repo.uploadBlob", | ||
"com.atproto.repo.importRepo", | ||
"com.atproto.sync.getBlob", | ||
"com.atproto.space.exportSpaceMeta", | ||
"com.atproto.space.importSpaceMeta", | ||
crates/pds-repo/src/lib.rs+26−1
| @@ -441,6 +441,29 @@ impl Repo { | ||
ops: Vec<Op>, | ||
swap_commit: Option<&str>, | ||
check: impl FnOnce() -> Result<(), E>, | ||
) -> Result<Vec<OpResult>, E> { | ||
self.write(src, ops, swap_commit, check, true) | ||
} | ||
| ||
/// Apply writes as one commit, all or nothing, as `apply_checked` does, | ||
/// but with no bound on what its event would carry: a repository | ||
/// imported whole, whose commit goes on no `#commit` event. | ||
pub fn import<E: From<Refused>>( | ||
&mut self, | ||
src: &dyn Source, | ||
ops: Vec<Op>, | ||
check: impl FnOnce() -> Result<(), E>, | ||
) -> Result<(), E> { | ||
self.write(src, ops, None, check, false).map(|_| ()) | ||
} | ||
| ||
fn write<E: From<Refused>>( | ||
&mut self, | ||
src: &dyn Source, | ||
ops: Vec<Op>, | ||
swap_commit: Option<&str>, | ||
check: impl FnOnce() -> Result<(), E>, | ||
bounded: bool, | ||
) -> Result<Vec<OpResult>, E> { | ||
if swap_commit.is_some_and(|s| s != self.head_string()) { | ||
return Err(Refused::StaleCommit.into()); | ||
| @@ -607,7 +630,9 @@ impl Repo { | ||
} | ||
let nodes: Vec<Block> = nodes.into_iter().collect(); | ||
let mut change = self.commit(rev, root, tree, gone, refs, evops, nodes, (records, blocks)); | ||
if event_blocks_len(&self.head, &self.head_bytes, &change.blocks) > MAX_EVENT_BLOCKS { | ||
if bounded | ||
&& event_blocks_len(&self.head, &self.head_bytes, &change.blocks) > MAX_EVENT_BLOCKS | ||
{ | ||
if let Some(u) = change.undo.take() { | ||
self.undo(u); | ||
} | ||
crates/pds-repo/src/mst.rs+53−5
| @@ -229,14 +229,20 @@ fn node(entries: &[(Vec<u8>, Vec<u8>)], depths: &[usize], level: usize) -> Optio | ||
/// order, and the CIDs of the nodes it holds, each once. | ||
pub type Walked = (Vec<(Vec<u8>, Vec<u8>)>, Vec<Vec<u8>>); | ||
| ||
/// The deepest a tree's nodes may be below its root: a key's depth is at | ||
/// most 128, two bits of its SHA-256 for each level. | ||
const MAX_LEVELS: usize = 129; | ||
| ||
/// Walk the tree rooted at `root`, its nodes found by `block`: its entries in | ||
/// key order and its nodes. Err for a node `block` does not find, one that is | ||
/// not a tree node (a map of exactly `l` and `e`, each entry exactly `p`, | ||
/// `k`, `v` and `t`), or keys not in strictly ascending order. Whether the | ||
/// tree is the one its entries build is not checked: `build_tree` says. | ||
/// `k`, `v` and `t`), a node reached twice, nodes deeper than any tree's, or | ||
/// keys not in strictly ascending order. Whether the tree is the one its | ||
/// entries build is not checked: `build_tree` says. | ||
pub fn walk<'a>(root: &[u8], block: impl Fn(&[u8]) -> Option<&'a [u8]>) -> Result<Walked, String> { | ||
let mut out: Walked = (Vec::new(), Vec::new()); | ||
visit(root, &block, &mut out)?; | ||
let mut seen = HashSet::new(); | ||
visit(root, &block, &mut out, &mut seen, 0)?; | ||
Ok(out) | ||
} | ||
| ||
| @@ -244,8 +250,16 @@ fn visit<'a>( | ||
cid: &[u8], | ||
block: &impl Fn(&[u8]) -> Option<&'a [u8]>, | ||
out: &mut Walked, | ||
seen: &mut HashSet<Vec<u8>>, | ||
level: usize, | ||
) -> Result<(), String> { | ||
let bad = |why: &str| format!("tree node {}: {why}", cid_string(cid)); | ||
if level >= MAX_LEVELS { | ||
return Err(bad("deeper than any tree's nodes")); | ||
} | ||
if !seen.insert(cid.to_vec()) { | ||
return Err(bad("reached twice")); | ||
} | ||
let bytes = block(cid).ok_or_else(|| bad("missing"))?; | ||
out.1.push(cid.to_vec()); | ||
let V::Map(mut m) = decode(bytes).map_err(|e| bad(&e))? else { | ||
| @@ -261,7 +275,7 @@ fn visit<'a>( | ||
return Err(bad("not exactly l and a list e")); | ||
}; | ||
if let Some(l) = link(l)? { | ||
visit(&l, block, out)?; | ||
visit(&l, block, out, seen, level + 1)?; | ||
} | ||
let mut prev: Vec<u8> = Vec::new(); | ||
for e in entries { | ||
| @@ -289,7 +303,7 @@ fn visit<'a>( | ||
} | ||
out.0.push((prev.clone(), v)); | ||
if let Some(t) = link(t)? { | ||
visit(&t, block, out)?; | ||
visit(&t, block, out, seen, level + 1)?; | ||
} | ||
} | ||
Ok(()) | ||
| @@ -450,4 +464,38 @@ mod tests { | ||
let cid = cid_of(0x71, &bytes); | ||
assert!(walk(&cid, |c| (*c == cid[..]).then_some(bytes.as_slice())).is_err()); | ||
} | ||
| ||
/// A node reached twice, as a left subtree and below an entry, is no | ||
/// tree, and is refused rather than walked again. | ||
#[test] | ||
fn a_node_reached_twice_is_refused() { | ||
let leaf = encode(&V::Map(vec![ | ||
("l".into(), V::Null), | ||
("e".into(), V::Arr(vec![])), | ||
])); | ||
let leaf_cid = cid_of(0x71, &leaf); | ||
let root = encode(&V::Map(vec![ | ||
("l".into(), V::Link(leaf_cid.clone())), | ||
( | ||
"e".into(), | ||
V::Arr(vec![V::Map(vec![ | ||
("p".into(), V::Int(0)), | ||
("k".into(), V::Bytes(b"a/b".to_vec())), | ||
("v".into(), V::Link(cid_of(0x71, b"x"))), | ||
("t".into(), V::Link(leaf_cid.clone())), | ||
])]), | ||
), | ||
])); | ||
let root_cid = cid_of(0x71, &root); | ||
let got = walk(&root_cid, |c| { | ||
if *c == root_cid[..] { | ||
Some(root.as_slice()) | ||
} else if *c == leaf_cid[..] { | ||
Some(leaf.as_slice()) | ||
} else { | ||
None | ||
} | ||
}); | ||
assert!(got.is_err_and(|e| e.contains("reached twice"))); | ||
} | ||
} | ||
crates/pds-server/src/identity/resolve.rsnew+430−0
430 lines changed: not loaded until asked for.
crates/pds-server/src/migration/tests.rsnew+1008−0
1008 lines changed: not loaded until asked for.
crates/pds-server/src/ops/trace.rs+5−1
| @@ -380,7 +380,8 @@ pub(crate) fn server_span( | ||
/// crawler, a service it forwards to or reads from (the AppView, those | ||
/// `atproto-proxy` names), a `did:web` document, a client's metadata or | ||
/// keys (OAuth's, or an attesting client's), a space's notification, a | ||
/// permission set's record, or the bucket blobs are kept in. | ||
/// permission set's record, a handle's `/.well-known/atproto-did`, or the | ||
/// bucket blobs are kept in. | ||
#[derive(Clone, Copy, PartialEq, Eq)] | ||
pub(crate) enum Target { | ||
Plc, | ||
| @@ -390,6 +391,7 @@ pub(crate) enum Target { | ||
Client, | ||
Space, | ||
Lexicon, | ||
Handle, | ||
Blobstore, | ||
} | ||
| ||
| @@ -403,6 +405,7 @@ impl Target { | ||
Target::Client => "client", | ||
Target::Space => "space", | ||
Target::Lexicon => "lexicon", | ||
Target::Handle => "handle", | ||
Target::Blobstore => "blobstore", | ||
} | ||
} | ||
| @@ -417,6 +420,7 @@ impl Target { | ||
Target::Client => ("client failure", Level::Debug), | ||
Target::Space => ("space notification failure", Level::Debug), | ||
Target::Lexicon => ("lexicon failure", Level::Debug), | ||
Target::Handle => ("handle failure", Level::Debug), | ||
Target::Blobstore => ("blobstore failure", Level::Warn), | ||
} | ||
} | ||
crates/pds-server/src/space_credentials/jwt.rs+7−2
| @@ -140,14 +140,19 @@ impl Key { | ||
/// whose `id` is `#atproto` or `<did>#atproto`, as a `Multikey` or in the | ||
/// legacy form. None for a document of another DID. | ||
pub fn of_document(doc: &Json, did: &str) -> Option<Key> { | ||
Key::of_document_named(doc, did, "atproto") | ||
} | ||
| ||
/// The key `#<id>` of `did`'s document, as `of_document` finds `#atproto`. | ||
pub fn of_document_named(doc: &Json, did: &str, id: &str) -> Option<Key> { | ||
if doc["id"] != did { | ||
return None; | ||
} | ||
let full = format!("{did}#atproto"); | ||
let (short, full) = (format!("#{id}"), format!("{did}#{id}")); | ||
let method = doc["verificationMethod"] | ||
.as_array()? | ||
.iter() | ||
.find(|m| m["id"] == "#atproto" || m["id"] == full.as_str())?; | ||
.find(|m| m["id"] == short.as_str() || m["id"] == full.as_str())?; | ||
let (typ, multibase) = ( | ||
method["type"].as_str()?, | ||
method["publicKeyMultibase"].as_str()?, | ||
crates/pds-server/src/blobs.rs+55−0
| @@ -500,6 +500,34 @@ impl Blobs { | ||
(self.refs.len(), self.held.len() - past) | ||
} | ||
| ||
/// The blobs its records reference that it does not hold, in order of | ||
/// CID, those after `cursor` (as strings), at most `limit`: each with | ||
/// the path of a record referencing it, the first in order of path | ||
/// (`spec/MIGRATION.md`). | ||
pub(crate) fn missing(&self, cursor: Option<&str>, limit: usize) -> Vec<(String, String)> { | ||
let mut cids: Vec<&String> = self | ||
.refs | ||
.keys() | ||
.filter(|c| !self.held.contains_key(*c) && cursor.is_none_or(|k| c.as_str() > k)) | ||
.collect(); | ||
cids.sort_unstable(); | ||
cids.truncate(limit); | ||
let mut paths: BTreeMap<&str, &str> = BTreeMap::new(); | ||
for (path, (_, refs)) in &self.records { | ||
for cid in refs { | ||
if cids.binary_search(&cid).is_ok() { | ||
let p = paths.entry(cid.as_str()).or_insert(path.as_str()); | ||
if path.as_str() < *p { | ||
*p = path.as_str(); | ||
} | ||
} | ||
} | ||
} | ||
cids.into_iter() | ||
.filter_map(|c| Some((c.clone(), paths.get(c.as_str())?.to_string()))) | ||
.collect() | ||
} | ||
| ||
/// Check a write's blob refs against the blobs as they were before it: | ||
/// a public write's, or a space write's (`space_repo`). | ||
pub(crate) fn check(&self, refs: &[BlobRef]) -> Result<(), XrpcError> { | ||
| @@ -969,6 +997,33 @@ pub(crate) fn apply( | ||
Ok(results) | ||
} | ||
| ||
/// Make the account's repository the tree an import brings, by `ops`, as | ||
/// one commit: its blob refs are not checked, each blob it does not hold | ||
/// becoming missing until it is uploaded (`spec/MIGRATION.md`), and their | ||
/// references are counted as a write's. | ||
pub(crate) fn import(st: &mut Store, ops: Vec<Op>) -> Result<(), XrpcError> { | ||
let mut refs = Vec::new(); | ||
for op in &ops { | ||
if let Op::Create { value, .. } | Op::Update { value, .. } = op { | ||
refs_in(value, &mut refs); | ||
} | ||
} | ||
let Store { | ||
repo, | ||
blobs, | ||
disk, | ||
ctx, | ||
wal, | ||
.. | ||
} = st; | ||
repo.import(&disk.source(&ctx.blocks), ops, || Ok::<(), XrpcError>(()))?; | ||
if let Some(c) = &repo.change { | ||
blobs.sync_before(wal, refs.iter().map(|r| cid_string(&r.cid))); | ||
blobs.committed(c); | ||
} | ||
Ok(()) | ||
} | ||
| ||
/// Remove the files of blobs a write stopped holding, once it is on disk: | ||
/// those not held again, by an upload since, or moving into place. With | ||
/// blobs in a bucket, have the deleter delete their objects (`blobstore`). | ||
crates/pds-server/src/cache.rs+8−3
| @@ -476,13 +476,18 @@ impl Slot { | ||
let mut r = crate::log::open_repo(c, &a.did, &self.key)?; | ||
self.compacted(&r.store); | ||
if r.fresh && !c.starting.load(Ordering::SeqCst) { | ||
let landing = crate::log::first_commit(&c.events, &a.did, &a.handle(), &mut r.store) | ||
.map_err(|e| format!("{}: {e}", a.did))?; | ||
// With no events if it was made deactivated, moving here. | ||
let quiet = crate::read(&a.state).deactivated; | ||
let landing = | ||
crate::log::first_commit(&c.events, &a.did, &a.handle(), &mut r.store, quiet) | ||
.map_err(|e| format!("{}: {e}", a.did))?; | ||
r.store | ||
.wal | ||
.wait(r.store.wal.written()) | ||
.map_err(|e| format!("{}: {e}", a.did))?; | ||
c.events.land(landing); | ||
if let Some(l) = landing { | ||
c.events.land(l); | ||
} | ||
} | ||
Ok(r.store) | ||
} | ||
crates/pds-server/src/email.rs+10−1
| @@ -51,15 +51,18 @@ pub(crate) enum Purpose { | ||
AuthFactor, | ||
/// `requestAccountDelete`'s (`spec/LIFECYCLE.md`). | ||
DeleteAccount, | ||
/// `requestPlcOperationSignature`'s (`spec/MIGRATION.md`). | ||
PlcOperation, | ||
} | ||
| ||
impl Purpose { | ||
const ALL: [Purpose; 5] = [ | ||
const ALL: [Purpose; 6] = [ | ||
Purpose::ConfirmEmail, | ||
Purpose::UpdateEmail, | ||
Purpose::ResetPassword, | ||
Purpose::AuthFactor, | ||
Purpose::DeleteAccount, | ||
Purpose::PlcOperation, | ||
]; | ||
| ||
/// Its name, as the log has it. | ||
| @@ -70,6 +73,7 @@ impl Purpose { | ||
Purpose::ResetPassword => "reset_password", | ||
Purpose::AuthFactor => "auth_factor", | ||
Purpose::DeleteAccount => "delete_account", | ||
Purpose::PlcOperation => "plc_operation", | ||
} | ||
} | ||
| ||
| @@ -85,6 +89,7 @@ impl Purpose { | ||
Purpose::ResetPassword => "resetPassword", | ||
Purpose::AuthFactor => "signInAuthFactor", | ||
Purpose::DeleteAccount => "deleteAccount", | ||
Purpose::PlcOperation => "plcOperation", | ||
} | ||
} | ||
| ||
| @@ -95,6 +100,7 @@ impl Purpose { | ||
Purpose::ResetPassword => "Password Reset Requested", | ||
Purpose::AuthFactor => "Sign-in Confirmation", | ||
Purpose::DeleteAccount => "Account Deletion Requested", | ||
Purpose::PlcOperation => "PLC Update Operation Requested", | ||
} | ||
} | ||
| ||
| @@ -107,6 +113,9 @@ impl Purpose { | ||
Purpose::ResetPassword => "To reset the password of your account, enter this code", | ||
Purpose::AuthFactor => "To sign in to your account, enter this code", | ||
Purpose::DeleteAccount => "To delete your account, enter this code", | ||
Purpose::PlcOperation => { | ||
"To sign an operation that changes your account's DID document, enter this code" | ||
} | ||
}; | ||
format!( | ||
"{what}:\n\n {token}\n\nIt works for 15 minutes, once. If you did not ask for it, ignore this email.\n" | ||
crates/pds-server/src/events.rs+13−0
| @@ -779,6 +779,19 @@ pub fn identity_event(did: &str, handle: &str, seq: u64, time: &str) -> Vec<u8> | ||
) | ||
} | ||
| ||
/// The `#identity` event of a DID whose document changed, with no handle: | ||
/// a PLC operation submitted for it (`spec/MIGRATION.md`). | ||
pub fn did_event(did: &str, seq: u64, time: &str) -> Vec<u8> { | ||
message( | ||
"#identity", | ||
vec![ | ||
("seq", V::Int(seq as i64)), | ||
("did", s(did)), | ||
("time", s(time)), | ||
], | ||
) | ||
} | ||
| ||
/// The `#account` event of an account's state: `active`, or not and why. | ||
pub fn account_event(did: &str, seq: u64, time: &str, status: Option<&str>) -> Vec<u8> { | ||
let mut body = vec![ | ||
crates/pds-server/src/identity.rs+86−7
crates/pds-server/src/lib.rs+27−3
crates/pds-server/src/lifecycle.rs+42−1
crates/pds-server/src/limits.rs+13−0
crates/pds-server/src/log.rs+49−15
crates/pds-server/src/migration.rsnew+594−0
594 lines changed: not loaded until asked for.
crates/pds-server/src/outbound.rs+56−12
crates/pds-server/src/plc.rs+35−0
crates/pds-server/src/proxy.rs+15−3
crates/pds-server/src/scopes.rs+26−4
crates/pds-server/src/server.rs+131−37
docs/guide/calling.md+13−0
docs/guide/comparing.md+13−0
docs/guide/deploying.md+3−1
docs-site/astro.config.mjs+1−1
harness/checks/moves.mjsnew+859−0
859 lines changed: not loaded until asked for.
harness/checks/operations.mjs+7−3
harness/lib/adapters/index.mjs+3−2
harness/lib/adapters/spec-pds.mjs+1−1
harness/lib/args.mjs+9−3
harness/lib/env.mjs+16−4
harness/lib/handles.mjsnew+121−0
harness/lib/processes.mjs+10−5
harness/lib/report.mjs+5−3
harness/compare.mjs+15−2
harness/gates.mjs+3−1
spec/lexicons/com/atproto/identity/requestPlcOperationSignature.jsonnew+10−0
spec/lexicons/com/atproto/identity/signPlcOperation.jsonnew+45−0
spec/lexicons/com/atproto/identity/submitPlcOperation.jsonnew+20−0
spec/lexicons/com/atproto/repo/importRepo.jsonnew+13−0
spec/lexicons/com/atproto/repo/listMissingBlobs.jsonnew+44−0
spec/ACCOUNTS.md+15−7
spec/COMMANDS.md+9−3
spec/DURABILITY.md+4−0
spec/EMAIL.md+3−1
spec/IDENTITY.md+71−16
spec/LIFECYCLE.md+9−2
spec/LIMITS.md+18−11
spec/MIGRATION.mdnew+437−0
437 lines changed: not loaded until asked for.