chadtmiller.com/group-host
atmosphere group host
0
0
Groups are the authority for their own spaces
crates/group-host/src/authority.rsnew+290−0
| @@ -0,0 +1,290 @@ | ||
//! Being the authority for groups' spaces: which spaces a group here has, | ||
//! who may read and write each, the repos written in each (the writer | ||
//! set `listRepos` answers), and telling the services that sync a space | ||
//! of each write. | ||
//! | ||
//! Who may do what is the host's own to decide, from its grants: the | ||
//! group itself always; others as granted, or anyone reading a space open | ||
//! to all. Groups and their roles fill the grants in. | ||
//! | ||
//! As a repo host, it owes the authority of each space a group writes to | ||
//! word of the write: kept in an outbox and tried again until it lands, | ||
//! or a day has passed, as pds.js's `outbox.js` does. | ||
| ||
use crate::Host; | ||
use crate::repo::invalid; | ||
use crate::space::NOTIFY_WRITE; | ||
use crate::store::{Notice, Space}; | ||
use crate::time::now_millis; | ||
use crate::xrpc::XrpcError; | ||
use anyhow::{Context, Result}; | ||
use atproto::service_auth::{self, Claims}; | ||
use atproto::space::SpaceRef; | ||
use atproto::space_auth::space_host_aud; | ||
use atproto::{Value, did, syntax}; | ||
use axum::http::StatusCode; | ||
use serde_json::json; | ||
| ||
/// What a user would do in a space. | ||
#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
pub enum Access { | ||
Read, | ||
Write, | ||
} | ||
| ||
/// How long a write's word is tried before it is given up, in seconds. | ||
pub const DELIVER_FOR: i64 = 24 * 60 * 60; | ||
/// The wait before the first retry, doubling each after, up to an hour. | ||
const FIRST_RETRY: i64 = 10; | ||
const LAST_RETRY: i64 = 60 * 60; | ||
/// How many notices one round of delivery tries. | ||
const ROUND: u32 = 50; | ||
| ||
/// The wait before retry number `attempts`, counted from 1, in seconds. | ||
pub fn retry_delay(attempts: i64) -> i64 { | ||
let doubled = FIRST_RETRY.saturating_mul(1 << (attempts - 1).clamp(0, 20)); | ||
doubled.min(LAST_RETRY) | ||
} | ||
| ||
fn now() -> i64 { | ||
now_millis() / 1000 | ||
} | ||
| ||
/// What delivering a notice came to. | ||
#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
pub enum Delivery { | ||
Delivered, | ||
/// It may land later: the authority was not reached, or said so. | ||
Retry, | ||
/// It never will: the authority refused it. | ||
Failed, | ||
} | ||
| ||
impl Host { | ||
/// Service auth from `iss` to `aud` for `lxm`, for a minute. | ||
pub(crate) fn claims(&self, iss: &str, aud: &str, lxm: &str) -> Claims { | ||
let now = now() as u64; | ||
Claims { | ||
iss: iss.into(), | ||
aud: aud.into(), | ||
exp: now + 60, | ||
iat: Some(now), | ||
lxm: Some(lxm.into()), | ||
jti: Some(self.clock.next()), | ||
} | ||
} | ||
| ||
/// Makes a space of `authority`'s, a group here, of `kind` at `skey`; | ||
/// open to any reader with `public_read`. Its URI. | ||
pub fn create_space( | ||
&self, | ||
authority: &str, | ||
kind: &str, | ||
skey: &str, | ||
public_read: bool, | ||
) -> Result<String, XrpcError> { | ||
let uri = format!("at://{authority}/space/{kind}/{skey}"); | ||
SpaceRef::parse(&uri).map_err(|e| invalid(e.to_string()))?; | ||
let account = self.store.account(authority).map_err(XrpcError::internal)?; | ||
if !account.is_some_and(|a| a.did == authority) { | ||
return Err(invalid(format!("{authority} is no group here"))); | ||
} | ||
let made = self | ||
.store | ||
.create_space(&uri, authority, public_read, now()) | ||
.map_err(XrpcError::internal)?; | ||
if !made { | ||
return Err(XrpcError::new( | ||
StatusCode::BAD_REQUEST, | ||
"SpaceAlreadyExists", | ||
format!("{uri} exists"), | ||
)); | ||
} | ||
Ok(uri) | ||
} | ||
| ||
/// The space at `uri`, if its authority is a group here. | ||
pub fn hosted_space(&self, uri: &str) -> Result<Space, XrpcError> { | ||
let space = self.store.space(uri).map_err(XrpcError::internal)?; | ||
space.ok_or_else(|| { | ||
XrpcError::new(StatusCode::BAD_REQUEST, "SpaceNotFound", "space not found") | ||
}) | ||
} | ||
| ||
/// Lets `did` read `space`, write it, or both: what it was let do | ||
/// before is replaced. | ||
pub fn grant(&self, space: &str, did: &str, read: bool, write: bool) -> Result<(), XrpcError> { | ||
self.hosted_space(space)?; | ||
if !syntax::is_did(did) { | ||
return Err(invalid(format!("{did} is no DID"))); | ||
} | ||
let granted = self.store.grant(space, did, read, write); | ||
granted.map_err(XrpcError::internal) | ||
} | ||
| ||
/// Takes back whatever `did` was let do in `space`. | ||
pub fn ungrant(&self, space: &str, did: &str) -> Result<(), XrpcError> { | ||
self.hosted_space(space)?; | ||
self.store.ungrant(space, did).map_err(XrpcError::internal) | ||
} | ||
| ||
/// Whether `user` may do `access` in `space` (at `uri`): with no user, | ||
/// whether anyone may read it. | ||
pub fn may( | ||
&self, | ||
uri: &str, | ||
space: &Space, | ||
user: Option<&str>, | ||
access: Access, | ||
) -> Result<bool> { | ||
let Some(user) = user else { | ||
return Ok(access == Access::Read && space.public_read); | ||
}; | ||
// The authority never locks itself out of its own space. | ||
if user == space.authority { | ||
return Ok(true); | ||
} | ||
let granted = self.store.granted(uri, user)?; | ||
Ok(match access { | ||
Access::Read => space.public_read || granted.is_some_and(|(read, _)| read), | ||
Access::Write => granted.is_some_and(|(_, write)| write), | ||
}) | ||
} | ||
| ||
/// A write to `space`, of a group here, by `repo`: kept in the writer | ||
/// set unless it knows a later one, and told to the space's syncers. | ||
pub(crate) fn record_writer( | ||
&self, | ||
space: &str, | ||
authority: &str, | ||
repo: &str, | ||
repo_rev: &str, | ||
data: &[u8], | ||
) -> Result<()> { | ||
let space_rev = self.clock.next(); | ||
let kept = self | ||
.store | ||
.record_writer(space, repo, repo_rev, data, &space_rev)?; | ||
let Some(prev) = kept else { | ||
return Ok(()); | ||
}; | ||
let mut body = json!({ | ||
"space": space, | ||
"repo": repo, | ||
"repoRev": repo_rev, | ||
"data": Value::Bytes(data.to_vec()).to_json(), | ||
"spaceRev": space_rev, | ||
}); | ||
if let Some(prev) = prev { | ||
body["prevSpaceRev"] = json!(prev); | ||
} | ||
let recipients = self.store.recipients(space, now())?; | ||
let signing = self | ||
.store | ||
.account(authority)? | ||
.context("the authority is here")? | ||
.signing; | ||
for (service, endpoint) in recipients { | ||
let claims = self.claims(authority, &service, NOTIFY_WRITE); | ||
let token = service_auth::sign(&signing, &claims); | ||
let send = self | ||
.http | ||
.post(format!("{endpoint}/xrpc/{NOTIFY_WRITE}")) | ||
.bearer_auth(token) | ||
.json(&body) | ||
.send(); | ||
// Best effort, after the write: a syncer that misses one finds | ||
// out with the next, or on its own next read. | ||
tokio::spawn(async move { | ||
let said = send.await.and_then(|r| r.error_for_status()); | ||
if let Err(e) = said { | ||
tracing::warn!(service, error = %e, "forwarding notifyWrite failed"); | ||
} | ||
}); | ||
} | ||
Ok(()) | ||
} | ||
| ||
/// Tries `notice` now: tells its space's authority, at its PDS, as the | ||
/// repo. | ||
pub async fn deliver(&self, notice: &Notice) -> Delivery { | ||
let Ok(space) = SpaceRef::parse(¬ice.space) else { | ||
return Delivery::Failed; | ||
}; | ||
let Ok(Some(account)) = self.store.account(¬ice.repo) else { | ||
return Delivery::Failed; | ||
}; | ||
let doc = match self.identity.kept(&space.authority) { | ||
Some(doc) => Ok(doc), | ||
None => self.identity.document(&space.authority).await, | ||
}; | ||
// An authority not found, or naming no PDS yet, may be found later. | ||
let Some(pds) = doc.ok().as_ref().and_then(did::pds) else { | ||
return Delivery::Retry; | ||
}; | ||
let aud = space_host_aud(&space.authority); | ||
let token = service_auth::sign( | ||
&account.signing, | ||
&self.claims(&account.did, &aud, NOTIFY_WRITE), | ||
); | ||
let body = json!({ | ||
"space": notice.space, | ||
"repo": notice.repo, | ||
"repoRev": notice.rev, | ||
"data": Value::Bytes(notice.data.clone()).to_json(), | ||
}); | ||
let sent = self | ||
.http | ||
.post(format!("{pds}/xrpc/{NOTIFY_WRITE}")) | ||
.bearer_auth(token) | ||
.json(&body) | ||
.send() | ||
.await; | ||
match sent.map(|r| r.status()) { | ||
Ok(s) if s.is_success() => Delivery::Delivered, | ||
Ok(s) if retryable(s) => Delivery::Retry, | ||
Ok(_) => Delivery::Failed, | ||
Err(_) => Delivery::Retry, | ||
} | ||
} | ||
| ||
/// Tries `notice`, and keeps what came of it: owed no more, or owed | ||
/// again after a wait. | ||
pub(crate) async fn try_notice(&self, notice: &Notice) -> Result<Delivery> { | ||
let delivery = self.deliver(notice).await; | ||
match delivery { | ||
Delivery::Retry => { | ||
let next = now() + retry_delay(notice.attempts + 1); | ||
self.store.retry(notice, next)?; | ||
} | ||
Delivery::Delivered => self.store.delivered(notice)?, | ||
Delivery::Failed => { | ||
tracing::warn!( | ||
space = notice.space, | ||
repo = notice.repo, | ||
"the authority refused notifyWrite" | ||
); | ||
self.store.delivered(notice)?; | ||
} | ||
} | ||
Ok(delivery) | ||
} | ||
| ||
/// Tries the notices owed now, and gives up those a day old. How many | ||
/// were tried. | ||
pub async fn deliver_due(&self) -> Result<usize> { | ||
for (repo, space, rev) in self.store.lapse(now())? { | ||
tracing::warn!(repo, space, rev, "notifyWrite given up after a day"); | ||
} | ||
let due = self.store.due(now(), ROUND)?; | ||
for notice in &due { | ||
self.try_notice(notice).await?; | ||
} | ||
Ok(due.len()) | ||
} | ||
} | ||
| ||
/// Whether a refusal says the same request may land later. | ||
fn retryable(status: StatusCode) -> bool { | ||
matches!(status.as_u16(), 408 | 425 | 429) || status.is_server_error() | ||
} | ||
crates/group-host/src/authority_api.rsnew+231−0
| @@ -0,0 +1,231 @@ | ||
//! 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. | ||
| ||
use crate::Host; | ||
use crate::api::{Params, invalid, page, param}; | ||
use crate::authority::Access; | ||
use crate::space::NOTIFY_WRITE; | ||
use crate::space_api::{credential, forbidden, now, service_caller}; | ||
use crate::store::Space; | ||
use crate::time::iso; | ||
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 axum::Json; | ||
use axum::extract::{Query, State}; | ||
use axum::http::{HeaderMap, StatusCode}; | ||
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; | ||
| ||
type Answer = Result<Json<Value>, XrpcError>; | ||
| ||
fn bad(error: &'static str, message: impl Into<String>) -> XrpcError { | ||
XrpcError::new(StatusCode::BAD_REQUEST, error, message) | ||
} | ||
| ||
fn not_found() -> XrpcError { | ||
bad("SpaceNotFound", "space not found") | ||
} | ||
| ||
/// The space `uri` names, written as a space is. | ||
fn space_ref(uri: &str) -> Result<SpaceRef, XrpcError> { | ||
SpaceRef::parse(uri).map_err(|e| invalid(e.to_string())) | ||
} | ||
| ||
fn text<'a>(body: &'a Value, name: &str) -> Result<&'a str, XrpcError> { | ||
body[name] | ||
.as_str() | ||
.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( | ||
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 user = match body["delegationToken"].as_str() { | ||
Some(token) => Some(delegated(&host, token, &space).await?), | ||
None => None, | ||
}; | ||
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.as_deref(), Access::Read); | ||
if !may.map_err(XrpcError::internal)? { | ||
return Err(not_found()); | ||
} | ||
let authority = host | ||
.store | ||
.account(&hosted.authority) | ||
.map_err(XrpcError::internal)?; | ||
let authority = authority.ok_or_else(not_found)?; | ||
let make = Make { | ||
iss: &authority.did, | ||
sub: uri, | ||
key_id: Some(kid), | ||
..Make::default() | ||
}; | ||
let credential = space_auth::create(Kind::Credential, &make, &authority.signing, now()) | ||
.map_err(XrpcError::internal)?; | ||
Ok(Json(json!({ "credential": credential }))) | ||
} | ||
| ||
/// The user a delegation token speaks for: signed by them, for this | ||
/// space's authority and this space, and not spent before. | ||
async fn delegated(host: &Host, token: &str, space: &SpaceRef) -> Result<String, XrpcError> { | ||
let refused = |m: String| bad("InvalidDelegationToken", m); | ||
let (_, claims) = space_auth::parse(Kind::Delegation, token).map_err(|e| refused(e.message))?; | ||
let aud = space_host_aud(&space.authority); | ||
let uri = space.to_string(); | ||
let expect = Expect { | ||
aud: Some(&aud), | ||
sub: Some(&uri), | ||
}; | ||
let check = |key: &PublicKey| space_auth::verify(Kind::Delegation, token, key, &expect, now()); | ||
let checked = host.identity.with_key(&claims.iss, check).await; | ||
let checked = checked.ok_or_else(|| refused(format!("no signing key for {}", claims.iss)))?; | ||
let claims = checked.map_err(|e| refused(e.message))?; | ||
let spent = host | ||
.store | ||
.spend(&claims.iss, &claims.jti, claims.exp as i64, now() as i64) | ||
.map_err(XrpcError::internal)?; | ||
if !spent { | ||
return Err(refused("the delegation token was used already".into())); | ||
} | ||
Ok(claims.iss) | ||
} | ||
| ||
/// 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( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
Json(body): Json<Value>, | ||
) -> Answer { | ||
let caller = service_caller(&host, &headers, NOTIFY_WRITE).await?; | ||
let uri = text(&body, "space")?; | ||
let space = space_ref(uri)?; | ||
let (repo, rev) = (text(&body, "repo")?, text(&body, "repoRev")?); | ||
if !syntax::is_tid(rev) { | ||
return Err(invalid("repoRev is a TID")); | ||
} | ||
let data = Drisl::from_json(&body["data"]); | ||
let Ok(Drisl::Bytes(data)) = data else { | ||
return Err(invalid("data is bytes")); | ||
}; | ||
// A repo host speaks for its own accounts alone. | ||
if caller.account() != repo { | ||
return Err(forbidden("notifyWrite's issuer is not the writer")); | ||
} | ||
if caller.aud != space.authority && caller.aud != space_host_aud(&space.authority) { | ||
return Err(forbidden("notifyWrite 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)?; | ||
let ahead = tid::micros(rev).unwrap_or_default() / 1_000_000; | ||
if ahead > now() + FUTURE_REV { | ||
return Err(bad("FutureRev", "repoRev is in the future")); | ||
} | ||
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")); | ||
} | ||
let kept = host.record_writer(uri, &hosted.authority, repo, rev, &data); | ||
kept.map_err(XrpcError::internal)?; | ||
Ok(Json(json!({}))) | ||
} | ||
| ||
/// The space a credential to it names, if its authority is here: the | ||
/// credential for the authority, not a repo. | ||
async fn as_authority(host: &Host, headers: &HeaderMap, uri: &str) -> Result<Space, XrpcError> { | ||
let space = space_ref(uri)?; | ||
credential(host, headers, uri, &space.authority).await?; | ||
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( | ||
State(host): State<Arc<Host>>, | ||
Query(p): Query<Params>, | ||
headers: HeaderMap, | ||
) -> Answer { | ||
let uri = param(&p, "space")?; | ||
as_authority(&host, &headers, uri).await?; | ||
let limit = page(&p, 100, 1000)?; | ||
let cursor = p.get("cursor").map(String::as_str); | ||
let writers = host | ||
.store | ||
.writers(uri, cursor, limit) | ||
.map_err(XrpcError::internal)?; | ||
let cursor = writers.last().map(|w| w.space_rev.clone()); | ||
let repos: Vec<Value> = writers | ||
.iter() | ||
.map(|w| { | ||
json!({ | ||
"did": w.did, | ||
"repoRev": w.repo_rev, | ||
"data": Drisl::Bytes(w.data.clone()).to_json(), | ||
"spaceRev": w.space_rev, | ||
}) | ||
}) | ||
.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!({}))) | ||
} | ||
crates/group-host/src/lib.rs+32−1
| @@ -4,6 +4,8 @@ | ||
//! says how it is built and what is still to come. | ||
| ||
pub mod api; | ||
pub mod authority; | ||
pub mod authority_api; | ||
pub mod blobs; | ||
pub mod config; | ||
pub mod firehose; | ||
| @@ -42,7 +44,7 @@ pub struct Host { | ||
pub events: tokio::sync::broadcast::Sender<()>, | ||
/// When the relays were last told of news. | ||
crawled: std::sync::Mutex<Option<std::time::Instant>>, | ||
http: reqwest::Client, | ||
pub(crate) http: reqwest::Client, | ||
} | ||
| ||
impl Host { | ||
| @@ -132,6 +134,26 @@ pub fn router(host: Arc<Host>) -> Router { | ||
"/xrpc/com.atproto.space.notifyCredentialRevoked", | ||
post(space_api::notify_credential_revoked), | ||
) | ||
.route( | ||
"/xrpc/com.atproto.space.getSpaceCredential", | ||
post(authority_api::get_space_credential), | ||
) | ||
.route( | ||
"/xrpc/com.atproto.space.notifyWrite", | ||
post(authority_api::notify_write), | ||
) | ||
.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), | ||
) | ||
.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)) | ||
| @@ -164,6 +186,15 @@ pub async fn serve(config: Config) -> anyhow::Result<()> { | ||
tokio::time::sleep(std::time::Duration::from_secs(60 * 60)).await; | ||
} | ||
}); | ||
// Word of writes owed to authorities elsewhere, 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"); | ||
tokio::time::sleep(std::time::Duration::from_secs(10)).await; | ||
} | ||
}); | ||
let app = router(host); | ||
axum::serve(listener, app) | ||
.with_graceful_shutdown(stopped()) | ||
crates/group-host/src/space.rs+32−57
| @@ -6,16 +6,13 @@ | ||
//! issues; `space_api` checks those. | ||
| ||
use crate::Host; | ||
use crate::authority::{Access, DELIVER_FOR}; | ||
use crate::repo::{Checked, Write, invalid}; | ||
use crate::store::{Account, Change, SpaceHead}; | ||
use crate::store::{Change, Notice, 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"; | ||
| @@ -24,8 +21,9 @@ 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. | ||
/// The authority not hearing of it fails nothing: the write is made. | ||
/// An authority here keeps it at once; one elsewhere is owed word of | ||
/// it, tried now and again until it lands or a day has passed. | ||
pub async fn space_write( | ||
&self, | ||
did: &str, | ||
| @@ -33,19 +31,41 @@ impl Host { | ||
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"); | ||
let commit = self.space_commit(did, &space, writes)?; | ||
if let Err(e) = self.tell_authority(&space, &commit).await { | ||
tracing::warn!(space = %space, repo = did, error = %format!("{e:#}"), "telling the authority failed"); | ||
} | ||
Ok(commit) | ||
} | ||
| ||
async fn tell_authority(&self, space: &SpaceRef, commit: &Commit) -> Result<()> { | ||
let uri = space.to_string(); | ||
if let Some(hosted) = self.store.space(&uri)? { | ||
if !self.may(&uri, &hosted, Some(&commit.repo), Access::Write)? { | ||
bail!("{} may not write in {uri}", commit.repo); | ||
} | ||
let data = commit.data; | ||
return self.record_writer(&uri, &hosted.authority, &commit.repo, &commit.rev, &data); | ||
} | ||
let notice = Notice { | ||
repo: commit.repo.clone(), | ||
space: uri, | ||
rev: commit.rev.clone(), | ||
data: commit.data.to_vec(), | ||
attempts: 0, | ||
}; | ||
let now = now_millis() / 1000; | ||
self.store.owe(¬ice, now, now + DELIVER_FOR)?; | ||
self.try_notice(¬ice).await?; | ||
Ok(()) | ||
} | ||
| ||
fn space_commit( | ||
&self, | ||
did: &str, | ||
space: &SpaceRef, | ||
writes: &[Write], | ||
) -> Result<(Account, Commit), XrpcError> { | ||
) -> Result<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(|| { | ||
| @@ -108,51 +128,6 @@ impl Host { | ||
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.identity.kept(&space.authority); | ||
let doc = match doc { | ||
Some(doc) => doc, | ||
None => self.identity.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(()) | ||
Ok(commit) | ||
} | ||
} | ||
crates/group-host/src/space_api.rs+10−6
| @@ -28,15 +28,15 @@ pub const NOTIFY_REVOKED: &str = "com.atproto.space.notifyCredentialRevoked"; | ||
const WANT_MAC: &str = "atproto-space-want-mac"; | ||
const MAC: HeaderName = HeaderName::from_static("atproto-space-mac"); | ||
| ||
fn unauthorized(code: &'static str, message: impl Into<String>) -> XrpcError { | ||
pub(crate) fn unauthorized(code: &'static str, message: impl Into<String>) -> XrpcError { | ||
XrpcError::new(StatusCode::UNAUTHORIZED, code, message) | ||
} | ||
| ||
fn refused(e: TokenError) -> XrpcError { | ||
pub(crate) fn refused(e: TokenError) -> XrpcError { | ||
unauthorized(e.code, e.message) | ||
} | ||
| ||
fn now() -> u64 { | ||
pub(crate) fn now() -> u64 { | ||
now_millis() as u64 / 1000 | ||
} | ||
| ||
| @@ -51,7 +51,7 @@ struct Asked { | ||
/// Atproto-Space-Credential <jwt>`): issued by the space's authority, for | ||
/// this space and this repo, unrevoked, and the request signed with the key | ||
/// it is bound to. | ||
async fn credential( | ||
pub(crate) async fn credential( | ||
host: &Host, | ||
headers: &HeaderMap, | ||
space: &str, | ||
| @@ -422,7 +422,11 @@ pub async fn list_blobs( | ||
| ||
/// The claims of the request's service auth (`Authorization: Bearer`), | ||
/// signed by its issuer's key and for `lxm`. | ||
async fn service_caller(host: &Host, headers: &HeaderMap, lxm: &str) -> Result<Claims, XrpcError> { | ||
pub(crate) async fn service_caller( | ||
host: &Host, | ||
headers: &HeaderMap, | ||
lxm: &str, | ||
) -> Result<Claims, XrpcError> { | ||
let bearer = headers | ||
.get(header::AUTHORIZATION) | ||
.and_then(|v| v.to_str().ok()) | ||
| @@ -444,7 +448,7 @@ async fn service_caller(host: &Host, headers: &HeaderMap, lxm: &str) -> Result<C | ||
Ok(claims) | ||
} | ||
| ||
fn forbidden(message: &str) -> XrpcError { | ||
pub(crate) fn forbidden(message: &str) -> XrpcError { | ||
XrpcError::new(StatusCode::FORBIDDEN, "Forbidden", message) | ||
} | ||
| ||
crates/group-host/src/store.rs+283−0
| @@ -105,6 +105,54 @@ const MIGRATIONS: &[&str] = &[ | ||
expires_at INTEGER NOT NULL, | ||
PRIMARY KEY (space, jti) | ||
); | ||
", | ||
" | ||
CREATE TABLE space ( | ||
uri TEXT PRIMARY KEY, | ||
authority TEXT NOT NULL REFERENCES account (did), | ||
public_read INTEGER NOT NULL, | ||
created_at INTEGER NOT NULL | ||
); | ||
CREATE TABLE space_grant ( | ||
space TEXT NOT NULL REFERENCES space (uri), | ||
did TEXT NOT NULL, | ||
read INTEGER NOT NULL, | ||
write INTEGER NOT NULL, | ||
PRIMARY KEY (space, did) | ||
); | ||
CREATE TABLE space_writer ( | ||
space TEXT NOT NULL REFERENCES space (uri), | ||
did TEXT NOT NULL, | ||
repo_rev TEXT NOT NULL, | ||
data BLOB NOT NULL, | ||
space_rev TEXT NOT NULL, | ||
PRIMARY KEY (space, did) | ||
); | ||
CREATE INDEX space_writer_rev ON space_writer (space, space_rev); | ||
CREATE TABLE space_recipient ( | ||
space TEXT NOT NULL REFERENCES space (uri), | ||
service TEXT NOT NULL, | ||
endpoint TEXT NOT NULL, | ||
expires_at INTEGER NOT NULL, | ||
PRIMARY KEY (space, service) | ||
); | ||
CREATE TABLE spent_token ( | ||
iss TEXT NOT NULL, | ||
jti TEXT NOT NULL, | ||
expires_at INTEGER NOT NULL, | ||
PRIMARY KEY (iss, jti) | ||
); | ||
CREATE TABLE outbox ( | ||
repo TEXT NOT NULL, | ||
space TEXT NOT NULL, | ||
rev TEXT NOT NULL, | ||
data BLOB NOT NULL, | ||
attempts INTEGER NOT NULL, | ||
next_at INTEGER NOT NULL, | ||
deliver_by INTEGER NOT NULL, | ||
PRIMARY KEY (repo, space) | ||
); | ||
CREATE INDEX outbox_due ON outbox (next_at); | ||
", | ||
]; | ||
| ||
| @@ -159,6 +207,25 @@ const REVOKE: &str = | ||
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 NEW_SPACE: &str = "INSERT INTO space (uri, authority, public_read, created_at) VALUES (?1, ?2, ?3, ?4) ON CONFLICT (uri) DO NOTHING"; | ||
const SPACE: &str = "SELECT authority, public_read FROM space WHERE uri = ?1"; | ||
const PUT_GRANT: &str = "INSERT INTO space_grant (space, did, read, write) VALUES (?1, ?2, ?3, ?4) ON CONFLICT (space, did) DO UPDATE SET read = ?3, write = ?4"; | ||
const GRANT: &str = "SELECT read, write FROM space_grant WHERE space = ?1 AND did = ?2"; | ||
const UNGRANT: &str = "DELETE FROM space_grant WHERE space = ?1 AND did = ?2"; | ||
const WRITER_REV: &str = "SELECT repo_rev FROM space_writer WHERE space = ?1 AND did = ?2"; | ||
const LAST_SPACE_REV: &str = "SELECT MAX(space_rev) FROM space_writer WHERE space = ?1"; | ||
const PUT_WRITER: &str = "INSERT INTO space_writer (space, did, repo_rev, data, space_rev) VALUES (?1, ?2, ?3, ?4, ?5) ON CONFLICT (space, did) DO UPDATE SET repo_rev = ?3, data = ?4, space_rev = ?5"; | ||
const WRITERS: &str = "SELECT did, repo_rev, data, space_rev FROM space_writer WHERE space = ?1 AND space_rev > ?2 ORDER BY space_rev LIMIT ?3"; | ||
const PUT_RECIPIENT: &str = "INSERT INTO space_recipient (space, service, endpoint, expires_at) VALUES (?1, ?2, ?3, ?4) ON CONFLICT (space, service) DO UPDATE SET endpoint = ?3, expires_at = ?4"; | ||
const RECIPIENTS: &str = "SELECT service, endpoint FROM space_recipient WHERE space = ?1 AND expires_at > ?2 ORDER BY service"; | ||
const UNREGISTER: &str = "DELETE FROM space_recipient WHERE space = ?1 AND service = ?2"; | ||
const FORGET_SPENT: &str = "DELETE FROM spent_token WHERE expires_at <= ?1"; | ||
const SPEND: &str = "INSERT OR IGNORE INTO spent_token (iss, jti, expires_at) VALUES (?1, ?2, ?3)"; | ||
const OWE: &str = "INSERT INTO outbox (repo, space, rev, data, attempts, next_at, deliver_by) VALUES (?1, ?2, ?3, ?4, 0, ?5, ?6) ON CONFLICT (repo, space) DO UPDATE SET rev = ?3, data = ?4, attempts = 0, next_at = ?5, deliver_by = ?6"; | ||
const DUE: &str = "SELECT repo, space, rev, data, attempts FROM outbox WHERE next_at <= ?1 ORDER BY next_at LIMIT ?2"; | ||
const DELIVERED: &str = "DELETE FROM outbox WHERE repo = ?1 AND space = ?2 AND rev = ?3"; | ||
const RETRY: &str = "UPDATE outbox SET attempts = attempts + 1, next_at = ?4 WHERE repo = ?1 AND space = ?2 AND rev = ?3"; | ||
const LAPSED: &str = "DELETE FROM outbox WHERE deliver_by <= ?1 RETURNING repo, space, rev"; | ||
const COLLECTIONS: &str = | ||
"SELECT DISTINCT collection FROM record WHERE did = ?1 ORDER BY collection"; | ||
| ||
| @@ -262,6 +329,35 @@ pub struct SpaceOp { | ||
pub value: Option<Vec<u8>>, | ||
} | ||
| ||
/// A space whose authority is an account here: the authority, and | ||
/// whether anyone may read it. | ||
#[derive(Debug, Clone, PartialEq)] | ||
pub struct Space { | ||
pub authority: String, | ||
pub public_read: bool, | ||
} | ||
| ||
/// A repo's last write in a space, as its authority knows it: its | ||
/// revision and digest, and the space's revision when it was told. | ||
#[derive(Debug, Clone, PartialEq)] | ||
pub struct Writer { | ||
pub did: String, | ||
pub repo_rev: String, | ||
pub data: Vec<u8>, | ||
pub space_rev: String, | ||
} | ||
| ||
/// A write an authority elsewhere is owed word of: the repo, the space, | ||
/// the revision and digest, and how often telling it has failed. | ||
#[derive(Debug, Clone, PartialEq)] | ||
pub struct Notice { | ||
pub repo: String, | ||
pub space: String, | ||
pub rev: String, | ||
pub data: Vec<u8>, | ||
pub attempts: i64, | ||
} | ||
| ||
/// A blob as kept: its type, its size, and whether it waits for a record | ||
/// to reference it. | ||
#[derive(Debug, Clone, PartialEq)] | ||
| @@ -831,6 +927,193 @@ impl Store { | ||
Ok(found.optional()?.is_some()) | ||
} | ||
| ||
/// Keeps a new space of `authority`'s; `false` if there is one at `uri`. | ||
pub fn create_space( | ||
&self, | ||
uri: &str, | ||
authority: &str, | ||
public_read: bool, | ||
now: i64, | ||
) -> Result<bool> { | ||
let conn = self.conn(); | ||
let added = conn.execute(NEW_SPACE, params![uri, authority, public_read, now])?; | ||
Ok(added > 0) | ||
} | ||
| ||
/// The space at `uri`, if its authority is here. | ||
pub fn space(&self, uri: &str) -> Result<Option<Space>> { | ||
let conn = self.conn(); | ||
let found = conn.query_row(SPACE, [uri], |r| { | ||
Ok(Space { | ||
authority: r.get(0)?, | ||
public_read: r.get(1)?, | ||
}) | ||
}); | ||
Ok(found.optional()?) | ||
} | ||
| ||
/// Lets `did` read or write `space`, or both, as given. | ||
pub fn grant(&self, space: &str, did: &str, read: bool, write: bool) -> Result<()> { | ||
let conn = self.conn(); | ||
conn.execute(PUT_GRANT, params![space, did, read, write])?; | ||
Ok(()) | ||
} | ||
| ||
/// What `did` may do in `space`: read, and write. | ||
pub fn granted(&self, space: &str, did: &str) -> Result<Option<(bool, bool)>> { | ||
let conn = self.conn(); | ||
let found = conn.query_row(GRANT, [space, did], |r| Ok((r.get(0)?, r.get(1)?))); | ||
Ok(found.optional()?) | ||
} | ||
| ||
/// Takes back whatever `did` was let do in `space`. | ||
pub fn ungrant(&self, space: &str, did: &str) -> Result<()> { | ||
let conn = self.conn(); | ||
conn.execute(UNGRANT, [space, did])?; | ||
Ok(()) | ||
} | ||
| ||
/// Keeps `did`'s repo in `space` as at `repo_rev` with digest `data`, at | ||
/// the space's revision `space_rev`, unless it is known at that | ||
/// revision or a later one: none then. The space's revision before. | ||
pub fn record_writer( | ||
&self, | ||
space: &str, | ||
did: &str, | ||
repo_rev: &str, | ||
data: &[u8], | ||
space_rev: &str, | ||
) -> Result<Option<Option<String>>> { | ||
let mut conn = self.conn(); | ||
let tx = conn.transaction()?; | ||
let known = tx.query_row(WRITER_REV, [space, did], |r| r.get::<_, String>(0)); | ||
if known.optional()?.is_some_and(|k| k.as_str() >= repo_rev) { | ||
return Ok(None); | ||
} | ||
let before = tx.query_row(LAST_SPACE_REV, [space], |r| r.get::<_, Option<String>>(0))?; | ||
let kept = tx.execute(PUT_WRITER, params![space, did, repo_rev, data, space_rev]); | ||
kept?; | ||
tx.commit()?; | ||
Ok(Some(before)) | ||
} | ||
| ||
/// The repos written in `space`, in the order the space last heard of | ||
/// each, after `cursor` (a space revision), at most `limit`. | ||
pub fn writers(&self, space: &str, cursor: Option<&str>, limit: u32) -> Result<Vec<Writer>> { | ||
let conn = self.conn(); | ||
let mut q = conn.prepare(WRITERS)?; | ||
let rows = q.query_map(params![space, cursor.unwrap_or(""), limit], |r| { | ||
Ok(Writer { | ||
did: r.get(0)?, | ||
repo_rev: r.get(1)?, | ||
data: r.get(2)?, | ||
space_rev: r.get(3)?, | ||
}) | ||
}); | ||
let rows = rows?; | ||
Ok(rows.collect::<rusqlite::Result<_>>()?) | ||
} | ||
| ||
/// Tells `service`, at `endpoint`, of `space`'s writes until | ||
/// `expires_at` (in seconds). | ||
pub fn register( | ||
&self, | ||
space: &str, | ||
service: &str, | ||
endpoint: &str, | ||
expires_at: i64, | ||
) -> Result<()> { | ||
let conn = self.conn(); | ||
conn.execute(PUT_RECIPIENT, params![space, service, endpoint, expires_at])?; | ||
Ok(()) | ||
} | ||
| ||
pub fn unregister(&self, space: &str, service: &str) -> Result<()> { | ||
let conn = self.conn(); | ||
conn.execute(UNREGISTER, [space, service])?; | ||
Ok(()) | ||
} | ||
| ||
/// The services told of `space`'s writes at `now`, and where. | ||
pub fn recipients(&self, space: &str, now: i64) -> Result<Vec<(String, String)>> { | ||
let conn = self.conn(); | ||
let mut q = conn.prepare(RECIPIENTS)?; | ||
let rows = q.query_map(params![space, now], |r| Ok((r.get(0)?, r.get(1)?))); | ||
let rows = rows?; | ||
Ok(rows.collect::<rusqlite::Result<_>>()?) | ||
} | ||
| ||
/// Spends `iss`'s token `jti`, good until `expires_at`: `false` if it | ||
/// was spent already. Those lapsed by `now` are forgotten. | ||
pub fn spend(&self, iss: &str, jti: &str, expires_at: i64, now: i64) -> Result<bool> { | ||
let mut conn = self.conn(); | ||
let tx = conn.transaction()?; | ||
let forgot = tx.execute(FORGET_SPENT, [now]); | ||
forgot?; | ||
let spent = tx.execute(SPEND, params![iss, jti, expires_at])?; | ||
tx.commit()?; | ||
Ok(spent > 0) | ||
} | ||
| ||
/// Owes `space`'s authority word that `repo` is at `rev`, with digest | ||
/// `data`, from `now` until `deliver_by`: in place of any word of an | ||
/// earlier revision. | ||
pub fn owe(&self, notice: &Notice, now: i64, deliver_by: i64) -> Result<()> { | ||
let conn = self.conn(); | ||
let owed = params![ | ||
notice.repo, | ||
notice.space, | ||
notice.rev, | ||
notice.data, | ||
now, | ||
deliver_by | ||
]; | ||
conn.execute(OWE, owed)?; | ||
Ok(()) | ||
} | ||
| ||
/// The notices due at `now`, at most `limit`, the longest due first. | ||
pub fn due(&self, now: i64, limit: u32) -> Result<Vec<Notice>> { | ||
let conn = self.conn(); | ||
let mut q = conn.prepare(DUE)?; | ||
let rows = q.query_map(params![now, limit], |r| { | ||
Ok(Notice { | ||
repo: r.get(0)?, | ||
space: r.get(1)?, | ||
rev: r.get(2)?, | ||
data: r.get(3)?, | ||
attempts: r.get(4)?, | ||
}) | ||
}); | ||
let rows = rows?; | ||
Ok(rows.collect::<rusqlite::Result<_>>()?) | ||
} | ||
| ||
/// Owes `notice` no more; one for a later revision stays owed. | ||
pub fn delivered(&self, notice: &Notice) -> Result<()> { | ||
let conn = self.conn(); | ||
conn.execute(DELIVERED, [¬ice.repo, ¬ice.space, ¬ice.rev])?; | ||
Ok(()) | ||
} | ||
| ||
/// Tries `notice` again at `next_at`. | ||
pub fn retry(&self, notice: &Notice, next_at: i64) -> Result<()> { | ||
let conn = self.conn(); | ||
let asked = params![notice.repo, notice.space, notice.rev, next_at]; | ||
conn.execute(RETRY, asked)?; | ||
Ok(()) | ||
} | ||
| ||
/// Gives up the notices still owed at `now` past their time, answering | ||
/// each's repo, space and revision. | ||
pub fn lapse(&self, now: i64) -> Result<Vec<(String, String, String)>> { | ||
let conn = self.conn(); | ||
let mut q = conn.prepare(LAPSED)?; | ||
let rows = q.query_map([now], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?))); | ||
let rows = rows?; | ||
Ok(rows.collect::<rusqlite::Result<_>>()?) | ||
} | ||
| ||
/// 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+23−1
| @@ -4,6 +4,7 @@ | ||
#![allow(dead_code)] | ||
| ||
pub mod net; | ||
pub mod spaces; | ||
| ||
use atproto::plc::Signed; | ||
use axum::extract::{Path, State}; | ||
| @@ -135,6 +136,25 @@ impl Running { | ||
/// A host whose groups' handles are under `.groups.test`, with `vars` | ||
/// besides, publishing to a fake PLC directory. | ||
pub async fn start(vars: &[(&str, &str)], refuse: bool) -> Running { | ||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); | ||
start_on(listener, vars, refuse).await | ||
} | ||
| ||
/// A host whose `PUBLIC_URL` is where it listens, for servers elsewhere | ||
/// to reach it. | ||
pub async fn start_reachable(vars: &[(&str, &str)]) -> Running { | ||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); | ||
let url = format!("http://{}", listener.local_addr().unwrap()); | ||
let mut vars = vars.to_vec(); | ||
vars.push(("PUBLIC_URL", &url)); | ||
start_on(listener, &vars, false).await | ||
} | ||
| ||
async fn start_on( | ||
listener: tokio::net::TcpListener, | ||
vars: &[(&str, &str)], | ||
refuse: bool, | ||
) -> Running { | ||
let (plc, plc_url) = start_plc(refuse).await; | ||
let data = tempfile::tempdir().unwrap(); | ||
let dir = data.path().to_str().unwrap().to_string(); | ||
| @@ -150,7 +170,9 @@ pub async fn start(vars: &[(&str, &str)], refuse: bool) -> Running { | ||
env.extend(vars.iter().map(|(k, v)| (k.to_string(), v.to_string()))); | ||
let config = Config::from(|k| env.get(k).cloned()).unwrap(); | ||
let host = Arc::new(Host::open(config).unwrap()); | ||
let url = serve(group_host::router(host.clone())).await; | ||
let url = format!("http://{}", listener.local_addr().unwrap()); | ||
let router = group_host::router(host.clone()); | ||
tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }); | ||
Running { | ||
host, | ||
url, | ||
crates/group-host/tests/common/spaces.rsnew+222−0
| @@ -0,0 +1,222 @@ | ||
//! Spaces to test against: an authority elsewhere, a syncer of its | ||
//! space, and reads of a repo in it. | ||
| ||
#![allow(dead_code)] | ||
| ||
use super::{Running, serve}; | ||
use atproto::Cid; | ||
use atproto::plc::Op; | ||
use atproto::space::{encapsulate, want_mac_header}; | ||
use atproto::space_auth::{self, Kind, Make, sign_request}; | ||
use atproto::{Curve, Keypair}; | ||
use axum::Router; | ||
use axum::extract::State; | ||
use axum::http::{HeaderMap, StatusCode}; | ||
use axum::routing::post; | ||
use group_host::repo::Write; | ||
use group_host::time::now_millis; | ||
use serde_json::{Value as Json, json}; | ||
use std::sync::{Arc, Mutex}; | ||
| ||
pub const RIDERS: &str = "riders.groups.test"; | ||
pub const RULE: &str = "fyi.opensocial.rule"; | ||
| ||
pub fn now() -> u64 { | ||
now_millis() as u64 / 1000 | ||
} | ||
| ||
pub fn rule(title: &str) -> Json { | ||
json!({"$type": RULE, "title": title, "createdAt": "2026-11-03T00:00:00Z"}) | ||
} | ||
| ||
pub fn create(collection: &str, rkey: &str, value: Json) -> Write { | ||
Write::Create { | ||
collection: collection.into(), | ||
rkey: rkey.into(), | ||
value, | ||
} | ||
} | ||
| ||
/// What an authority's PDS was told: each notifyWrite's authorization | ||
/// and body. | ||
#[derive(Default)] | ||
pub struct Told { | ||
pub writes: Mutex<Vec<(String, Json)>>, | ||
/// What it answers each notification: 200 unless set. | ||
pub status: Mutex<Option<u16>>, | ||
} | ||
| ||
impl Told { | ||
/// Answers each notification with `status` from now on. | ||
pub fn answer(&self, status: u16) { | ||
*self.status.lock().unwrap() = Some(status); | ||
} | ||
} | ||
| ||
pub async fn notify_write( | ||
State(told): State<Arc<Told>>, | ||
headers: HeaderMap, | ||
axum::Json(body): axum::Json<Json>, | ||
) -> StatusCode { | ||
let auth = headers["authorization"].to_str().unwrap().to_string(); | ||
told.writes.lock().unwrap().push((auth, body)); | ||
let status = told.status.lock().unwrap().unwrap_or(200); | ||
StatusCode::from_u16(status).unwrap() | ||
} | ||
| ||
/// A space's authority elsewhere: an account on the directory, its PDS | ||
/// here, hearing of writes. | ||
pub struct Authority { | ||
pub did: String, | ||
pub key: Keypair, | ||
pub told: Arc<Told>, | ||
/// Its rotation key, its PDS, and its last operation, to change its | ||
/// document with. | ||
pub rotation: Keypair, | ||
pub pds: String, | ||
pub last: Option<Cid>, | ||
} | ||
| ||
pub async fn authority(h: &Running, refuse: bool, pds: bool) -> Authority { | ||
let told = Arc::new(Told::default()); | ||
if refuse { | ||
told.answer(500); | ||
} | ||
let router = Router::new() | ||
.route("/xrpc/com.atproto.space.notifyWrite", post(notify_write)) | ||
.with_state(told.clone()); | ||
let url = serve(router).await; | ||
let key = Keypair::generate(Curve::K256); | ||
let rotation = Keypair::generate(Curve::K256); | ||
let mut op = Op::atproto( | ||
&key.public().did_key(), | ||
&[rotation.public().did_key()], | ||
"authority.test", | ||
&url, | ||
); | ||
if !pds { | ||
op.services.clear(); | ||
} | ||
let genesis = op.sign(None, &rotation); | ||
let did = genesis.did(); | ||
let res = h | ||
.http | ||
.post(format!("{}/{did}", plc_url(h))) | ||
.json(&genesis.to_json()) | ||
.send() | ||
.await | ||
.unwrap(); | ||
assert!(res.status().is_success()); | ||
Authority { | ||
did, | ||
key, | ||
told, | ||
rotation, | ||
pds: url, | ||
last: Some(genesis.cid()), | ||
} | ||
} | ||
| ||
impl Authority { | ||
/// Signs with a new key from now on, its document saying so. | ||
pub async fn rotate(&mut self, h: &Running) { | ||
self.key = Keypair::generate(Curve::K256); | ||
let op = Op::atproto( | ||
&self.key.public().did_key(), | ||
&[self.rotation.public().did_key()], | ||
"authority.test", | ||
&self.pds, | ||
); | ||
let signed = op.sign(self.last, &self.rotation); | ||
let res = h | ||
.http | ||
.post(format!("{}/{}", plc_url(h), self.did)) | ||
.json(&signed.to_json()) | ||
.send() | ||
.await | ||
.unwrap(); | ||
assert!(res.status().is_success()); | ||
self.last = Some(signed.cid()); | ||
} | ||
} | ||
| ||
pub fn plc_url(h: &Running) -> String { | ||
h.host.config.plc_url.clone() | ||
} | ||
| ||
/// A syncer holding a credential to `space`, bound to its key. | ||
pub struct Syncer { | ||
pub key: Keypair, | ||
pub credential: String, | ||
} | ||
| ||
pub fn credential(authority: &Authority, space: &str, key: &Keypair, iss: &str) -> String { | ||
let make = Make { | ||
iss, | ||
sub: space, | ||
key_id: Some(&key.public().did_key()), | ||
..Make::default() | ||
}; | ||
space_auth::create(Kind::Credential, &make, &authority.key, now()).unwrap() | ||
} | ||
| ||
pub fn syncer(authority: &Authority, space: &str) -> Syncer { | ||
let key = Keypair::generate(Curve::P256); | ||
let credential = credential(authority, space, &key, &authority.did); | ||
Syncer { key, credential } | ||
} | ||
| ||
/// What a read answers: its status, headers and body. | ||
pub struct Read { | ||
pub status: u16, | ||
pub headers: reqwest::header::HeaderMap, | ||
pub body: Vec<u8>, | ||
} | ||
| ||
impl Read { | ||
pub fn json(&self) -> Json { | ||
serde_json::from_slice(&self.body).unwrap() | ||
} | ||
| ||
pub fn error(&self) -> (u16, String) { | ||
(self.status, self.json()["error"].as_str().unwrap().into()) | ||
} | ||
| ||
pub fn mac(&self) -> Option<&str> { | ||
self.headers | ||
.get("atproto-space-mac") | ||
.map(|v| v.to_str().unwrap()) | ||
} | ||
} | ||
| ||
/// `GET nsid?query` with `headers`. | ||
pub async fn read(h: &Running, nsid: &str, query: &str, headers: &[(&str, String)]) -> Read { | ||
let mut req = h.http.get(format!("{}/xrpc/{nsid}?{query}", h.url)); | ||
for (k, v) in headers { | ||
req = req.header(*k, v); | ||
} | ||
let res = req.send().await.unwrap(); | ||
Read { | ||
status: res.status().as_u16(), | ||
headers: res.headers().clone(), | ||
body: res.bytes().await.unwrap().to_vec(), | ||
} | ||
} | ||
| ||
/// The headers a syncer reads `repo` with: its credential, signed, and a | ||
/// key share for a MAC of `kind`; and the secret agreed. | ||
pub fn signed( | ||
s: &Syncer, | ||
repo: &str, | ||
kem: &str, | ||
kind: &str, | ||
) -> (Vec<(&'static str, String)>, [u8; 32]) { | ||
let authorization = format!("Atproto-Space-Credential {}", s.credential); | ||
let mut headers: Vec<(&str, String)> = sign_request(&s.key, &authorization, repo) | ||
.unwrap() | ||
.into_iter() | ||
.collect(); | ||
let (share, secret) = encapsulate(kem).unwrap(); | ||
headers.push(("atproto-space-want-mac", want_mac_header(kind, &share))); | ||
(headers, secret) | ||
} | ||
crates/group-host/tests/authority.rsnew+676−0
676 lines changed: not loaded until asked for.
crates/group-host/tests/interop.rs+150−2
| @@ -4,11 +4,13 @@ | ||
mod common; | ||
| ||
use atproto::did; | ||
use atproto::space::{COMMIT_MAC, encapsulate, mac_header, star, want_mac_header}; | ||
use atproto::space::{ | ||
COMMIT_MAC, RECORD_MAC, encapsulate, mac_header, record_mac, star, want_mac_header, | ||
}; | ||
use atproto::space_auth::{Expect, Kind, sign_request, space_host_aud, verify}; | ||
use atproto::{Curve, Keypair}; | ||
use common::net::net; | ||
use common::start; | ||
use common::{start, start_reachable}; | ||
use group_host::repo::Write; | ||
use serde_json::{Value, json}; | ||
use std::collections::BTreeMap; | ||
| @@ -248,3 +250,149 @@ async fn a_groups_repo_in_a_space_of_the_reference_pds() { | ||
)]); | ||
assert_eq!(res.bytes().await.unwrap().to_vec(), star(&commit, &records)); | ||
} | ||
| ||
/// What `GET nsid` with `query` and `headers` answers at `url`. | ||
async fn get( | ||
url: &str, | ||
nsid: &str, | ||
query: &[(&str, &str)], | ||
headers: &[(&str, String)], | ||
) -> (reqwest::StatusCode, reqwest::header::HeaderMap, Value) { | ||
let mut req = reqwest::Client::new() | ||
.get(format!("{url}/xrpc/{nsid}")) | ||
.query(query); | ||
for (k, v) in headers { | ||
req = req.header(*k, v); | ||
} | ||
let res = req.send().await.unwrap(); | ||
let (status, headers) = (res.status(), res.headers().clone()); | ||
(status, headers, res.json().await.unwrap_or(Value::Null)) | ||
} | ||
| ||
#[tokio::test] | ||
async fn the_host_as_authority_for_a_member_on_the_reference_pds() { | ||
let net = net(); | ||
if !net.spaces { | ||
eprintln!("the reference PDS has no spaces: GROUP_HOST_DEV_ENV names the alpha's build"); | ||
return; | ||
} | ||
let h = start_reachable(&[("PLC_URL", net.plc.as_str())]).await; | ||
let group = h.host.create_account("runners.groups.test").await.unwrap(); | ||
let space = h | ||
.host | ||
.create_space(&group, "fyi.opensocial.content", "self", false) | ||
.unwrap(); | ||
let alice = &net.accounts[0]; | ||
h.host.grant(&space, &alice.did, true, true).unwrap(); | ||
let session = call( | ||
&net.pds, | ||
"com.atproto.server.createSession", | ||
"", | ||
&json!({"identifier": alice.handle, "password": alice.password}), | ||
) | ||
.await; | ||
let jwt = session["accessJwt"].as_str().unwrap(); | ||
| ||
// Alice writes in the group's space at her own PDS, which tells the | ||
// host, the space's authority. | ||
let note = json!({"$type": "fyi.opensocial.note", "text": "Hello", "createdAt": "2026-11-03T00:00:00Z"}); | ||
let made = call( | ||
&net.pds, | ||
"com.atproto.space.createRecord", | ||
jwt, | ||
&json!({"space": space, "repo": alice.did, "collection": "fyi.opensocial.note", "rkey": "one", "record": note}), | ||
) | ||
.await; | ||
let mut writers = Vec::new(); | ||
for _ in 0..100 { | ||
writers = h.host.store.writers(&space, None, 10).unwrap(); | ||
if !writers.is_empty() { | ||
break; | ||
} | ||
tokio::time::sleep(std::time::Duration::from_millis(100)).await; | ||
} | ||
assert_eq!( | ||
writers.len(), | ||
1, | ||
"the reference PDS never told the host of {made}" | ||
); | ||
assert_eq!(writers[0].did, alice.did); | ||
| ||
// Her PDS's delegation token buys a credential from the host. | ||
let (status, _, token) = get( | ||
&net.pds, | ||
"com.atproto.space.getDelegationToken", | ||
&[("space", space.as_str())], | ||
&[("authorization", format!("Bearer {jwt}"))], | ||
) | ||
.await; | ||
assert!(status.is_success(), "{status} {token}"); | ||
let key = Keypair::generate(Curve::P256); | ||
let res = reqwest::Client::new() | ||
.post(format!("{}/xrpc/com.atproto.space.getSpaceCredential", h.url)) | ||
.json(&json!({"space": space, "credentialKid": key.public().did_key(), "delegationToken": token["token"]})) | ||
.send() | ||
.await | ||
.unwrap(); | ||
assert_eq!(res.status(), 200); | ||
let issued: Value = res.json().await.unwrap(); | ||
let authorization = format!( | ||
"Atproto-Space-Credential {}", | ||
issued["credential"].as_str().unwrap() | ||
); | ||
| ||
// Her PDS takes the host's credential, and vouches for her record. | ||
let theirs: Value = reqwest::Client::new() | ||
.get(format!("{}/{}", net.plc, alice.did)) | ||
.send() | ||
.await | ||
.unwrap() | ||
.json() | ||
.await | ||
.unwrap(); | ||
let kem = did::kem_key(&theirs).unwrap().did_key(); | ||
let (share, secret) = encapsulate(&kem).unwrap(); | ||
let mut headers: Vec<(&str, String)> = sign_request(&key, &authorization, &alice.did) | ||
.unwrap() | ||
.into_iter() | ||
.collect(); | ||
headers.push(( | ||
"atproto-space-want-mac", | ||
want_mac_header(RECORD_MAC, &share), | ||
)); | ||
let (status, said, record) = get( | ||
&net.pds, | ||
"com.atproto.space.getRecord", | ||
&[ | ||
("space", space.as_str()), | ||
("repo", alice.did.as_str()), | ||
("collection", "fyi.opensocial.note"), | ||
("rkey", "one"), | ||
], | ||
&headers, | ||
) | ||
.await; | ||
assert!(status.is_success(), "{status} {record}"); | ||
assert_eq!(record["value"], note); | ||
let uri = record["uri"].as_str().unwrap(); | ||
let cid = atproto::Cid::parse(record["cid"].as_str().unwrap()).unwrap(); | ||
assert_eq!( | ||
said["atproto-space-mac"].to_str().unwrap(), | ||
mac_header(RECORD_MAC, &record_mac(&secret, uri, &cid)) | ||
); | ||
| ||
// And the host lists her repo to the same credential. | ||
let headers: Vec<(&str, String)> = sign_request(&key, &authorization, &group) | ||
.unwrap() | ||
.into_iter() | ||
.collect(); | ||
let (status, _, repos) = get( | ||
&h.url, | ||
"com.atproto.space.listRepos", | ||
&[("space", space.as_str())], | ||
&headers, | ||
) | ||
.await; | ||
assert_eq!(status, 200, "{repos}"); | ||
assert_eq!(repos["repos"][0]["did"], alice.did); | ||
} | ||