chadtmiller.com/group-host
atmosphere group host
0
0
Groups speak the space alpha of November 13, on atproto 0.2
.knotless/workflows/test.yml+4−2
| @@ -18,8 +18,10 @@ on: | ||
pull: {base: [refs/heads/main, refs/heads/feature/*]} | ||
cache: [target, /usr/local/cargo/registry, /usr/local/rustup, /opt/tools, /opt/node, /opt/atproto, harness/node_modules] | ||
env: | ||
# The space alpha the tests run against. | ||
ATPROTO_COMMIT: 11c5d98cd50261c5e1201fedc5c6c05a7b8d1ccf | ||
# The space alpha the tests run against: permissioned-data-alpha as of | ||
# November 13, 2026, the build @atproto/space 0.0.0-spaces-alpha-20261113224550 | ||
# was published from. | ||
ATPROTO_COMMIT: 83d473dec69bbf19fe95fcbbb20a39842779db82 | ||
# Bumped when the steps that build the alpha change, to build it again. | ||
ALPHA_BUILD: "2" | ||
steps: | ||
crates/group-host/src/account_move.rs+1−1
| @@ -401,7 +401,7 @@ impl Host { | ||
.moving_json(mover, m, "com.atproto.space.listSpaces", &page, None) | ||
.await?; | ||
let uris = listed["spaces"].as_array().into_iter().flatten(); | ||
spaces.extend(uris.filter_map(|s| s["uri"].as_str().map(String::from))); | ||
spaces.extend(uris.filter_map(|s| s["space"].as_str().map(String::from))); | ||
cursor = next(&listed); | ||
} | ||
let (mut records, mut files) = (0, 0); | ||
crates/group-host/src/authority.rs+360−84
444 lines changed: not loaded until asked for.
crates/group-host/src/authority_api.rs+119−91
| @@ -1,28 +1,29 @@ | ||
//! The `com.atproto.space.*` methods a space's authority answers, for the | ||
//! spaces of the groups here: issuing credentials, hearing of writes, | ||
//! listing the repos written, and registering the services told of them. | ||
//! spaces of the groups here: authorizing a syncer, with a credential and | ||
//! a registration to be told of changes; hearing of writes; and listing | ||
//! the changes to the writer set. | ||
| ||
use crate::Host; | ||
use crate::api::{Params, invalid, page, param}; | ||
use crate::authority::Access; | ||
use crate::space::NOTIFY_WRITE; | ||
use crate::authority::{Access, repo_removed, repo_write}; | ||
use crate::space::NOTIFY_REPO_UPDATE; | ||
use crate::space_api::{credential, forbidden, now, refused, service_caller}; | ||
use crate::store::Space; | ||
use crate::time::iso; | ||
use crate::store::{Registration, Space}; | ||
use crate::xrpc::XrpcError; | ||
use atproto::space::SpaceRef; | ||
use atproto::space_auth::{self, Expect, Kind, Make, space_host_aud}; | ||
use atproto::{PublicKey, Value as Drisl, did, syntax, tid}; | ||
use atproto::{PublicKey, Value as Drisl, syntax, tid}; | ||
use axum::Json; | ||
use axum::extract::{Query, State}; | ||
use axum::http::{HeaderMap, StatusCode}; | ||
use reqwest::Url; | ||
use serde_json::{Value, json}; | ||
use std::sync::Arc; | ||
| ||
/// How long a service is told of a space's writes once it registers. | ||
const REGISTERED_FOR: u64 = 24 * 60 * 60; | ||
/// How far ahead of the host's clock a revision may be. | ||
const FUTURE_REV: u64 = 5 * 60; | ||
/// The longest token a syncer registers with, in bytes. | ||
const TOKEN_AT_MOST: usize = 512; | ||
| ||
type Answer = Result<Json<Value>, XrpcError>; | ||
| ||
| @@ -45,29 +46,82 @@ fn text<'a>(body: &'a Value, name: &str) -> Result<&'a str, XrpcError> { | ||
.ok_or_else(|| invalid(format!("{name} is required"))) | ||
} | ||
| ||
/// A space credential for the body's `credentialKid`, a P-256 key of the | ||
/// caller's: to the user a `delegationToken` names, if the space lets them | ||
/// read it, or to anyone, without one, for a space anyone may read. A user | ||
/// it does not let read is answered as if there were no such space. | ||
pub async fn get_space_credential( | ||
/// The endpoint and token a body's `notify` registers, if it has one: an | ||
/// https URL (or http, while this host is on http itself, as a network of | ||
/// test servers is), and a token of at most 512 bytes. | ||
fn notify_of(host: &Host, body: &Value) -> Result<Option<Registration>, XrpcError> { | ||
let notify = &body["notify"]; | ||
if notify.is_null() { | ||
return Ok(None); | ||
} | ||
let (endpoint, token) = (text(notify, "endpoint")?, text(notify, "token")?); | ||
let http_here = host.config.public_url.starts_with("http://"); | ||
let url = Url::parse(endpoint).ok(); | ||
if !url.is_some_and(|u| u.scheme() == "https" || (http_here && u.scheme() == "http")) { | ||
return Err(invalid("notify's endpoint is an https URL")); | ||
} | ||
if token.len() > TOKEN_AT_MOST { | ||
return Err(invalid("notify's token is at most 512 bytes")); | ||
} | ||
Ok(Some(Registration { | ||
endpoint: endpoint.into(), | ||
token: token.into(), | ||
})) | ||
} | ||
| ||
/// A space credential for the body's `credentialKey`, a P-256 key of the | ||
/// caller's, and the space's revision: to the user a `delegationToken` | ||
/// names, if the space lets them read it, or to anyone, without one, for a | ||
/// space anyone may read. A user it does not let read is answered as if | ||
/// there were no such space, and the registration they ask for withdrawn. | ||
/// With `notify`, the endpoint it names is told of the space's changes | ||
/// while the credential lasts, once it confirms it asked to be. | ||
pub async fn authorize_space_sync( | ||
State(host): State<Arc<Host>>, | ||
Json(body): Json<Value>, | ||
) -> Answer { | ||
let uri = text(&body, "space")?; | ||
let space = space_ref(uri)?; | ||
let kid = text(&body, "credentialKid")?; | ||
if !matches!(PublicKey::from_did_key(kid), Ok(PublicKey::P256(_))) { | ||
return Err(invalid("credentialKid is a P-256 did:key")); | ||
let key = text(&body, "credentialKey")?; | ||
if !matches!(PublicKey::from_did_key(key), Ok(PublicKey::P256(_))) { | ||
return Err(invalid("credentialKey is a P-256 did:key")); | ||
} | ||
let notify = notify_of(&host, &body)?; | ||
let authority = host | ||
.store | ||
.account(&space.authority) | ||
.map_err(XrpcError::internal)?; | ||
let authority = authority | ||
.filter(|a| a.did == space.authority) | ||
.ok_or_else(not_found)?; | ||
let off = host.store.deactivation(&authority.did); | ||
if off.map_err(XrpcError::internal)?.is_some() { | ||
return Err(bad( | ||
"RepoDeactivated", | ||
"the space's authority is switched off", | ||
)); | ||
} | ||
// Whoever asks: a syncer that missed the deletion learns of it here. | ||
let deleted = host.store.space_deleted(uri).map_err(XrpcError::internal)?; | ||
if deleted { | ||
return Err(bad("SpaceDeleted", "the space was deleted")); | ||
} | ||
let delegation = match body["delegationToken"].as_str() { | ||
Some(token) => Some(delegated(&host, token, &space).await?), | ||
None => None, | ||
}; | ||
// `clientAttestation` is taken and neither checked nor used: no space | ||
// here admits by the app asking. | ||
let user = delegation.as_ref().map(|d| d.iss.as_str()); | ||
let hosted = host.store.space(uri).map_err(XrpcError::internal)?; | ||
let hosted = hosted.ok_or_else(not_found)?; | ||
let may = host.may(uri, &hosted, user, Access::Read); | ||
if !may.map_err(XrpcError::internal)? { | ||
// A syncer that lost the space is told of it no more. | ||
if let Some(to) = ¬ify { | ||
let gone = host.store.unregister(uri, to); | ||
gone.map_err(XrpcError::internal)?; | ||
} | ||
return Err(not_found()); | ||
} | ||
// Spent once it buys a credential: one token, one credential. | ||
| @@ -80,27 +134,41 @@ pub async fn get_space_credential( | ||
)); | ||
} | ||
} | ||
let authority = host | ||
.store | ||
.account(&hosted.authority) | ||
.map_err(XrpcError::internal)?; | ||
let authority = authority.ok_or_else(not_found)?; | ||
// An endpoint registered already, lapsed or not, confirmed it then. | ||
if let Some(to) = ¬ify { | ||
let registered = host.store.registration(uri, to); | ||
if registered.map_err(XrpcError::internal)?.is_none() { | ||
host.confirm_registration(uri, to).await?; | ||
} | ||
} | ||
let make = Make { | ||
iss: &authority.did, | ||
sub: uri, | ||
key_id: Some(kid), | ||
key_id: Some(key), | ||
..Make::default() | ||
}; | ||
let credential = space_auth::create(Kind::Credential, &make, &authority.signing, now()) | ||
.map_err(XrpcError::internal)?; | ||
let (_, issued) = space_auth::parse(Kind::Credential, &credential).map_err(refused)?; | ||
// Kept, so a member who loses the space has theirs revoked. | ||
if let Some(user) = user { | ||
let (_, issued) = space_auth::parse(Kind::Credential, &credential).map_err(refused)?; | ||
host.store | ||
.issued(uri, user, &issued.jti, issued.exp as i64, now() as i64) | ||
.map_err(XrpcError::internal)?; | ||
} | ||
Ok(Json(json!({ "credential": credential }))) | ||
// Renewed with each credential, so a syncer that keeps authorizing | ||
// stays registered. | ||
if let Some(to) = ¬ify { | ||
let kept = host.store.register(uri, to, issued.exp as i64); | ||
kept.map_err(XrpcError::internal)?; | ||
} | ||
// Read once registered, so that any change after it is told. | ||
let space_rev = host.store.space_rev(uri).map_err(XrpcError::internal)?; | ||
let mut answer = json!({ "credential": credential }); | ||
if let Some(rev) = space_rev { | ||
answer["spaceRev"] = json!(rev); | ||
} | ||
Ok(Json(answer)) | ||
} | ||
| ||
/// What a delegation token says, once it is signed by the user it names, | ||
| @@ -127,12 +195,12 @@ async fn delegated( | ||
/// A repo host says a repo of one of its accounts was written in a space | ||
/// of a group here: kept in the space's writer set if the space lets the | ||
/// account write, and told to the space's syncers. | ||
pub async fn notify_write( | ||
pub async fn notify_repo_update( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
Json(body): Json<Value>, | ||
) -> Answer { | ||
let caller = service_caller(&host, &headers, NOTIFY_WRITE).await?; | ||
let caller = service_caller(&host, &headers, NOTIFY_REPO_UPDATE).await?; | ||
let uri = text(&body, "space")?; | ||
let space = space_ref(uri)?; | ||
let (repo, rev) = (text(&body, "repo")?, text(&body, "repoRev")?); | ||
| @@ -145,10 +213,12 @@ pub async fn notify_write( | ||
}; | ||
// A repo host speaks for its own accounts alone. | ||
if caller.account() != repo { | ||
return Err(forbidden("notifyWrite's issuer is not the writer")); | ||
return Err(forbidden("notifyRepoUpdate's issuer is not the repo")); | ||
} | ||
if caller.aud != space.authority && caller.aud != space_host_aud(&space.authority) { | ||
return Err(forbidden("notifyWrite is not for this space's authority")); | ||
return Err(forbidden( | ||
"notifyRepoUpdate is not for this space's authority", | ||
)); | ||
} | ||
let hosted = host.store.space(uri).map_err(XrpcError::internal)?; | ||
let hosted = hosted.ok_or_else(not_found)?; | ||
| @@ -158,9 +228,9 @@ pub async fn notify_write( | ||
} | ||
let may = host.may(uri, &hosted, Some(repo), Access::Write); | ||
if !may.map_err(XrpcError::internal)? { | ||
return Err(forbidden("the writer may not write in this space")); | ||
return Err(forbidden("the repo may not write in this space")); | ||
} | ||
let kept = host.record_writer(uri, &hosted.authority, repo, rev, &data); | ||
let kept = host.record_writer(uri, repo, rev, &data); | ||
kept.map_err(XrpcError::internal)?; | ||
Ok(Json(json!({}))) | ||
} | ||
| @@ -173,9 +243,10 @@ async fn as_authority(host: &Host, headers: &HeaderMap, uri: &str) -> Result<Spa | ||
host.hosted_space(uri) | ||
} | ||
| ||
/// The repos written in a space, in the order the space last heard of | ||
/// each: who syncs it reads each from its host. | ||
pub async fn list_repos( | ||
/// The changes to a space's writer set, in its order: the last for each | ||
/// repo, a write or its removal. Who syncs it reads each repo written from | ||
/// its host. | ||
pub async fn list_writers( | ||
State(host): State<Arc<Host>>, | ||
Query(p): Query<Params>, | ||
headers: HeaderMap, | ||
| @@ -184,66 +255,23 @@ pub async fn list_repos( | ||
as_authority(&host, &headers, uri).await?; | ||
let limit = page(&p, 100, 1000)?; | ||
let cursor = p.get("cursor").map(String::as_str); | ||
let writers = host | ||
let changes = host | ||
.store | ||
.writers(uri, cursor, limit) | ||
.writer_log(uri, cursor, limit) | ||
.map_err(XrpcError::internal)?; | ||
// A short page is the last: no cursor to ask for an empty one after it. | ||
let cursor = writers | ||
.last() | ||
.filter(|_| writers.len() == limit as usize) | ||
.map(|w| w.space_rev.clone()); | ||
let repos: Vec<Value> = writers | ||
let repos: Vec<Value> = changes | ||
.iter() | ||
.map(|w| { | ||
json!({ | ||
"did": w.did, | ||
"repoRev": w.repo_rev, | ||
"data": Drisl::Bytes(w.data.clone()).to_json(), | ||
"spaceRev": w.space_rev, | ||
}) | ||
.map(|c| { | ||
let (w, prev) = (&c.writer, c.prev_space_rev.as_deref()); | ||
match c.removed { | ||
true => repo_removed(&w.did, &w.space_rev, prev), | ||
false => repo_write(&w.did, &w.repo_rev, &w.data, &w.space_rev, prev), | ||
} | ||
}) | ||
.collect(); | ||
Ok(Json(json!({"repos": repos, "cursor": cursor}))) | ||
} | ||
| ||
/// A service that syncs a space is told of its writes, for a day, at the | ||
/// endpoint its own DID document names. | ||
pub async fn register_notify( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
Json(body): Json<Value>, | ||
) -> Answer { | ||
let uri = text(&body, "space")?; | ||
let service = text(&body, "service")?; | ||
as_authority(&host, &headers, uri).await?; | ||
let (who, fragment) = service.split_once('#').unwrap_or((service, "atproto_pds")); | ||
let doc = host.identity.document(who).await.ok(); | ||
let endpoint = doc.and_then(|d| did::service(&d, &format!("#{fragment}"))); | ||
let endpoint = endpoint.ok_or_else(|| { | ||
bad( | ||
"ServiceNotResolvable", | ||
format!("no service endpoint for {service}"), | ||
) | ||
})?; | ||
let until = now() + REGISTERED_FOR; | ||
host.store | ||
.register(uri, service, &endpoint, until as i64) | ||
.map_err(XrpcError::internal)?; | ||
Ok(Json(json!({ "expiresAt": iso(until as i64 * 1000) }))) | ||
} | ||
| ||
/// A service is told of a space's writes no more. | ||
pub async fn unregister_notify( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
Json(body): Json<Value>, | ||
) -> Answer { | ||
let uri = text(&body, "space")?; | ||
let service = text(&body, "service")?; | ||
as_authority(&host, &headers, uri).await?; | ||
host.store | ||
.unregister(uri, service) | ||
.map_err(XrpcError::internal)?; | ||
Ok(Json(json!({}))) | ||
let mut answer = json!({ "repos": repos }); | ||
if let Some(last) = changes.last() { | ||
answer["cursor"] = json!(last.writer.space_rev); | ||
} | ||
Ok(Json(answer)) | ||
} | ||
crates/group-host/src/group_invites.rs+23−22
| @@ -1,7 +1,7 @@ | ||
//! Invites. A group invites someone by writing an invite in its own repo | ||
//! in the invitee's inbox: a space under the invitee's own DID, at their | ||
//! PDS, which lets this host say who may write there | ||
//! (`com.atproto.managedspace.checkUserAccess`). An app writes it as the | ||
//! (`com.atproto.managedspace.checkAccess`). An app writes it as the | ||
//! group, through `com.atproto.space.*` with a session for the group, and | ||
//! takes it back by deleting it. The invitee's apps read it there; the | ||
//! host keeps its own list of what it sent, which is what redeems an | ||
| @@ -35,8 +35,8 @@ use std::sync::Arc; | ||
| ||
type Answer = Result<Json<Value>, XrpcError>; | ||
| ||
/// The method a space's authority asks this host who may read or write. | ||
pub const CHECK_USER_ACCESS: &str = "com.atproto.managedspace.checkUserAccess"; | ||
/// The method a space's authority asks this host what a repo may do. | ||
pub const CHECK_ACCESS: &str = "com.atproto.managedspace.checkAccess"; | ||
| ||
fn bad(error: &'static str, message: impl Into<String>) -> XrpcError { | ||
XrpcError::new(StatusCode::BAD_REQUEST, error, message) | ||
| @@ -473,16 +473,17 @@ pub async fn decline_invite( | ||
Ok(Json(json!({}))) | ||
} | ||
| ||
/// Whether a user may read or write a space this host manages for its | ||
/// authority: someone's inbox, which its owner reads and groups here | ||
/// write their invites in. McpRequest by the space's authority, with service | ||
/// auth for this host. | ||
pub async fn check_user_access( | ||
/// Whether an account may read or write a space this host manages for | ||
/// its authority: someone's inbox, which its owner reads and groups here | ||
/// write their invites in. Asked by the space's authority, with service | ||
/// auth for this host (`<host DID>#opensocial`, the managing app an inbox | ||
/// names). | ||
pub async fn check_access( | ||
State(host): State<Arc<Host>>, | ||
Query(p): Query<Params>, | ||
headers: HeaderMap, | ||
) -> Answer { | ||
let asker = caller(&host, &headers, CHECK_USER_ACCESS).await?; | ||
let asker = caller(&host, &headers, CHECK_ACCESS).await?; | ||
let asker = asker | ||
.ok_or_else(|| crate::space_api::unauthorized("AuthMissing", "service auth is required"))?; | ||
let space = SpaceRef::parse(param(&p, "space")?).map_err(|e| invalid(e.to_string()))?; | ||
| @@ -493,20 +494,20 @@ pub async fn check_user_access( | ||
"only the space's authority asks", | ||
)); | ||
} | ||
let user = param(&p, "user")?; | ||
let inbox = space.kind == format!("{NS}.invites"); | ||
let authorized = match p.get("access").map(String::as_str) { | ||
// Its owner reads it; a group here writes in it. | ||
Some("write") => { | ||
inbox | ||
&& host | ||
.store | ||
.account(user) | ||
.map_err(XrpcError::internal)? | ||
.is_some_and(|a| a.did == user) | ||
&& group_of(&host, user).is_ok() | ||
// Its owner reads it; a group here writes in it. Without a repo, no | ||
// one is asking as anyone, and may do neither. | ||
let (read, write) = match p.get("repo").filter(|_| inbox) { | ||
Some(repo) => { | ||
let group = host | ||
.store | ||
.account(repo) | ||
.map_err(XrpcError::internal)? | ||
.is_some_and(|a| &a.did == repo) | ||
&& group_of(&host, repo).is_ok(); | ||
(repo == &space.authority, group) | ||
} | ||
_ => inbox && user == space.authority, | ||
None => (false, false), | ||
}; | ||
Ok(Json(json!({ "authorized": authorized }))) | ||
Ok(Json(json!({ "read": read, "write": write }))) | ||
} | ||
crates/group-host/src/group_lifecycle.rs+5−4
| @@ -86,10 +86,11 @@ pub async fn activate_group( | ||
/// Deletes a group: its DID is ended; its account, repos and spaces here | ||
/// go, and what the host keeps of them; the services syncing its spaces | ||
/// are told. The directory refusing, the group stays, to be deleted | ||
/// again. They are told first, while the group has a key to sign with: | ||
/// best effort, so a delete that then fails has told them of one that | ||
/// did not happen, and they find it again when they next read. What | ||
/// members wrote in its spaces is theirs, at their own PDSes. | ||
/// again. They are told first, while the host still knows where: best | ||
/// effort, and nothing kept to try again, as the group goes with its | ||
/// spaces; so a delete that then fails has told them of one that did not | ||
/// happen, and they find it again when they next authorize. What members | ||
/// wrote in its spaces is theirs, at their own PDSes. | ||
pub async fn delete_group( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
crates/group-host/src/group_members.rs+9−8
| @@ -7,7 +7,8 @@ | ||
//! | ||
//! Someone who stops being a member reads its spaces no more: the | ||
//! credentials they hold are revoked, the apps they signed in as the group | ||
//! end, and the index forgets what they wrote there. | ||
//! end, and they leave the writer set of each of its spaces, the index | ||
//! forgetting what they wrote there and the spaces' syncers told. | ||
| ||
use crate::Host; | ||
use crate::group::{did_rkey, members_space}; | ||
| @@ -184,12 +185,12 @@ impl Host { | ||
Ok(()) | ||
} | ||
| ||
/// Forgets, in the index of each of `group`'s spaces, what `member` | ||
/// wrote there. | ||
pub(crate) fn unindex_member(&self, group: &str, member: &str) -> Result<(), XrpcError> { | ||
/// Takes `member` out of the writer set of each of `group`'s spaces: | ||
/// the index forgets what they wrote there, and the spaces' syncers | ||
/// are told. | ||
pub(crate) fn remove_writer_of(&self, group: &str, member: &str) -> Result<(), XrpcError> { | ||
for space in self.store.spaces_of(group).map_err(XrpcError::internal)? { | ||
self.store | ||
.unindex(&space, member) | ||
self.remove_writer(&space, member) | ||
.map_err(XrpcError::internal)?; | ||
} | ||
Ok(()) | ||
| @@ -197,7 +198,7 @@ impl Host { | ||
| ||
/// Takes `member` out of `group`: what they hold of it ended first, so | ||
/// that if that fails they are still in and may ask again; then their | ||
/// membership, and what they wrote, forgotten. | ||
/// membership, and their place among its spaces' writers. | ||
async fn put_out(&self, group: &str, member: &str) -> Result<(), XrpcError> { | ||
self.cut_off(group, member).await?; | ||
let gone = Write::Delete { | ||
| @@ -207,7 +208,7 @@ impl Host { | ||
let (space, gone) = (members_space(group), [gone]); | ||
let written = self.space_write(group, &space, &gone); | ||
written.await?; | ||
self.unindex_member(group, member) | ||
self.remove_writer_of(group, member) | ||
} | ||
} | ||
| ||
crates/group-host/src/import_space.rs+3−7
| @@ -201,7 +201,7 @@ impl Host { | ||
.writers | ||
.into_iter() | ||
.filter(|w| w.did != did) | ||
.map(|w| (w.did, w.rev, w.data, self.clock.next())) | ||
.map(|w| (w.did, w.repo_rev, w.data, self.clock.next())) | ||
.collect(); | ||
let now = crate::time::now_millis(); | ||
let kept = self | ||
| @@ -237,12 +237,8 @@ impl Host { | ||
let mut hash = LtHash::default(); | ||
let mut writes = Vec::new(); | ||
for (path, value) in &records { | ||
let Some((collection, rkey)) = path.split_once('/') else { | ||
return Err(refused( | ||
"InvalidArchive", | ||
format!("{path} is no record's path"), | ||
)); | ||
}; | ||
// `read_star` takes only `collection/rkey` keys. | ||
let (collection, rkey) = path.split_once('/').expect("a record path"); | ||
hash.add(&element(collection, rkey, &Cid::of_cbor(value))); | ||
writes.extend(create(path, value).filter(keeps)); | ||
} | ||
crates/group-host/src/index.rs+42−34
| @@ -19,7 +19,8 @@ use crate::store::SpaceHead; | ||
use crate::time::now_millis; | ||
use anyhow::{Context, Result, bail, ensure}; | ||
use atproto::space::{ | ||
COMMIT_MAC, Commit, LtHash, element, encapsulate, parse_mac_header, read_star, want_mac_header, | ||
COMMIT_MAC, Commit, LtHash, accept_signature, check_commit_mac, element, encapsulate, | ||
read_repo_star, | ||
}; | ||
use atproto::space_auth::{self, Kind, Make, sign_request}; | ||
use atproto::{Cid, Curve, Keypair, Value, did, drisl}; | ||
| @@ -48,14 +49,22 @@ struct Remote { | ||
key: Keypair, | ||
} | ||
| ||
/// An answer vouched for: the secret agreed for it, the MAC it carried, | ||
/// and its body. | ||
/// An answer to a request that asked for a MAC: the key share asked with, | ||
/// the secret agreed with it, and the answer's headers and body. | ||
struct Vouched { | ||
share: String, | ||
secret: [u8; 32], | ||
mac: Vec<u8>, | ||
headers: reqwest::header::HeaderMap, | ||
body: Vec<u8>, | ||
} | ||
| ||
impl Vouched { | ||
/// An answer's header by its name in lower case. | ||
fn header(&self, name: &str) -> Option<&str> { | ||
self.headers.get(name).and_then(|v| v.to_str().ok()) | ||
} | ||
} | ||
| ||
impl Remote { | ||
async fn ask(&self, host: &Host, method: &str, params: &[(&str, &str)]) -> Result<Vouched> { | ||
let (share, secret) = encapsulate(&self.kem)?; | ||
| @@ -64,32 +73,28 @@ impl Remote { | ||
.get(format!("{}/xrpc/com.atproto.space.{method}", self.pds)) | ||
.query(&[("space", self.space.as_str()), ("repo", self.did.as_str())]) | ||
.query(params) | ||
.header( | ||
"atproto-space-want-mac", | ||
want_mac_header(COMMIT_MAC, &share), | ||
); | ||
.header("accept-signature", accept_signature(COMMIT_MAC, &share)); | ||
for (k, v) in sign_request(&self.key, &self.authorization, &self.did)? { | ||
req = req.header(k, v); | ||
} | ||
let res = req.send().await?.error_for_status()?; | ||
let header = res.headers().get("atproto-space-mac"); | ||
let header = header.and_then(|h| h.to_str().ok()).unwrap_or_default(); | ||
// A page without a commit carries no MAC. | ||
let mac = parse_mac_header(header, COMMIT_MAC).unwrap_or_default(); | ||
let headers = res.headers().clone(); | ||
let body = crate::index_api::capped(res, REPO_AT_MOST).await; | ||
let body = body.context("an answer past the most a repo is read for")?; | ||
Ok(Vouched { secret, mac, body }) | ||
Ok(Vouched { | ||
share, | ||
secret, | ||
headers, | ||
body, | ||
}) | ||
} | ||
| ||
/// Whether `commit` is this repo's, vouched for with `mac`. | ||
fn vouched(&self, commit: &Commit, answer: &Vouched) -> Result<()> { | ||
/// The commit `answer`'s MAC vouches for, if it is this repo's. | ||
fn vouched(&self, answer: &Vouched) -> Result<Commit> { | ||
let commit = check_commit_mac(|n| answer.header(n), &answer.share, &answer.secret)?; | ||
let ours = commit.repo == self.did && commit.space == self.space; | ||
ensure!(ours, "a commit of another repo"); | ||
ensure!( | ||
commit.mac(&answer.secret).to_vec() == answer.mac, | ||
"a commit not vouched for" | ||
); | ||
Ok(()) | ||
Ok(commit) | ||
} | ||
} | ||
| ||
| @@ -247,7 +252,7 @@ impl Host { | ||
let mut last: BTreeMap<String, Json> = BTreeMap::new(); | ||
let mut cursor: Option<String> = None; | ||
let mut seen = HashSet::new(); | ||
let (commit, answer) = loop { | ||
let (page, answer) = loop { | ||
let mut params = vec![("since", from.rev.as_str()), ("limit", PAGE)]; | ||
if let Some(c) = &cursor { | ||
params.push(("cursor", c)); | ||
| @@ -274,12 +279,14 @@ impl Host { | ||
// A server that answers a page it gave would be read forever. | ||
ensure!(seen.insert(cursor.clone()), "the oplog repeats a page"); | ||
if cursor.is_none() { | ||
let commit = | ||
commit_of(&page["commit"]).context("the oplog's head with no commit")?; | ||
break (commit, answer); | ||
break (page, answer); | ||
} | ||
}; | ||
remote.vouched(&commit, &answer)?; | ||
// Every page carries the repo's head; the last one's is where the | ||
// oplog leads. | ||
let commit = remote.vouched(&answer)?; | ||
let written = commit_of(&page["commit"]).context("the oplog's head with no commit")?; | ||
ensure!(written == commit, "a commit not the one vouched for"); | ||
ensure!( | ||
hash.digest() == commit.data, | ||
"the oplog does not come to its commit" | ||
| @@ -319,14 +326,18 @@ impl Host { | ||
/// commit it opens with. | ||
async fn read_whole(&self, remote: &Remote) -> Result<()> { | ||
let answer = remote.ask(self, "getRepo", &[]).await?; | ||
let (commit, records) = read_star(&answer.body)?; | ||
remote.vouched(&commit, &answer)?; | ||
let (commit, records) = read_repo_star( | ||
&answer.body, | ||
&remote.space, | ||
&remote.did, | ||
&answer.share, | ||
&answer.secret, | ||
|n| answer.header(n), | ||
)?; | ||
let mut hash = LtHash::default(); | ||
let mut changes = Changes::new(); | ||
for (path, bytes) in records { | ||
let (collection, rkey) = path | ||
.split_once('/') | ||
.context("a record's path with no key")?; | ||
let (collection, rkey) = path.split_once('/').expect("a record's path"); | ||
let cid = Cid::of_cbor(&bytes); | ||
hash.add(&element(collection, rkey, &cid)); | ||
// Hashed as it is, kept only if it is a record. | ||
| @@ -342,10 +353,7 @@ impl Host { | ||
), | ||
} | ||
} | ||
ensure!( | ||
hash.digest() == commit.data, | ||
"the repo does not come to its commit" | ||
); | ||
// The archive's records came to its commit as it was read. | ||
let head = SpaceHead { | ||
rev: commit.rev, | ||
state: hash.state(), | ||
crates/group-host/src/lexicons.rs+1−1
| @@ -122,7 +122,7 @@ pub const FILES: &[&str] = &[ | ||
lexicon!("upstream/com/atproto/identity/resolveHandle"), | ||
lexicon!("upstream/com/atproto/label/defs"), | ||
lexicon!("upstream/com/atproto/label/label"), | ||
lexicon!("upstream/com/atproto/managedspace/checkUserAccess"), | ||
lexicon!("upstream/com/atproto/managedspace/checkAccess"), | ||
lexicon!("upstream/com/atproto/managedspace/policy"), | ||
lexicon!("upstream/com/atproto/moderation/defs"), | ||
lexicon!("upstream/com/atproto/repo/strongRef"), | ||
crates/group-host/src/lib.rs+15−20
| @@ -215,28 +215,20 @@ pub(crate) fn routes(host: Arc<Host>) -> Router { | ||
get(space_api::list_blobs), | ||
) | ||
.route( | ||
"/xrpc/com.atproto.space.notifyCredentialRevoked", | ||
post(space_api::notify_credential_revoked), | ||
"/xrpc/com.atproto.space.notifyCredentialsRevoked", | ||
post(space_api::notify_credentials_revoked), | ||
) | ||
.route( | ||
"/xrpc/com.atproto.space.getSpaceCredential", | ||
post(authority_api::get_space_credential), | ||
"/xrpc/com.atproto.space.authorizeSpaceSync", | ||
post(authority_api::authorize_space_sync), | ||
) | ||
.route( | ||
"/xrpc/com.atproto.space.notifyWrite", | ||
post(authority_api::notify_write), | ||
"/xrpc/com.atproto.space.notifyRepoUpdate", | ||
post(authority_api::notify_repo_update), | ||
) | ||
.route( | ||
"/xrpc/com.atproto.space.listRepos", | ||
get(authority_api::list_repos), | ||
) | ||
.route( | ||
"/xrpc/com.atproto.space.registerNotify", | ||
post(authority_api::register_notify), | ||
) | ||
.route( | ||
"/xrpc/com.atproto.space.unregisterNotify", | ||
post(authority_api::unregister_notify), | ||
"/xrpc/com.atproto.space.listWriters", | ||
get(authority_api::list_writers), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.createGroup", | ||
| @@ -324,8 +316,8 @@ pub(crate) fn routes(host: Arc<Host>) -> Router { | ||
post(group_invites::decline_invite), | ||
) | ||
.route( | ||
"/xrpc/com.atproto.managedspace.checkUserAccess", | ||
get(group_invites::check_user_access), | ||
"/xrpc/com.atproto.managedspace.checkAccess", | ||
get(group_invites::check_access), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.getAuthorization", | ||
| @@ -688,12 +680,15 @@ pub async fn serve(config: Config) -> anyhow::Result<()> { | ||
let _ = tokio::time::timeout(minute, woken).await; | ||
} | ||
}); | ||
// Word of writes owed to authorities elsewhere, tried as it falls due. | ||
// Word of writes owed to authorities elsewhere, and word of lapses and | ||
// deletions owed to syncers, tried as it falls due. | ||
let delivering = host.clone(); | ||
tokio::spawn(async move { | ||
loop { | ||
let tried = delivering.deliver_due().await; | ||
tracing::debug!(?tried, "delivered the notifyWrites due"); | ||
tracing::debug!(?tried, "delivered the notifyRepoUpdates due"); | ||
let retried = delivering.retry_syncers_due().await; | ||
tracing::debug!(?retried, "retried the word owed to syncers"); | ||
tokio::time::sleep(std::time::Duration::from_secs(10)).await; | ||
} | ||
}); | ||
crates/group-host/src/member_writes.rs+5−4
crates/group-host/src/migration.rs+4−4
crates/group-host/src/oauth_clients.rs+33−25
crates/group-host/src/scopes.rs+2−2
crates/group-host/src/space.rs+2−2
crates/group-host/src/space_api.rs+87−66
crates/group-host/src/store.rs+339−47
crates/group-host/tests/common/mod.rs+55−0
crates/group-host/tests/common/spaces.rs+131−16
crates/group-host/tests/account_move.rs+4−4
crates/group-host/tests/authority.rs+560−126
686 lines changed: not loaded until asked for.
crates/group-host/tests/group_spaces.rs+19−14
crates/group-host/tests/groups.rs+4−4
crates/group-host/tests/identity.rs+3−16
crates/group-host/tests/import.rs+1−1
crates/group-host/tests/index.rs+17−15
crates/group-host/tests/interop.rs+60−53
crates/group-host/tests/invites.rs+43−25
crates/group-host/tests/lifecycle.rs+51−35
crates/group-host/tests/members.rs+27−3
crates/group-host/tests/migration.rs+1−1
crates/group-host/tests/moderation.rs+7−25
crates/group-host/tests/spaces.rs+109−95
crates/group-host/tests/tokens.rs+5−2
crates/opensocial/src/lib.rs+1−1
crates/opensocial/tests/commands.rs+13−6
docs/design/membership.md+9−5
docs/design/README.md+1−1
docs/design/spaces.md+72−32
docs/reference/api.md+8−7
harness/lexicons.mjs+6−1
lexicons/upstream/com/atproto/managedspace/checkAccess.jsonnew+44−0
lexicons/upstream/com/atproto/managedspace/checkUserAccess.jsondeleted+0−48
lexicons/upstream/com/atproto/managedspace/policy.json+3−3
web/src/lib/permissions.ts+3−3
web/package-lock.json+2788−2981
A large diff, not shown.