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

Records are served with their proof by com.atproto.sync.getRecord

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:sync/get-record
.changeset/sync-get-record.mdnew+7−0
@@ -0,0 +1,7 @@
---
default: patch
---
# A group's record is served with its proof
The host answers `com.atproto.sync.getRecord`, as a PDS does: a CAR rooted at the group's signed commit, holding the tree's nodes down to the record and the record itself, or proving it absent. Apps that read a record a group just wrote through `getRecord` were refused with `MethodNotImplemented`, so the record showed only once the network brought it.
crates/group-host/src/api.rs+13−0
@@ -186,6 +186,19 @@ pub async fn get_repo(
Ok(([(header::CONTENT_TYPE, "application/vnd.ipld.car")], car).into_response())
}
/// A record with the proof of it, or of its absence, from the repo's
/// signed commit: a CAR, as a PDS answers it.
pub async fn get_sync_record(
State(host): State<Arc<Host>>,
Query(p): Query<Params>,
) -> Result<Response, XrpcError> {
let did = &did_of(&host, param(&p, "did")?)?;
let (collection, rkey) = (param(&p, "collection")?, param(&p, "rkey")?);
let car = host.record_proof(did, collection, rkey);
let car = car.map_err(XrpcError::internal)?;
Ok(([(header::CONTENT_TYPE, "application/vnd.ipld.car")], car).into_response())
}
pub async fn get_latest_commit(State(host): State<Arc<Host>>, Query(p): Query<Params>) -> Answer {
let did = &did_of(&host, param(&p, "did")?)?;
let head = host.store.head(did).map_err(XrpcError::internal)?;
crates/group-host/src/lib.rs+4−0
@@ -197,6 +197,10 @@ pub(crate) fn routes(host: Arc<Host>) -> Router {
.route("/xrpc/com.atproto.repo.getRecord", get(api::get_record))
.route("/xrpc/com.atproto.repo.listRecords", get(api::list_records))
.route("/xrpc/com.atproto.sync.getRepo", get(api::get_repo))
.route(
"/xrpc/com.atproto.sync.getRecord",
get(api::get_sync_record),
)
.route(
"/xrpc/com.atproto.sync.getLatestCommit",
get(api::get_latest_commit),
crates/group-host/src/limits.rs+3−2
@@ -48,7 +48,8 @@ macro_rules! limit {
/// Every request from one address, but those [`by_path`] spares.
pub const BY_ADDRESS: Limit = limit!("address", 3000, 5 * MINUTE);
/// A whole repo, read from one address, as a relay reads them.
/// A whole repo, or a record with its proof, read from one address, as a
/// relay or an app reads them.
pub const SYNC_REPO: Limit = limit!("sync-repo", 6000, 5 * MINUTE);
/// Groups made from one address, each an identity in the directory.
pub const NEW_GROUPS: Limit = limit!("new-groups", 100, 5 * MINUTE);
@@ -246,7 +247,7 @@ fn by_path(path: &str) -> &'static [Limit] {
// Asked by the machine's own checks and the proxy, and a relay's
// stream, open for as long as it reads.
"/xrpc/_health" | "/tls/ask" | "/xrpc/com.atproto.sync.subscribeRepos" => &[],
"/xrpc/com.atproto.sync.getRepo" => &[SYNC_REPO],
"/xrpc/com.atproto.sync.getRepo" | "/xrpc/com.atproto.sync.getRecord" => &[SYNC_REPO],
"/xrpc/org.atgrp.internal.createGroup" | "/xrpc/org.atgrp.internal.provisionGroup" => {
&[BY_ADDRESS, NEW_GROUPS]
}
crates/group-host/src/repo.rs+15−0
@@ -488,6 +488,21 @@ impl Host {
walk(tree.root_node(), &records, &mut blocks);
Ok(car::write(&[head.cid], blocks.iter().map(|(c, b)| (c, *b))))
}
/// The proof of `collection/rkey` in `did`'s repo as it is now, as a
/// CAR rooted at its signed commit: the commit, the tree's nodes down
/// to the key's place and its neighbours', and the record when it is
/// there; when it is not, the same nodes prove it absent.
pub fn record_proof(&self, did: &str, collection: &str, rkey: &str) -> Result<Vec<u8>> {
let head = self.store.head(did)?.context("an account has a repo")?;
let tree = Tree::build(&self.store.paths(did)?);
let mut blocks = tree.covering_proof(&format!("{collection}/{rkey}"));
let record = self.store.record(did, collection, rkey)?;
blocks.extend(record.map(|r| (r.cid, r.value)));
let commit = std::iter::once((&head.cid, &head.block[..]));
let rest = blocks.iter().map(|(c, b)| (c, &b[..]));
Ok(car::write(&[head.cid], commit.chain(rest)))
}
}
/// An `#identity` event: `did` known as `handle`, for the relays to
crates/group-host/tests/repos.rs+114−1
@@ -4,12 +4,13 @@
mod common;
use atproto::mst::Tree;
use atproto::{Commit, PublicKey, car};
use atproto::{Cid, Commit, PublicKey, car, drisl};
use common::start;
use group_host::repo::Write;
use group_host::store::{Account, Head, Store};
use group_host::xrpc::XrpcError;
use serde_json::{Value, json};
use std::collections::BTreeMap;
const RIDERS: &str = "riders.groups.test";
@@ -575,3 +576,115 @@ async fn describes_itself_as_a_pds_that_names_groups_under_its_domain() {
h.host.config.blob_upload_limit
);
}
/// The record `key` names in the tree under `root`, found down the path
/// `blocks` prove: `None` when the path proves it absent. A node the path
/// needs and `blocks` lack fails it, as an app reading the proof fails.
fn proved(blocks: &BTreeMap<Cid, Vec<u8>>, root: Cid, key: &str) -> Option<Cid> {
let link = |v: &drisl::Value| match v {
drisl::Value::Link(c) => Some(*c),
_ => None,
};
let mut at = root;
loop {
let drisl::Value::Map(node) = drisl::decode(&blocks[&at]).unwrap() else {
panic!("{at} is not a tree node");
};
let drisl::Value::Array(written) = &node["e"] else {
panic!("a node without entries");
};
let (mut last, mut below) = (Vec::new(), link(&node["l"]));
for entry in written {
let drisl::Value::Map(e) = entry else {
panic!("an entry that is not a map");
};
let (drisl::Value::Integer(shared), drisl::Value::Bytes(rest)) = (&e["p"], &e["k"])
else {
panic!("an entry without its key");
};
last.truncate(*shared as usize);
last.extend_from_slice(rest);
let here = std::str::from_utf8(&last).unwrap();
if here == key {
return link(&e["v"]);
}
if here > key {
break;
}
below = link(&e["t"]);
}
at = below?;
}
}
#[tokio::test]
async fn proves_a_record_or_its_absence_from_the_signed_commit() {
let h = start(&[], false).await;
let did = h.host.create_account(RIDERS).await.unwrap();
let writes: Vec<Write> = (0..200)
.map(|i| create(&format!("r{i:03}"), "A rule"))
.collect();
let head = h.host.write(&did, &writes).unwrap();
let signing = h.host.store.account(&did).unwrap().unwrap().signing;
let signing = PublicKey::from_did_key(&signing.public().did_key()).unwrap();
let proof = |rkey: &str| {
let url = format!(
"{}/xrpc/com.atproto.sync.getRecord?did={did}&collection=org.atgrp.rule&rkey={rkey}",
h.url
);
let http = h.http.clone();
async move {
let res = http.get(url).send().await.unwrap();
assert_eq!(res.status(), 200);
assert_eq!(res.headers()["content-type"], "application/vnd.ipld.car");
car::read(&res.bytes().await.unwrap()).unwrap()
}
};
// The record, reached from the signed commit's tree, its block with it.
let car = proof("r123").await;
assert_eq!(car.roots, [head.cid]);
let commit = Commit::verified(&car.blocks[&car.roots[0]], &did, &signing).unwrap();
let cid = proved(&car.blocks, commit.data, "org.atgrp.rule/r123").unwrap();
let (_, record) = h
.get(
"com.atproto.repo.getRecord",
&format!("repo={did}&collection=org.atgrp.rule&rkey=r123"),
)
.await;
assert_eq!(cid.to_string(), record["cid"]);
assert_eq!(Cid::of_cbor(&car.blocks[&cid]), cid);
// A proof, not the repo: a path down a tree of many layers.
assert!(car.blocks.len() < 20);
// A record not there is proved absent from the same commit.
for rkey in ["r123x", "a", "zzz"] {
let car = proof(rkey).await;
let commit = Commit::verified(&car.blocks[&car.roots[0]], &did, &signing).unwrap();
let key = format!("org.atgrp.rule/{rkey}");
assert_eq!(proved(&car.blocks, commit.data, &key), None, "{rkey}");
}
// A repo not here, and a group switched off, are refused by name.
for (query, error) in [
(
"did=did:plc:nobody&collection=org.atgrp.rule&rkey=r1",
"RepoNotFound",
),
(&*format!("did={did}&rkey=r1"), "InvalidRequest"),
] {
let (status, body) = h.get("com.atproto.sync.getRecord", query).await;
assert_eq!((status, body["error"].as_str()), (400, Some(error)));
}
h.host.deactivate_account(&did, &did, &[]).unwrap();
let (status, body) = h
.get(
"com.atproto.sync.getRecord",
&format!("did={did}&collection=org.atgrp.rule&rkey=r123"),
)
.await;
assert_eq!(
(status, body["error"].as_str()),
(400, Some("RepoDeactivated"))
);
}
docs/design/limits.md+4−3
@@ -61,7 +61,7 @@ group's and its person's limits.
| What | Points | Window | Counted by |
| --- | --- | --- | --- |
| every request, but those below that have their own | 3000 | 5 minutes | address |
| `com.atproto.sync.getRepo` | 6000 | 5 minutes | address |
| `com.atproto.sync.getRepo`, `com.atproto.sync.getRecord`, together | 6000 | 5 minutes | address |
| `createGroup`, `provisionGroup` | 100 | 5 minutes | address |
| `/oauth/par` | 300 | 5 minutes | address |
| `/mcp/register` | 30 | 5 minutes | address |
@@ -75,8 +75,9 @@ group's and its person's limits.
| `requestJoin` | 10, and 100 | 5 minutes, and a day | person |
A request to a method with a limit of its own spends from the
every-request limit too. `com.atproto.sync.getRepo` is the one
exception, since a relay reads whole repos in bursts. The host's health
every-request limit too. `com.atproto.sync.getRepo` and
`com.atproto.sync.getRecord` are the exceptions, since a relay reads
whole repos in bursts, and an app a record each of its accounts wrote. The host's health
check, `/tls/ask` and the firehose (`com.atproto.sync.subscribeRepos`)
spend nothing.
docs/reference/api.md+1−1
@@ -310,7 +310,7 @@ repos as any PDS does:
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GET com.atproto.server.describeServer` | describes the host as a PDS: its DID, the domain it names its groups under, `BLOB_UPLOAD_LIMIT`, and that no one signs up |
| `GET com.atproto.repo.describeRepo`, `GET com.atproto.repo.getRecord`, `GET com.atproto.repo.listRecords` | serve a group's public repo |
| `GET com.atproto.sync.getRepo`, `GET com.atproto.sync.getLatestCommit`, `GET com.atproto.sync.listRepos`, `GET com.atproto.sync.getBlob`, `GET com.atproto.sync.listBlobs` | sync the repos. A blob only a space holds isn't served or listed. `listRepos` and `listBlobs` answer pages of up to 1000 (500 by default), as atproto's lexicons have them |
| `GET com.atproto.sync.getRepo`, `GET com.atproto.sync.getRecord`, `GET com.atproto.sync.getLatestCommit`, `GET com.atproto.sync.listRepos`, `GET com.atproto.sync.getBlob`, `GET com.atproto.sync.listBlobs` | sync the repos. `getRecord` answers a CAR rooted at the repo's signed commit, with the tree's nodes proving the record, and the record when it is there; a record not there is proved absent the same way. A blob only a space holds isn't served or listed. `listRepos` and `listBlobs` answer pages of up to 1000 (500 by default), as atproto's lexicons have them |
| `GET com.atproto.sync.subscribeRepos` | the firehose, over a WebSocket |
| `GET com.atproto.identity.resolveHandle` | resolves a handle here to its DID. For a caller who's signed in, it resolves any handle through `HANDLE_RESOLVERS` |
| `GET /.well-known/did.json` | the host's own DID document when `SERVICE_DID` is a `did:web`, with its `#atproto_pds` and `#atgrp` services at `PUBLIC_URL` |