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

Groups keep repos in spaces, read with an authority's credential

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:host/space-repos
crates/atproto/src/space.rs+42−0
@@ -10,6 +10,7 @@
use crate::cid::Cid;
use crate::drisl::{self, Value};
use crate::keys::{Keypair, PublicKey};
use crate::syntax;
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use hmac::{Hmac, Mac};
@@ -33,6 +34,47 @@ fn err<T>(what: impl Into<String>) -> Result<T, SpaceError> {
Err(SpaceError(what.into()))
}
/// A space, as `at://<authority>/space/<type>/<skey>` names it: the DID
/// of its authority, its type (an NSID), and its key (a record key).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SpaceRef {
pub authority: String,
pub kind: String,
pub skey: String,
}
impl SpaceRef {
/// The space `uri` names, written exactly as [`SpaceRef`]'s `Display`
/// writes one.
pub fn parse(uri: &str) -> Result<SpaceRef, SpaceError> {
let parts: Vec<&str> = uri.strip_prefix("at://").unwrap_or("").split('/').collect();
match parts[..] {
[authority, "space", kind, skey]
if syntax::is_did(authority)
&& syntax::is_nsid(kind)
&& syntax::is_record_key(skey) =>
{
Ok(SpaceRef {
authority: authority.into(),
kind: kind.into(),
skey: skey.into(),
})
}
_ => err(format!("not a space: {uri}")),
}
}
}
impl fmt::Display for SpaceRef {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"at://{}/space/{}/{}",
self.authority, self.kind, self.skey
)
}
}
/// The lanes of an LtHash, each a little-endian u16.
const LANES: usize = 1024;
/// An LtHash's whole state, in bytes.
crates/atproto/tests/space.rs+26−2
@@ -4,8 +4,8 @@
use atproto::cid::Cid;
use atproto::keys::{Curve, Keypair};
use atproto::space::{
COMMIT_MAC, Commit, LtHash, RECORD_MAC, STATE_BYTES, decapsulate, element, encapsulate,
mac_header, parse_want_mac, record_mac, star, want_mac_header,
COMMIT_MAC, Commit, LtHash, RECORD_MAC, STATE_BYTES, SpaceRef, decapsulate, element,
encapsulate, mac_header, parse_want_mac, record_mac, star, want_mac_header,
};
use serde_json::Value;
use std::collections::BTreeMap;
@@ -120,6 +120,30 @@ fn agrees_secrets_as_the_vectors_say() {
assert_eq!(decapsulate(&author, &share).unwrap(), theirs);
}
#[test]
fn reads_space_refs() {
let uri = "at://did:plc:abc/space/fyi.opensocial.members/self";
let space = SpaceRef::parse(uri).unwrap();
assert_eq!(space.authority, "did:plc:abc");
assert_eq!(space.kind, "fyi.opensocial.members");
assert_eq!(space.skey, "self");
assert_eq!(space.to_string(), uri);
for bad in [
"did:plc:abc/space/fyi.opensocial.members/self",
"at://did:plc:abc/space/fyi.opensocial.members",
"at://did:plc:abc/space/fyi.opensocial.members/self/",
"at://did:plc:abc/repo/fyi.opensocial.members/self",
"at://alice.test/space/fyi.opensocial.members/self",
"at://did:plc:abc/space/members/self",
"at://did:plc:abc/space/fyi.opensocial.members/..",
] {
assert_eq!(
SpaceRef::parse(bad).unwrap_err().to_string(),
format!("not a space: {bad}")
);
}
}
#[test]
fn refuses_keys_and_headers_it_cannot_use() {
let k256 = Keypair::generate(Curve::K256);
crates/group-host/src/api.rs+21−16
@@ -13,15 +13,15 @@ use serde_json::{Value, json};
use std::collections::HashMap;
use std::sync::Arc;
type Params = Query<HashMap<String, String>>;
pub(crate) type Params = HashMap<String, String>;
type Answer = Result<Json<Value>, XrpcError>;
fn invalid(message: impl Into<String>) -> XrpcError {
pub(crate) fn invalid(message: impl Into<String>) -> XrpcError {
XrpcError::new(StatusCode::BAD_REQUEST, "InvalidRequest", message)
}
/// The parameter `name`, which the method needs.
fn param<'a>(params: &'a HashMap<String, String>, name: &str) -> Result<&'a str, XrpcError> {
pub(crate) fn param<'a>(params: &'a Params, name: &str) -> Result<&'a str, XrpcError> {
params
.get(name)
.map(String::as_str)
@@ -29,14 +29,19 @@ fn param<'a>(params: &'a HashMap<String, String>, name: &str) -> Result<&'a str,
}
/// The page size `limit` asks for: 1 to 100, 50 unless it says.
fn limit(params: &HashMap<String, String>) -> Result<u32, XrpcError> {
fn limit(params: &Params) -> Result<u32, XrpcError> {
page(params, 50, 100)
}
/// The page size `limit` asks for: 1 to `max`, `default` unless it says.
pub(crate) fn page(params: &Params, default: u32, max: u32) -> Result<u32, XrpcError> {
match params.get("limit") {
None => Ok(50),
None => Ok(default),
Some(l) => l
.parse()
.ok()
.filter(|n| (1..=100).contains(n))
.ok_or_else(|| invalid("limit is 1 to 100")),
.filter(|n| (1..=max).contains(n))
.ok_or_else(|| invalid(format!("limit is 1 to {max}"))),
}
}
@@ -61,7 +66,7 @@ fn view(did: &str, r: &Record) -> Value {
json!({"uri": format!("at://{did}/{}/{}", r.collection, r.rkey), "cid": r.cid.to_string(), "value": value})
}
pub async fn describe_repo(State(host): State<Arc<Host>>, Query(p): Params) -> Answer {
pub async fn describe_repo(State(host): State<Arc<Host>>, Query(p): Query<Params>) -> Answer {
let repo = param(&p, "repo")?;
let account = host.store.account(repo).map_err(XrpcError::internal)?;
let account = account.ok_or_else(|| repo_not_found(repo))?;
@@ -83,7 +88,7 @@ pub async fn describe_repo(State(host): State<Arc<Host>>, Query(p): Params) -> A
})))
}
pub async fn get_record(State(host): State<Arc<Host>>, Query(p): Params) -> Answer {
pub async fn get_record(State(host): State<Arc<Host>>, Query(p): Query<Params>) -> Answer {
let did = did_of(&host, param(&p, "repo")?)?;
let (collection, rkey) = (param(&p, "collection")?, param(&p, "rkey")?);
let found = host
@@ -102,7 +107,7 @@ pub async fn get_record(State(host): State<Arc<Host>>, Query(p): Params) -> Answ
Ok(Json(view(&did, &found.ok_or_else(not_found)?)))
}
pub async fn list_records(State(host): State<Arc<Host>>, Query(p): Params) -> Answer {
pub async fn list_records(State(host): State<Arc<Host>>, Query(p): Query<Params>) -> Answer {
let did = did_of(&host, param(&p, "repo")?)?;
let (collection, limit) = (param(&p, "collection")?, limit(&p)?);
let reverse = p.get("reverse").is_some_and(|r| r == "true");
@@ -122,7 +127,7 @@ pub async fn list_records(State(host): State<Arc<Host>>, Query(p): Params) -> An
pub async fn get_repo(
State(host): State<Arc<Host>>,
Query(p): Params,
Query(p): Query<Params>,
) -> Result<Response, XrpcError> {
let did = param(&p, "did")?;
let car = host.export(did).map_err(XrpcError::internal)?;
@@ -130,14 +135,14 @@ pub async fn get_repo(
Ok(([(header::CONTENT_TYPE, "application/vnd.ipld.car")], car).into_response())
}
pub async fn get_latest_commit(State(host): State<Arc<Host>>, Query(p): Params) -> Answer {
pub async fn get_latest_commit(State(host): State<Arc<Host>>, Query(p): Query<Params>) -> Answer {
let did = param(&p, "did")?;
let head = host.store.head(did).map_err(XrpcError::internal)?;
let head = head.ok_or_else(|| repo_not_found(did))?;
Ok(Json(json!({"cid": head.cid.to_string(), "rev": head.rev})))
}
pub async fn list_repos(State(host): State<Arc<Host>>, Query(p): Params) -> Answer {
pub async fn list_repos(State(host): State<Arc<Host>>, Query(p): Query<Params>) -> Answer {
let limit = limit(&p)?;
let repos = host
.store
@@ -154,7 +159,7 @@ pub async fn list_repos(State(host): State<Arc<Host>>, Query(p): Params) -> Answ
Ok(Json(json!({"repos": repos, "cursor": cursor})))
}
pub async fn resolve_handle(State(host): State<Arc<Host>>, Query(p): Params) -> Answer {
pub async fn resolve_handle(State(host): State<Arc<Host>>, Query(p): Query<Params>) -> Answer {
let handle = param(&p, "handle")?.to_ascii_lowercase();
let account = host.store.account(&handle).map_err(XrpcError::internal)?;
let account = account.filter(|a| a.handle == handle);
@@ -172,7 +177,7 @@ pub async fn resolve_handle(State(host): State<Arc<Host>>, Query(p): Params) ->
/// browser neither sniffs nor runs it.
pub async fn get_blob(
State(host): State<Arc<Host>>,
Query(p): Params,
Query(p): Query<Params>,
) -> Result<Response, XrpcError> {
let did = did_of(&host, param(&p, "did")?)?;
let cid = param(&p, "cid")?;
@@ -197,7 +202,7 @@ pub async fn get_blob(
Ok((headers, bytes).into_response())
}
pub async fn list_blobs(State(host): State<Arc<Host>>, Query(p): Params) -> Answer {
pub async fn list_blobs(State(host): State<Arc<Host>>, Query(p): Query<Params>) -> Answer {
let did = did_of(&host, param(&p, "did")?)?;
let limit = limit(&p)?;
let (since, cursor) = (
crates/group-host/src/lib.rs+40−2
@@ -10,12 +10,14 @@ pub mod firehose;
pub mod plc;
pub mod repo;
pub mod secrets;
pub mod space;
pub mod space_api;
pub mod store;
pub mod time;
pub mod xrpc;
use axum::extract::Path;
use axum::routing::get;
use axum::routing::{get, post};
use axum::{Json, Router};
use config::Config;
use serde_json::{Value, json};
@@ -58,11 +60,21 @@ impl Host {
writing: Default::default(),
events: tokio::sync::broadcast::channel(16).0,
crawled: Default::default(),
http: reqwest::Client::new(),
http: client(),
})
}
}
/// How long the host waits on another server before giving up on it: a
/// server that takes a request and never answers holds nothing up longer.
pub const OUTGOING_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
/// A client for the host's requests to other servers.
pub fn client() -> reqwest::Client {
let built = reqwest::Client::builder().timeout(OUTGOING_TIMEOUT).build();
built.expect("a client with a timeout builds")
}
/// The host's routes.
pub fn router(host: Arc<Host>) -> Router {
Router::new()
@@ -89,6 +101,32 @@ pub fn router(host: Arc<Host>) -> Router {
"/xrpc/com.atproto.identity.resolveHandle",
get(api::resolve_handle),
)
.route(
"/xrpc/com.atproto.space.getRecord",
get(space_api::get_record),
)
.route(
"/xrpc/com.atproto.space.listRecords",
get(space_api::list_records),
)
.route("/xrpc/com.atproto.space.getRepo", get(space_api::get_repo))
.route(
"/xrpc/com.atproto.space.getLatestCommit",
get(space_api::get_latest_commit),
)
.route(
"/xrpc/com.atproto.space.listRepoOps",
get(space_api::list_repo_ops),
)
.route("/xrpc/com.atproto.space.getBlob", get(space_api::get_blob))
.route(
"/xrpc/com.atproto.space.listBlobs",
get(space_api::list_blobs),
)
.route(
"/xrpc/com.atproto.space.notifyCredentialRevoked",
post(space_api::notify_credential_revoked),
)
.route("/.well-known/did.json", get(api::did_json))
.route("/.well-known/atproto-did", get(api::atproto_did))
.route("/xrpc/{nsid}", get(not_implemented).post(not_implemented))
crates/group-host/src/plc.rs+1−1
@@ -14,7 +14,7 @@ impl Directory {
pub fn new(url: &str) -> Directory {
Directory {
url: url.trim_end_matches('/').to_string(),
http: reqwest::Client::new(),
http: crate::client(),
}
}
crates/group-host/src/repo.rs+78−45
@@ -34,6 +34,30 @@ pub enum Write {
},
}
impl Write {
/// Where it writes: its collection and record key.
pub fn path(&self) -> (&str, &str) {
match self {
Write::Create {
collection, rkey, ..
}
| Write::Update {
collection, rkey, ..
}
| Write::Delete { collection, rkey } => (collection, rkey),
}
}
}
/// A write checked against the records it changes: its path
/// (`collection/rkey`), the record it puts as its CID and DRISL (none for
/// a delete), and the blobs that record references.
pub(crate) struct Checked {
pub path: String,
pub put: Option<(Cid, Vec<u8>)>,
pub blobs: Vec<Cid>,
}
/// A commit made: its CID and revision.
#[derive(Debug, Clone, PartialEq)]
pub struct Committed {
@@ -41,7 +65,7 @@ pub struct Committed {
pub rev: String,
}
fn invalid(message: impl Into<String>) -> XrpcError {
pub(crate) fn invalid(message: impl Into<String>) -> XrpcError {
XrpcError::new(StatusCode::BAD_REQUEST, "InvalidRequest", message)
}
@@ -83,13 +107,16 @@ impl Host {
return Err(taken());
}
let signing = Keypair::generate(Curve::K256);
let kem = Keypair::generate(Curve::P256);
let rotation = [self.secrets.rotation.public().did_key()];
let op = Op::atproto(
let mut op = Op::atproto(
&signing.public().did_key(),
&rotation,
handle,
&self.config.public_url,
);
op.verification_methods
.insert("atproto_kem".into(), kem.public().did_key());
let genesis = op.sign(None, &self.secrets.rotation);
let did = genesis.did();
let failed = |e: anyhow::Error| {
@@ -107,6 +134,7 @@ impl Host {
did: did.clone(),
handle: handle.to_string(),
signing,
kem,
};
let tree = Tree::build(&BTreeMap::new());
let head = self.sign(&account, &tree);
@@ -189,46 +217,8 @@ impl Host {
let mut new_blobs = Vec::new();
let mut blocks = BTreeMap::new();
for write in writes {
let (collection, rkey, value, exists) = match write {
Write::Create {
collection,
rkey,
value,
} => (collection, rkey, Some(value), false),
Write::Update {
collection,
rkey,
value,
} => (collection, rkey, Some(value), true),
Write::Delete { collection, rkey } => (collection, rkey, None, true),
};
if !syntax::is_nsid(collection) || !syntax::is_record_key(rkey) {
return Err(invalid(format!(
"{collection}/{rkey} is not a record's path"
)));
}
let path = format!("{collection}/{rkey}");
if paths.contains_key(&path) != exists {
let what = if exists {
"no record at"
} else {
"a record already at"
};
return Err(invalid(format!("there is {what} {path}")));
}
let put = value.map(|v| record(collection, v)).transpose()?;
// A record may reference only blobs uploaded to its account.
let refs = value.map(blob_refs).unwrap_or_default();
for cid in &refs {
let blob = self
.store
.blob(&account.did, cid)
.map_err(XrpcError::internal)?;
if blob.is_none() {
return Err(invalid(format!("blob {cid} was not uploaded to {did}")));
}
}
new_blobs.extend(refs.iter().copied());
let Checked { path, put, blobs } = self.check(&account.did, write, &paths)?;
new_blobs.extend(blobs.iter().copied());
let prev = match &put {
Some((cid, bytes)) => {
blocks.insert(*cid, bytes.clone());
@@ -237,11 +227,12 @@ impl Host {
None => paths.remove(&path),
};
ops.push(op(path, put.as_ref().map(|(cid, _)| *cid), prev));
let (collection, rkey) = write.path();
changes.push(Change {
collection: collection.clone(),
rkey: rkey.clone(),
collection: collection.into(),
rkey: rkey.into(),
put,
blobs: refs,
blobs,
});
}
let tree = Tree::build(&paths);
@@ -277,6 +268,48 @@ impl Host {
})
}
/// `write` to `did`'s records, now at `paths`, checked: its path is a
/// record's, a create's free and an update's or delete's taken, its
/// record one by the data model of its collection's `$type`, and each
/// blob it references uploaded to `did`.
pub(crate) fn check(
&self,
did: &str,
write: &Write,
paths: &BTreeMap<String, Cid>,
) -> Result<Checked, XrpcError> {
let (collection, rkey) = write.path();
let (value, exists) = match write {
Write::Create { value, .. } => (Some(value), false),
Write::Update { value, .. } => (Some(value), true),
Write::Delete { .. } => (None, true),
};
if !syntax::is_nsid(collection) || !syntax::is_record_key(rkey) {
return Err(invalid(format!(
"{collection}/{rkey} is not a record's path"
)));
}
let path = format!("{collection}/{rkey}");
if paths.contains_key(&path) != exists {
let what = if exists {
"no record at"
} else {
"a record already at"
};
return Err(invalid(format!("there is {what} {path}")));
}
let put = value.map(|v| record(collection, v)).transpose()?;
// A record may reference only blobs uploaded to its account.
let blobs = value.map(blob_refs).unwrap_or_default();
for cid in &blobs {
let blob = self.store.blob(did, cid).map_err(XrpcError::internal)?;
if blob.is_none() {
return Err(invalid(format!("blob {cid} was not uploaded to {did}")));
}
}
Ok(Checked { path, put, blobs })
}
/// Wakes the firehose's streams, and tells the relays in
/// `PDS_CRAWLERS` this host has news: at most every twenty minutes,
/// and the first time after it starts, so a relay that marked it
crates/group-host/src/space.rsnew+154−0
@@ -0,0 +1,154 @@
//! A group's repos in spaces, as their repo host: its records in each
//! space it writes to, summed into the space alpha's set hash rather than
//! a signed tree, and each write told to the space's authority.
//!
//! Who may read them is the authority's to say, by the credentials it
//! issues; `space_api` checks those.
use crate::Host;
use crate::repo::{Checked, Write, invalid};
use crate::store::{Account, Change, SpaceHead};
use crate::time::now_millis;
use crate::xrpc::XrpcError;
use anyhow::{Context, Result, bail};
use atproto::service_auth::{self, Claims};
use atproto::space::{Commit, LtHash, SpaceRef, element};
use atproto::space_auth::space_host_aud;
use atproto::{Value, did};
use serde_json::json;
/// The method a repo host tells an authority of a write with.
pub const NOTIFY_WRITE: &str = "com.atproto.space.notifyWrite";
impl Host {
/// Makes `writes` to `did`'s repo in `space`, as one revision, and
/// tells the space's authority. Its commit.
///
/// The authority not hearing of it fails nothing: the write is made,
/// and the authority learns of it with the next.
pub async fn space_write(
&self,
did: &str,
space: &str,
writes: &[Write],
) -> Result<Commit, XrpcError> {
let space = SpaceRef::parse(space).map_err(|e| invalid(e.to_string()))?;
let (account, commit) = self.space_commit(did, &space, writes)?;
if let Err(e) = self.notify_write(&account, &space, &commit).await {
tracing::warn!(space = %space, repo = did, error = %format!("{e:#}"), "notifyWrite failed");
}
Ok(commit)
}
fn space_commit(
&self,
did: &str,
space: &SpaceRef,
writes: &[Write],
) -> Result<(Account, Commit), XrpcError> {
let _one_at_a_time = self.writing.lock().expect("not poisoned");
let account = self.store.account(did).map_err(XrpcError::internal)?;
let account = account.ok_or_else(|| {
XrpcError::new(
axum::http::StatusCode::BAD_REQUEST,
"RepoNotFound",
format!("no repo {did} here"),
)
})?;
let uri = space.to_string();
let head = self
.store
.space_head(&account.did, &uri)
.map_err(XrpcError::internal)?;
let mut hash = match &head {
Some(h) => LtHash::from_state(&h.state).expect("a state the host wrote"),
None => LtHash::default(),
};
let mut paths = self
.store
.space_paths(&account.did, &uri)
.map_err(XrpcError::internal)?;
let mut changes = Vec::new();
for write in writes {
let Checked { path, put, blobs } = self.check(&account.did, write, &paths)?;
let (collection, rkey) = write.path();
let prev = match &put {
Some((cid, _)) => paths.insert(path, *cid),
None => paths.remove(&path),
};
if let Some(prev) = prev {
hash.remove(&element(collection, rkey, &prev));
}
if let Some((cid, _)) = &put {
hash.add(&element(collection, rkey, cid));
}
changes.push(Change {
collection: collection.into(),
rkey: rkey.into(),
put,
blobs,
});
}
let new = SpaceHead {
rev: self.clock.next(),
state: hash.state(),
};
let prev = head.as_ref().map(|h| h.rev.as_str());
let moved = self
.store
.space_commit(&account.did, &uri, prev, &new, &changes);
let raced = format!("{did}'s repo in {uri} moved under a write");
let orphans = moved
.and_then(|moved| moved.context(raced))
.map_err(XrpcError::internal)?;
self.remove_blobs(orphans.iter().map(|cid| (account.did.as_str(), cid)));
let commit = Commit {
repo: account.did.clone(),
space: uri,
rev: new.rev,
data: hash.digest(),
};
Ok((account, commit))
}
/// Tells `space`'s authority, at its PDS, that `account`'s repo there
/// is now at `commit`, asking as the account.
async fn notify_write(
&self,
account: &Account,
space: &SpaceRef,
commit: &Commit,
) -> Result<()> {
let doc = self.plc.document(&space.authority).await?;
let pds = did::pds(&doc).context("the authority's document names no PDS")?;
let now = now_millis() as u64 / 1000;
let claims = Claims {
iss: account.did.clone(),
aud: space_host_aud(&space.authority),
exp: now + 60,
iat: Some(now),
lxm: Some(NOTIFY_WRITE.into()),
jti: Some(self.clock.next()),
};
let token = service_auth::sign(&account.signing, &claims);
let body = json!({
"space": commit.space,
"repo": commit.repo,
"repoRev": commit.rev,
"data": Value::Bytes(commit.data.to_vec()).to_json(),
});
let res = self
.http
.post(format!("{pds}/xrpc/{NOTIFY_WRITE}"))
.bearer_auth(token)
.json(&body)
.send()
.await?;
let status = res.status();
if !status.is_success() {
let said = res.text().await.unwrap_or_default();
bail!("the authority refused ({status}): {said}");
}
Ok(())
}
}
crates/group-host/src/space_api.rsnew+487−0
487 lines changed: not loaded until asked for.
crates/group-host/src/store.rs+341−5
@@ -17,6 +17,7 @@ const MIGRATIONS: &[&str] = &[
did TEXT PRIMARY KEY,
handle TEXT NOT NULL UNIQUE,
signing_key BLOB NOT NULL,
kem_key BLOB NOT NULL,
created_at INTEGER NOT NULL
);
CREATE TABLE repo (
@@ -62,10 +63,52 @@ const MIGRATIONS: &[&str] = &[
PRIMARY KEY (did, collection, rkey, cid)
);
CREATE INDEX record_blob_cid ON record_blob (did, cid);
",
"
CREATE TABLE space_repo (
did TEXT NOT NULL REFERENCES account (did),
space TEXT NOT NULL,
rev TEXT NOT NULL,
state BLOB NOT NULL,
PRIMARY KEY (did, space)
);
CREATE TABLE space_record (
did TEXT NOT NULL,
space TEXT NOT NULL,
path TEXT NOT NULL,
cid TEXT NOT NULL,
value BLOB NOT NULL,
rev TEXT NOT NULL,
PRIMARY KEY (did, space, path)
);
CREATE TABLE space_op (
did TEXT NOT NULL,
space TEXT NOT NULL,
rev TEXT NOT NULL,
idx INTEGER NOT NULL,
path TEXT NOT NULL,
cid TEXT,
prev TEXT,
PRIMARY KEY (did, space, rev, idx)
);
CREATE TABLE space_record_blob (
did TEXT NOT NULL,
space TEXT NOT NULL,
path TEXT NOT NULL,
cid TEXT NOT NULL,
PRIMARY KEY (did, space, path, cid)
);
CREATE INDEX space_record_blob_cid ON space_record_blob (did, cid);
CREATE TABLE revoked_credential (
space TEXT NOT NULL,
jti TEXT NOT NULL,
expires_at INTEGER NOT NULL,
PRIMARY KEY (space, jti)
);
",
];
const NEW_ACCOUNT: &str = "INSERT INTO account (did, handle, signing_key, created_at) VALUES (?1, ?2, ?3, ?4) ON CONFLICT (handle) DO NOTHING";
const NEW_ACCOUNT: &str = "INSERT INTO account (did, handle, signing_key, kem_key, created_at) VALUES (?1, ?2, ?3, ?4, ?5) ON CONFLICT (handle) DO NOTHING";
const PUT_RECORD: &str = "INSERT INTO record (did, collection, rkey, cid, value, rev) VALUES (?1, ?2, ?3, ?4, ?5, ?6) ON CONFLICT (did, collection, rkey) DO UPDATE SET cid = ?4, value = ?5, rev = ?6";
const LIST_UP: &str = "SELECT collection, rkey, cid, value FROM record WHERE did = ?1 AND collection = ?2 AND rkey > ?3 ORDER BY rkey LIMIT ?4";
const LIST_DOWN: &str = "SELECT collection, rkey, cid, value FROM record WHERE did = ?1 AND collection = ?2 AND rkey < ?3 ORDER BY rkey DESC LIMIT ?4";
@@ -74,7 +117,7 @@ const UNLINK: &str = "DELETE FROM record_blob WHERE did = ?1 AND collection = ?2
const LINK: &str =
"INSERT OR IGNORE INTO record_blob (did, collection, rkey, cid) VALUES (?1, ?2, ?3, ?4)";
const KEEP_BLOB: &str = "UPDATE blob SET temporary = 0 WHERE did = ?1 AND cid = ?2";
const FORGET_ORPHAN: &str = "DELETE FROM blob WHERE did = ?1 AND cid = ?2 AND temporary = 0 AND NOT EXISTS (SELECT 1 FROM record_blob WHERE did = ?1 AND cid = ?2)";
const FORGET_ORPHAN: &str = "DELETE FROM blob WHERE did = ?1 AND cid = ?2 AND temporary = 0 AND NOT EXISTS (SELECT 1 FROM record_blob WHERE did = ?1 AND cid = ?2) AND NOT EXISTS (SELECT 1 FROM space_record_blob WHERE did = ?1 AND cid = ?2)";
const PUT_BLOB: &str = "INSERT INTO blob (did, cid, mime_type, size, temporary, created_at) VALUES (?1, ?2, ?3, ?4, 1, ?5) ON CONFLICT (did, cid) DO UPDATE SET mime_type = excluded.mime_type";
const GET_BLOB: &str = "SELECT mime_type, size, temporary FROM blob WHERE did = ?1 AND cid = ?2";
const LIST_BLOBS: &str = "SELECT DISTINCT rb.cid FROM record_blob rb JOIN record r ON r.did = rb.did AND r.collection = rb.collection AND r.rkey = rb.rkey WHERE rb.did = ?1 AND r.rev > ?2 AND rb.cid > ?3 ORDER BY rb.cid LIMIT ?4";
@@ -84,6 +127,38 @@ const SEQUENCE: &str = "INSERT INTO event (did, kind, body) VALUES (?1, ?2, ?3)"
const EVENTS: &str = "SELECT seq, kind, body FROM event WHERE seq > ?1 ORDER BY seq LIMIT ?2";
const ACCOUNTS: &str =
"SELECT did, cid, rev, commit_block FROM repo WHERE did > ?1 ORDER BY did LIMIT ?2";
const SPACE_HEAD: &str = "SELECT rev, state FROM space_repo WHERE did = ?1 AND space = ?2";
const SPACE_START: &str = "INSERT INTO space_repo (did, space, rev, state) VALUES (?1, ?2, ?3, ?4) ON CONFLICT (did, space) DO NOTHING";
const SPACE_MOVE: &str =
"UPDATE space_repo SET rev = ?3, state = ?4 WHERE did = ?1 AND space = ?2 AND rev = ?5";
const SPACE_PATHS: &str = "SELECT path, cid FROM space_record WHERE did = ?1 AND space = ?2";
const SPACE_CID: &str = "SELECT cid FROM space_record WHERE did = ?1 AND space = ?2 AND path = ?3";
const SPACE_PUT: &str = "INSERT INTO space_record (did, space, path, cid, value, rev) VALUES (?1, ?2, ?3, ?4, ?5, ?6) ON CONFLICT (did, space, path) DO UPDATE SET cid = ?4, value = ?5, rev = ?6";
const SPACE_DELETE: &str = "DELETE FROM space_record WHERE did = ?1 AND space = ?2 AND path = ?3";
const SPACE_OP: &str = "INSERT INTO space_op (did, space, rev, idx, path, cid, prev) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)";
const SPACE_LINKED: &str =
"SELECT cid FROM space_record_blob WHERE did = ?1 AND space = ?2 AND path = ?3";
const SPACE_UNLINK: &str =
"DELETE FROM space_record_blob WHERE did = ?1 AND space = ?2 AND path = ?3";
const SPACE_LINK: &str =
"INSERT OR IGNORE INTO space_record_blob (did, space, path, cid) VALUES (?1, ?2, ?3, ?4)";
const SPACE_RECORD: &str =
"SELECT path, cid, value FROM space_record WHERE did = ?1 AND space = ?2 AND path = ?3";
const SPACE_RECORDS: &str =
"SELECT path, cid, value FROM space_record WHERE did = ?1 AND space = ?2 ORDER BY path";
// A collection's records are those whose path starts `<collection>/`.
const SPACE_LIST_UP: &str = "SELECT path, cid, value FROM space_record WHERE did = ?1 AND space = ?2 AND (?3 IS NULL OR substr(path, 1, length(?3) + 1) = ?3 || '/') AND path > ?4 ORDER BY path LIMIT ?5";
const SPACE_LIST_DOWN: &str = "SELECT path, cid, value FROM space_record WHERE did = ?1 AND space = ?2 AND (?3 IS NULL OR substr(path, 1, length(?3) + 1) = ?3 || '/') AND path < ?4 ORDER BY path DESC LIMIT ?5";
// An op's value is its record's, while the record is still what it made.
const SPACE_OPS: &str = "SELECT o.rev, o.idx, o.path, o.cid, o.prev, r.value FROM space_op o LEFT JOIN space_record r ON r.did = o.did AND r.space = o.space AND r.path = o.path AND r.cid = o.cid WHERE o.did = ?1 AND o.space = ?2 AND (o.rev > ?3 OR (o.rev = ?3 AND o.idx > ?4)) ORDER BY o.rev, o.idx LIMIT ?5";
const SPACE_BLOBS: &str = "SELECT DISTINCT rb.cid FROM space_record_blob rb JOIN space_record r ON r.did = rb.did AND r.space = rb.space AND r.path = rb.path WHERE rb.did = ?1 AND rb.space = ?2 AND r.rev > ?3 AND rb.cid > ?4 ORDER BY rb.cid LIMIT ?5";
const SPACE_HAS_BLOB: &str =
"SELECT 1 FROM space_record_blob WHERE did = ?1 AND space = ?2 AND cid = ?3 LIMIT 1";
const REVOKE: &str =
"INSERT OR IGNORE INTO revoked_credential (space, jti, expires_at) VALUES (?1, ?2, ?3)";
const FORGET_REVOKED: &str = "DELETE FROM revoked_credential WHERE expires_at <= ?1";
const REVOKED: &str =
"SELECT 1 FROM revoked_credential WHERE space = ?1 AND jti = ?2 AND expires_at > ?3";
const COLLECTIONS: &str =
"SELECT DISTINCT collection FROM record WHERE did = ?1 ORDER BY collection";
@@ -97,6 +172,9 @@ pub struct Account {
pub handle: String,
/// Signs its repo's commits.
pub signing: Keypair,
/// The P-256 key a space's syncer agrees a secret with, to have this
/// account's repos in spaces vouched for (`#atproto_kem`).
pub kem: Keypair,
}
/// A repo's current commit.
@@ -161,6 +239,29 @@ pub struct Change {
pub blobs: Vec<Cid>,
}
/// A repo's state in a space: its revision, and its records' set hash
/// (`atproto::space::LtHash::state`).
#[derive(Debug, Clone, PartialEq)]
pub struct SpaceHead {
pub rev: String,
pub state: Vec<u8>,
}
/// A change made to a repo in a space, in the order made: its revision
/// and place in it, the path, the record's CID after (none for a delete)
/// and before (none for a create), and its value, while the record is
/// still as the change left it.
#[derive(Debug, Clone, PartialEq)]
pub struct SpaceOp {
pub rev: String,
pub idx: i64,
pub collection: String,
pub rkey: String,
pub cid: Option<Cid>,
pub prev: Option<Cid>,
pub value: Option<Vec<u8>>,
}
/// A blob as kept: its type, its size, and whether it waits for a record
/// to reference it.
#[derive(Debug, Clone, PartialEq)]
@@ -175,6 +276,23 @@ fn cid(text: String) -> Cid {
Cid::parse(&text).expect("a CID the host wrote")
}
/// A path the host wrote, as `collection/rkey`.
fn split(path: &str) -> (String, String) {
let (collection, rkey) = path.split_once('/').expect("a path the host wrote");
(collection.into(), rkey.into())
}
/// A record in a space, from its path, CID and value.
fn space_record(row: &rusqlite::Row) -> rusqlite::Result<Record> {
let (collection, rkey) = split(&row.get::<_, String>(0)?);
Ok(Record {
collection,
rkey,
cid: cid(row.get(1)?),
value: row.get(2)?,
})
}
fn record(row: &rusqlite::Row) -> rusqlite::Result<Record> {
Ok(Record {
collection: row.get(0)?,
@@ -225,6 +343,7 @@ impl Store {
account.did,
account.handle,
account.signing.to_bytes().to_vec(),
account.kem.to_bytes().to_vec(),
now
],
);
@@ -246,23 +365,25 @@ impl Store {
let found = self
.conn()
.query_row(
"SELECT did, handle, signing_key FROM account WHERE did = ?1 OR handle = lower(?1)",
"SELECT did, handle, signing_key, kem_key FROM account WHERE did = ?1 OR handle = lower(?1)",
[did_or_handle],
|r| {
Ok((
r.get::<_, String>(0)?,
r.get::<_, String>(1)?,
r.get::<_, Vec<u8>>(2)?,
r.get::<_, Vec<u8>>(3)?,
))
},
)
.optional()?;
found
.map(|(did, handle, key)| {
.map(|(did, handle, signing, kem)| {
Ok(Account {
did,
handle,
signing: Keypair::from_bytes(Curve::K256, &key)?,
signing: Keypair::from_bytes(Curve::K256, &signing)?,
kem: Keypair::from_bytes(Curve::P256, &kem)?,
})
})
.transpose()
@@ -495,6 +616,221 @@ impl Store {
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
/// `did`'s repo in `space`, if it has written there.
pub fn space_head(&self, did: &str, space: &str) -> Result<Option<SpaceHead>> {
let conn = self.conn();
let found = conn.query_row(SPACE_HEAD, [did, space], |r| {
Ok(SpaceHead {
rev: r.get(0)?,
state: r.get(1)?,
})
});
Ok(found.optional()?)
}
/// Every record of `did`'s in `space`, by path, with its CID.
pub fn space_paths(&self, did: &str, space: &str) -> Result<BTreeMap<String, Cid>> {
let conn = self.conn();
let mut q = conn.prepare(SPACE_PATHS)?;
let rows = q.query_map([did, space], |r| Ok((r.get(0)?, cid(r.get(1)?))));
let rows = rows?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
/// Moves `did`'s repo in `space` from `prev` (none for its first
/// write) to `head`, with `changes`, each kept as an op, unless another
/// write moved it first: none then, and nothing changes. Blobs are
/// linked and forgotten as [`Store::commit`] does.
pub fn space_commit(
&self,
did: &str,
space: &str,
prev: Option<&str>,
head: &SpaceHead,
changes: &[Change],
) -> Result<Option<Vec<Cid>>> {
let mut conn = self.conn();
let tx = conn.transaction()?;
let moved = match prev {
None => tx.execute(SPACE_START, params![did, space, head.rev, head.state]),
Some(prev) => tx.execute(SPACE_MOVE, params![did, space, head.rev, head.state, prev]),
};
if moved? == 0 {
return Ok(None);
}
let mut unlinked = Vec::new();
for (idx, change) in changes.iter().enumerate() {
let path = format!("{}/{}", change.collection, change.rkey);
let before = tx.query_row(SPACE_CID, params![did, space, path], |r| {
r.get::<_, String>(0)
});
let before = before.optional()?;
let mut q = tx.prepare(SPACE_LINKED)?;
let links = q.query_map(params![did, space, path], |r| Ok(cid(r.get(0)?)));
unlinked.extend(links?.collect::<rusqlite::Result<Vec<_>>>()?);
let cleared = tx.execute(SPACE_UNLINK, params![did, space, path]);
cleared?;
for blob in &change.blobs {
let link = tx.execute(SPACE_LINK, params![did, space, path, blob.to_string()]);
link?;
let kept = tx.execute(KEEP_BLOB, params![did, blob.to_string()]);
kept?;
}
let after = change.put.as_ref().map(|(cid, _)| cid.to_string());
let done = match &change.put {
Some((cid, value)) => tx.execute(
SPACE_PUT,
params![did, space, path, cid.to_string(), value, head.rev],
),
None => tx.execute(SPACE_DELETE, params![did, space, path]),
};
done?;
let op = tx.execute(
SPACE_OP,
params![did, space, head.rev, idx as i64, path, after, before],
);
op?;
}
let mut orphans = Vec::new();
for cid in unlinked {
let gone = tx.execute(FORGET_ORPHAN, params![did, cid.to_string()]);
if gone? > 0 {
orphans.push(cid);
}
}
tx.commit()?;
Ok(Some(orphans))
}
/// `did`'s record in `space` at `collection/rkey`.
pub fn space_record(
&self,
did: &str,
space: &str,
collection: &str,
rkey: &str,
) -> Result<Option<Record>> {
let conn = self.conn();
let path = format!("{collection}/{rkey}");
let found = conn.query_row(SPACE_RECORD, [did, space, &path], space_record);
Ok(found.optional()?)
}
/// Every record of `did`'s in `space`, by path, as DRISL.
pub fn space_records(&self, did: &str, space: &str) -> Result<BTreeMap<String, Vec<u8>>> {
let conn = self.conn();
let mut q = conn.prepare(SPACE_RECORDS)?;
let rows = q.query_map([did, space], |r| Ok((r.get(0)?, r.get(2)?)));
let rows = rows?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
/// `did`'s records in `space`, of `collection` or all, past `cursor`
/// (a path), at most `limit`: last path first, or first with `reverse`.
pub fn space_list(
&self,
did: &str,
space: &str,
collection: Option<&str>,
cursor: Option<&str>,
limit: u32,
reverse: bool,
) -> Result<Vec<Record>> {
let conn = self.conn();
let sql = if reverse {
SPACE_LIST_UP
} else {
SPACE_LIST_DOWN
};
// No path sorts before "" or after "\u{7f}": its characters are ASCII.
let from = cursor.unwrap_or(if reverse { "" } else { "\u{7f}" });
let mut q = conn.prepare(sql)?;
let rows = q.query_map(params![did, space, collection, from, limit], space_record)?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
/// The changes to `did`'s repo in `space` after `since` (a revision)
/// and `cursor` (an op's revision and place), at most `limit`, with the
/// repo's state as they leave it, read at one moment.
pub fn space_ops(
&self,
did: &str,
space: &str,
after: (&str, i64),
limit: u32,
) -> Result<(Vec<SpaceOp>, Option<SpaceHead>)> {
let conn = self.conn();
let mut q = conn.prepare(SPACE_OPS)?;
let rows = q.query_map(params![did, space, after.0, after.1, limit], |r| {
let (collection, rkey) = split(&r.get::<_, String>(2)?);
Ok(SpaceOp {
rev: r.get(0)?,
idx: r.get(1)?,
collection,
rkey,
cid: r.get::<_, Option<String>>(3)?.map(cid),
prev: r.get::<_, Option<String>>(4)?.map(cid),
value: r.get(5)?,
})
});
let ops = rows?.collect::<rusqlite::Result<_>>()?;
let head = conn.query_row(SPACE_HEAD, [did, space], |r| {
Ok(SpaceHead {
rev: r.get(0)?,
state: r.get(1)?,
})
});
Ok((ops, head.optional()?))
}
/// The blobs `did`'s records in `space` reference, as
/// [`Store::list_blobs`] lists a repo's.
pub fn space_blobs(
&self,
did: &str,
space: &str,
since: Option<&str>,
cursor: Option<&str>,
limit: u32,
) -> Result<Vec<Cid>> {
let conn = self.conn();
let mut q = conn.prepare(SPACE_BLOBS)?;
let asked = params![did, space, since.unwrap_or(""), cursor.unwrap_or(""), limit];
let rows = q.query_map(asked, |r| Ok(cid(r.get(0)?)));
let rows = rows?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
/// Whether a record of `did`'s in `space` references blob `cid`.
pub fn space_has_blob(&self, did: &str, space: &str, cid: &Cid) -> Result<bool> {
let conn = self.conn();
let found = conn.query_row(SPACE_HAS_BLOB, [did, space, &cid.to_string()], |_| Ok(()));
Ok(found.optional()?.is_some())
}
/// Keeps the credentials `jtis` to `space` as revoked until
/// `expires_at` (in seconds), when they would have lapsed anyway; those
/// lapsed by `now` are forgotten.
pub fn revoke(&self, space: &str, jtis: &[String], expires_at: i64, now: i64) -> Result<()> {
let mut conn = self.conn();
let tx = conn.transaction()?;
let forgot = tx.execute(FORGET_REVOKED, [now]);
forgot?;
for jti in jtis {
let kept = tx.execute(REVOKE, params![space, jti, expires_at]);
kept?;
}
tx.commit()?;
Ok(())
}
/// Whether the credential `jti` to `space` is revoked at `now`.
pub fn revoked(&self, space: &str, jti: &str, now: i64) -> Result<bool> {
let conn = self.conn();
let found = conn.query_row(REVOKED, params![space, jti, now], |_| Ok(()));
Ok(found.optional()?.is_some())
}
/// Up to `limit` events after `cursor`, in order.
pub fn events_after(&self, cursor: i64, limit: u32) -> Result<Vec<Sequenced>> {
let conn = self.conn();
crates/group-host/tests/common/mod.rs+20−6
@@ -62,20 +62,34 @@ async fn document(
let Some(Signed::Update { op, .. }) = ops.get(&did).and_then(|l| l.last()) else {
return Err(StatusCode::NOT_FOUND);
};
let key = op.verification_methods["atproto"]
.strip_prefix("did:key:")
.unwrap();
let methods: Vec<Value> = op
.verification_methods
.iter()
.map(|(name, key)| {
json!({
"id": format!("{did}#{name}"),
"type": "Multikey",
"controller": did,
"publicKeyMultibase": key.strip_prefix("did:key:").unwrap(),
})
})
.collect();
let services: Vec<Value> = op
.services
.iter()
.map(|(name, s)| json!({"id": format!("#{name}"), "type": s.kind, "serviceEndpoint": s.endpoint}))
.collect();
Ok(Json(json!({
"@context": ["https://www.w3.org/ns/did/v1", "https://w3id.org/security/multikey/v1"],
"id": did,
"alsoKnownAs": op.also_known_as,
"verificationMethod": [{"id": format!("{did}#atproto"), "type": "Multikey", "controller": did, "publicKeyMultibase": key}],
"service": [{"id": "#atproto_pds", "type": "AtprotoPersonalDataServer", "serviceEndpoint": op.services["atproto_pds"].endpoint}],
"verificationMethod": methods,
"service": services,
})))
}
/// Serves `router` on a free port, answering its address.
async fn serve(router: Router) -> String {
pub async fn serve(router: Router) -> String {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
crates/group-host/tests/common/net.rs+6−0
@@ -51,6 +51,12 @@ pub fn net() -> &'static Net {
break serde_json::from_str(&line).unwrap();
}
};
// Named, the alpha is what the tests are to run on: none skips.
let named = std::env::var_os("GROUP_HOST_DEV_ENV").is_some();
assert!(
net.spaces || !named,
"GROUP_HOST_DEV_ENV names a PDS without spaces"
);
std::thread::spawn(move || for _ in lines {});
*CHILD.lock().unwrap() = Some(child);
net
crates/group-host/tests/interop.rs+163−1
crates/group-host/tests/repos.rs+6−0
crates/group-host/tests/spaces.rsnew+1209−0
1209 lines changed: not loaded until asked for.
docs/design/README.md+8−4
docs/design/spaces.mdnew+77−0
docs/README.md+2−1