chadtmiller.com/group-host
atmosphere group host
0
0
Groups invite people into their inboxes, and invites admit them
crates/group-host/src/group_invites.rsnew+379−0
| @@ -0,0 +1,379 @@ | ||
//! Invites. A group invites someone by writing an invite in its own repo | ||
//! in the invitee's inbox: a space under the invitee's own DID, at their | ||
//! PDS, which lets this host say who may write there | ||
//! (`com.atproto.managedspace.checkUserAccess`). The invitee's apps read | ||
//! it there; the host keeps its own list of what it sent, which is what | ||
//! redeems an invite, as the inbox is its owner's to read, not the | ||
//! group's. | ||
//! | ||
//! An invite is redeemed by asking to join: admitted at once, whatever | ||
//! the group's join policy, with its default roles. | ||
//! | ||
//! As the prototype's `methods/invites.ts` and `checkUserAccess.ts`. | ||
| ||
use crate::Host; | ||
use crate::api::{Params, invalid, page, param}; | ||
use crate::group::meta_space; | ||
use crate::group_api::{caller, group_of, signed_in}; | ||
use crate::group_members::acting; | ||
use crate::rbac::NS; | ||
use crate::repo::Write; | ||
use crate::store::Invite; | ||
use crate::time::{iso, now_millis}; | ||
use crate::xrpc::XrpcError; | ||
use atproto::space::SpaceRef; | ||
use atproto::syntax; | ||
use axum::Json; | ||
use axum::extract::{Query, State}; | ||
use axum::http::{HeaderMap, StatusCode}; | ||
use serde_json::{Value, json}; | ||
use std::sync::Arc; | ||
| ||
type Answer = Result<Json<Value>, XrpcError>; | ||
| ||
/// The method a space's authority asks this host who may read or write. | ||
pub const CHECK_USER_ACCESS: &str = "com.atproto.managedspace.checkUserAccess"; | ||
| ||
fn bad(error: &'static str, message: impl Into<String>) -> XrpcError { | ||
XrpcError::new(StatusCode::BAD_REQUEST, error, message) | ||
} | ||
| ||
/// Someone's inbox: where groups' invites to them arrive. | ||
pub fn inbox_of(did: &str) -> String { | ||
format!("at://{did}/space/{NS}.inbox/self") | ||
} | ||
| ||
fn uri_of(invite: &Invite) -> String { | ||
format!( | ||
"{}/{}/{NS}.invite/{}", | ||
inbox_of(&invite.invitee), | ||
invite.group, | ||
invite.rkey | ||
) | ||
} | ||
| ||
fn view(invite: &Invite) -> Value { | ||
let mut view = json!({ | ||
"uri": uri_of(invite), | ||
"invitee": invite.invitee, | ||
"createdAt": iso(invite.created_at), | ||
}); | ||
if let Some(m) = &invite.message { | ||
view["message"] = json!(m); | ||
} | ||
if let Some(at) = invite.expires_at { | ||
view["expiresAt"] = json!(iso(at)); | ||
} | ||
view | ||
} | ||
| ||
/// An RFC 3339 datetime in UTC (`2026-11-03T00:00:00Z`, fractions of a | ||
/// second allowed), in milliseconds since 1970. | ||
pub fn millis_of(text: &str) -> Option<i64> { | ||
let text = text.strip_suffix('Z')?; | ||
let (date, time) = text.split_once('T')?; | ||
let (hms, frac) = time.split_once('.').unwrap_or((time, "")); | ||
// Digits alone, of the widths RFC 3339 writes them. | ||
let number = |part: &str, width: usize| -> Option<i64> { | ||
let digits = part.len() == width && part.bytes().all(|b| b.is_ascii_digit()); | ||
digits.then(|| part.parse().ok()).flatten() | ||
}; | ||
let fields = |text: &str, sep: char, widths: &[usize]| -> Option<Vec<i64>> { | ||
let parts: Vec<&str> = text.split(sep).collect(); | ||
let fits = parts.len() == widths.len(); | ||
fits.then(|| { | ||
parts | ||
.iter() | ||
.zip(widths) | ||
.map(|(p, w)| number(p, *w)) | ||
.collect() | ||
})? | ||
}; | ||
let d = fields(date, '-', &[4, 2, 2])?; | ||
let t = fields(hms, ':', &[2, 2, 2])?; | ||
let (y, m, day, h, min, s) = (d[0], d[1], d[2], t[0], t[1], t[2]); | ||
let frac_ok = frac.bytes().all(|b| b.is_ascii_digit()); | ||
let leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0; | ||
let days_in = [ | ||
31, | ||
if leap { 29 } else { 28 }, | ||
31, | ||
30, | ||
31, | ||
30, | ||
31, | ||
31, | ||
30, | ||
31, | ||
30, | ||
31, | ||
]; | ||
let in_month = | ||
(1..=12).contains(&m) && (1..=days_in[(m - 1).clamp(0, 11) as usize]).contains(&day); | ||
if !frac_ok || !in_month || h > 23 || min > 59 || s > 60 { | ||
return None; | ||
} | ||
let ms: i64 = format!("{frac:0<3}")[..3].parse().ok()?; | ||
// Days since 1970, by the civil calendar. | ||
let (y, m) = if m <= 2 { (y - 1, m + 9) } else { (y, m - 3) }; | ||
let era = y.div_euclid(400); | ||
let yoe = y - era * 400; | ||
let doy = (153 * m + 2) / 5 + day - 1; | ||
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; | ||
let days = era * 146_097 + doe - 719_468; | ||
Some(((days * 24 + h) * 60 + min) * 60_000 + s * 1000 + ms) | ||
} | ||
| ||
impl Host { | ||
/// Takes `invite` back: its record out of the group's repo in the | ||
/// inbox, and the host's list. | ||
async fn take_back(&self, invite: &Invite) -> Result<(), XrpcError> { | ||
let gone = Write::Delete { | ||
collection: format!("{NS}.invite"), | ||
rkey: invite.rkey.clone(), | ||
}; | ||
let inbox = inbox_of(&invite.invitee); | ||
let written = self.space_write(&invite.group, &inbox, std::slice::from_ref(&gone)); | ||
written.await?; | ||
let forgot = self.store.uninvite(&invite.group, &invite.invitee); | ||
forgot.map_err(XrpcError::internal) | ||
} | ||
| ||
/// `group`'s invite to `did`, if one waits and has not lapsed: taken | ||
/// back, as it is redeemed. | ||
pub(crate) async fn redeem(&self, group: &str, did: &str) -> Result<bool, XrpcError> { | ||
let invited = self | ||
.store | ||
.invited(group, did) | ||
.map_err(XrpcError::internal)?; | ||
let live = invited.filter(|i| i.expires_at.is_none_or(|at| at > now_millis())); | ||
match live { | ||
Some(invite) => { | ||
self.take_back(&invite).await?; | ||
Ok(true) | ||
} | ||
None => Ok(false), | ||
} | ||
} | ||
} | ||
| ||
/// Invites someone, for one holding `invite`: an invite written in the | ||
/// group's repo in their inbox, told to their PDS. One already waiting is | ||
/// the one answered. | ||
pub async fn create_invite( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
Json(body): Json<Value>, | ||
) -> Answer { | ||
let (members, me, _) = acting(&host, &headers, &body, "createInvite", Some("invite")).await?; | ||
let invitee = body["invitee"].as_str().unwrap_or_default(); | ||
if !syntax::is_did(invitee) { | ||
return Err(invalid("invitee is a DID")); | ||
} | ||
if members.membership(invitee)?.is_some() { | ||
return Err(bad("AlreadyMember", "they are a member already")); | ||
} | ||
let expires_at = match body["expiresAt"].as_str() { | ||
Some(at) => Some(millis_of(at).ok_or_else(|| invalid("expiresAt is a datetime"))?), | ||
None => None, | ||
}; | ||
let group = members.group.clone(); | ||
// One waiting is the one answered; one lapsed is taken back, and a | ||
// fresh one written. | ||
let invited = host | ||
.store | ||
.invited(&group, invitee) | ||
.map_err(XrpcError::internal)?; | ||
if let Some(waiting) = invited { | ||
if waiting.expires_at.is_none_or(|at| at > now_millis()) { | ||
return Ok(Json(json!({ "uri": uri_of(&waiting) }))); | ||
} | ||
host.take_back(&waiting).await?; | ||
} | ||
let invite = Invite { | ||
seq: 0, | ||
group: group.clone(), | ||
invitee: invitee.into(), | ||
by: me.clone(), | ||
message: body["message"].as_str().map(String::from), | ||
rkey: host.clock.next(), | ||
created_at: now_millis(), | ||
expires_at, | ||
}; | ||
let mut record = | ||
json!({"$type": format!("{NS}.invite"), "by": me, "createdAt": iso(invite.created_at)}); | ||
if let Some(m) = &invite.message { | ||
record["message"] = json!(m); | ||
} | ||
if let Some(at) = body["expiresAt"].as_str() { | ||
record["expiresAt"] = json!(at); | ||
} | ||
let write = Write::Create { | ||
collection: format!("{NS}.invite"), | ||
rkey: invite.rkey.clone(), | ||
value: record, | ||
}; | ||
let inbox = inbox_of(invitee); | ||
let written = host.space_write(&group, &inbox, std::slice::from_ref(&write)); | ||
written.await?; | ||
host.store.invite(&invite).map_err(XrpcError::internal)?; | ||
Ok(Json(json!({ "uri": uri_of(&invite) }))) | ||
} | ||
| ||
/// The group's invites waiting, newest first, for one holding `invite`. | ||
pub async fn list_invites( | ||
State(host): State<Arc<Host>>, | ||
Query(p): Query<Params>, | ||
headers: HeaderMap, | ||
) -> Answer { | ||
let body = json!({ "group": param(&p, "group")? }); | ||
let (members, _, _) = acting(&host, &headers, &body, "listInvites", Some("invite")).await?; | ||
let limit = page(&p, 50, 100)?; | ||
let before = match p.get("cursor") { | ||
None => None, | ||
Some(c) => Some( | ||
c.parse::<i64>() | ||
.map_err(|_| invalid("a cursor this host gave"))?, | ||
), | ||
}; | ||
let waiting = host | ||
.store | ||
.invites(&members.group, before, now_millis(), limit) | ||
.map_err(XrpcError::internal)?; | ||
let cursor = waiting | ||
.last() | ||
.filter(|_| waiting.len() == limit as usize) | ||
.map(|i| i.seq.to_string()); | ||
let invites: Vec<Value> = waiting.iter().map(view).collect(); | ||
Ok(Json(json!({"invites": invites, "cursor": cursor}))) | ||
} | ||
| ||
/// Takes back an invite, by its URI, for one holding `invite`. | ||
pub async fn revoke_invite( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
Json(body): Json<Value>, | ||
) -> Answer { | ||
let (members, _, _) = acting(&host, &headers, &body, "revokeInvite", Some("invite")).await?; | ||
let uri = body["uri"] | ||
.as_str() | ||
.ok_or_else(|| invalid("uri is required"))?; | ||
let invitee = uri.strip_prefix("at://").and_then(|r| r.split('/').next()); | ||
let invitee = invitee | ||
.filter(|d| syntax::is_did(d)) | ||
.ok_or_else(|| invalid("not an invite's URI"))?; | ||
let invited = host | ||
.store | ||
.invited(&members.group, invitee) | ||
.map_err(XrpcError::internal)?; | ||
let invite = invited.ok_or_else(|| bad("InviteNotFound", "no invite to them waits"))?; | ||
host.take_back(&invite).await?; | ||
Ok(Json(json!({}))) | ||
} | ||
| ||
/// The caller's own invites waiting, from the groups here, newest first; | ||
/// with `group`, that group's only. | ||
pub async fn get_actor_invites( | ||
State(host): State<Arc<Host>>, | ||
Query(p): Query<Params>, | ||
headers: HeaderMap, | ||
) -> Answer { | ||
let me = signed_in(&host, &headers, &format!("{NS}.getActorInvites")).await?; | ||
let waiting = host | ||
.store | ||
.invites_to(&me, now_millis()) | ||
.map_err(XrpcError::internal)?; | ||
let only = p.get("group"); | ||
let mut invites = Vec::new(); | ||
for invite in waiting | ||
.iter() | ||
.filter(|i| only.is_none_or(|g| *g == i.group)) | ||
{ | ||
if host.deactivation(&invite.group)?.is_some() { | ||
continue; | ||
} | ||
let handle = group_of(&host, &invite.group)?; | ||
let mut group = json!({"did": invite.group, "handle": handle, "address": host.store.address(&invite.group).map_err(XrpcError::internal)?}); | ||
let profile = host | ||
.group_record( | ||
&invite.group, | ||
&meta_space(&invite.group), | ||
&format!("{NS}.profile"), | ||
"self", | ||
) | ||
.map_err(XrpcError::internal)? | ||
.unwrap_or_default(); | ||
if let Some(name) = profile.get("displayName") { | ||
group["displayName"] = name.clone(); | ||
} | ||
if let Some(cid) = profile["avatar"]["ref"]["$link"].as_str() { | ||
group["avatar"] = json!(cid); | ||
} | ||
let mut shown = | ||
json!({"group": group, "by": invite.by, "createdAt": iso(invite.created_at)}); | ||
if let Some(m) = &invite.message { | ||
shown["message"] = json!(m); | ||
} | ||
invites.push(shown); | ||
} | ||
Ok(Json(json!({ "invites": invites }))) | ||
} | ||
| ||
/// Turns down the group's invite to the caller: it goes from the group's | ||
/// list and their inbox. The group may invite them again. | ||
pub async fn decline_invite( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
Json(body): Json<Value>, | ||
) -> Answer { | ||
let me = signed_in(&host, &headers, &format!("{NS}.declineInvite")).await?; | ||
let group = body["group"] | ||
.as_str() | ||
.ok_or_else(|| invalid("group is required"))?; | ||
group_of(&host, group)?; | ||
let invited = host | ||
.store | ||
.invited(group, &me) | ||
.map_err(XrpcError::internal)?; | ||
let invite = invited.ok_or_else(|| bad("InviteNotFound", "no invite to you waits"))?; | ||
host.take_back(&invite).await?; | ||
Ok(Json(json!({}))) | ||
} | ||
| ||
/// Whether a user may read or write a space this host manages for its | ||
/// authority: someone's inbox, which its owner reads and groups here | ||
/// write their invites in. Asked by the space's authority, with service | ||
/// auth for this host. | ||
pub async fn check_user_access( | ||
State(host): State<Arc<Host>>, | ||
Query(p): Query<Params>, | ||
headers: HeaderMap, | ||
) -> Answer { | ||
let asker = caller(&host, &headers, CHECK_USER_ACCESS).await?; | ||
let asker = asker | ||
.ok_or_else(|| crate::space_api::unauthorized("AuthMissing", "service auth is required"))?; | ||
let space = SpaceRef::parse(param(&p, "space")?).map_err(|e| invalid(e.to_string()))?; | ||
if asker != space.authority { | ||
return Err(XrpcError::new( | ||
StatusCode::FORBIDDEN, | ||
"Forbidden", | ||
"only the space's authority asks", | ||
)); | ||
} | ||
let user = param(&p, "user")?; | ||
let inbox = space.kind == format!("{NS}.inbox"); | ||
let authorized = match p.get("access").map(String::as_str) { | ||
// Its owner reads it; a group here writes in it. | ||
Some("write") => { | ||
inbox | ||
&& host | ||
.store | ||
.account(user) | ||
.map_err(XrpcError::internal)? | ||
.is_some_and(|a| a.did == user) | ||
&& group_of(&host, user).is_ok() | ||
} | ||
_ => inbox && user == space.authority, | ||
}; | ||
Ok(Json(json!({ "authorized": authorized }))) | ||
} | ||
crates/group-host/src/group_join.rs+11−3
| @@ -1,6 +1,7 @@ | ||
//! Joining a group: at once for one whose profile says `open`; by a | ||
//! request someone holding `admit` decides on for one that says | ||
//! `approval`; not without an invite for one that says `invite`. | ||
//! Joining a group: at once for one whose profile says `open`, or for one | ||
//! holding its invite; by a request someone holding `admit` decides on | ||
//! for one that says `approval`; not without an invite for one that says | ||
//! `invite`. | ||
//! | ||
//! A request waits in the host, not in the group's records: who asks is | ||
//! no member, and the members space is for members. Decided, it goes: a | ||
| @@ -61,6 +62,13 @@ pub async fn request_join( | ||
if members.membership(&me)?.is_some() { | ||
return Err(bad("AlreadyMember", "you are a member already")); | ||
} | ||
// An invite is pre-approval: redeemed, whatever the policy. | ||
if host.redeem(group, &me).await? { | ||
let roles = members.default_roles()?; | ||
members.put_membership(&me, &roles).await?; | ||
host.store.decide(group, &me).map_err(XrpcError::internal)?; | ||
return Ok(Json(json!({"status": "admitted"}))); | ||
} | ||
let profile = host | ||
.group_record(group, &meta_space(group), &format!("{NS}.profile"), "self") | ||
.map_err(XrpcError::internal)? | ||
crates/group-host/src/lib.rs+25−0
| @@ -13,6 +13,7 @@ pub mod group; | ||
pub mod group_api; | ||
pub mod group_config; | ||
pub mod group_handle; | ||
pub mod group_invites; | ||
pub mod group_join; | ||
pub mod group_lifecycle; | ||
pub mod group_members; | ||
| @@ -277,6 +278,30 @@ pub fn router(host: Arc<Host>) -> Router { | ||
"/xrpc/fyi.opensocial.cancelJoinRequest", | ||
post(group_join::cancel_join_request), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.createInvite", | ||
post(group_invites::create_invite), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.listInvites", | ||
get(group_invites::list_invites), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.revokeInvite", | ||
post(group_invites::revoke_invite), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.getActorInvites", | ||
get(group_invites::get_actor_invites), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.declineInvite", | ||
post(group_invites::decline_invite), | ||
) | ||
.route( | ||
"/xrpc/com.atproto.managedspace.checkUserAccess", | ||
get(group_invites::check_user_access), | ||
) | ||
.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+103−0
| @@ -211,6 +211,20 @@ pub const MIGRATIONS: &[&str] = &[ | ||
created_at INTEGER NOT NULL, | ||
UNIQUE (grp, did) | ||
); | ||
", | ||
" | ||
CREATE TABLE invite ( | ||
seq INTEGER PRIMARY KEY AUTOINCREMENT, | ||
grp TEXT NOT NULL REFERENCES account (did), | ||
invitee TEXT NOT NULL, | ||
by TEXT NOT NULL, | ||
message TEXT, | ||
rkey TEXT NOT NULL, | ||
created_at INTEGER NOT NULL, | ||
expires_at INTEGER, | ||
UNIQUE (grp, invitee) | ||
); | ||
CREATE INDEX invite_to ON invite (invitee); | ||
", | ||
]; | ||
| ||
| @@ -318,12 +332,18 @@ const ASKED: &str = | ||
"SELECT seq, did, message, created_at FROM join_request WHERE grp = ?1 AND did = ?2"; | ||
const ASKING: &str = "SELECT seq, did, message, created_at FROM join_request WHERE grp = ?1 AND seq < ?2 ORDER BY seq DESC LIMIT ?3"; | ||
const DECIDE: &str = "DELETE FROM join_request WHERE grp = ?1 AND did = ?2"; | ||
const INVITE: &str = "INSERT INTO invite (grp, invitee, by, message, rkey, created_at, expires_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)"; | ||
const INVITED: &str = "SELECT seq, grp, invitee, by, message, rkey, created_at, expires_at FROM invite WHERE grp = ?1 AND invitee = ?2"; | ||
const INVITES: &str = "SELECT seq, grp, invitee, by, message, rkey, created_at, expires_at FROM invite WHERE grp = ?1 AND seq < ?2 AND (expires_at IS NULL OR expires_at > ?3) ORDER BY seq DESC LIMIT ?4"; | ||
const INVITES_TO: &str = "SELECT seq, grp, invitee, by, message, rkey, created_at, expires_at FROM invite WHERE invitee = ?1 AND (expires_at IS NULL OR expires_at > ?2) ORDER BY seq DESC"; | ||
const UNINVITE: &str = "DELETE FROM invite WHERE grp = ?1 AND invitee = ?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 invite WHERE grp = ?1", | ||
"DELETE FROM join_request WHERE grp = ?1", | ||
"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)", | ||
| @@ -530,6 +550,34 @@ fn join_request(row: &rusqlite::Row) -> rusqlite::Result<JoinRequest> { | ||
}) | ||
} | ||
| ||
/// An invite a group sent: in order, the group, whom, who in it sent it, | ||
/// what they said, its record's key in the invitee's inbox, when, and | ||
/// when it lapses, if it does. | ||
#[derive(Debug, Clone, PartialEq)] | ||
pub struct Invite { | ||
pub seq: i64, | ||
pub group: String, | ||
pub invitee: String, | ||
pub by: String, | ||
pub message: Option<String>, | ||
pub rkey: String, | ||
pub created_at: i64, | ||
pub expires_at: Option<i64>, | ||
} | ||
| ||
fn invite(row: &rusqlite::Row) -> rusqlite::Result<Invite> { | ||
Ok(Invite { | ||
seq: row.get(0)?, | ||
group: row.get(1)?, | ||
invitee: row.get(2)?, | ||
by: row.get(3)?, | ||
message: row.get(4)?, | ||
rkey: row.get(5)?, | ||
created_at: row.get(6)?, | ||
expires_at: row.get(7)?, | ||
}) | ||
} | ||
| ||
/// A blob as kept: its type, its size, and whether it waits for a record | ||
/// to reference it. | ||
#[derive(Debug, Clone, PartialEq)] | ||
| @@ -1312,6 +1360,61 @@ impl Store { | ||
Ok(conn.execute(DECIDE, [group, did])? > 0) | ||
} | ||
| ||
/// Keeps a group's invite. | ||
pub fn invite(&self, invite: &Invite) -> Result<()> { | ||
let conn = self.conn(); | ||
let i = invite; | ||
let kept = params![ | ||
i.group, | ||
i.invitee, | ||
i.by, | ||
i.message, | ||
i.rkey, | ||
i.created_at, | ||
i.expires_at | ||
]; | ||
conn.execute(INVITE, kept)?; | ||
Ok(()) | ||
} | ||
| ||
/// `group`'s invite to `invitee`, lapsed or not. | ||
pub fn invited(&self, group: &str, invitee: &str) -> Result<Option<Invite>> { | ||
let conn = self.conn(); | ||
let found = conn.query_row(INVITED, [group, invitee], invite); | ||
Ok(found.optional()?) | ||
} | ||
| ||
/// `group`'s invites not lapsed at `now`, newest first, before | ||
/// `before`, at most `limit`. | ||
pub fn invites( | ||
&self, | ||
group: &str, | ||
before: Option<i64>, | ||
now: i64, | ||
limit: u32, | ||
) -> Result<Vec<Invite>> { | ||
let conn = self.conn(); | ||
let mut q = conn.prepare(INVITES)?; | ||
let asked = params![group, before.unwrap_or(i64::MAX), now, limit]; | ||
let rows = q.query_map(asked, invite)?; | ||
Ok(rows.collect::<rusqlite::Result<_>>()?) | ||
} | ||
| ||
/// The invites to `invitee` not lapsed at `now`, newest first. | ||
pub fn invites_to(&self, invitee: &str, now: i64) -> Result<Vec<Invite>> { | ||
let conn = self.conn(); | ||
let mut q = conn.prepare(INVITES_TO)?; | ||
let rows = q.query_map(params![invitee, now], invite)?; | ||
Ok(rows.collect::<rusqlite::Result<_>>()?) | ||
} | ||
| ||
/// Forgets `group`'s invite to `invitee`. | ||
pub fn uninvite(&self, group: &str, invitee: &str) -> Result<()> { | ||
let conn = self.conn(); | ||
conn.execute(UNINVITE, [group, invitee])?; | ||
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/mod.rs+12−0
| @@ -163,6 +163,18 @@ pub async fn start_reachable(vars: &[(&str, &str)]) -> Running { | ||
start_on(listener, &vars, false).await | ||
} | ||
| ||
/// A host reachable by name, at `http://localhost:<port>`, its `did:web` | ||
/// of that name: for servers elsewhere that resolve its DID, as one | ||
/// resolves `localhost` over http. It listens on every address, IPv6 and | ||
/// IPv4, whichever `localhost` is. | ||
pub async fn start_reachable_by_name(vars: &[(&str, &str)]) -> Running { | ||
let listener = tokio::net::TcpListener::bind("[::]:0").await.unwrap(); | ||
let url = format!("http://localhost:{}", listener.local_addr().unwrap().port()); | ||
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)], | ||
crates/group-host/tests/interop.rs+101−0
| @@ -408,3 +408,104 @@ async fn the_host_as_authority_for_a_member_on_the_reference_pds() { | ||
assert_eq!(status, 200, "{repos}"); | ||
assert_eq!(repos["repos"][0]["did"], alice.did); | ||
} | ||
| ||
#[tokio::test] | ||
async fn an_invite_into_an_inbox_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 = common::start_reachable_by_name(&[("PLC_URL", net.plc.as_str())]).await; | ||
let service = h.host.config.service_did.clone(); | ||
assert!(service.starts_with("did:web:localhost"), "{service}"); | ||
| ||
// Alice's inbox, at her PDS, a space this host manages for her. | ||
let alice = &net.accounts[0]; | ||
let session = call( | ||
&net.pds, | ||
"com.atproto.server.createSession", | ||
"", | ||
&json!({"identifier": alice.handle, "password": alice.password}), | ||
) | ||
.await; | ||
let jwt = session["accessJwt"].as_str().unwrap(); | ||
let created = call( | ||
&net.pds, | ||
"com.atproto.space.createSpace", | ||
jwt, | ||
&json!({ | ||
"spaceType": "fyi.opensocial.inbox", | ||
"skey": "self", | ||
"policy": {"$type": "com.atproto.managedspace.policy", "managingApp": service}, | ||
}), | ||
) | ||
.await; | ||
let inbox = created["uri"].as_str().unwrap().to_string(); | ||
| ||
// A group here invites her: its write is told to her PDS, which asks | ||
// this host whether the group may write there. | ||
let founder = common::spaces::authority(&h, false, true).await; | ||
let group = common::groups::start_group( | ||
&h, | ||
&founder, | ||
json!({"handle": "riders.groups.test", "displayName": "Riders"}), | ||
) | ||
.await; | ||
let lxm = "fyi.opensocial.createInvite"; | ||
let (status, made) = common::groups::post( | ||
&h, | ||
lxm, | ||
&json!({"group": group, "invitee": alice.did}), | ||
&[common::groups::auth(&h, &founder, lxm)], | ||
) | ||
.await; | ||
assert_eq!(status, 200, "{made}"); | ||
// Nothing is owed: her PDS took the write. | ||
let later = group_host::time::now_millis() / 1000 + 3600; | ||
assert_eq!( | ||
h.host.store.due(later, 10).unwrap(), | ||
vec![], | ||
"her PDS refused the invite" | ||
); | ||
| ||
// And it keeps the group among her inbox's writers. | ||
let (_, _, token) = get( | ||
&net.pds, | ||
"com.atproto.space.getDelegationToken", | ||
&[("space", inbox.as_str())], | ||
&[("authorization", format!("Bearer {jwt}"))], | ||
) | ||
.await; | ||
let key = Keypair::generate(Curve::P256); | ||
let issued = call( | ||
&net.pds, | ||
"com.atproto.space.getSpaceCredential", | ||
"", | ||
&json!({"space": inbox, "credentialKid": key.public().did_key(), "delegationToken": token["token"]}), | ||
) | ||
.await; | ||
let authorization = format!( | ||
"Atproto-Space-Credential {}", | ||
issued["credential"].as_str().unwrap() | ||
); | ||
let headers: Vec<(&str, String)> = sign_request(&key, &authorization, &alice.did) | ||
.unwrap() | ||
.into_iter() | ||
.collect(); | ||
let (status, _, repos) = get( | ||
&net.pds, | ||
"com.atproto.space.listRepos", | ||
&[("space", inbox.as_str())], | ||
&headers, | ||
) | ||
.await; | ||
assert!(status.is_success(), "{status} {repos}"); | ||
let writers: Vec<&str> = repos["repos"] | ||
.as_array() | ||
.unwrap() | ||
.iter() | ||
.map(|r| r["did"].as_str().unwrap()) | ||
.collect(); | ||
assert!(writers.contains(&group.as_str()), "{repos}"); | ||
} | ||
crates/group-host/tests/invites.rsnew+401−0
401 lines changed: not loaded until asked for.
crates/group-host/tests/serve.rs+1−1
| @@ -50,7 +50,7 @@ async fn answers_health_and_refuses_unknown_methods() { | ||
assert_eq!(health["version"], env!("CARGO_PKG_VERSION")); | ||
| ||
for req in [ | ||
http.get(format!("{}/xrpc/fyi.opensocial.listInvites", host.1)), | ||
http.get(format!("{}/xrpc/fyi.opensocial.listSubjects", host.1)), | ||
http.post(format!("{}/xrpc/fyi.opensocial.applyLabel", host.1)), | ||
] { | ||
let res = req.send().await.unwrap(); | ||
docs/design/membership.md+31−4
| @@ -47,14 +47,39 @@ How people get in is the group's profile's `joinPolicy`: | ||
is bound as giving them is); `denyJoinRequest` turns one down; | ||
`cancelJoinRequest` withdraws one's own; `getJoinRequest` is one's | ||
own, while it waits. | ||
- `invite`: not without an invite (`InviteRequired`), which comes with | ||
invites. | ||
- `invite`: not without an invite (`InviteRequired`). | ||
| ||
An invite admits its invitee whatever the policy: asking to join | ||
redeems it, with the group's default roles. | ||
| ||
A request waits in the host, not in the group's records: who asks is no | ||
member, and the members space is for members. Decided, it goes: a | ||
request turned down looks the same as one never made, so its asker may | ||
ask again and the group need not say. | ||
| ||
## Invites | ||
| ||
A group invites someone by writing an invite in its own repo in their | ||
inbox: a space under their own DID (`fyi.opensocial.inbox`), at their | ||
PDS, whose policy lets this host say who reads and writes it. The host | ||
answers its authority (`com.atproto.managedspace.checkUserAccess`, with | ||
service auth from the authority): its owner reads it, and only groups on | ||
this host write in it. The group's write is told to the invitee's PDS as | ||
any write to a space elsewhere is, owed until it lands. The invitee's | ||
apps read the invite there; the host keeps its own list of what it sent, | ||
which is what redeems an invite, as the inbox is its owner's to read, | ||
not the group's. | ||
| ||
- `createInvite` (for `invite`) invites someone not yet a member, with | ||
words and a lapse if it says; one already waiting is the one answered. | ||
- `listInvites` (for `invite`) lists those waiting, newest first, the | ||
lapsed left out. | ||
- `revokeInvite` (for `invite`) takes one back by its URI; `declineInvite` | ||
is its invitee's own say. Either takes the record out of the inbox and | ||
the host's list; the group may invite them again. | ||
- `getActorInvites` is the caller's own invites waiting, from the groups | ||
here, for a group's site, which can't read the caller's inbox. | ||
| ||
## Out is out | ||
| ||
A member put out, or leaving, reads the group's spaces no more: | ||
| @@ -78,5 +103,7 @@ 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. | ||
the lexicon's `RoleInUse` says; leaving or being put out revokes | ||
credentials, which the prototype left to lapse; an inbox takes invites | ||
from groups here alone, where the prototype let anyone write in it; and | ||
an invite's `expiresAt` is kept to. | ||
docs/design/README.md+2−2
| @@ -92,8 +92,8 @@ says otherwise. | ||
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)); joining | ||
and join requests (`group_join.rs`; done); then invites with | ||
`checkUserAccess` for their inboxes: `rbac.ts`, `methods/{roles,membership,join,invites}.ts`. | ||
and join requests (`group_join.rs`; done); invites, with | ||
`checkUserAccess` for their inboxes (`group_invites.rs`; done): `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`, | ||
lexicons/fyi/opensocial/admitMember.json+4−0
| @@ -49,6 +49,10 @@ | ||
{ | ||
"name": "NotAssignable", | ||
"description": "A role asked for is not the caller's to give." | ||
}, | ||
{ | ||
"name": "AlreadyMember", | ||
"description": "The account is a member already." | ||
} | ||
] | ||
} | ||