chadtmiller.com/group-host
atmosphere group host
0
0
Roles are defined and given; members are put out or leave, and read no more
crates/group-host/src/authority.rs+61−1
| @@ -15,13 +15,14 @@ use crate::Host; | ||
use crate::rbac::{self, NS}; | ||
use crate::repo::invalid; | ||
use crate::space::NOTIFY_WRITE; | ||
use crate::space_api::NOTIFY_REVOKED; | ||
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::space_auth::{self, space_host_aud}; | ||
use atproto::{Value, did, syntax}; | ||
use axum::http::StatusCode; | ||
use serde_json::json; | ||
| @@ -261,6 +262,65 @@ impl Host { | ||
Ok(()) | ||
} | ||
| ||
/// Revokes the credentials `did` holds to `authority`'s spaces: at | ||
/// once for the repos here, and told to the host of each writer | ||
/// elsewhere in those spaces, best effort, as the authority. | ||
pub async fn revoke_credentials(&self, authority: &str, did: &str) -> Result<()> { | ||
let mut by_space: std::collections::BTreeMap<String, (Vec<String>, i64)> = | ||
Default::default(); | ||
for (space, jti, expires_at) in self.store.issued_to(authority, did, now())? { | ||
let (jtis, until) = by_space.entry(space).or_default(); | ||
jtis.push(jti); | ||
*until = (*until).max(expires_at + 2 * space_auth::CLOCK_SKEW as i64); | ||
} | ||
let signing = self | ||
.store | ||
.account(authority)? | ||
.context("the authority is here")? | ||
.signing; | ||
for (space, (jtis, until)) in by_space { | ||
self.store.revoke(&space, &jtis, until, now())?; | ||
for writer in self.store.writers(&space, None, u32::MAX)? { | ||
let here = self | ||
.store | ||
.account(&writer.did)? | ||
.is_some_and(|a| a.did == writer.did); | ||
if here { | ||
continue; | ||
} | ||
let told = self | ||
.tell_revoked(&signing, authority, &writer.did, &space, &jtis) | ||
.await; | ||
if let Err(e) = told { | ||
tracing::warn!(space, repo = writer.did, error = %format!("{e:#}"), "notifyCredentialRevoked failed"); | ||
} | ||
} | ||
} | ||
Ok(()) | ||
} | ||
| ||
async fn tell_revoked( | ||
&self, | ||
signing: &atproto::Keypair, | ||
authority: &str, | ||
writer: &str, | ||
space: &str, | ||
jtis: &[String], | ||
) -> Result<()> { | ||
let doc = self.identity.document(writer).await?; | ||
let pds = did::pds(&doc).context("the writer's document names no PDS")?; | ||
let claims = self.claims(authority, writer, NOTIFY_REVOKED); | ||
let res = self | ||
.http | ||
.post(format!("{pds}/xrpc/{NOTIFY_REVOKED}")) | ||
.bearer_auth(service_auth::sign(signing, &claims)) | ||
.json(&json!({ "space": space, "credentials": jtis })) | ||
.send() | ||
.await?; | ||
res.error_for_status()?; | ||
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<()> { | ||
crates/group-host/src/authority_api.rs+8−1
| @@ -6,7 +6,7 @@ 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::space_api::{credential, forbidden, now, refused, service_caller}; | ||
use crate::store::Space; | ||
use crate::time::iso; | ||
use crate::xrpc::XrpcError; | ||
| @@ -93,6 +93,13 @@ pub async fn get_space_credential( | ||
}; | ||
let credential = space_auth::create(Kind::Credential, &make, &authority.signing, now()) | ||
.map_err(XrpcError::internal)?; | ||
// 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 }))) | ||
} | ||
| ||
crates/group-host/src/group_members.rsnew+473−0
473 lines changed: not loaded until asked for.
crates/group-host/src/index.rs+6−0
| @@ -17,6 +17,7 @@ | ||
//! prototype's `spaceIndex.ts` keeps what it reads. | ||
| ||
use crate::Host; | ||
use crate::authority::Access; | ||
use crate::store::SpaceHead; | ||
use crate::time::now_millis; | ||
use anyhow::{Context, Result, bail, ensure}; | ||
| @@ -152,6 +153,11 @@ impl Host { | ||
return Ok(()); | ||
}; | ||
for writer in self.store.writers(space, None, u32::MAX)? { | ||
// One the space no longer lets write is no longer kept. | ||
if !self.may(space, &hosted, Some(&writer.did), Access::Write)? { | ||
self.store.unindex(space, &writer.did)?; | ||
continue; | ||
} | ||
let indexed = self.store.index_state(space, &writer.did)?; | ||
let at = indexed | ||
.as_ref() | ||
crates/group-host/src/lib.rs+21−0
| @@ -14,6 +14,7 @@ pub mod group_api; | ||
pub mod group_config; | ||
pub mod group_handle; | ||
pub mod group_lifecycle; | ||
pub mod group_members; | ||
pub mod group_spaces; | ||
pub mod identity; | ||
pub mod index; | ||
| @@ -231,6 +232,26 @@ pub fn router(host: Arc<Host>) -> Router { | ||
"/xrpc/fyi.opensocial.getSpaceBlob", | ||
get(index_api::get_space_blob), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.putRole", | ||
post(group_members::put_role), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.deleteRole", | ||
post(group_members::delete_role), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.assignRoles", | ||
post(group_members::assign_roles), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.ejectMember", | ||
post(group_members::eject_member), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.leaveGroup", | ||
post(group_members::leave_group), | ||
) | ||
.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+68−1
| @@ -11,7 +11,7 @@ use std::path::Path; | ||
use std::sync::{Mutex, MutexGuard}; | ||
| ||
/// Each version of the schema, applied in order to a database below it. | ||
const MIGRATIONS: &[&str] = &[ | ||
pub const MIGRATIONS: &[&str] = &[ | ||
" | ||
CREATE TABLE account ( | ||
did TEXT PRIMARY KEY, | ||
| @@ -191,6 +191,16 @@ const MIGRATIONS: &[&str] = &[ | ||
// Accounts made before addresses were kept: each its handle then. | ||
" | ||
INSERT OR IGNORE INTO address (did, address) SELECT did, handle FROM account; | ||
", | ||
" | ||
CREATE TABLE issued_credential ( | ||
space TEXT NOT NULL, | ||
did TEXT NOT NULL, | ||
jti TEXT NOT NULL, | ||
expires_at INTEGER NOT NULL, | ||
PRIMARY KEY (space, jti) | ||
); | ||
CREATE INDEX issued_credential_to ON issued_credential (did); | ||
", | ||
]; | ||
| ||
| @@ -271,6 +281,7 @@ 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 issued_credential WHERE space = ?1", | ||
"DELETE FROM space WHERE uri = ?1", | ||
]; | ||
/// And the authority's own repo in it. | ||
| @@ -286,12 +297,19 @@ const UNINDEX: &str = "DELETE FROM index_record WHERE space = ?1 AND did = ?2 AN | ||
const INDEX: &str = "INSERT INTO index_record (space, did, path, cid, value, indexed_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)"; | ||
const INDEXED: &str = "SELECT seq, did, path, cid, value, indexed_at FROM index_record WHERE space = ?1 AND (?2 IS NULL OR substr(path, 1, length(?2) + 1) = ?2 || '/') AND seq < ?3 ORDER BY seq DESC LIMIT ?4"; | ||
const INDEXED_ONE: &str = "SELECT seq, did, path, cid, value, indexed_at FROM index_record WHERE space = ?1 AND did = ?2 AND path = ?3"; | ||
const ISSUE: &str = | ||
"INSERT INTO issued_credential (space, did, jti, expires_at) VALUES (?1, ?2, ?3, ?4)"; | ||
const FORGET_ISSUED: &str = "DELETE FROM issued_credential WHERE expires_at <= ?1"; | ||
const ISSUED_TO: &str = "SELECT space, jti, expires_at FROM issued_credential WHERE did = ?1 AND expires_at > ?2 AND space IN (SELECT uri FROM space WHERE authority = ?3) ORDER BY space"; | ||
const UNINDEX_WRITER: &str = "DELETE FROM index_record WHERE space = ?1 AND did = ?2"; | ||
const UNINDEX_STATE: &str = "DELETE FROM index_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"; | ||
const ACTIVATE: &str = "DELETE FROM deactivation WHERE did = ?1"; | ||
/// What goes with an account, in an order its references allow. | ||
const FORGET_ACCOUNT: &[&str] = &[ | ||
"DELETE FROM issued_credential WHERE space IN (SELECT uri FROM space WHERE authority = ?1)", | ||
"DELETE FROM index_record WHERE space IN (SELECT uri FROM space WHERE authority = ?1)", | ||
"DELETE FROM index_repo WHERE space IN (SELECT uri FROM space WHERE authority = ?1)", | ||
"DELETE FROM deactivation WHERE did = ?1", | ||
| @@ -1180,6 +1198,55 @@ impl Store { | ||
Ok(found.optional()?) | ||
} | ||
| ||
/// Keeps that the credential `jti` to `space` went to `did`, until it | ||
/// lapses at `expires_at`; those lapsed by `now` are forgotten. | ||
pub fn issued( | ||
&self, | ||
space: &str, | ||
did: &str, | ||
jti: &str, | ||
expires_at: i64, | ||
now: i64, | ||
) -> Result<()> { | ||
let mut conn = self.conn(); | ||
let tx = conn.transaction()?; | ||
let forgot = tx.execute(FORGET_ISSUED, [now]); | ||
forgot?; | ||
let kept = tx.execute(ISSUE, params![space, did, jti, expires_at]); | ||
kept?; | ||
tx.commit()?; | ||
Ok(()) | ||
} | ||
| ||
/// The credentials to `authority`'s spaces still good at `now` that | ||
/// went to `did`: each space, jti and lapse. | ||
pub fn issued_to( | ||
&self, | ||
authority: &str, | ||
did: &str, | ||
now: i64, | ||
) -> Result<Vec<(String, String, i64)>> { | ||
let conn = self.conn(); | ||
let mut q = conn.prepare(ISSUED_TO)?; | ||
let rows = q.query_map(params![did, now, authority], |r| { | ||
Ok((r.get(0)?, r.get(1)?, r.get(2)?)) | ||
}); | ||
let rows = rows?; | ||
Ok(rows.collect::<rusqlite::Result<_>>()?) | ||
} | ||
| ||
/// Forgets what the index read of `did`'s repo in `space`. | ||
pub fn unindex(&self, space: &str, did: &str) -> Result<()> { | ||
let mut conn = self.conn(); | ||
let tx = conn.transaction()?; | ||
let gone = tx.execute(UNINDEX_WRITER, [space, did]); | ||
gone?; | ||
let gone = tx.execute(UNINDEX_STATE, [space, did]); | ||
gone?; | ||
tx.commit()?; | ||
Ok(()) | ||
} | ||
| ||
/// 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/common/spaces.rs+4−0
| @@ -88,6 +88,10 @@ pub async fn authority(h: &Running, refuse: bool, pds: bool) -> Authority { | ||
"/xrpc/com.atproto.space.notifySpaceDeleted", | ||
post(notify_write), | ||
) | ||
.route( | ||
"/xrpc/com.atproto.space.notifyCredentialRevoked", | ||
post(notify_write), | ||
) | ||
.with_state(told.clone()); | ||
let url = serve(router).await; | ||
let key = Keypair::generate(Curve::K256); | ||
crates/group-host/tests/identity.rs+12−3
| @@ -182,10 +182,19 @@ fn gives_an_account_made_before_addresses_its_handle_as_its_address() { | ||
// As a database from before: no address, its schema a version back. | ||
let conn = rusqlite::Connection::open(&path).unwrap(); | ||
conn.execute("DELETE FROM address", []).unwrap(); | ||
let version: i64 = conn | ||
.pragma_query_value(None, "user_version", |r| r.get(0)) | ||
// Back to just before the backfill: what came after it, undone. | ||
let migrations = group_host::store::MIGRATIONS; | ||
let backfill = migrations | ||
.iter() | ||
.position(|m| m.contains("INSERT OR IGNORE INTO address")) | ||
.unwrap(); | ||
conn.pragma_update(None, "user_version", version - 1) | ||
for later in &migrations[backfill + 1..] { | ||
for table in later.split("CREATE TABLE ").skip(1) { | ||
let name = table.split_whitespace().next().unwrap(); | ||
conn.execute(&format!("DROP TABLE {name}"), []).unwrap(); | ||
} | ||
} | ||
conn.pragma_update(None, "user_version", backfill as i64) | ||
.unwrap(); | ||
drop(conn); | ||
let store = group_host::store::Store::open(&path).unwrap(); | ||
crates/group-host/tests/members.rsnew+523−0
523 lines changed: not loaded until asked for.
crates/group-host/tests/serve.rs+1−1
| @@ -51,7 +51,7 @@ async fn answers_health_and_refuses_unknown_methods() { | ||
| ||
for req in [ | ||
http.get(format!("{}/xrpc/fyi.opensocial.listInvites", host.1)), | ||
http.post(format!("{}/xrpc/fyi.opensocial.assignRoles", host.1)), | ||
http.post(format!("{}/xrpc/fyi.opensocial.createInvite", host.1)), | ||
] { | ||
let res = req.send().await.unwrap(); | ||
assert_eq!(res.status(), 501); | ||
docs/design/membership.mdnew+60−0
| @@ -0,0 +1,60 @@ | ||
# Membership | ||
| ||
Who is in a group, and what each may do, are records in its members | ||
space, written by the group: a membership for each member, naming their | ||
roles; a role record for each role, its name and words; and one | ||
permissions record, granting each role OAuth scopes and the roles its | ||
holders may give. The host's methods ask by action (`invite`, `admit`, | ||
`role.assign`, `eject`, `group.configure`, …), each answered by the one | ||
scope that grants it, and roles compose by union (`rbac.rs`). | ||
| ||
## Roles | ||
| ||
- `putRole` (for `group.configure`) defines a role or changes one: its | ||
name and words; whether its people are bots; whether every new member | ||
gets it (kept when not said); what it may do, as the scopes of its | ||
actions beside any other scope it held; its public-repo collections | ||
(kept when not said); and the roles its holders may give. | ||
- `deleteRole` (for `group.configure`) takes away a role nobody holds | ||
(`RoleInUse` while someone does). | ||
| ||
A group never loses its last way to be run: the last role that may | ||
configure it keeps that (`LastConfigurer`), and stays. | ||
| ||
## Members | ||
| ||
- `assignRoles` (for `role.assign`) gives a member the roles named in | ||
place of theirs. Each role added or taken away must be one the | ||
caller's roles may give; each must be defined; the member must be | ||
one. Everyone in a group holds `member`, which lets them read the | ||
members space: it goes only when they do (`MemberRole`). | ||
- `ejectMember` (for `eject`) puts a member out, if the caller's roles | ||
may give or take each of theirs. | ||
- `leaveGroup` takes the caller out. The last member able to configure | ||
the group may not leave (`LastConfigurer`). | ||
| ||
## Out is out | ||
| ||
A member put out, or leaving, reads the group's spaces no more: | ||
| ||
- their membership goes, so the access records let them read nothing | ||
that needs a role; | ||
- the credentials the group issued them are revoked: at once for the | ||
repos on this host, and told to the host of each other writer in | ||
those spaces (`notifyCredentialRevoked`, signed by the group, best | ||
effort), so they lapse everywhere rather than within the hour. The | ||
authority keeps each credential it issues, to whom, until it lapses, | ||
for this; | ||
- the index forgets what they wrote, and keeps only writers the space | ||
still lets write. | ||
| ||
What they wrote stays in their own repos, at their own PDSes. | ||
| ||
## From the prototype | ||
| ||
As `methods/roles.ts`, `methods/membership.ts` and `leaveGroup`, with | ||
these changes: `assignRoles` refuses someone who is not a member, where | ||
the prototype would write them a membership and so admit them; roles | ||
given must be defined; `deleteRole` refuses a role someone holds, as | ||
the lexicon's `RoleInUse` says; and leaving or being put out revokes | ||
credentials, which the prototype left to lapse. | ||
docs/design/README.md+5−3
| @@ -89,9 +89,11 @@ says otherwise. | ||
`group.ts`, `bootstrap.ts`, `methods/{groups,handle,profile,rules,lifecycle,spaces,spaceRecords}.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`. | ||
5. **Membership and roles.** Roles and permissions, assigning, leaving | ||
and ejecting, with credentials revoked for whoever is out | ||
(`group_members.rs`; done, see [membership](membership.md)); then | ||
joining and join requests, and invites with `checkUserAccess` for | ||
their inboxes: `rbac.ts`, `methods/{roles,membership,join,invites}.ts`. | ||
6. **Signing in.** Service auth for callers; the OAuth server an app signs | ||
in to as a group (PAR, DPoP, consent, refresh), group tokens, app | ||
passwords, connected apps, provisioning: `auth.ts`, `pds/auth.ts`, | ||