chadtmiller.com/monolith
An atproto PDS
0
0
Account lifecycle and email: deactivation, deletion, takedowns, and confirming, changing and resetting by email
crates/pds/src/main.rs+2−1
| @@ -3,7 +3,8 @@ | ||
const SERVE_HELP: &str = "Usage: pds serve\n\n\ | ||
Run the server, configured by its environment: PDS_PORT, PDS_DATA_DIR, PDS_HOSTNAME,\n\ | ||
PDS_PUBLIC_URL, PDS_HANDLE_DOMAINS, PDS_PLC_URL, PDS_PLC_ROTATION_KEY_HEX and,\n\ | ||
if set, PDS_RECOVERY_DID_KEY.\n"; | ||
if set, PDS_RECOVERY_DID_KEY; PDS_EMAIL_SMTP_URL and PDS_EMAIL_FROM, both or\n\ | ||
neither; and PDS_DEV_MAIL_DIR, for development only.\n"; | ||
| ||
fn main() { | ||
let args: Vec<String> = std::env::args().skip(1).collect(); | ||
crates/pds-lexicon/src/lib.rs+13−2
| @@ -665,7 +665,9 @@ 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(), 64, "{tools:?}"); | ||
assert_eq!(tools.len(), 77, "{tools:?}"); | ||
assert!(tools.contains(&"server_delete_account".to_string()) && tools.contains(&"admin_update_subject_status".to_string())); | ||
assert!(tools.contains(&"server_request_password_reset".to_string()) && tools.contains(&"server_update_email".to_string())); | ||
assert!(tools.contains(&"space_list_blobs".to_string())); | ||
assert!(tools.contains(&"space_notify_write".to_string()) && tools.contains(&"space_list_repos".to_string())); | ||
assert!(tools.contains(&"sync_list_repos".to_string()) && tools.contains(&"sync_get_repo_status".to_string())); | ||
| @@ -689,7 +691,7 @@ mod tests { | ||
assert!(method("com.atproto.space.importSpaceMeta").unwrap().raw_input()); | ||
assert!(method("com.atproto.space.importRepo").unwrap().raw_input()); | ||
assert!(!method("com.atproto.repo.createRecord").unwrap().raw_input()); | ||
assert_eq!(groups(), ["actor", "feed", "identity", "memberspace", "notification", "repo", "server", "space", "sync"]); | ||
assert_eq!(groups(), ["actor", "admin", "feed", "identity", "memberspace", "notification", "repo", "server", "space", "sync"]); | ||
assert!(method("com.atproto.repo.defs").is_none()); | ||
assert!(method("com.atproto.space.policy").is_none()); | ||
} | ||
| @@ -703,6 +705,15 @@ mod tests { | ||
} | ||
} | ||
| ||
/// `deactivateAccount`'s `deleteAfter` is held to its datetime format | ||
/// (`format.rs`). | ||
#[test] | ||
fn delete_after_is_a_datetime() { | ||
let m = method("com.atproto.server.deactivateAccount").unwrap(); | ||
assert!(m.check_input(&json!({ "deleteAfter": "tomorrow" })).is_err()); | ||
assert!(m.check_input(&json!({ "deleteAfter": "2030-01-01T00:00:00.000Z" })).is_ok()); | ||
} | ||
| ||
#[test] | ||
fn input_schema() { | ||
let m = method("com.atproto.repo.listRecords").unwrap(); | ||
crates/pds-repo/src/lib.rs+15−0
| @@ -212,6 +212,21 @@ impl Repo { | ||
cid_string(&self.head) | ||
} | ||
| ||
/// The latest commit's block. | ||
pub fn head_bytes(&self) -> &[u8] { | ||
&self.head_bytes | ||
} | ||
| ||
/// How many distinct blocks the latest commit and its tree are: the | ||
/// commit, every node of the tree, and every record, each CID once. | ||
pub fn block_count(&self) -> usize { | ||
let mut cids: HashSet<&[u8]> = HashSet::new(); | ||
cids.insert(&self.head); | ||
cids.extend(self.tree.nodes().into_iter().map(|n| n.cid.as_slice())); | ||
cids.extend(self.records.values().map(|r| r.cid.as_slice())); | ||
cids.len() | ||
} | ||
| ||
/// The tree's `(key, record cid)` pairs, in key order. | ||
fn entries(&self) -> Vec<(Vec<u8>, Vec<u8>)> { | ||
self.records.iter().map(|(k, r)| (k.as_bytes().to_vec(), r.cid.clone())).collect() | ||
crates/pds-server/src/lifecycle/tests.rsnew+766−0
766 lines changed: not loaded until asked for.
crates/pds-server/src/oauth/page.rs+22−7
| @@ -154,11 +154,13 @@ fn param<'q>(q: &'q [(String, String)], k: &str) -> Option<&'q str> { | ||
| ||
/// An account, as the page and the API show it. | ||
fn account_json(svc: &Service, a: &Account) -> Json { | ||
let m = crate::email::lock(&a.mail).clone(); | ||
let deactivated = crate::read(&a.state).deactivated; | ||
let mut out = json!({ | ||
"did": a.did, "pds": format!("did:web:{}", svc.config.hostname), "emailVerified": false, | ||
"emailAuthFactor": false, "handle": a.handle(), "deactivated": false, | ||
"did": a.did, "pds": format!("did:web:{}", svc.config.hostname), "emailVerified": m.confirmed, | ||
"emailAuthFactor": m.auth_factor, "handle": a.handle(), "deactivated": deactivated, | ||
}); | ||
if let Some(e) = &a.email { | ||
if let Some(e) = &m.email { | ||
out["email"] = json!(e); | ||
} | ||
let profile = crate::read(&a.store).repo.records.get("app.bsky.actor.profile/self").map(|r| pds_repo::data::to_json(&r.value)); | ||
| @@ -274,8 +276,9 @@ fn authorization_page(svc: &Service, request_uri: &str, client: &client::Client, | ||
if let Some(l) = &r.ui_locales { | ||
data["uiLocales"] = json!(l); | ||
} | ||
// The account the hint names here, if any. | ||
let hinted = r.login_hint.as_deref().and_then(|h| svc.account(h)); | ||
// The account the hint names here, if any: a taken-down one is none, | ||
// its DID shown as given and it not selected. | ||
let hinted = r.login_hint.as_deref().and_then(|h| svc.account(h)).filter(|a| crate::read(&a.state).takedown.is_none()); | ||
if let Some(h) = &r.login_hint { | ||
data["loginHint"] = json!(match &hinted { | ||
Some(a) if h.starts_with("did:") => a.handle(), | ||
| @@ -285,7 +288,8 @@ fn authorization_page(svc: &Service, request_uri: &str, client: &client::Client, | ||
let sessions: Vec<Json> = loaded | ||
.signed_in | ||
.iter() | ||
.filter_map(|(did, at)| svc.account(did).map(|a| json!({ "account": account_json(svc, &a), "loginRequired": clients::silent::needs_sign_in(r, *at, now) }))) | ||
// A taken-down account stays signed in on the device, but is not shown. | ||
.filter_map(|(did, at)| svc.account(did).filter(|a| crate::read(&a.state).takedown.is_none()).map(|a| json!({ "account": account_json(svc, &a), "loginRequired": clients::silent::needs_sign_in(r, *at, now) }))) | ||
.collect(); | ||
// A public client's request selects the hinted account only when it asks | ||
// for consent, none when asked to create an account; a confidential | ||
| @@ -497,11 +501,14 @@ fn text<'b>(b: &'b Map<String, Json>, k: &str) -> &'b str { | ||
async fn sign_in(svc: &Shared, tx: &mut Tx<'_>, device: &str, request_id: &str, b: &Map<String, Json>) -> Result<Json, String> { | ||
let refused = || Err("Invalid identifier or password".to_string()); | ||
let Some(account) = crate::server::login(svc, text(b, "identifier")) else { return refused() }; | ||
let Some(hash) = account.password.clone() else { return refused() }; | ||
let Some(hash) = crate::email::lock(&account.mail).password.clone() else { return refused() }; | ||
let pw = text(b, "password").to_string(); | ||
if !tokio::task::spawn_blocking(move || crate::server::password::verify(&pw, &hash)).await.unwrap_or(false) { | ||
return refused(); | ||
} | ||
if crate::read(&account.state).takedown.is_some() { | ||
return Err("Account was taken down".into()); | ||
} | ||
let remember = b.get("remember").and_then(Json::as_bool); | ||
let did = account.did.clone(); | ||
// Remembered, or left out for an account already signed in here, it is | ||
| @@ -604,6 +611,14 @@ async fn consent(svc: &Shared, tx: &mut Tx<'_>, headers: &HeaderMap, device: &st | ||
if let Err(f) = loaded { | ||
return end_with(svc, id, r, f.at_consent(), "The client cannot be loaded"); | ||
} | ||
// A deactivated account signs in, but approves nothing (`spec/LIFECYCLE.md`). | ||
// A taken-down account still signed in on the device approves nothing either. | ||
if svc.account(did).is_some_and(|a| crate::read(&a.state).takedown.is_some()) { | ||
return end_with(svc, id, r, "invalid_request", "Account was taken down"); | ||
} | ||
if svc.account(did).is_some_and(|a| crate::read(&a.state).deactivated) { | ||
return end_with(svc, id, r, "access_denied", "This account has been deactivated"); | ||
} | ||
let scope = b.get("scope").and_then(Json::as_str).map_or_else(|| r.scope.clone(), |s| narrow(&r.scope, s)); | ||
if !scope.iter().any(|t| t == "atproto") { | ||
return end_with(svc, id, r, "access_denied", "The atproto scope is required"); | ||
crates/pds-server/src/oauth/tests.rs+15−0
| @@ -305,6 +305,21 @@ impl<'s> App<'s> { | ||
} | ||
panic!("the server kept asking for a nonce"); | ||
} | ||
| ||
/// A JSON procedure with an access token and a proof. | ||
pub async fn post(&mut self, nsid: &str, access: &str, body: Json) -> Got { | ||
let path = format!("/xrpc/{nsid}"); | ||
for _ in 0..2 { | ||
let proof = self.proof("POST", &path, Some(access)); | ||
let r = self.srv.request("POST", &path).header("authorization", format!("DPoP {access}")).header("dpop", proof).header("content-type", "application/json").body(body.to_string()); | ||
let g = got(r).await; | ||
self.keep_nonce(&g); | ||
if g.error() != "use_dpop_nonce" { | ||
return g; | ||
} | ||
} | ||
panic!("the server kept asking for a nonce"); | ||
} | ||
} | ||
| ||
/// A browser: the cookies it was given. | ||
crates/pds-server/src/blobs.rs+80−13
| @@ -47,8 +47,9 @@ pub(crate) const UPLOAD_LIMIT: u64 = 5 * 1024 * 1024; | ||
| ||
const UPLOAD: &str = "com.atproto.repo.uploadBlob"; | ||
| ||
/// The kinds of entry an account's log has of its blobs. | ||
pub(crate) const ENTRIES: &[&str] = &["blob", "blobGone"]; | ||
/// The kinds of entry an account's log has of its blobs: an upload, one no | ||
/// longer held, and a takedown or its lifting (`spec/LIFECYCLE.md`). | ||
pub(crate) const ENTRIES: &[&str] = &["blob", "blobGone", "takedownBlob"]; | ||
| ||
/// How often uploads held past their time are logged as gone, and their files removed. | ||
const SWEEP_EVERY: std::time::Duration = std::time::Duration::from_secs(30); | ||
| @@ -83,6 +84,8 @@ struct Undo { | ||
held: Vec<(String, Option<Held>)>, | ||
bytes: u64, | ||
doomed: usize, | ||
/// The takedowns of the blobs it stopped holding. | ||
takedowns: Vec<(String, String)>, | ||
} | ||
| ||
/// An account's blobs, kept with its repository and changed under its lock. | ||
| @@ -113,6 +116,9 @@ pub(crate) struct Blobs { | ||
/// is held, both in seconds. | ||
now: u64, | ||
ttl: u64, | ||
/// The blobs held taken down, by CID, each with its reference: a blob no | ||
/// longer held is no longer taken down. | ||
takedowns: BTreeMap<String, String>, | ||
} | ||
| ||
/// A blob ref in a record. | ||
| @@ -234,12 +240,43 @@ impl Blobs { | ||
self.held.get(cid).filter(|_| self.refs.contains_key(cid)) | ||
} | ||
| ||
/// Whether it holds `cid`: stored, and if unreferenced, within its time. | ||
fn holds(&self, cid: &str) -> bool { | ||
self.held.contains_key(cid) && !self.expired(cid) | ||
} | ||
| ||
/// A blob it holds: its takedown's reference, if it is down. | ||
pub(crate) fn held_takedown(&self, cid: &str) -> Option<Option<&str>> { | ||
self.holds(cid).then(|| self.takedowns.get(cid).map(String::as_str)) | ||
} | ||
| ||
fn taken_down(&self, cid: &str) -> bool { | ||
self.holds(cid) && self.takedowns.contains_key(cid) | ||
} | ||
| ||
/// The entry that takes down a blob it holds with reference `r`, or | ||
/// lifts that with none: none if that changes nothing. | ||
pub(crate) fn takedown_entry(&self, cid: &str, r: Option<&str>) -> Option<Json> { | ||
let changes = match r { | ||
Some(_) => self.holds(cid), | ||
None => self.takedowns.contains_key(cid), | ||
}; | ||
changes.then(|| json!({ "t": "takedownBlob", "cid": cid, "ref": r })) | ||
} | ||
| ||
/// How many distinct blobs its records reference, and how many it holds, | ||
/// at `now` with uploads held for `ttl`. | ||
pub(crate) fn counts(&self, now: u64, ttl: u64) -> (usize, usize) { | ||
let past = self.unreferenced.iter().take_while(|(at, _)| at.saturating_add(ttl) <= now).count(); | ||
(self.refs.len(), self.held.len() - past) | ||
} | ||
| ||
/// 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> { | ||
for r in refs { | ||
let cid = cid_string(&r.cid); | ||
let Some(h) = self.held.get(&cid).filter(|_| !self.expired(&cid)) else { return err(400, "BlobNotFound", format!("Could not find blob: {cid}")) }; | ||
let Some(h) = self.held.get(&cid).filter(|_| !self.expired(&cid) && !self.takedowns.contains_key(&cid)) else { return err(400, "BlobNotFound", format!("Could not find blob: {cid}")) }; | ||
// One some record, public or in a space, references already is taken as it is. | ||
if self.referenced(&cid) { | ||
continue; | ||
| @@ -254,12 +291,17 @@ impl Blobs { | ||
Ok(()) | ||
} | ||
| ||
/// Hold `cid`, or stop holding it, keeping the index of those unreferenced and the bytes held. | ||
/// Hold `cid`, or stop holding it, keeping the index of those | ||
/// unreferenced and the bytes held: one no longer held is no longer | ||
/// taken down. | ||
fn set_held(&mut self, cid: &str, h: Option<Held>) { | ||
if let Some(old) = self.held.remove(cid) { | ||
self.unreferenced.remove(&(old.at, cid.to_string())); | ||
self.bytes -= old.size; | ||
} | ||
if h.is_none() { | ||
self.takedowns.remove(cid); | ||
} | ||
if let Some(h) = h { | ||
if !self.referenced(cid) { | ||
self.unreferenced.insert((h.at, cid.to_string())); | ||
| @@ -306,6 +348,9 @@ impl Blobs { | ||
} | ||
self.refs.remove(&cid); | ||
if d < 0 && held.is_some() && !self.space_refs.contains_key(&cid) { | ||
if let Some(t) = self.takedowns.get(&cid) { | ||
undo.takedowns.push((cid.clone(), t.clone())); | ||
} | ||
self.set_held(&cid, None); | ||
self.doomed.push(cid); | ||
} | ||
| @@ -370,6 +415,7 @@ impl Blobs { | ||
} | ||
self.bytes = u.bytes; | ||
self.doomed.truncate(u.doomed); | ||
self.takedowns.extend(u.takedowns); | ||
} | ||
| ||
/// What uploading `cid` would do. | ||
| @@ -391,7 +437,11 @@ impl Blobs { | ||
let mime = self.held[cid].mime.clone(); | ||
self.set_held(cid, Some(Held { mime, ..h })); | ||
} | ||
Upload::Afresh | Upload::New => self.set_held(cid, Some(h)), | ||
Upload::Afresh | Upload::New => { | ||
// One taken down and past its time is no longer held, nor down. | ||
self.takedowns.remove(cid); | ||
self.set_held(cid, Some(h)); | ||
} | ||
} | ||
} | ||
| ||
| @@ -405,6 +455,14 @@ impl Blobs { | ||
self.set_held(cid, None); | ||
return Ok(()); | ||
} | ||
if e["t"] == "takedownBlob" { | ||
match &e["ref"] { | ||
Json::String(r) if self.held.contains_key(cid) => self.takedowns.insert(cid.to_string(), r.clone()), | ||
Json::Null => self.takedowns.remove(cid), | ||
_ => return Err(format!("a takedown of a blob not held, or with a ref not a string: {e}")), | ||
}; | ||
return Ok(()); | ||
} | ||
let (Some(mime), Some(size), Some(at)) = (e["mimeType"].as_str(), e["size"].as_u64(), e["at"].as_u64()) else { | ||
return Err(format!("a blob with no mimeType, size or at: {e}")); | ||
}; | ||
| @@ -447,7 +505,7 @@ impl Blobs { | ||
let refs: BTreeMap<_, _> = self.refs.iter().collect(); | ||
let space_refs: BTreeMap<_, _> = self.space_refs.iter().collect(); | ||
let records: BTreeMap<_, _> = self.records.iter().collect(); | ||
format!("{:?}", (&self.held, refs, space_refs, records, &self.unreferenced, self.bytes)) | ||
format!("{:?}", (&self.held, refs, space_refs, records, &self.unreferenced, self.bytes, &self.takedowns)) | ||
} | ||
} | ||
| ||
| @@ -672,13 +730,15 @@ fn png_image(file: &mut File) -> bool { | ||
} | ||
} | ||
| ||
/// `uploadBlob` checks its token, its `Content-Type`, what an OAuth scope | ||
/// needs of that media type, then its size, pays its rate limits and checks | ||
/// the free space (`limits::guard`), then the account's quota, and stores the | ||
/// body under its CID. An OAuth token's call has `Bearer::OAuth` already. | ||
/// `uploadBlob` checks its token, its account's state, its `Content-Type`, | ||
/// what an OAuth scope needs of that media type, then its size, pays its | ||
/// rate limits and checks the free space (`limits::guard`), then the | ||
/// account's quota, and stores the body under its CID. An OAuth token's call | ||
/// has `Bearer::OAuth` already. | ||
async fn upload_blob(svc: Shared, call: &Call<'_>, headers: &HeaderMap, body: &mut Body) -> Result<Resp, XrpcError> { | ||
crate::method_of(call)?; | ||
let did = svc.auth(call.bearer).did()?; | ||
crate::lifecycle::gate(&svc, UPLOAD, &did)?; | ||
let Some(account) = svc.account(&did) else { return internal() }; | ||
// The media type is the header up to its first `;`, as sent. | ||
let given = headers.get(header::CONTENT_TYPE).map(|v| String::from_utf8_lossy(v.as_bytes()).into_owned()).unwrap_or_default(); | ||
| @@ -741,6 +801,10 @@ async fn store(svc: Shared, account: Arc<Account>, dir: PathBuf, tmp: Temp, cid: | ||
let how = st.blobs.upload_of(&cid); | ||
let logged = if !matches!(placed, Ok(Ok(()))) { | ||
internal() | ||
} else if let Err(e) = crate::lifecycle::not_deleted(&account) { | ||
Err(e) | ||
} else if st.blobs.taken_down(&cid) { | ||
invalid("Blob has been takendown, cannot re-upload") | ||
} else if matches!(how, Upload::New | Upload::Afresh) && st.blobs.counted() + blob.size > svc.config.blob_quota { | ||
err(400, "BlobQuotaExceeded", "The account's blobs would be past its quota") | ||
} else { | ||
| @@ -792,13 +856,15 @@ pub(crate) struct Served { | ||
cid: String, | ||
} | ||
| ||
/// `getBlob` takes no token, but refuses one the server did not give out (`scopes::admit`). | ||
/// `getBlob` takes no token, but refuses one the server would not take, as | ||
/// the lifecycle's gate checks it (`lifecycle::gate_query`). | ||
fn get_blob(s: &Service, _: &Call, shown: &mut Shown, p: &Map<String, Json>) -> Result<Resp, XrpcError> { | ||
let (did, cid) = (required(p, "did")?, required(p, "cid")?); | ||
let Some(a) = s.account(did) else { return repo_not_found(did) }; | ||
let st = read(&a.store); | ||
shown.0.push((st.wal.clone(), st.wal.written())); | ||
let Some(h) = st.blobs.served(cid) else { return invalid("Blob not found") }; | ||
// One taken down is as one not held, to the account and the admin too. | ||
let Some(h) = st.blobs.served(cid).filter(|_| !st.blobs.taken_down(cid)) else { return invalid("Blob not found") }; | ||
let Ok(file) = File::open(blob_dir(&s.dir, &a.did).join(cid)) else { return internal() }; | ||
Ok(Resp::Blob(Served { file, mime: h.mime.clone(), size: h.size, cid: cid.to_string() })) | ||
} | ||
| @@ -866,7 +932,8 @@ pub(crate) fn response(b: Served) -> Response { | ||
} | ||
| ||
/// `listBlobs`: the CIDs records reference, in order, after the cursor; with | ||
/// `since`, only those of records written after that rev. | ||
/// `since`, only those of records written after that rev. Its | ||
/// `Authorization` is the gate's, as `getBlob`'s is. | ||
fn list_blobs(s: &Service, _: &Call, shown: &mut Shown, p: &Map<String, Json>) -> Result<Resp, XrpcError> { | ||
let did = required(p, "did")?; | ||
let limit = p.get("limit").and_then(Json::as_u64).unwrap_or(500) as usize; | ||
crates/pds-server/src/compact.rs+140−10
| @@ -1,9 +1,12 @@ | ||
//! 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, each account's app | ||
//! passwords and the sessions it keeps, OAuth's entries with only each | ||
//! session's latest refresh, the single-use values still held, and each | ||
//! account's entry, with the email and password it has now, the invite codes | ||
//! and their uses, each account's app passwords and the sessions it keeps, | ||
//! what is known of its email and the tokens mailed for it, its state, and | ||
//! the firehose events the log holds; each deletion, with the places of its | ||
//! account's events, of which nothing else is kept; OAuth's entries with only | ||
//! each session's latest refresh; the single-use values still held; and each | ||
//! account's preferences as last put. So however often sessions, password | ||
//! or OAuth, are refreshed, the log holds no more than what is kept, and a | ||
//! constant factor of slack. | ||
| @@ -13,9 +16,10 @@ | ||
//! ago, and single-use values held no longer than that: none of those can be | ||
//! named by an entry still to come. | ||
| ||
use crate::email::{self, Mail}; | ||
use crate::sessions::{self, Keep}; | ||
use crate::{Service, Shared}; | ||
use serde_json::Value as Json; | ||
use serde_json::{Value as Json, json}; | ||
use std::collections::HashMap; | ||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; | ||
| ||
| @@ -66,20 +70,29 @@ pub(crate) fn run(s: &Service) -> Result<(), String> { | ||
} | ||
| ||
/// What `frames` hold now, as entries, without sessions that expired before | ||
/// `before`, nor single-use values and revocations whose `until` is not after `now`. | ||
/// `before`, nor anything of the accounts deleted but their deletions, nor | ||
/// single-use values and revocations whose `until` is not after `now`. | ||
fn fold(frames: Vec<Vec<Json>>, before: u64, now: u64) -> Result<Vec<Vec<Json>>, String> { | ||
let mut accounts = Vec::new(); | ||
let mut mails: HashMap<String, Mail> = HashMap::new(); | ||
let mut held = 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(); | ||
let mut lifecycle = crate::lifecycle::Replayed::default(); | ||
// Each account's last preferences, in the order the accounts first put them. | ||
let mut prefs: Vec<Json> = Vec::new(); | ||
let mut prefs_at: HashMap<String, usize> = HashMap::new(); | ||
let (mut oauth, mut spent) = (Vec::new(), Vec::new()); | ||
let mut gone = std::collections::HashSet::new(); | ||
for e in frames.into_iter().flatten() { | ||
match e["t"].as_str() { | ||
Some("account") => accounts.push(e), | ||
Some("account") => { | ||
let did = e["did"].as_str().ok_or_else(|| format!("an account with no did: {e}"))?; | ||
let text = |k: &str| e[k].as_str().map(str::to_string); | ||
mails.insert(did.to_string(), Mail::new(text("email"), text("password"))); | ||
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(|| { | ||
| @@ -88,7 +101,16 @@ fn fold(frames: Vec<Vec<Json>>, before: u64, now: u64) -> Result<Vec<Vec<Json>>, | ||
}); | ||
keeps[at].1.apply(&e)?; | ||
} | ||
Some(t) if email::ENTRIES.contains(&t) => email::replay(&mut mails, &e)?, | ||
Some(t) if crate::invites::ENTRIES.contains(&t) => invites.replay(&e)?, | ||
Some(t) if crate::lifecycle::ENTRIES.contains(&t) => { | ||
let is_account = e["did"].as_str().is_some_and(|did| mails.contains_key(did)); | ||
if let Some(did) = lifecycle.replay(&e, is_account)? { | ||
accounts.retain(|a| a["did"] != did.as_str()); | ||
mails.remove(&did); | ||
gone.insert(did); | ||
} | ||
} | ||
Some(crate::preferences::ENTRY) => { | ||
let did = e["did"].as_str().ok_or_else(|| format!("an entry with no did: {e}"))?.to_string(); | ||
match prefs_at.get(&did) { | ||
| @@ -114,15 +136,26 @@ fn fold(frames: Vec<Vec<Json>>, before: u64, now: u64) -> Result<Vec<Vec<Json>>, | ||
t => return Err(format!("a log entry of no known type: {t:?}")), | ||
} | ||
} | ||
let mut entries = accounts; | ||
let mut entries = Vec::new(); | ||
let mut mailed = Vec::new(); | ||
for mut a in accounts { | ||
let did = a["did"].as_str().unwrap_or_default().to_string(); | ||
let m = &mails[&did]; | ||
a["email"] = json!(m.email); | ||
a["password"] = json!(m.password); | ||
entries.push(a); | ||
mailed.extend(m.entries(&did)); | ||
} | ||
entries.extend(invites.entries()); | ||
entries.extend(held); | ||
for (did, k) in &keeps { | ||
for (did, k) in keeps.iter().filter(|(did, _)| mails.contains_key(did)) { | ||
entries.extend(k.entries(did, before)); | ||
} | ||
entries.extend(latest_refreshes(oauth)); | ||
entries.extend(mailed); | ||
entries.extend(lifecycle.entries()); | ||
entries.extend(latest_refreshes(crate::oauth::without_accounts(oauth, &gone))); | ||
entries.extend(spent); | ||
entries.extend(prefs); | ||
entries.extend(prefs.into_iter().filter(|e| e["did"].as_str().is_some_and(|did| mails.contains_key(did)))); | ||
Ok(entries.chunks(FRAME_ENTRIES).map(<[Json]>::to_vec).collect()) | ||
} | ||
| ||
| @@ -248,4 +281,101 @@ mod tests { | ||
assert_eq!(folded[0]["v"], json!("b")); | ||
assert_eq!(folded[1]["credentials"], json!(["new"])); | ||
} | ||
| ||
/// A deleted account's OAuth sessions, sign-ins and approved requests are | ||
/// forgotten when it is deleted, after a restart, and in a compacted log, | ||
/// which replays to the same; the other account's stay, and work. | ||
#[tokio::test] | ||
async fn a_deleted_accounts_oauth_is_forgotten() { | ||
use crate::email::testing::{last_token, open_with_sink}; | ||
use crate::oauth::tests::{App, Browser, approved, kept, serve, text}; | ||
let plc = plc().await; | ||
let dir = scratch("compact-deleted-oauth"); | ||
let sink = scratch("compact-deleted-oauth-mail"); | ||
let srv = serve(open_with_sink(&dir, &plc, &sink)).await; | ||
let (alice, _) = create(&srv.svc, "alice").await; | ||
let (bob, bob_token) = create(&srv.svc, "bob").await; | ||
let mut app = App::new(&srv, "atproto"); | ||
let mut browser = Browser::new(&srv); | ||
let (pushed, code) = approved(&mut app, &mut browser, "alice").await; | ||
let alice_tokens = app.exchange(&code, &pushed).await.json(); | ||
let (pushed, code) = approved(&mut app, &mut browser, "bob").await; | ||
let bob_tokens = app.exchange(&code, &pushed).await.json(); | ||
app.refresh(&text(&bob_tokens, "refresh_token")).await; | ||
// A request approved for bob, its code not exchanged. | ||
let (pushed, code) = approved(&mut app, &mut browser, "bob").await; | ||
call(&srv.svc, "com.atproto.server.requestAccountDelete", Some(&bob_token), Json::Null).await.unwrap(); | ||
call(&srv.svc, "com.atproto.server.deleteAccount", None, json!({ "did": bob, "password": "bob-pw", "token": last_token(&sink) })).await.unwrap(); | ||
let after = kept(&srv.svc); | ||
let state = format!("{:?}", after.0); | ||
assert!(!state.contains(&bob) && state.contains(&alice), "{state}"); | ||
assert_eq!(app.exchange(&code, &pushed).await.status, 400); | ||
let restarted = open(&dir, &plc); | ||
assert_eq!(restarted.oauth.snapshot(), after.0); | ||
drop(restarted); | ||
run(&srv.svc).unwrap(); | ||
assert_eq!(open(&dir, &plc).oauth.snapshot(), after.0); | ||
// Alice's session works on. | ||
assert_eq!(app.refresh(&text(&alice_tokens, "refresh_token")).await.status, 200); | ||
let _ = std::fs::remove_dir_all(&dir); | ||
let _ = std::fs::remove_dir_all(&sink); | ||
} | ||
| ||
/// A takedown, or its lifting, and a deactivation with an OAuth token end | ||
/// every OAuth session of the account, after a restart too; a deactivation | ||
/// with a password session ends none. A deactivation with an OAuth token | ||
/// deletes the account's app passwords too, but not the sessions made | ||
/// with them, after a restart and a compaction too (`spec/LIFECYCLE.md`). | ||
#[tokio::test] | ||
async fn account_states_end_oauth_sessions() { | ||
use crate::oauth::tests::{App, Browser, approved, serve, text}; | ||
let plc = plc().await; | ||
let dir = scratch("state-ends-oauth"); | ||
let srv = serve(open(&dir, &plc)).await; | ||
let (did, token) = create(&srv.svc, "alice").await; | ||
let mut app = App::new(&srv, "atproto account:status?action=manage"); | ||
let mut browser = Browser::new(&srv); | ||
async fn session(app: &mut App<'_>, browser: &mut Browser<'_>) -> Json { | ||
let (pushed, code) = approved(app, browser, "alice").await; | ||
app.exchange(&code, &pushed).await.json() | ||
} | ||
let admin = format!("Basic {}", base64::Engine::encode(&base64::engine::general_purpose::STANDARD, format!("admin:{ADMIN_PASSWORD}"))); | ||
let takedown = |applied: bool| json!({ "subject": { "$type": "com.atproto.admin.defs#repoRef", "did": did }, "takedown": { "applied": applied } }).to_string(); | ||
let sessions = |s: &Service| format!("{:?}", s.oauth.snapshot()).matches("Session {").count(); | ||
let login = |password: &str| json!({ "identifier": "alice.test", "password": password }); | ||
let pw = call(&srv.svc, "com.atproto.server.createAppPassword", Some(&token), json!({ "name": "phone" })).await.unwrap(); | ||
let pw = pw["password"].as_str().unwrap().to_string(); | ||
// A password session's deactivation ends none, and keeps its app passwords. | ||
let kept = session(&mut app, &mut browser).await; | ||
call(&srv.svc, "com.atproto.server.deactivateAccount", Some(&token), json!({})).await.unwrap(); | ||
assert_eq!(app.get_session(&text(&kept, "access_token")).await.status, 200); | ||
let app_session = call(&srv.svc, "com.atproto.server.createSession", None, login(&pw)).await.unwrap(); | ||
call(&srv.svc, "com.atproto.server.activateAccount", Some(&token), Json::Null).await.unwrap(); | ||
// An OAuth token's ends both. | ||
let other = session(&mut app, &mut browser).await; | ||
assert_eq!(sessions(&srv.svc), 2); | ||
assert_eq!(app.post("com.atproto.server.deactivateAccount", &text(&other, "access_token"), json!({})).await.status, 200); | ||
assert_eq!(sessions(&srv.svc), 0); | ||
assert_eq!(app.get_session(&text(&kept, "access_token")).await.error(), "invalid_token"); | ||
assert_eq!(app.refresh(&text(&other, "refresh_token")).await.error(), "invalid_grant"); | ||
assert_eq!(sessions(&open(&dir, &plc)), 0); | ||
// Its app password is gone; the session made with it refreshes. | ||
assert_eq!(call(&srv.svc, "com.atproto.server.createSession", None, login(&pw)).await.unwrap_err(), "AuthenticationRequired"); | ||
assert_eq!(call(&srv.svc, "com.atproto.server.listAppPasswords", Some(&token), Json::Null).await.unwrap(), json!({ "passwords": [] })); | ||
call(&srv.svc, "com.atproto.server.refreshSession", Some(app_session["refreshJwt"].as_str().unwrap()), Json::Null).await.unwrap(); | ||
let keeps = srv.svc.sessions.snapshot(); | ||
assert_eq!(open(&dir, &plc).sessions.snapshot(), keeps); | ||
run(&srv.svc).unwrap(); | ||
assert_eq!(open(&dir, &plc).sessions.snapshot(), keeps); | ||
call(&srv.svc, "com.atproto.server.activateAccount", Some(&token), Json::Null).await.unwrap(); | ||
// A lifting of a takedown that was not applied ends them too. | ||
for applied in [false, true] { | ||
session(&mut app, &mut browser).await; | ||
assert_eq!(sessions(&srv.svc), 1); | ||
call_raw(&srv.svc, "com.atproto.admin.updateSubjectStatus", crate::sessions::Bearer::of(Some(&admin)), &[], &takedown(applied)).await.unwrap(); | ||
assert_eq!(sessions(&srv.svc), 0); | ||
assert_eq!(sessions(&open(&dir, &plc)), 0); | ||
} | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
} | ||
crates/pds-server/src/email.rsnew+1356−0
1356 lines changed: not loaded until asked for.
crates/pds-server/src/events.rs+123−30
| @@ -12,7 +12,7 @@ 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::sync::{Arc, Mutex, PoisonError}; | ||
use std::time::{SystemTime, UNIX_EPOCH}; | ||
| ||
/// The firehose's events, numbered across all accounts. A write takes its | ||
| @@ -28,6 +28,11 @@ use std::time::{SystemTime, UNIX_EPOCH}; | ||
/// 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. | ||
/// | ||
/// A deleted account's events are dropped (`spec/LIFECYCLE.md`): each keeps | ||
/// its place, so that no number is given twice, but is served only to the | ||
/// subscriptions that began before it was dropped. A restart recovers them | ||
/// as gaps, from the deletion's entry in `accounts.log`. | ||
pub(crate) struct Firehose { | ||
seq: Mutex<Seq>, | ||
/// How many events subscribers may be sent. | ||
| @@ -36,10 +41,14 @@ pub(crate) struct Firehose { | ||
subscribers: Mutex<(HashMap<String, usize>, usize)>, | ||
} | ||
| ||
/// An event: its `ord`, and its frame once it is on disk. | ||
/// An event: its `ord`, its account, and its frame once it is on disk. | ||
struct Slot { | ||
ord: u64, | ||
did: Option<Arc<str>>, | ||
frame: Option<Bytes>, | ||
/// When it was dropped, by the count of drops: 0 for a gap a restart | ||
/// recovered, served to no one, which has no frame. | ||
dropped: Option<u64>, | ||
} | ||
| ||
struct Seq { | ||
| @@ -48,6 +57,8 @@ struct Seq { | ||
next_ord: u64, | ||
/// How many events from the first are on disk. | ||
published: usize, | ||
/// How many times events have been dropped. | ||
drops: u64, | ||
} | ||
| ||
/// Events on their way to the disk, numbered from `seq` and ordered from | ||
| @@ -58,6 +69,15 @@ pub(crate) struct Landing { | ||
pub frames: Vec<Bytes>, | ||
} | ||
| ||
/// An event as the logs recovered it: its account's, or a gap where a | ||
/// deleted account's was. | ||
pub(crate) struct Recovered { | ||
pub ord: u64, | ||
pub did: Option<Arc<str>>, | ||
/// None for a gap. | ||
pub frame: Option<Bytes>, | ||
} | ||
| ||
impl Seq { | ||
/// Where the event with this `ord` is. | ||
fn at(&self, ord: u64) -> usize { | ||
| @@ -65,12 +85,20 @@ impl Seq { | ||
} | ||
} | ||
| ||
impl Slot { | ||
/// Whether subscribers may pass it: on disk, or a gap. | ||
fn passable(&self) -> bool { | ||
self.frame.is_some() || self.dropped == Some(0) | ||
} | ||
} | ||
| ||
impl Firehose { | ||
/// The events recovered, all on disk, each with its `ord`, in order. | ||
pub fn new(events: Vec<(u64, Bytes)>) -> Firehose { | ||
pub fn new(events: Vec<Recovered>) -> Firehose { | ||
let n = events.len(); | ||
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 }; | ||
let next_ord = events.last().map_or(1, |e| e.ord + 1); | ||
let events = events.into_iter().map(|e| Slot { ord: e.ord, dropped: e.frame.is_none().then_some(0), did: e.did, frame: e.frame }).collect(); | ||
let seq = Seq { events, next_ord, published: n, drops: 0 }; | ||
Firehose { seq: Mutex::new(seq), published: tokio::sync::watch::channel(n).0, subscribers: Mutex::default() } | ||
} | ||
| ||
| @@ -78,11 +106,12 @@ impl Firehose { | ||
self.seq.lock().unwrap_or_else(PoisonError::into_inner) | ||
} | ||
| ||
/// Number `n` new events: answers the first one's seq and `ord`. | ||
pub fn reserve(&self, n: usize) -> (u64, u64) { | ||
/// Number `n` new events of an account: answers the first one's seq and `ord`. | ||
pub fn reserve(&self, did: &str, n: usize) -> (u64, u64) { | ||
let mut s = self.lock(); | ||
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 })); | ||
let did: Arc<str> = Arc::from(did); | ||
s.events.extend((0..n as u64).map(|i| Slot { ord: ord + i, did: Some(did.clone()), frame: None, dropped: None })); | ||
s.next_ord += n as u64; | ||
(seq, ord) | ||
} | ||
| @@ -98,7 +127,7 @@ impl Firehose { | ||
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].frame.is_some() { | ||
while s.published < s.events.len() && s.events[s.published].passable() { | ||
s.published += 1; | ||
} | ||
s.published | ||
| @@ -125,17 +154,44 @@ impl Firehose { | ||
} | ||
} | ||
| ||
/// The events from seq `from + 1` to `to`, all of which are on disk. | ||
pub fn get(&self, from: usize, to: usize) -> Vec<Bytes> { | ||
/// The `ord` of every event of an account's not dropped. | ||
pub fn ords_of(&self, did: &str) -> Vec<u64> { | ||
self.lock().events.iter().filter(|e| e.dropped.is_none() && e.did.as_deref() == Some(did)).map(|e| e.ord).collect() | ||
} | ||
| ||
/// Drop the events with these `ord`s: from now on they are served only to | ||
/// the subscriptions that began before. | ||
pub fn drop_events(&self, ords: &[u64]) { | ||
let mut s = self.lock(); | ||
s.drops += 1; | ||
let drops = s.drops; | ||
for ord in ords { | ||
let at = s.at(*ord); | ||
if s.events.get(at).is_some_and(|e| e.ord == *ord) { | ||
s.events[at].dropped = Some(drops); | ||
} | ||
} | ||
} | ||
| ||
/// How many times events have been dropped: what a subscription begun | ||
/// now passes over. | ||
pub fn drops(&self) -> u64 { | ||
self.lock().drops | ||
} | ||
| ||
/// The events from seq `from + 1` to `to`, all of which are on disk, for | ||
/// a subscription begun after `drops` drops. | ||
pub fn get(&self, from: usize, to: usize, drops: u64) -> 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().filter_map(|s| s.frame.clone()).collect()) | ||
let s = self.lock(); | ||
s.events.get(from..to).map_or_else(Vec::new, |e| e.iter().filter(|e| e.dropped.is_none_or(|d| d > drops)).filter_map(|e| e.frame.clone()).collect()) | ||
} | ||
| ||
pub fn subscribe(&self) -> tokio::sync::watch::Receiver<usize> { | ||
self.published.subscribe() | ||
} | ||
| ||
/// How many events there are, on disk or not. | ||
/// How many events there are, on disk or not, gaps among them. | ||
#[cfg(test)] | ||
pub fn len(&self) -> usize { | ||
self.lock().events.len() | ||
| @@ -223,26 +279,33 @@ 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))]) | ||
} | ||
| ||
/// 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![("seq", V::Int(seq as i64)), ("did", s(did)), ("time", s(time)), ("active", V::Bool(status.is_none()))]; | ||
if let Some(st) = status { | ||
body.push(("status", s(st))); | ||
} | ||
message("#account", body) | ||
} | ||
| ||
/// The `#sync` event of a commit, by its block and rev. | ||
pub fn sync_event(did: &str, seq: u64, time: &str, head_bytes: &[u8], rev: &str) -> Vec<u8> { | ||
let head = cid_of(0x71, head_bytes); | ||
message( | ||
"#sync", | ||
vec![("seq", V::Int(seq as i64)), ("did", s(did)), ("blocks", V::Bytes(car_file(&head, [(head.as_slice(), head_bytes)]))), ("rev", s(rev)), ("time", s(time))], | ||
) | ||
} | ||
| ||
/// What a new account's stream starts with, from `#identity` to `#sync`, | ||
/// numbered from `seq`. | ||
pub fn initial_events(did: &str, handle: &str, seq: u64, c: &Change) -> Vec<Vec<u8>> { | ||
let head = cid_of(0x71, &c.head_bytes); | ||
let time = timestamp(); | ||
let n = |i: u64| V::Int((seq + i) as i64); | ||
vec![ | ||
identity_event(did, handle, seq, &time), | ||
message("#account", vec![("seq", n(1)), ("did", s(did)), ("time", s(&time)), ("active", V::Bool(true))]), | ||
account_event(did, seq + 1, &time, None), | ||
commit_event(did, seq + 2, c), | ||
message( | ||
"#sync", | ||
vec![ | ||
("seq", n(3)), | ||
("did", s(did)), | ||
("blocks", V::Bytes(car_file(&head, [(head.as_slice(), c.head_bytes.as_slice())]))), | ||
("rev", s(&c.rev)), | ||
("time", s(&time)), | ||
], | ||
), | ||
sync_event(did, seq + 3, &time, &c.head_bytes, &c.rev), | ||
] | ||
} | ||
| ||
| @@ -313,6 +376,8 @@ pub async fn subscribe( | ||
/// 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) { | ||
// The events dropped before it begins, it never gets. | ||
let drops = st.events.drops(); | ||
let start = { | ||
let rx = st.events.subscribe(); | ||
let last = *rx.borrow(); | ||
| @@ -329,7 +394,7 @@ async fn stream(st: Shared, cursor: Option<Result<u64, std::num::ParseIntError>> | ||
}; | ||
loop { | ||
let upto = *rx.borrow_and_update(); | ||
let batch = st.events.get(pos, upto); | ||
let batch = st.events.get(pos, upto, drops); | ||
pos = upto; | ||
for frame in batch { | ||
if socket.send(Message::Binary(frame)).await.is_err() { | ||
| @@ -385,18 +450,46 @@ mod tests { | ||
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)); | ||
let (a, b, c) = (f.reserve("did:plc:a", 1), f.reserve("did:plc:a", 1), f.reserve("did:plc:a", 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); | ||
let d = f.reserve("did:plc:a", 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(); | ||
let seqs: Vec<i64> = f.get(0, 3, 0).iter().map(|e| seq_of(e)).collect(); | ||
assert_eq!(seqs, [1, 2, 3]); | ||
} | ||
| ||
/// A deleted account's events keep their places: a subscription begun | ||
/// before they were dropped gets them, one begun after does not, and a | ||
/// restart's gaps are passed over and never served; numbers go on after | ||
/// every one given out. | ||
#[test] | ||
fn dropped_events_keep_their_places() { | ||
let gap = |ord| Recovered { ord, did: None, frame: None }; | ||
let kept = |ord, seq| Recovered { ord, did: Some(Arc::from("did:plc:b")), frame: Some(landing(seq, ord).frames.remove(0)) }; | ||
let f = Firehose::new(vec![kept(1, 1), gap(2), kept(4, 3)]); | ||
assert_eq!(*f.subscribe().borrow(), 3); | ||
let seqs = |v: Vec<Bytes>| v.iter().map(|e| seq_of(e)).collect::<Vec<_>>(); | ||
assert_eq!(seqs(f.get(0, 3, 0)), [1, 3]); | ||
let live = f.drops(); | ||
let a = f.reserve("did:plc:a", 2); | ||
assert_eq!(a, (4, 5)); | ||
let mut l = landing(a.0, a.1); | ||
l.frames.push(Bytes::from(identity_event("did:plc:a", "a.test", a.0 + 1, "t"))); | ||
f.land(l); | ||
let b = f.reserve("did:plc:b", 1); | ||
f.land(landing(b.0, b.1)); | ||
assert_eq!(f.ords_of("did:plc:a"), [5, 6]); | ||
f.drop_events(&f.ords_of("did:plc:a")); | ||
assert!(f.ords_of("did:plc:a").is_empty()); | ||
assert_eq!(seqs(f.get(0, 6, live)), [1, 3, 4, 5, 6]); | ||
assert_eq!(seqs(f.get(0, 6, f.drops())), [1, 3, 6]); | ||
assert_eq!(f.reserve("did:plc:b", 1), (7, 8)); | ||
} | ||
} | ||
crates/pds-server/src/federation.rs+30−11
| @@ -20,13 +20,14 @@ pub(crate) fn handler(nsid: &str) -> Option<Handler> { | ||
} | ||
| ||
/// Every account whose repository has its first commit, in the order | ||
/// `accounts.log` has them. A cursor is how many accounts come before the | ||
/// next page; as accounts are only ever added at the end, it stays good. The | ||
/// listing stops before an account still being made, so that no cursor | ||
/// passes over it. | ||
/// `accounts.log` has them, each active or not and why | ||
/// (`spec/LIFECYCLE.md`). A cursor is how many accounts come before the next | ||
/// page; as accounts are only ever added at the end, and those deleted keep | ||
/// their places, unlisted, it stays good. The listing stops before an | ||
/// account still being made, so that no cursor passes over it. | ||
fn list_repos(s: &Service, _: &Call, shown: &mut Shown, p: &Map<String, Json>) -> Result<Resp, XrpcError> { | ||
let limit = p.get("limit").and_then(Json::as_u64).unwrap_or(500) as usize; | ||
let (from, accounts): (usize, Vec<Arc<Account>>) = { | ||
let accounts: Vec<(usize, Arc<Account>)> = { | ||
let d = read(&s.directory); | ||
let from = match opt(p, "cursor") { | ||
None | Some("") => 0, | ||
| @@ -35,25 +36,43 @@ fn list_repos(s: &Service, _: &Call, shown: &mut Shown, p: &Map<String, Json>) - | ||
_ => return invalid("Malformed cursor"), | ||
}, | ||
}; | ||
(from, d.order[from..].iter().map_while(|did| d.by_did.get(did).cloned()).take(limit).collect()) | ||
let listed = d.order[from..] | ||
.iter() | ||
.enumerate() | ||
.filter(|(_, did)| !d.deleted.contains(*did)) | ||
.map_while(|(i, did)| d.by_did.get(did).map(|a| (from + i, a.clone()))) | ||
.take(limit) | ||
.collect(); | ||
listed | ||
}; | ||
let repos: Vec<Json> = accounts | ||
.iter() | ||
.map(|a| { | ||
.map(|(_, a)| { | ||
let st = read(&a.store); | ||
shown.0.push((st.wal.clone(), st.wal.written())); | ||
json!({ "did": a.did, "head": st.repo.head_string(), "rev": st.repo.rev, "active": true }) | ||
let mut r = json!({ "did": a.did, "head": st.repo.head_string(), "rev": st.repo.rev, "active": true }); | ||
if let Some(status) = crate::lifecycle::status(a) { | ||
r["active"] = json!(false); | ||
r["status"] = json!(status); | ||
} | ||
r | ||
}) | ||
.collect(); | ||
let mut out = json!({ "repos": repos }); | ||
if !accounts.is_empty() { | ||
out["cursor"] = json!((from + accounts.len()).to_string()); | ||
if let Some((at, _)) = accounts.last() { | ||
out["cursor"] = json!((at + 1).to_string()); | ||
} | ||
Ok(Resp::Json(out)) | ||
} | ||
| ||
/// An active account's `{did, active, rev}`, or one not active's status instead of its rev. | ||
fn get_repo_status(s: &Service, _: &Call, shown: &mut Shown, p: &Map<String, Json>) -> Result<Resp, XrpcError> { | ||
s.with_repo(shown, required(p, "did")?, not_found, |a, r| Ok(Resp::Json(json!({ "did": a.did, "active": true, "rev": r.rev })))) | ||
s.with_repo(shown, required(p, "did")?, not_found, |a, r| { | ||
Ok(Resp::Json(match crate::lifecycle::status(a) { | ||
None => json!({ "did": a.did, "active": true, "rev": r.rev }), | ||
Some(status) => json!({ "did": a.did, "active": false, "status": status }), | ||
})) | ||
}) | ||
} | ||
| ||
/// The blocks asked for, all of which the repository must hold now. | ||
crates/pds-server/src/identity.rs+24−10
| @@ -32,12 +32,12 @@ pub(crate) fn handler(nsid: &str) -> Option<Handler> { | ||
}) | ||
} | ||
| ||
/// A handle in any case: an account's answers its DID; one under the | ||
/// server's domains that no account has is `HandleNotFound`; any other is | ||
/// not the server's, and it resolves none. | ||
/// A handle in any case: an active account's answers its DID; one under the | ||
/// server's domains that no active account has is `HandleNotFound`; any | ||
/// other is not the server's, and it resolves none. | ||
fn resolve_handle(s: &Service, _: &Call, _: &mut Shown, p: &Map<String, Json>) -> Result<Resp, XrpcError> { | ||
let handle = required(p, "handle")?.to_lowercase(); | ||
if let Some(did) = read(&s.directory).handles.get(&handle) { | ||
if let Some(did) = active_did(s, &handle) { | ||
return Ok(Resp::Json(json!({ "did": did }))); | ||
} | ||
if s.config.handle_domains.iter().any(|d| handle.ends_with(d.as_str())) { | ||
| @@ -46,8 +46,15 @@ fn resolve_handle(s: &Service, _: &Call, _: &mut Shown, p: &Map<String, Json>) - | ||
invalid("Unable to resolve handle") | ||
} | ||
| ||
/// The DID of the active account whose handle this is: one not active is as none's. | ||
fn active_did(s: &Service, handle: &str) -> Option<String> { | ||
let a = s.account(handle)?; | ||
crate::lifecycle::status(&a).is_none().then(|| a.did.clone()) | ||
} | ||
| ||
/// What a DID document of the token's account on this server holds, as | ||
/// `createAccount`'s genesis operation would hold it now. | ||
/// `createAccount`'s genesis operation would hold it now: without its | ||
/// handle while it is taken down. | ||
fn recommended_credentials(s: &Service, call: &Call, _: &mut Shown, _: &Map<String, Json>) -> Result<Resp, XrpcError> { | ||
let did = s.auth(call.bearer).did()?; | ||
let Some(a) = s.account(&did) else { return internal() }; | ||
| @@ -56,12 +63,15 @@ fn recommended_credentials(s: &Service, call: &Call, _: &mut Shown, _: &Map<Stri | ||
if let Some(kem) = &a.kem { | ||
methods["atproto_kem"] = json!(kem.public().did_key()); | ||
} | ||
Ok(Resp::Json(json!({ | ||
"alsoKnownAs": [format!("at://{}", a.handle())], | ||
let mut out = json!({ | ||
"verificationMethods": methods, | ||
"rotationKeys": plc::rotation_keys(&s.config), | ||
"services": { "atproto_pds": { "type": "AtprotoPersonalDataServer", "endpoint": s.config.public_url } }, | ||
}))) | ||
}); | ||
if read(&a.state).takedown.is_none() { | ||
out["alsoKnownAs"] = json!([format!("at://{}", a.handle())]); | ||
} | ||
Ok(Resp::Json(out)) | ||
} | ||
| ||
/// An account's DID document, as the directory last served it, if it was | ||
| @@ -136,7 +146,11 @@ fn host_did(s: &Service, host: &str) -> Option<String> { | ||
Some((name, port)) if !port.is_empty() && port.bytes().all(|c| c.is_ascii_digit()) => name, | ||
_ => host, | ||
}; | ||
read(&s.directory).handles.get(name).cloned() | ||
// A DID is no handle. | ||
if name.starts_with("did:") { | ||
return None; | ||
} | ||
active_did(s, name) | ||
} | ||
| ||
/// A handle change recorded and not yet settled: the handle, and its operation's CID. | ||
| @@ -524,7 +538,7 @@ mod tests { | ||
fn events(s: &Service) -> Vec<Json> { | ||
let n = s.events.len(); | ||
s.events | ||
.get(0, n) | ||
.get(0, n, 0) | ||
.iter() | ||
.map(|f| { | ||
let (head, at) = pds_repo::data::decode_prefix(f).unwrap(); | ||
crates/pds-server/src/invites.rs+1−1
crates/pds-server/src/lib.rs+112−36
crates/pds-server/src/lifecycle.rsnew+852−0
852 lines changed: not loaded until asked for.
crates/pds-server/src/limits.rs+35−3
crates/pds-server/src/log.rs+306−28
crates/pds-server/src/oauth.rs+96−0
crates/pds-server/src/preferences.rs+12−0
crates/pds-server/src/proxy.rs+14−4
crates/pds-server/src/repo.rs+15−6
crates/pds-server/src/scopes.rs+35−7
crates/pds-server/src/server.rs+40−19
crates/pds-server/src/sessions.rs+110−8
crates/pds-server/src/space_authority.rs+17−8
crates/pds-server/src/space_repo.rs+16−2
crates/pds-server/src/validation.rs+1−1
crates/pds-server/Cargo.toml+1−0
harness/checks/accounts.mjs+3−3
harness/checks/email.mjsnew+349−0
harness/checks/firehose.mjs+1−1
harness/checks/lifecycle.mjsnew+1044−0
1044 lines changed: not loaded until asked for.
harness/checks/limits.mjs+65−2
harness/checks/oauth-scopes.mjs+24−1
harness/lib/args.mjs+7−2
harness/lib/mail.mjsnew+73−0
harness/lib/processes.mjs+3−0
harness/lib/via.mjs+1−0
harness/spaces/export.mjs+33−5
harness/compare.mjs+16−2
harness/gates.mjs+4−2
spec/lexicons/com/atproto/admin/defs.jsonnew+71−0
spec/lexicons/com/atproto/admin/getSubjectStatus.jsonnew+43−0
spec/lexicons/com/atproto/admin/updateSubjectStatus.jsonnew+56−0
spec/lexicons/com/atproto/server/activateAccount.jsonnew+10−0
spec/lexicons/com/atproto/server/checkAccountStatus.jsonnew+38−0
spec/lexicons/com/atproto/server/confirmEmail.jsonnew+27−0
spec/lexicons/com/atproto/server/deactivateAccount.jsonnew+23−0
spec/lexicons/com/atproto/server/deleteAccount.jsonnew+23−0
spec/lexicons/com/atproto/server/requestAccountDelete.jsonnew+10−0
spec/lexicons/com/atproto/server/requestEmailConfirmation.jsonnew+10−0
spec/lexicons/com/atproto/server/requestEmailUpdate.jsonnew+20−0
spec/lexicons/com/atproto/server/requestPasswordReset.jsonnew+20−0
spec/lexicons/com/atproto/server/resetPassword.jsonnew+22−0
spec/lexicons/com/atproto/server/updateEmail.jsonnew+30−0
spec/ACCOUNTS.md+8−5
spec/BLOBS.md+2−1
spec/DURABILITY.md+9−4
spec/EMAIL.mdnew+356−0
spec/FEDERATION.md+2−1
spec/IDENTITY.md+2−1
spec/LIFECYCLE.mdnew+584−0
584 lines changed: not loaded until asked for.