chadtmiller.com/group-host
atmosphere group host
0
0
Members make, change and end the group's spaces
crates/group-host/src/authority.rs+30−16
| @@ -230,31 +230,45 @@ impl Host { | ||
/// gone, as the authority, before its key is: best effort, as a syncer | ||
/// that misses it learns so when its credential is refused. | ||
pub fn tell_spaces_deleted(&self, authority: &str) -> Result<()> { | ||
for space in self.store.spaces_of(authority)? { | ||
self.tell_space_deleted(authority, &space)?; | ||
} | ||
Ok(()) | ||
} | ||
| ||
fn tell_space_deleted(&self, authority: &str, space: &str) -> Result<()> { | ||
let signing = self | ||
.store | ||
.account(authority)? | ||
.context("the authority is here")? | ||
.signing; | ||
for space in self.store.spaces_of(authority)? { | ||
for (service, endpoint) in self.store.recipients(&space, now())? { | ||
let claims = self.claims(authority, &service, NOTIFY_SPACE_DELETED); | ||
let send = self | ||
.http | ||
.post(format!("{endpoint}/xrpc/{NOTIFY_SPACE_DELETED}")) | ||
.bearer_auth(service_auth::sign(&signing, &claims)) | ||
.json(&json!({ "space": space })) | ||
.send(); | ||
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, "notifySpaceDeleted failed"); | ||
} | ||
}); | ||
} | ||
for (service, endpoint) in self.store.recipients(space, now())? { | ||
let claims = self.claims(authority, &service, NOTIFY_SPACE_DELETED); | ||
let send = self | ||
.http | ||
.post(format!("{endpoint}/xrpc/{NOTIFY_SPACE_DELETED}")) | ||
.bearer_auth(service_auth::sign(&signing, &claims)) | ||
.json(&json!({ "space": space })) | ||
.send(); | ||
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, "notifySpaceDeleted failed"); | ||
} | ||
}); | ||
} | ||
Ok(()) | ||
} | ||
| ||
/// Ends `authority`'s space at `space`: its syncers are told, and its | ||
/// state and the authority's own repo in it go. | ||
pub fn end_space(&self, authority: &str, space: &str) -> Result<()> { | ||
self.tell_space_deleted(authority, space)?; | ||
let orphans = self.store.delete_space(space, authority)?; | ||
self.remove_blobs(orphans.iter().map(|cid| (authority, cid))); | ||
Ok(()) | ||
} | ||
| ||
/// Tries `notice` now: tells its space's authority, at its PDS, as the | ||
/// repo. | ||
pub async fn deliver(&self, notice: &Notice) -> Delivery { | ||
crates/group-host/src/group.rs+22−0
| @@ -233,6 +233,28 @@ impl Host { | ||
Ok(Made { did, meta, members }) | ||
} | ||
| ||
/// Lists the group, by a declaration in its public repo pointing at | ||
/// its meta space, or not. | ||
pub async fn declare(&self, group: &str, listed: bool) -> Result<(), XrpcError> { | ||
let collection = format!("{NS}.declaration"); | ||
let declared = self.store.record(group, &collection, "self"); | ||
let declared = declared.map_err(XrpcError::internal)?.is_some(); | ||
let write = match (listed, declared) { | ||
(true, false) => put( | ||
&collection, | ||
"self", | ||
json!({"$type": collection, "meta": meta_space(group), "createdAt": iso(now_millis())}), | ||
), | ||
(false, true) => Write::Delete { | ||
collection, | ||
rkey: "self".into(), | ||
}, | ||
_ => return Ok(()), | ||
}; | ||
self.write(group, &[write])?; | ||
Ok(()) | ||
} | ||
| ||
/// The group's own record in `space`, as JSON. | ||
pub fn group_record( | ||
&self, | ||
crates/group-host/src/group_config.rs+26−4
| @@ -62,6 +62,16 @@ impl Host { | ||
Ok(self.configurers(group)?.iter().any(|c| c == did)) | ||
} | ||
| ||
/// Whether `did`'s roles in `group` carry `action`. | ||
pub fn may_do(&self, group: &str, did: &str, action: &str) -> Result<bool, XrpcError> { | ||
let members = members_space(group); | ||
let permissions = self | ||
.group_record(group, &members, &format!("{NS}.permissions"), "self") | ||
.map_err(XrpcError::internal)?; | ||
let roles = self.roles(group, did).map_err(XrpcError::internal)?; | ||
Ok(actions_for(&grants(&permissions.unwrap_or_default()), &roles).contains(action)) | ||
} | ||
| ||
/// Everyone whose roles in `group` carry `group.configure`. | ||
pub fn configurers(&self, group: &str) -> Result<Vec<String>, XrpcError> { | ||
let members = members_space(group); | ||
| @@ -85,9 +95,21 @@ impl Host { | ||
/// Puts the group's record at `collection/rkey` in meta, made or replaced: | ||
/// its URI and CID. | ||
async fn put(host: &Host, group: &str, collection: &str, rkey: &str, value: Value) -> Answer { | ||
let meta = meta_space(group); | ||
put_in(host, group, &meta_space(group), collection, rkey, value).await | ||
} | ||
| ||
/// Puts the group's record at `collection/rkey` in `space`, made or | ||
/// replaced: its URI and CID. | ||
pub(crate) async fn put_in( | ||
host: &Host, | ||
group: &str, | ||
meta: &str, | ||
collection: &str, | ||
rkey: &str, | ||
value: Value, | ||
) -> Answer { | ||
let current = host | ||
.group_record(group, &meta, collection, rkey) | ||
.group_record(group, meta, collection, rkey) | ||
.map_err(XrpcError::internal)?; | ||
let (collection, rkey) = (collection.to_string(), rkey.to_string()); | ||
let write = match current { | ||
| @@ -102,10 +124,10 @@ async fn put(host: &Host, group: &str, collection: &str, rkey: &str, value: Valu | ||
value, | ||
}, | ||
}; | ||
host.space_write(group, &meta, &[write]).await?; | ||
host.space_write(group, meta, &[write]).await?; | ||
let kept = host | ||
.store | ||
.space_record(group, &meta, &collection, &rkey) | ||
.space_record(group, meta, &collection, &rkey) | ||
.map_err(XrpcError::internal)? | ||
.expect("the record just written"); | ||
let uri = format!("{meta}/{group}/{collection}/{rkey}"); | ||
crates/group-host/src/group_spaces.rsnew+243−0
| @@ -0,0 +1,243 @@ | ||
//! The spaces a group's members make beside its two own: a calendar, a | ||
//! forum, a channel. Each is the group's, with its access record saying | ||
//! who reads it, who writes in it in their own name, and which roles | ||
//! write in it as the group; and an entry in the members space's index, | ||
//! which apps read to find it. | ||
//! | ||
//! As the prototype's `methods/spaces.ts`, except that deleting a space | ||
//! ends it, as its authority, where the prototype only took it out of the | ||
//! index. | ||
| ||
use crate::Host; | ||
use crate::api::invalid; | ||
use crate::group::{members_space, meta_space}; | ||
use crate::group_api::{group_of, signed_in}; | ||
use crate::group_config::put_in; | ||
use crate::rbac::{Access, NS, PUBLIC}; | ||
use crate::repo::Write; | ||
use crate::time::{iso, now_millis}; | ||
use crate::xrpc::XrpcError; | ||
use atproto::space::SpaceRef; | ||
use atproto::syntax; | ||
use axum::Json; | ||
use axum::extract::State; | ||
use axum::http::{HeaderMap, StatusCode}; | ||
use serde_json::{Value, json}; | ||
use std::sync::Arc; | ||
| ||
type Answer = Result<Json<Value>, XrpcError>; | ||
| ||
fn refused(error: &'static str, message: impl Into<String>) -> XrpcError { | ||
XrpcError::new(StatusCode::BAD_REQUEST, error, message) | ||
} | ||
| ||
fn forbidden(message: impl Into<String>) -> XrpcError { | ||
XrpcError::new(StatusCode::FORBIDDEN, "Forbidden", message) | ||
} | ||
| ||
/// The group a body names, once its caller of `lxm` may do `action` in it. | ||
async fn acting( | ||
host: &Host, | ||
headers: &HeaderMap, | ||
body: &Value, | ||
lxm: &str, | ||
action: &str, | ||
) -> Result<String, XrpcError> { | ||
let me = signed_in(host, headers, &format!("{NS}.{lxm}")).await?; | ||
let group = body["group"] | ||
.as_str() | ||
.ok_or_else(|| invalid("group is required"))?; | ||
group_of(host, group)?; | ||
if !host.may_do(group, &me, action)? { | ||
return Err(forbidden(format!("missing {action}"))); | ||
} | ||
Ok(group.to_string()) | ||
} | ||
| ||
/// An audience list as given, `[{role}]`, if it is one. | ||
fn audience(body: &Value, key: &str) -> Result<Option<Vec<Value>>, XrpcError> { | ||
let Some(given) = body.get(key) else { | ||
return Ok(None); | ||
}; | ||
let roles = given | ||
.as_array() | ||
.filter(|a| a.iter().all(|r| r["role"].is_string())); | ||
let roles = roles.ok_or_else(|| invalid(format!("{key} is a list of {{role}}")))?; | ||
Ok(Some(roles.clone())) | ||
} | ||
| ||
/// The group's index entries of its spaces: key and record. | ||
fn index(host: &Host, group: &str) -> Result<Vec<(String, Value)>, XrpcError> { | ||
host.group_records(group, &members_space(group), &format!("{NS}.space")) | ||
.map_err(XrpcError::internal) | ||
} | ||
| ||
/// The key of `space`'s entry in the group's index. | ||
fn entry_of(host: &Host, group: &str, space: &str) -> Result<(String, Value), XrpcError> { | ||
let entries = index(host, group)?; | ||
let entry = entries.into_iter().find(|(_, e)| e["space"] == space); | ||
entry.ok_or_else(|| refused("SpaceNotFound", "the space is not in the group's index")) | ||
} | ||
| ||
/// The space a body names, the group's, and its access record: refused | ||
/// for one kept for chosen people, which only they change. | ||
fn own_space(host: &Host, group: &str, body: &Value) -> Result<(String, Value), XrpcError> { | ||
let space = body["space"] | ||
.as_str() | ||
.ok_or_else(|| invalid("space is required"))?; | ||
let named = SpaceRef::parse(space).map_err(|e| invalid(e.to_string()))?; | ||
if named.authority != group { | ||
return Err(invalid("the space is not this group's")); | ||
} | ||
let access = host | ||
.group_record(group, space, &format!("{NS}.access"), "self") | ||
.map_err(XrpcError::internal)?; | ||
let access = access.ok_or_else(|| refused("SpaceNotFound", "no such space"))?; | ||
if Access::of(&access).people.is_some() { | ||
return Err(forbidden( | ||
"that space is for chosen people: only they change it", | ||
)); | ||
} | ||
Ok((space.to_string(), access)) | ||
} | ||
| ||
/// Adds a space to the group, for one holding `space.create`. | ||
pub async fn create_space( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
Json(body): Json<Value>, | ||
) -> Answer { | ||
let group = acting(&host, &headers, &body, "createSpace", "space.create").await?; | ||
let kind = body["spaceType"].as_str().unwrap_or_default(); | ||
if !syntax::is_nsid(kind) { | ||
return Err(invalid("spaceType is an NSID")); | ||
} | ||
let readers = | ||
audience(&body, "readableBy")?.ok_or_else(|| invalid("readableBy is required"))?; | ||
let writers = audience(&body, "writableBy")?; | ||
let skey = match body["skey"].as_str() { | ||
Some(skey) => skey.to_string(), | ||
None => host.clock.next(), | ||
}; | ||
let uri = host.create_space(&group, kind, &skey, false)?; | ||
let at = iso(now_millis()); | ||
let mut access = | ||
json!({"$type": format!("{NS}.access"), "readableBy": readers, "createdAt": at}); | ||
if let Some(writers) = writers.filter(|w| !w.is_empty()) { | ||
access["writableBy"] = json!(writers); | ||
} | ||
if let Some(scopes) = body.get("credentialScopes") { | ||
access["credentialScopes"] = scopes.clone(); | ||
} | ||
let access_write = Write::Create { | ||
collection: format!("{NS}.access"), | ||
rkey: "self".into(), | ||
value: access, | ||
}; | ||
host.space_write(&group, &uri, &[access_write]).await?; | ||
let mut entry = json!({"$type": format!("{NS}.space"), "space": uri, "createdAt": at}); | ||
if let Some(name) = body["name"].as_str() { | ||
entry["name"] = json!(name); | ||
} | ||
let indexed = Write::Create { | ||
collection: format!("{NS}.space"), | ||
rkey: host.clock.next(), | ||
value: entry, | ||
}; | ||
host.space_write(&group, &members_space(&group), &[indexed]) | ||
.await?; | ||
Ok(Json(json!({ "uri": uri }))) | ||
} | ||
| ||
/// Changes a space: its name, who reads it, who writes in it in their own | ||
/// name, and which roles write in it as the group. For one holding | ||
/// `space.configure`. | ||
pub async fn update_space( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
Json(body): Json<Value>, | ||
) -> Answer { | ||
let group = acting(&host, &headers, &body, "updateSpace", "space.configure").await?; | ||
let (access_collection, space_collection) = (format!("{NS}.access"), format!("{NS}.space")); | ||
let (space, current) = own_space(&host, &group, &body)?; | ||
let (meta, members) = (meta_space(&group), members_space(&group)); | ||
let readers = audience(&body, "readableBy")?.filter(|r| !r.is_empty()); | ||
let writers = audience(&body, "writableBy")?; | ||
let names = |list: &[Value]| -> Vec<String> { | ||
list.iter() | ||
.filter_map(|r| r["role"].as_str().map(String::from)) | ||
.collect() | ||
}; | ||
if let Some(readers) = &readers { | ||
// The members space unreadable by members would lock the group out | ||
// of its own roster, whoever changes it included. | ||
if space == members && !names(readers).iter().any(|r| r == "member") { | ||
return Err(invalid("the members space stays readable by member")); | ||
} | ||
// Meta's readers are the group's visibility: it is declared only | ||
// while anyone may read it. | ||
if space == meta { | ||
host.declare(&group, names(readers).iter().any(|r| r == PUBLIC)) | ||
.await?; | ||
} | ||
} | ||
// Writing in the members space in one's own name is joining: who may | ||
// stays as it is. | ||
if writers.is_some() && space == members { | ||
return Err(invalid("who may write in the members space is fixed")); | ||
} | ||
if readers.is_some() || writers.is_some() || body.get("credentialScopes").is_some() { | ||
let mut access = current.clone(); | ||
if let Some(readers) = readers { | ||
access["readableBy"] = json!(readers); | ||
} | ||
if let Some(writers) = writers { | ||
let fields = access.as_object_mut().expect("an access record"); | ||
fields.remove("writableBy"); | ||
if !writers.is_empty() { | ||
fields.insert("writableBy".into(), json!(writers)); | ||
} | ||
} | ||
if let Some(scopes) = body.get("credentialScopes") { | ||
access["credentialScopes"] = scopes.clone(); | ||
} | ||
let put = put_in(&host, &group, &space, &access_collection, "self", access); | ||
let _written = put.await?; | ||
} | ||
if let Some(name) = body["name"].as_str() { | ||
let (rkey, mut entry) = entry_of(&host, &group, &space)?; | ||
entry["name"] = json!(name); | ||
let put = put_in(&host, &group, &members, &space_collection, &rkey, entry); | ||
let _written = put.await?; | ||
} | ||
Ok(Json(json!({}))) | ||
} | ||
| ||
/// Ends a space, for one holding `space.delete`: the services syncing it | ||
/// are told, and its authority's state and the group's own repo in it go. | ||
/// What members wrote there is theirs, at their own PDSes. Meta and | ||
/// members stay: nothing works without them. | ||
pub async fn delete_space( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
Json(body): Json<Value>, | ||
) -> Answer { | ||
let group = acting(&host, &headers, &body, "deleteSpace", "space.delete").await?; | ||
let (space, _) = own_space(&host, &group, &body)?; | ||
if space == meta_space(&group) || space == members_space(&group) { | ||
return Err(refused( | ||
"WellKnownSpace", | ||
"the meta and members spaces stay", | ||
)); | ||
} | ||
let (rkey, _) = entry_of(&host, &group, &space)?; | ||
let unindexed = Write::Delete { | ||
collection: format!("{NS}.space"), | ||
rkey, | ||
}; | ||
host.space_write(&group, &members_space(&group), &[unindexed]) | ||
.await?; | ||
host.end_space(&group, &space) | ||
.map_err(XrpcError::internal)?; | ||
Ok(Json(json!({}))) | ||
} | ||
crates/group-host/src/lib.rs+13−0
| @@ -14,6 +14,7 @@ pub mod group_api; | ||
pub mod group_config; | ||
pub mod group_handle; | ||
pub mod group_lifecycle; | ||
pub mod group_spaces; | ||
pub mod identity; | ||
pub mod lifecycle; | ||
pub mod plc; | ||
| @@ -203,6 +204,18 @@ pub fn router(host: Arc<Host>) -> Router { | ||
"/xrpc/fyi.opensocial.updateGroupHandle", | ||
post(group_handle::update_group_handle), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.createSpace", | ||
post(group_spaces::create_space), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.updateSpace", | ||
post(group_spaces::update_space), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.deleteSpace", | ||
post(group_spaces::delete_space), | ||
) | ||
.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/store.rs+44−0
| @@ -240,6 +240,19 @@ const DUE: &str = "SELECT repo, space, rev, data, attempts FROM outbox WHERE nex | ||
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"; | ||
/// What goes with a space whose authority is here. | ||
const FORGET_SPACE: &[&str] = &[ | ||
"DELETE FROM space_recipient WHERE space = ?1", | ||
"DELETE FROM space_writer WHERE space = ?1", | ||
"DELETE FROM space_grant WHERE space = ?1", | ||
"DELETE FROM space WHERE uri = ?1", | ||
]; | ||
/// And the authority's own repo in it. | ||
const FORGET_OWN_REPO: &[&str] = &[ | ||
"DELETE FROM space_op WHERE space = ?1 AND did = ?2", | ||
"DELETE FROM space_record WHERE space = ?1 AND did = ?2", | ||
"DELETE FROM space_repo WHERE space = ?1 AND did = ?2", | ||
]; | ||
const SPACES_OF: &str = "SELECT uri FROM space WHERE authority = ?1 ORDER BY uri"; | ||
const DEACTIVATE: &str = "INSERT INTO deactivation (did, at, by, stewards) VALUES (?1, ?2, ?3, ?4) ON CONFLICT (did) DO NOTHING"; | ||
const DEACTIVATION: &str = "SELECT at, by, stewards FROM deactivation WHERE did = ?1"; | ||
| @@ -1004,6 +1017,37 @@ impl Store { | ||
Ok(found.optional()?) | ||
} | ||
| ||
/// Forgets the space at `uri` and `authority`'s own repo in it. The | ||
/// blobs only that repo referenced, for their files to go. | ||
pub fn delete_space(&self, uri: &str, authority: &str) -> Result<Vec<Cid>> { | ||
let mut conn = self.conn(); | ||
let tx = conn.transaction()?; | ||
let unlinked: Vec<Cid> = { | ||
let mut q = tx.prepare( | ||
"DELETE FROM space_record_blob WHERE space = ?1 AND did = ?2 RETURNING cid", | ||
)?; | ||
let rows = q.query_map([uri, authority], |r| Ok(cid(r.get(0)?))); | ||
rows?.collect::<rusqlite::Result<_>>()? | ||
}; | ||
for sql in FORGET_SPACE { | ||
let gone = tx.execute(sql, [uri]); | ||
gone?; | ||
} | ||
for sql in FORGET_OWN_REPO { | ||
let gone = tx.execute(sql, [uri, authority]); | ||
gone?; | ||
} | ||
let mut orphans = Vec::new(); | ||
for cid in unlinked { | ||
let gone = tx.execute(FORGET_ORPHAN, params![authority, cid.to_string()]); | ||
if gone? > 0 { | ||
orphans.push(cid); | ||
} | ||
} | ||
tx.commit()?; | ||
Ok(orphans) | ||
} | ||
| ||
/// The spaces `authority` is the authority for. | ||
pub fn spaces_of(&self, authority: &str) -> Result<Vec<String>> { | ||
let conn = self.conn(); | ||
crates/group-host/tests/group_spaces.rsnew+450−0
450 lines changed: not loaded until asked for.
docs/design/groups.md+24−0
| @@ -78,6 +78,30 @@ so the host writes them for a caller holding `group.configure`: | ||
so a label citing it still does; a new one goes last unless it says | ||
where. `deleteRule` takes one away; a label citing it keeps the URI. | ||
| ||
## Its other spaces | ||
| ||
Beside meta and members, a group's members make spaces for what they do | ||
together: a calendar, a forum, a channel. Each is the group's, its | ||
authority the group, with an access record and an entry in the members | ||
space's index, which apps read to find it. | ||
| ||
- `createSpace` (for `space.create`) makes one, of a type and key, with | ||
who reads it, who writes in it in their own name (any member, unless | ||
it says), and which roles write in it as the group. | ||
- `updateSpace` (for `space.configure`) changes its name, readers, | ||
writers or roles. The members space stays readable by members, and who | ||
writes in it in their own name, which is joining, stays as it is. | ||
Meta's readers are the group's visibility: its declaration is made | ||
when anyone may read meta, and taken away when not. | ||
- `deleteSpace` (for `space.delete`) ends one: its syncers are told, | ||
its state as the authority and the group's own repo in it go, and it | ||
leaves the index. What members wrote there is theirs, at their own | ||
PDSes. Meta and members stay. The prototype only took a space out of | ||
the index, leaving it issuing credentials to any it had let read. | ||
| ||
A space kept for chosen people is theirs: nobody who runs the group | ||
changes or ends it. | ||
| ||
## Its handle | ||
| ||
A group starts with a handle one label under `HANDLE_DOMAIN`, which is | ||
docs/design/README.md+4−3
| @@ -83,10 +83,11 @@ says otherwise. | ||
`rbac.rs`; done, see [groups](groups.md)), their profile, images and | ||
rules (`group_config.rs`; done), switching them off and on and | ||
deleting them (`lifecycle.rs`, `group_lifecycle.rs`; done), handles | ||
on their own domains (`group_handle.rs`; done), then spaces made and | ||
configured by members, `checkUserAccess`, and the space index: | ||
on their own domains (`group_handle.rs`; done), spaces made and | ||
configured by members (`group_spaces.rs`; done), then the space index: | ||
`group.ts`, `bootstrap.ts`, `methods/{groups,handle,profile,rules,lifecycle,spaces,spaceRecords}.ts`, | ||
`spaceIndex.ts`, `methods/checkUserAccess.ts`. | ||
`spaceIndex.ts`. (`checkUserAccess`, for invite inboxes, comes with | ||
invites.) | ||
5. **Membership and roles.** Roles and permissions, assigning, joining | ||
and join requests, invites, leaving and ejecting: `rbac.ts`, | ||
`methods/{roles,membership,join,invites}.ts`. | ||