//! The repository's records: the `com.atproto.repo` methods, as //! `spec/REPO.md` says, of any account's repository. use crate::validation::Validate; use crate::{ Apply, Call, Handler, Resp, Service, Shared, Shown, Store, XrpcError, blobs, commit_meta, err, internal, invalid, opt, required, }; use pds_repo::data::*; use pds_repo::*; use serde_json::{Map, Value as Json, json}; pub(crate) fn handler(nsid: &str) -> Option { Some(match nsid { "com.atproto.repo.getRecord" => Handler::Proxy(crate::proxy::get_record), "com.atproto.repo.listRecords" => Handler::Query(list_records), "com.atproto.repo.describeRepo" => Handler::Lookup(|s, p| Box::pin(describe_repo(s, p))), "com.atproto.repo.createRecord" => Handler::Write(create_record), "com.atproto.repo.putRecord" => Handler::Write(put_record), "com.atproto.repo.deleteRecord" => Handler::Write(delete_record), "com.atproto.repo.applyWrites" => Handler::Write(apply_writes), _ => return None, }) } fn not_found() -> XrpcError { XrpcError { status: 400, name: "InvalidRequest", message: "Could not find repo".into(), } } fn record_json(r: &Repo, collection: &str, rkey: &str, rec: &Record) -> Json { json!({ "uri": r.uri(collection, rkey), "cid": cid_string(&rec.cid), "value": to_json(&rec.value) }) } /// A record of a repository here, of an active account /// (`crate::proxy::get_record` forwards the rest). A record taken down is /// not found, to its account's own token too. pub(crate) fn get_record( s: &Service, _: &Call, shown: &mut Shown, p: &Map, ) -> Result { let (collection, rkey) = (required(p, "collection")?, required(p, "rkey")?); s.with_store(shown, required(p, "repo")?, not_found, |_, st| { let (r, path) = (&st.repo, format!("{collection}/{rkey}")); match st.record(&path) { Some(rec) if opt(p, "cid").is_none_or(|c| c == cid_string(&rec.cid)) && !st.takedowns.contains_key(&path) => { Ok(Resp::Json(record_json(r, collection, rkey, &rec))) } _ => err( 400, "RecordNotFound", format!("Could not locate record: {}", r.uri(collection, rkey)), ), } }) } /// A page of a collection: newest (greatest key) first unless `reverse`, read /// from the range of the collection's keys after the cursor. fn list_records( s: &Service, _: &Call, shown: &mut Shown, p: &Map, ) -> Result { let collection = required(p, "collection")?; let limit = p.get("limit").and_then(Json::as_u64).unwrap_or(50) as usize; let reverse = p.get("reverse").and_then(Json::as_bool) == Some(true); // Every key of the collection, and only those, begins with `lo`; a // cursor's key is `lo` + the cursor. Newest first reads back from // before the cursor, or from past every key (`hi`, as '0' follows '/'); // `reverse` reads on from after the cursor. let (lo, hi) = (format!("{collection}/"), format!("{collection}0")); let from = match (opt(p, "cursor"), reverse) { (None, false) => hi, (None, true) => lo.clone(), (Some(c), false) => format!("{lo}{c}"), // Past the cursor's key: nothing sorts between it and it with a 0 byte. (Some(c), true) => format!("{lo}{c}\0"), }; s.with_store(shown, required(p, "repo")?, not_found, |_, st| { let r = &st.repo; // Those taken down are not listed: read on past them. let mut page: Vec<(String, Record)> = Vec::new(); let mut from = from; while page.len() < limit { let want = limit - page.len(); let got = st.records(collection, &from, !reverse, want); let done = got.len() < want; if let Some((last, _)) = got.last() { from = if reverse { format!("{last}\0") } else { last.clone() }; } page.extend( got.into_iter() .filter(|(k, _)| !st.takedowns.contains_key(k)), ); if done { break; } } let records: Vec = page .iter() .map(|(k, rec)| record_json(r, collection, &k[lo.len()..], rec)) .collect(); let mut out = json!({ "records": records }); if let Some((k, _)) = page.last() { out["cursor"] = json!(&k[lo.len()..]); } Ok(Resp::Json(out)) }) } /// The repository, and its account's DID document as the directory serves /// it now, or a `did:web`'s host: one that cannot be read is `400 /// InvalidRequest` (`spec/IDENTITY.md`). async fn describe_repo(s: Shared, p: Map) -> Result { let repo = required(&p, "repo")?; let missing = || XrpcError { status: 400, name: "RepoNotFound", message: format!("Could not find repo: {repo}"), }; let mut shown = Shown::default(); let (mut out, did) = s.with_store(&mut shown, repo, missing, |a, st| { let cols = st.collections(); Ok(( json!({ "handle": a.handle(), "did": a.did, "collections": cols }), a.did.clone(), )) })?; let Ok(doc) = crate::identity::did_doc(&s, &did).await else { return invalid(format!("Could not resolve DID {did}")); }; out["handleIsCorrect"] = json!(crate::identity::names_handle( &doc, out["handle"].as_str().unwrap_or_default() )); out["didDoc"] = doc; shown.durable().await?; Ok(Resp::Json(out)) } // ---- Writes ----------------------------------------------------------- /// A record as input, in the data model and an object. fn record_value(b: &Map, field: &str) -> Result { let Some(j) = b.get(field) else { return invalid(format!("Input/{field} is required")); }; record_from_json(j).or_else(invalid) } /// A record whose `$type` is its collection, given it if it has none. The /// reference checks this after the write's `repo`, not with its input. pub(crate) fn typed(v: V, collection: &str) -> Result { let V::Map(mut m) = v else { return invalid("record must be an object"); }; match m.iter().find(|(k, _)| k == "$type") { Some((_, V::Str(t))) if t == collection => Ok(V::Map(m)), Some((_, V::Str(_))) => invalid("$type does not match collection"), None => { m.push(("$type".into(), V::Str(collection.into()))); Ok(V::Map(m)) } _ => invalid("$type must be a string"), } } /// What a check of a record against its lexicon found: its `validationStatus`, or why it is refused. type Checked = Result, XrpcError>; /// The record a write makes, from its input's `field`, and its check /// (`spec/VALIDATION.md`): a refusal waits until the record's `$type` is /// checked, after the write's `repo`. fn checked_record( b: &Map, field: &str, validate: Validate, collection: &str, rkey: Option<&str>, ) -> Result<(V, Checked), XrpcError> { let value = record_value(b, field)?; Ok((value, validate.check(collection, rkey, &b[field]))) } /// The `validationStatus` a space write answers, as its `validate` asks /// (`spec/SPACES.md`): `unknown` by default, none with `false`. `true` is /// refused: with the record, once the write's `repo` and scope are checked. pub(crate) fn validation_status(b: &Map) -> Result, XrpcError> { match b.get("validate") { None => Ok(Some("unknown")), Some(Json::Bool(false)) => Ok(None), Some(_) => invalid("Lexicon not found"), } } /// A write's answer, with its `validationStatus` if it has one. pub(crate) fn with_status(mut answer: Json, status: Option<&str>) -> Json { if let Some(v) = status { answer["validationStatus"] = json!(v); } answer } /// The record one write created or updated: the last result, after the /// deletes of the duplicates a `createRecord` replaces. fn written(results: Vec) -> Result<(String, String), XrpcError> { match results.into_iter().next_back() { Some(OpResult::Create { uri, cid } | OpResult::Update { uri, cid }) => Ok((uri, cid)), _ => internal(), } } /// `createRecord`: the record, checked as `validate` asks, in a commit that /// first deletes the records it duplicates (`spec/VALIDATION.md`). fn create_record(b: &Map) -> Result { let (collection, rkey) = ( required(b, "collection")?.to_string(), opt(b, "rkey").map(String::from), ); let validate = Validate::of(b); let (value, checked) = checked_record(b, "record", validate, &collection, rkey.as_deref())?; let swap = opt(b, "swapCommit").map(String::from); Ok(Box::new(move |st: &mut Store| { let value = typed(value, &collection)?; let status = checked?; blobs::refuse_legacy(&value)?; let dups = validate.duplicates(st, &collection, &value); let mut ops: Vec = dups .into_iter() .map(|rkey| Op::Delete { collection: collection.clone(), rkey, }) .collect(); ops.push(Op::Create { collection, rkey, value, }); let (uri, cid) = written(blobs::apply(st, ops, swap.as_deref())?)?; Ok(Resp::Json(with_status( json!({ "uri": uri, "cid": cid, "commit": commit_meta(&st.repo) }), status, ))) })) } fn put_record(b: &Map) -> Result { let (collection, rkey) = ( required(b, "collection")?.to_string(), required(b, "rkey")?.to_string(), ); let validate = Validate::of(b); let (value, checked) = checked_record(b, "record", validate, &collection, Some(&rkey))?; let (swap, swap_record) = ( opt(b, "swapCommit").map(String::from), b.get("swapRecord").cloned(), ); Ok(Box::new(move |st: &mut Store| { let value = typed(value, &collection)?; let status = checked?; blobs::refuse_legacy(&value)?; let existing = st .record(&format!("{collection}/{rkey}")) .map(|rec| cid_string(&rec.cid)); let r = &st.repo; if existing.is_some() && existing.as_deref() == Some(cid_string(&make_record(value.clone()).cid).as_str()) { // Writing what is already there makes no commit. return Ok(Resp::Json(with_status( json!({ "uri": r.uri(&collection, &rkey), "cid": existing }), status, ))); } // `swapRecord: null` asks that there be no record. match swap_record { None => {} Some(Json::Null) if existing.is_none() => {} Some(Json::String(c)) if existing.as_deref() == Some(c.as_str()) => {} Some(_) => return err(400, "InvalidSwap", "Record was at a different CID"), } let op = if existing.is_some() { Op::Update { collection, rkey, value, } } else { Op::Create { collection, rkey: Some(rkey), value, } }; let (uri, cid) = written(blobs::apply(st, vec![op], swap.as_deref())?)?; Ok(Resp::Json(with_status( json!({ "uri": uri, "cid": cid, "commit": commit_meta(&st.repo) }), status, ))) })) } fn delete_record(b: &Map) -> Result { let (collection, rkey) = ( required(b, "collection")?.to_string(), required(b, "rkey")?.to_string(), ); let (swap, swap_record) = ( opt(b, "swapCommit").map(String::from), opt(b, "swapRecord").map(String::from), ); Ok(Box::new(move |st: &mut Store| { let existing = st .record(&format!("{collection}/{rkey}")) .map(|rec| cid_string(&rec.cid)); if existing.is_none() { return Ok(Resp::Json(json!({}))); } if swap_record.is_some_and(|c| existing.as_deref() != Some(c.as_str())) { return err(400, "InvalidSwap", "Record was at a different CID"); } blobs::apply(st, vec![Op::Delete { collection, rkey }], swap.as_deref())?; Ok(Resp::Json(json!({ "commit": commit_meta(&st.repo) }))) })) } fn apply_writes(b: &Map) -> Result { let validate = Validate::of(b); let Some(Json::Array(writes)) = b.get("writes") else { return invalid("Input/writes must be an array"); }; let mut ops = Vec::with_capacity(writes.len()); // Each write's check, in order: the `validationStatus` of its result, or why it is refused. let mut checks = Vec::with_capacity(writes.len()); for w in writes { let Json::Object(w) = w else { return invalid("invalid write"); }; let collection = required(w, "collection")?.to_string(); let (op, check) = match opt(w, "$type") { Some("com.atproto.repo.applyWrites#create") => { let rkey = opt(w, "rkey").map(String::from); let (value, check) = checked_record(w, "value", validate, &collection, rkey.as_deref())?; ( Op::Create { collection, rkey, value, }, check, ) } Some("com.atproto.repo.applyWrites#update") => { let rkey = required(w, "rkey")?.to_string(); let (value, check) = checked_record(w, "value", validate, &collection, Some(&rkey))?; ( Op::Update { collection, rkey, value, }, check, ) } Some("com.atproto.repo.applyWrites#delete") => ( Op::Delete { collection, rkey: required(w, "rkey")?.into(), }, Ok(None), ), _ => return invalid("unknown write type"), }; ops.push(op); checks.push(check); } let swap = opt(b, "swapCommit").map(String::from); Ok(Box::new(move |st: &mut Store| { let mut statuses = Vec::with_capacity(ops.len()); for (op, check) in ops.iter_mut().zip(checks) { if let Op::Create { collection, value, .. } | Op::Update { collection, value, .. } = op { *value = typed(std::mem::replace(value, V::Null), collection)?; statuses.push(check?); blobs::refuse_legacy(value)?; } else { statuses.push(None); } } let results: Vec = blobs::apply(st, ops, swap.as_deref())? .into_iter() .zip(statuses) .map(|(res, status)| match res { OpResult::Create { uri, cid } => { with_status(json!({ "$type": "com.atproto.repo.applyWrites#createResult", "uri": uri, "cid": cid }), status) } OpResult::Update { uri, cid } => { with_status(json!({ "$type": "com.atproto.repo.applyWrites#updateResult", "uri": uri, "cid": cid }), status) } OpResult::Delete => json!({ "$type": "com.atproto.repo.applyWrites#deleteResult" }), }) .collect(); Ok(Resp::Json( json!({ "commit": commit_meta(&st.repo), "results": results }), )) })) } #[cfg(test)] mod tests { use crate::testing::*; use serde_json::json; /// listRecords pages through its collection alone, both ways. #[tokio::test] async fn list_records_pages_a_collection() { let plc = plc().await; let dir = scratch("list"); let s = open(&dir, &plc); let (did, owner) = create(&s, "alice").await; let (_, other) = create(&s, "bob").await; for c in ["a.b.c", "a.b.cd", "a.b.c.d", "a.b.b"] { for k in ["-x", "1", "m", "z~"] { call( &s, "com.atproto.repo.putRecord", Some(&owner), json!({ "repo": did, "collection": c, "rkey": k, "record": {} }), ) .await .unwrap(); } } // Bob's records are his alone. call( &s, "com.atproto.repo.putRecord", Some(&other), json!({ "repo": "bob.test", "collection": "a.b.c", "rkey": "n", "record": {} }), ) .await .unwrap(); let list = |repo: &'static str, reverse: bool, cursor: Option<&'static str>| { let s = s.clone(); let repo = if repo == "alice" { did.clone() } else { repo.to_string() }; async move { let mut p = vec![ ("repo".to_string(), repo), ("collection".into(), "a.b.c".into()), ("limit".into(), "3".into()), ]; p.extend(reverse.then(|| ("reverse".to_string(), "true".to_string()))); p.extend(cursor.map(|c| ("cursor".to_string(), c.to_string()))); let got = call_with(&s, "com.atproto.repo.listRecords", None, &p, json!({})) .await .unwrap(); let keys: Vec = got["records"] .as_array() .unwrap() .iter() .map(|r| { r["uri"] .as_str() .unwrap() .rsplit('/') .next() .unwrap() .to_string() }) .collect(); (keys, got["cursor"].as_str().map(str::to_string)) } }; assert_eq!( list("alice", false, None).await, (vec!["z~".into(), "m".into(), "1".into()], Some("1".into())) ); assert_eq!( list("alice", false, Some("1")).await, (vec!["-x".into()], Some("-x".into())) ); assert_eq!(list("alice", false, Some("-x")).await, (vec![], None)); assert_eq!( list("alice", true, None).await, (vec!["-x".into(), "1".into(), "m".into()], Some("m".into())) ); assert_eq!( list("alice", true, Some("m")).await, (vec!["z~".into()], Some("z~".into())) ); assert_eq!( list("alice", true, Some("")).await, (vec!["-x".into(), "1".into(), "m".into()], Some("m".into())) ); assert_eq!(list("alice", false, Some("")).await.0, Vec::::new()); assert_eq!( list("bob.test", false, None).await, (vec!["n".into()], Some("n".into())) ); let _ = std::fs::remove_dir_all(&dir); } /// A write to another account's repository, or to one no account has, is /// refused after its token and input are checked, before its `$type`. #[tokio::test] async fn writes_to_another_account() { let plc = plc().await; let dir = scratch("other-account"); let s = open(&dir, &plc); let (alice, ta) = create(&s, "alice").await; let (bob, tb) = create(&s, "bob").await; let put = |repo: &str, record: serde_json::Value| json!({ "repo": repo, "collection": "a.b.c", "rkey": "k", "record": record }); let nsid = "com.atproto.repo.putRecord"; // Token first, then input. assert_eq!( call(&s, nsid, None, put(&bob, json!({}))).await, Err("AuthMissing".into()) ); assert_eq!( call(&s, nsid, Some("forged"), put("nobody.test", json!(1.5))).await, Err("InvalidToken".into()) ); assert_eq!( call(&s, nsid, Some(&ta), put(&bob, json!({ "f": 1.5 }))).await, Err("InvalidRequest".into()) ); assert_eq!(call(&s, nsid, Some(&ta), json!({ "repo": bob, "collection": "a.b.c", "rkey": "k", "record": {}, "validate": null })).await, Err("InvalidRequest".into())); // `validate: true` on a type with no lexicon is refused with the record, after the repo. assert_eq!(call(&s, nsid, Some(&ta), json!({ "repo": bob, "collection": "a.b.c", "rkey": "k", "record": {}, "validate": true })).await, Err("AuthenticationRequired".into())); // Then the repo, before the record's $type. for repo in [bob.as_str(), "bob.test"] { assert_eq!( call(&s, nsid, Some(&ta), put(repo, json!({ "$type": "x.y.z" }))).await, Err("AuthenticationRequired".into()) ); } assert_eq!( call( &s, nsid, Some(&ta), put("nobody.test", json!({ "$type": "x.y.z" })) ) .await, Err("AccountNotFound".into()) ); assert_eq!( call( &s, nsid, Some(&ta), put("did:plc:aaaaaaaaaaaaaaaaaaaaaaaa", json!({})) ) .await, Err("AccountNotFound".into()) ); // A handle is matched as given: none here has a capital letter. assert_eq!( call(&s, nsid, Some(&ta), put("ALICE.test", json!({}))).await, Err("AccountNotFound".into()) ); let p = [("repo".to_string(), "Bob.test".to_string())]; assert_eq!( call_with(&s, "com.atproto.repo.describeRepo", None, &p, json!({})).await, Err("RepoNotFound".into()) ); assert_eq!( call( &s, nsid, Some(&ta), put(&alice, json!({ "$type": "x.y.z" })) ) .await, Err("InvalidRequest".into()) ); for (nsid, body) in [ ( "com.atproto.repo.createRecord", json!({ "repo": bob, "collection": "a.b.c", "record": {} }), ), ( "com.atproto.repo.deleteRecord", json!({ "repo": bob, "collection": "a.b.c", "rkey": "k" }), ), ( "com.atproto.repo.applyWrites", json!({ "repo": bob, "writes": [] }), ), ] { assert_eq!( call(&s, nsid, Some(&ta), body).await, Err("AuthenticationRequired".into()), "{nsid}" ); } // Each writes its own, and reads anyone's. call(&s, nsid, Some(&ta), put(&alice, json!({ "n": 1 }))) .await .unwrap(); call(&s, nsid, Some(&tb), put("bob.test", json!({ "n": 2 }))) .await .unwrap(); for (repo, n) in [ (alice.as_str(), 1), ("alice.test", 1), (bob.as_str(), 2), ("bob.test", 2), ] { let p = [ ("repo".to_string(), repo.to_string()), ("collection".into(), "a.b.c".into()), ("rkey".into(), "k".into()), ]; let got = call_with(&s, "com.atproto.repo.getRecord", None, &p, json!({})) .await .unwrap(); assert_eq!(got["value"]["n"], json!(n), "{repo}"); } let p = [("repo".to_string(), "bob.test".to_string())]; let got = call_with(&s, "com.atproto.repo.describeRepo", None, &p, json!({})) .await .unwrap(); assert_eq!( ( got["did"].clone(), got["handle"].clone(), got["collections"].clone() ), (json!(bob), json!("bob.test"), json!(["a.b.c"])) ); assert_eq!(got["didDoc"]["id"], json!(bob)); let p = [("repo".to_string(), "nobody.test".to_string())]; assert_eq!( call_with(&s, "com.atproto.repo.describeRepo", None, &p, json!({})).await, Err("RepoNotFound".into()) ); let _ = std::fs::remove_dir_all(&dir); } /// `applyWrites` of more than 200 writes is `InvalidRequest`, after the /// token, the input and the `repo`, before the swap and the `$type`s; /// 200 is taken, and so is none. A body over its method's limit is /// `PayloadTooLargeError` after the token, before anything else. #[tokio::test] async fn write_counts_and_sizes() { let plc = plc().await; let dir = scratch("write-counts"); let s = open(&dir, &plc); let (alice, ta) = create(&s, "alice").await; let (bob, _) = create(&s, "bob").await; let writes = |repo: &str, n: usize, t: &str| { let w: Vec = (0..n).map(|_| json!({ "$type": "com.atproto.repo.applyWrites#create", "collection": "a.b.c", "value": { "$type": t } })).collect(); json!({ "repo": repo, "writes": w }) }; let apply = "com.atproto.repo.applyWrites"; assert_eq!( call(&s, apply, Some(&ta), writes(&bob, 201, "a.b.c")).await, Err("AuthenticationRequired".into()) ); assert_eq!( call(&s, apply, Some(&ta), writes("nobody.test", 201, "a.b.c")).await, Err("AccountNotFound".into()) ); assert_eq!( call(&s, apply, Some(&ta), writes(&alice, 201, "x.y.z")).await, Err("InvalidRequest".into()) ); let mut stale = writes(&alice, 250, "a.b.c"); stale["swapCommit"] = json!("bafyreie5737gdxlw5i64vzichcalba3z2v5n6icifvx5xytvske7mr3hpm"); assert_eq!( call(&s, apply, Some(&ta), stale).await, Err("InvalidRequest".into()) ); assert!(repo_of(&s, &alice, |r| r.record_count() == 0)); let got = call(&s, apply, Some(&ta), writes(&alice, 200, "a.b.c")) .await .unwrap(); assert_eq!(got["results"].as_array().unwrap().len(), 200); call(&s, apply, Some(&ta), writes(&alice, 0, "a.b.c")) .await .unwrap(); // Sizes: a body one byte over the limit, after the token. let over = |n: usize| { let head = format!(r#"{{"repo":"{alice}","collection":"a.b.c","rkey":"k","record":{{"t":""#); format!("{head}{}\"}}}}", "x".repeat(n - head.len() - 3)) }; use crate::sessions::Bearer; assert_eq!(over(1_000_001).len(), 1_000_001); let put = "com.atproto.repo.putRecord"; assert_eq!( call_raw(&s, put, Bearer::Token(&ta), &[], &over(1_000_001)).await, Err("PayloadTooLargeError".into()) ); assert_eq!( call_raw(&s, put, Bearer::None, &[], &over(1_000_001)).await, Err("AuthMissing".into()) ); call_raw(&s, put, Bearer::Token(&ta), &[], &over(1_000_000)) .await .unwrap(); assert_eq!( call_raw( &s, "com.atproto.repo.deleteRecord", Bearer::Token(&ta), &[], &over(153_601) ) .await, Err("PayloadTooLargeError".into()) ); assert_eq!( call_raw( &s, "com.atproto.server.createSession", Bearer::None, &[], &over(153_601) ) .await, Err("PayloadTooLargeError".into()) ); let _ = std::fs::remove_dir_all(&dir); } }