~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0

People join a group at once, by request, or not without an invite

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:host/joining
crates/group-host/src/group_api.rs+20−0
@@ -232,6 +232,11 @@ pub async fn get_group(
if member {
viewer["accepted"] = json!(accepted(&host, &members, me).map_err(XrpcError::internal)?);
}
// Their own request, while it waits.
let asked = host.store.asked(group, me).map_err(XrpcError::internal)?;
if let Some(request) = asked.filter(|_| !member) {
viewer["request"] = crate::group_join::request_view(&request);
}
view["viewer"] = viewer;
}
let mut out = json!({ "group": view });
@@ -297,6 +302,21 @@ pub async fn get_group(
spaces.push(space);
}
out["spaces"] = json!(spaces);
// The requests waiting, for one who may admit them.
if actions.contains("admit") {
let waiting = host
.store
.asking(group, None, 100)
.map_err(XrpcError::internal)?;
out["joinRequests"] = waiting
.iter()
.map(|r| {
let mut view = crate::group_join::request_view(r);
view["actor"] = json!({"did": r.did});
view
})
.collect();
}
Ok(Json(out))
}
crates/group-host/src/group_join.rsnew+217−0
@@ -0,0 +1,217 @@
//! 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`.
//!
//! 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.
//!
//! As the prototype's `requestJoin` and `methods/join.ts`.
use crate::Host;
use crate::api::{Params, invalid, page, param};
use crate::group::meta_space;
use crate::group_api::{group_of, signed_in};
use crate::group_members::{Members, acting};
use crate::rbac::{NS, listed};
use crate::store::JoinRequest;
use crate::time::{iso, now_millis};
use crate::xrpc::XrpcError;
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>;
fn bad(error: &'static str, message: impl Into<String>) -> XrpcError {
XrpcError::new(StatusCode::BAD_REQUEST, error, message)
}
fn no_request() -> XrpcError {
bad("JoinRequestNotFound", "no request from them is waiting")
}
/// A request as a view shows it.
pub fn request_view(r: &JoinRequest) -> Value {
let mut view = json!({"did": r.did, "createdAt": iso(r.created_at)});
if let Some(message) = &r.message {
view["message"] = json!(message);
}
view
}
/// Asks to join: admitted at once to a group open to all, queued for one
/// that approves its members, refused without an invite for one that
/// invites them.
pub async fn request_join(
State(host): State<Arc<Host>>,
headers: HeaderMap,
Json(body): Json<Value>,
) -> Answer {
let me = signed_in(&host, &headers, &format!("{NS}.requestJoin")).await?;
let group = body["group"]
.as_str()
.ok_or_else(|| invalid("group is required"))?;
group_of(&host, group)?;
host.active(group)?;
let members = Members::of(&host, group)?;
if members.membership(&me)?.is_some() {
return Err(bad("AlreadyMember", "you are a member already"));
}
let profile = host
.group_record(group, &meta_space(group), &format!("{NS}.profile"), "self")
.map_err(XrpcError::internal)?
.unwrap_or_default();
match profile["joinPolicy"].as_str() {
Some("open") => {
let roles = members.default_roles()?;
members.put_membership(&me, &roles).await?;
// A request they made before the group opened waits no more.
host.store.decide(group, &me).map_err(XrpcError::internal)?;
Ok(Json(json!({"status": "admitted"})))
}
Some("invite") => Err(bad("InviteRequired", "this group joins by invite")),
_ => {
let message = body["message"].as_str();
// As the lexicon has it: 300 graphemes, 3000 bytes, at most.
if message.is_some_and(|m| m.len() > 3000 || m.chars().count() > 300) {
return Err(invalid("a message is 300 characters at most"));
}
host.store
.ask(group, &me, message, now_millis())
.map_err(XrpcError::internal)?;
Ok(Json(json!({"status": "pending"})))
}
}
}
/// The caller's own request to join, while it waits.
pub async fn get_join_request(
State(host): State<Arc<Host>>,
Query(p): Query<Params>,
headers: HeaderMap,
) -> Answer {
let me = signed_in(&host, &headers, &format!("{NS}.getJoinRequest")).await?;
let group = param(&p, "group")?;
group_of(&host, group)?;
let asked = host.store.asked(group, &me).map_err(XrpcError::internal)?;
Ok(Json(match asked {
Some(r) => json!({ "request": request_view(&r) }),
None => json!({}),
}))
}
/// The requests waiting to join, newest first, for one holding `admit`.
pub async fn list_join_requests(
State(host): State<Arc<Host>>,
Query(p): Query<Params>,
headers: HeaderMap,
) -> Answer {
let group = param(&p, "group")?;
let body = json!({ "group": group });
let (members, _, _) = acting(&host, &headers, &body, "listJoinRequests", Some("admit")).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
.asking(&members.group, before, limit)
.map_err(XrpcError::internal)?;
let cursor = waiting
.last()
.filter(|_| waiting.len() == limit as usize)
.map(|r| r.seq.to_string());
let requests: Vec<Value> = waiting.iter().map(request_view).collect();
Ok(Json(json!({"requests": requests, "cursor": cursor})))
}
/// Admits one who asked, with the roles named or the group's defaults,
/// each one the caller may give: admitting gives roles, so it is bound as
/// giving them is.
pub async fn admit_member(
State(host): State<Arc<Host>>,
headers: HeaderMap,
Json(body): Json<Value>,
) -> Answer {
let (members, _, mine) = acting(&host, &headers, &body, "admitMember", Some("admit")).await?;
let did = body["did"]
.as_str()
.ok_or_else(|| invalid("did is required"))?;
let asked = host
.store
.asked(&members.group, did)
.map_err(XrpcError::internal)?;
if asked.is_none() {
return Err(no_request());
}
// A member by now, by another way in: their request is stale, and
// their roles are not this method's to replace.
if members.membership(did)?.is_some() {
host.store
.decide(&members.group, did)
.map_err(XrpcError::internal)?;
return Err(bad("AlreadyMember", "they are a member already"));
}
let roles = match body.get("roles") {
Some(_) => listed(&body, "roles", "role"),
None => members.default_roles()?,
};
if roles.is_empty() {
return Err(invalid("roles names the roles to give"));
}
let assignable = members.assignable(&mine, "role.assign");
let blocked: Vec<&String> = roles.iter().filter(|r| !assignable.contains(*r)).collect();
if !blocked.is_empty() {
return Err(bad(
"NotAssignable",
format!("not yours to give: {blocked:?}"),
));
}
members.put_membership(did, &roles).await?;
host.store
.decide(&members.group, did)
.map_err(XrpcError::internal)?;
Ok(Json(json!({})))
}
/// Turns down one who asked, for one holding `admit`. They may ask again.
pub async fn deny_join_request(
State(host): State<Arc<Host>>,
headers: HeaderMap,
Json(body): Json<Value>,
) -> Answer {
let (members, _, _) = acting(&host, &headers, &body, "denyJoinRequest", Some("admit")).await?;
let did = body["member"]
.as_str()
.ok_or_else(|| invalid("member is required"))?;
let decided = host.store.decide(&members.group, did);
if !decided.map_err(XrpcError::internal)? {
return Err(no_request());
}
Ok(Json(json!({})))
}
/// Withdraws the caller's own request to join.
pub async fn cancel_join_request(
State(host): State<Arc<Host>>,
headers: HeaderMap,
Json(body): Json<Value>,
) -> Answer {
let me = signed_in(&host, &headers, &format!("{NS}.cancelJoinRequest")).await?;
let group = body["group"]
.as_str()
.ok_or_else(|| invalid("group is required"))?;
group_of(&host, group)?;
if !host.store.decide(group, &me).map_err(XrpcError::internal)? {
return Err(no_request());
}
Ok(Json(json!({})))
}
crates/group-host/src/group_members.rs+55−31
@@ -40,15 +40,15 @@ fn forbidden(message: impl Into<String>) -> XrpcError {
}
/// A group's members space, its grants, and its records there.
struct Members<'a> {
host: &'a Host,
group: String,
space: String,
grants: Vec<Grant>,
pub(crate) struct Members<'a> {
pub host: &'a Host,
pub group: String,
pub space: String,
pub grants: Vec<Grant>,
}
impl<'a> Members<'a> {
fn of(host: &'a Host, group: &str) -> Result<Members<'a>, XrpcError> {
pub(crate) fn of(host: &'a Host, group: &str) -> Result<Members<'a>, XrpcError> {
let space = members_space(group);
let permissions = host
.group_record(group, &space, &format!("{NS}.permissions"), "self")
@@ -61,14 +61,14 @@ impl<'a> Members<'a> {
})
}
fn records(&self, collection: &str) -> Result<Vec<(String, Value)>, XrpcError> {
pub(crate) fn records(&self, collection: &str) -> Result<Vec<(String, Value)>, XrpcError> {
self.host
.group_records(&self.group, &self.space, &format!("{NS}.{collection}"))
.map_err(XrpcError::internal)
}
/// `did`'s roles, and whether they are a member at all.
fn membership(&self, did: &str) -> Result<Option<Vec<String>>, XrpcError> {
pub(crate) fn membership(&self, did: &str) -> Result<Option<Vec<String>>, XrpcError> {
let record = self
.host
.group_record(
@@ -81,12 +81,12 @@ impl<'a> Members<'a> {
Ok(record.map(|m| listed(&m, "roles", "role")))
}
fn can(&self, roles: &[String], action: &str) -> bool {
pub(crate) fn can(&self, roles: &[String], action: &str) -> bool {
actions_for(&self.grants, roles).contains(action)
}
/// The roles holders of `roles` may give or take for `action`.
fn assignable(&self, roles: &[String], action: &str) -> BTreeSet<String> {
pub(crate) fn assignable(&self, roles: &[String], action: &str) -> BTreeSet<String> {
self.grants
.iter()
.filter(|g| roles.contains(&g.role) && actions_of(&g.scopes).contains(action))
@@ -94,6 +94,47 @@ impl<'a> Members<'a> {
.collect()
}
/// The roles every new member gets: those the group marks so, or
/// `member` in a group that marks none.
pub(crate) fn default_roles(&self) -> Result<Vec<String>, XrpcError> {
let marked: Vec<String> = self
.records("role")?
.into_iter()
.filter(|(_, r)| r["default"] == true)
.map(|(k, _)| k)
.collect();
Ok(if marked.is_empty() {
vec!["member".into()]
} else {
marked
})
}
/// Writes `did`'s membership, holding `roles`.
pub(crate) async fn put_membership(
&self,
did: &str,
roles: &[String],
) -> Result<(), XrpcError> {
let membership = json!({
"$type": format!("{NS}.membership"),
"member": did,
"roles": objects("role", roles),
"createdAt": iso(now_millis()),
});
let (collection, key) = (format!("{NS}.membership"), did_rkey(did));
let put = put_in(
self.host,
&self.group,
&self.space,
&collection,
&key,
membership,
);
let _written = put.await?;
Ok(())
}
/// Refuses a change that would leave nobody able to configure the
/// group: `who` holding `roles` after it, or out of it with none.
fn keeps_a_configurer(&self, who: &str, roles: &[String]) -> Result<(), XrpcError> {
@@ -115,7 +156,7 @@ impl<'a> Members<'a> {
}
/// The roles whose grant lets their holders configure the group.
fn configuring(&self) -> BTreeSet<String> {
pub(crate) fn configuring(&self) -> BTreeSet<String> {
self.grants
.iter()
.filter(|g| actions_of(&g.scopes).contains("group.configure"))
@@ -123,7 +164,7 @@ impl<'a> Members<'a> {
.collect()
}
fn permissions(&self, grants: &[Grant]) -> Value {
pub(crate) fn permissions(&self, grants: &[Grant]) -> Value {
let grants: Vec<Value> = grants.iter().map(Grant::to_json).collect();
json!({"$type": format!("{NS}.permissions"), "grants": grants, "createdAt": iso(now_millis())})
}
@@ -131,7 +172,7 @@ impl<'a> Members<'a> {
/// The group a body names and its members space, once the caller of
/// `lxm` may do `action` in it; and the caller's roles.
async fn acting<'a>(
pub(crate) async fn acting<'a>(
host: &'a Host,
headers: &HeaderMap,
body: &Value,
@@ -384,24 +425,7 @@ pub async fn assign_roles(
));
}
members.keeps_a_configurer(member, &roles)?;
let membership = json!({
"$type": format!("{NS}.membership"),
"member": member,
"roles": objects("role", &roles),
"createdAt": iso(now_millis()),
});
let space = members.space.clone();
let collection = format!("{NS}.membership");
let member_key = did_rkey(member);
let put = put_in(
&host,
&members.group,
&space,
&collection,
&member_key,
membership,
);
let _written = put.await?;
members.put_membership(member, &roles).await?;
Ok(Json(json!({})))
}
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_join;
pub mod group_lifecycle;
pub mod group_members;
pub mod group_spaces;
@@ -252,6 +253,30 @@ pub fn router(host: Arc<Host>) -> Router {
"/xrpc/fyi.opensocial.leaveGroup",
post(group_members::leave_group),
)
.route(
"/xrpc/fyi.opensocial.requestJoin",
post(group_join::request_join),
)
.route(
"/xrpc/fyi.opensocial.getJoinRequest",
get(group_join::get_join_request),
)
.route(
"/xrpc/fyi.opensocial.listJoinRequests",
get(group_join::list_join_requests),
)
.route(
"/xrpc/fyi.opensocial.admitMember",
post(group_join::admit_member),
)
.route(
"/xrpc/fyi.opensocial.denyJoinRequest",
post(group_join::deny_join_request),
)
.route(
"/xrpc/fyi.opensocial.cancelJoinRequest",
post(group_join::cancel_join_request),
)
.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+65−0
@@ -201,6 +201,16 @@ pub const MIGRATIONS: &[&str] = &[
PRIMARY KEY (space, jti)
);
CREATE INDEX issued_credential_to ON issued_credential (did);
",
"
CREATE TABLE join_request (
seq INTEGER PRIMARY KEY AUTOINCREMENT,
grp TEXT NOT NULL REFERENCES account (did),
did TEXT NOT NULL,
message TEXT,
created_at INTEGER NOT NULL,
UNIQUE (grp, did)
);
",
];
@@ -303,12 +313,18 @@ const FORGET_ISSUED: &str = "DELETE FROM issued_credential WHERE expires_at <= ?
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 ASK: &str = "INSERT INTO join_request (grp, did, message, created_at) VALUES (?1, ?2, ?3, ?4) ON CONFLICT (grp, did) DO NOTHING";
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 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 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)",
"DELETE FROM index_repo WHERE space IN (SELECT uri FROM space WHERE authority = ?1)",
@@ -495,6 +511,25 @@ fn indexed(row: &rusqlite::Row) -> rusqlite::Result<Indexed> {
})
}
/// A request to join a group, while it waits: in order, who asks, what
/// they said, and when.
#[derive(Debug, Clone, PartialEq)]
pub struct JoinRequest {
pub seq: i64,
pub did: String,
pub message: Option<String>,
pub created_at: i64,
}
fn join_request(row: &rusqlite::Row) -> rusqlite::Result<JoinRequest> {
Ok(JoinRequest {
seq: row.get(0)?,
did: row.get(1)?,
message: row.get(2)?,
created_at: row.get(3)?,
})
}
/// A blob as kept: its type, its size, and whether it waits for a record
/// to reference it.
#[derive(Debug, Clone, PartialEq)]
@@ -1247,6 +1282,36 @@ impl Store {
Ok(())
}
/// Keeps `did`'s request to join `group`, unless one waits already.
pub fn ask(&self, group: &str, did: &str, message: Option<&str>, now: i64) -> Result<()> {
let conn = self.conn();
conn.execute(ASK, params![group, did, message, now])?;
Ok(())
}
/// `did`'s request to join `group`, while it waits.
pub fn asked(&self, group: &str, did: &str) -> Result<Option<JoinRequest>> {
let conn = self.conn();
let found = conn.query_row(ASKED, [group, did], join_request);
Ok(found.optional()?)
}
/// The requests waiting to join `group`, newest first, before `before`
/// (a sequence number), at most `limit`.
pub fn asking(&self, group: &str, before: Option<i64>, limit: u32) -> Result<Vec<JoinRequest>> {
let conn = self.conn();
let mut q = conn.prepare(ASKING)?;
let asked = params![group, before.unwrap_or(i64::MAX), limit];
let rows = q.query_map(asked, join_request)?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
/// Settles `did`'s request to join `group`: `false` if none waited.
pub fn decide(&self, group: &str, did: &str) -> Result<bool> {
let conn = self.conn();
Ok(conn.execute(DECIDE, [group, did])? > 0)
}
/// 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/joining.rsnew+351−0
@@ -0,0 +1,351 @@
//! Joining: at once, by request, or not without an invite; requests
//! listed, admitted, turned down and withdrawn.
mod common;
use common::groups::*;
use common::spaces::*;
use common::{Running, start};
use serde_json::{Value as Json, json};
const NS: &str = "fyi.opensocial";
async fn call(h: &Running, who: &Authority, method: &str, body: Json) -> (u16, Json) {
let lxm = format!("{NS}.{method}");
post(h, &lxm, &body, &[auth(h, who, &lxm)]).await
}
async fn ask(h: &Running, who: &Authority, method: &str, query: &str) -> (u16, Json) {
let lxm = format!("{NS}.{method}");
get(h, &lxm, query, &[auth(h, who, &lxm)]).await
}
fn error(said: &(u16, Json)) -> (u16, &str) {
(said.0, said.1["error"].as_str().unwrap_or_default())
}
async fn group(h: &Running, founder: &Authority, policy: &str) -> String {
start_group(
h,
founder,
json!({"handle": RIDERS, "displayName": "Riders", "joinPolicy": policy}),
)
.await
}
#[tokio::test]
async fn an_open_group_admits_at_once() {
let h = start(&[], false).await;
let [alice, bob, _] = people(&h).await;
let did = group(&h, &alice, "open").await;
// Its default roles, or member when none is marked.
assert_eq!(
call(&h, &bob, "requestJoin", json!({"group": did})).await,
(200, json!({"status": "admitted"}))
);
assert_eq!(h.host.roles(&did, &bob.did).unwrap(), ["member"]);
assert_eq!(
error(&call(&h, &bob, "requestJoin", json!({"group": did})).await),
(400, "AlreadyMember")
);
// A request made before the group opened is gone once they are in.
let eve = authority(&h, false, true).await;
h.host.store.ask(&did, &eve.did, None, 0).unwrap();
call(&h, &eve, "requestJoin", json!({"group": did})).await;
assert_eq!(h.host.store.asked(&did, &eve.did).unwrap(), None);
// Those marked default are what the next gets.
call(
&h,
&alice,
"putRole",
json!({"group": did, "role": "rider", "name": "Rider", "actions": [], "default": true}),
)
.await;
let carol = authority(&h, false, true).await;
call(&h, &carol, "requestJoin", json!({"group": did})).await;
assert_eq!(h.host.roles(&did, &carol.did).unwrap(), ["member", "rider"]);
// With none marked, member.
for role in ["member", "rider"] {
call(
&h,
&alice,
"putRole",
json!({"group": did, "role": role, "name": role, "actions": [], "default": false}),
)
.await;
}
let dave = authority(&h, false, true).await;
call(&h, &dave, "requestJoin", json!({"group": did})).await;
assert_eq!(h.host.roles(&did, &dave.did).unwrap(), ["member"]);
}
#[tokio::test]
async fn an_invite_only_group_needs_an_invite() {
let h = start(&[], false).await;
let [alice, bob, _] = people(&h).await;
let did = group(&h, &alice, "invite").await;
assert_eq!(
error(&call(&h, &bob, "requestJoin", json!({"group": did})).await),
(400, "InviteRequired")
);
for body in [json!({}), json!({"group": "did:plc:nobody"})] {
assert_eq!(call(&h, &bob, "requestJoin", body).await.0, 400);
}
h.host.deactivate_account(&did, &alice.did, &[]).unwrap();
assert_eq!(
error(&call(&h, &bob, "requestJoin", json!({"group": did})).await),
(400, "RepoDeactivated")
);
}
#[tokio::test]
async fn a_group_that_approves_its_members_keeps_requests() {
let h = start(&[], false).await;
let [alice, bob, carol] = people(&h).await;
let did = group(&h, &alice, "approval").await;
let asked = call(
&h,
&bob,
"requestJoin",
json!({"group": did, "message": "I ride too."}),
)
.await;
assert_eq!(asked, (200, json!({"status": "pending"})));
// Asked twice, still one.
call(
&h,
&bob,
"requestJoin",
json!({"group": did, "message": "Again"}),
)
.await;
call(&h, &carol, "requestJoin", json!({"group": did})).await;
// Each sees their own.
let (_, mine) = ask(&h, &bob, "getJoinRequest", &format!("group={did}")).await;
assert_eq!(
(
mine["request"]["did"].clone(),
mine["request"]["message"].clone()
),
(json!(bob.did), json!("I ride too."))
);
let dave = authority(&h, false, true).await;
assert_eq!(
ask(&h, &dave, "getJoinRequest", &format!("group={did}")).await,
(200, json!({}))
);
// And getGroup shows it to them, and all of them to whoever admits.
let lxm = format!("{NS}.getGroup");
let (_, theirs) = get(&h, &lxm, &format!("group={did}"), &[auth(&h, &bob, &lxm)]).await;
assert_eq!(theirs["group"]["viewer"]["request"]["did"], bob.did);
let (_, admins) = get(&h, &lxm, &format!("group={did}"), &[auth(&h, &alice, &lxm)]).await;
let waiting: Vec<&str> = admins["joinRequests"]
.as_array()
.unwrap()
.iter()
.map(|r| r["actor"]["did"].as_str().unwrap())
.collect();
assert_eq!(waiting, [carol.did.as_str(), bob.did.as_str()]);
// Listed for one who may admit, newest first, a page at a time.
let (_, page) = ask(
&h,
&alice,
"listJoinRequests",
&format!("group={did}&limit=1"),
)
.await;
assert_eq!(page["requests"][0]["did"], carol.did);
let cursor = page["cursor"].as_str().unwrap();
let (_, rest) = ask(
&h,
&alice,
"listJoinRequests",
&format!("group={did}&cursor={cursor}"),
)
.await;
assert_eq!(
(rest["requests"][0]["did"].clone(), rest["cursor"].clone()),
(json!(bob.did), Json::Null)
);
assert_eq!(
error(&ask(&h, &bob, "listJoinRequests", &format!("group={did}")).await),
(403, "Forbidden")
);
assert_eq!(
error(
&ask(
&h,
&alice,
"listJoinRequests",
&format!("group={did}&cursor=x")
)
.await
),
(400, "InvalidRequest")
);
// Admitted with the defaults, or the roles named that the admitter may give.
let said = call(
&h,
&alice,
"admitMember",
json!({"group": did, "did": bob.did, "roles": [{"role": "admin"}]}),
)
.await;
assert_eq!(error(&said), (400, "NotAssignable"));
assert_eq!(
call(
&h,
&alice,
"admitMember",
json!({"group": did, "did": bob.did})
)
.await,
(200, json!({}))
);
assert_eq!(h.host.roles(&did, &bob.did).unwrap(), ["member"]);
assert_eq!(
ask(&h, &bob, "getJoinRequest", &format!("group={did}"))
.await
.1,
json!({})
);
assert_eq!(
error(
&call(
&h,
&alice,
"admitMember",
json!({"group": did, "did": bob.did})
)
.await
),
(400, "JoinRequestNotFound")
);
// A request gone stale, its asker a member another way: refused,
// and gone.
let eve = authority(&h, false, true).await;
call(&h, &eve, "requestJoin", json!({"group": did})).await;
h.host
.space_write(
&did,
&group_host::group::members_space(&did),
&[group_host::repo::Write::Create {
collection: format!("{NS}.membership"),
rkey: eve.did.clone(),
value: json!({"$type": format!("{NS}.membership"), "member": eve.did, "roles": [{"role": "member"}], "createdAt": "2026-11-03T00:00:00Z"}),
}],
)
.await
.unwrap();
let said = call(
&h,
&alice,
"admitMember",
json!({"group": did, "did": eve.did}),
)
.await;
assert_eq!(error(&said), (400, "AlreadyMember"));
assert_eq!(
ask(&h, &eve, "getJoinRequest", &format!("group={did}"))
.await
.1,
json!({})
);
// Nobody is admitted with no roles.
let said = call(
&h,
&alice,
"admitMember",
json!({"group": did, "did": carol.did, "roles": []}),
)
.await;
assert_eq!(error(&said), (400, "InvalidRequest"));
// A message is as long as the lexicon says.
let frank = authority(&h, false, true).await;
let long = "x".repeat(301);
let said = call(
&h,
&frank,
"requestJoin",
json!({"group": did, "message": long}),
)
.await;
assert_eq!(error(&said), (400, "InvalidRequest"));
// A member who may not admit, may not.
let said = call(
&h,
&bob,
"admitMember",
json!({"group": did, "did": carol.did}),
)
.await;
assert_eq!(error(&said), (403, "Forbidden"));
let said = call(
&h,
&alice,
"admitMember",
json!({"group": did, "did": carol.did, "roles": [{"role": "member"}]}),
)
.await;
assert_eq!(said.0, 200);
// Turned down, as if never asked: they may ask again.
call(&h, &dave, "requestJoin", json!({"group": did})).await;
assert_eq!(
call(
&h,
&alice,
"denyJoinRequest",
json!({"group": did, "member": dave.did})
)
.await,
(200, json!({}))
);
assert_eq!(
ask(&h, &dave, "getJoinRequest", &format!("group={did}"))
.await
.1,
json!({})
);
assert_eq!(
error(
&call(
&h,
&alice,
"denyJoinRequest",
json!({"group": did, "member": dave.did})
)
.await
),
(400, "JoinRequestNotFound")
);
// Or withdrawn by its asker.
call(&h, &dave, "requestJoin", json!({"group": did})).await;
assert_eq!(
call(&h, &dave, "cancelJoinRequest", json!({"group": did})).await,
(200, json!({}))
);
assert_eq!(
error(&call(&h, &dave, "cancelJoinRequest", json!({"group": did})).await),
(400, "JoinRequestNotFound")
);
for (who, method, body) in [
(&alice, "admitMember", json!({"group": did})),
(&alice, "denyJoinRequest", json!({"group": did})),
(&dave, "cancelJoinRequest", json!({})),
] {
assert_eq!(
error(&call(&h, who, method, body).await),
(400, "InvalidRequest"),
"{method}"
);
}
// A member's getGroup has no request of theirs.
let (_, members) = get(&h, &lxm, &format!("group={did}"), &[auth(&h, &bob, &lxm)]).await;
assert_eq!(members["group"]["viewer"].get("request"), None);
}
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.createInvite", host.1)),
http.post(format!("{}/xrpc/fyi.opensocial.applyLabel", host.1)),
] {
let res = req.send().await.unwrap();
assert_eq!(res.status(), 501);
docs/design/membership.md+22−0
@@ -33,6 +33,28 @@ configure it keeps that (`LastConfigurer`), and stays.
- `leaveGroup` takes the caller out. The last member able to configure
the group may not leave (`LastConfigurer`).
## Joining
How people get in is the group's profile's `joinPolicy`:
- `open`: `requestJoin` admits them at once, with the roles the group
marks default (`member`, unless it marks others).
- `approval`: `requestJoin` keeps their request, with what they say, for
one holding `admit`. `listJoinRequests` lists those waiting, newest
first; `getGroup` shows them to whoever may admit, and to the asker
their own. `admitMember` admits one, with the defaults or the roles
named, each one the admitter may give (admitting gives roles, so it
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.
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.
## Out is out
A member put out, or leaving, reads the group's spaces no more:
docs/design/README.md+3−3
@@ -91,9 +91,9 @@ says otherwise.
invites.)
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`.
(`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`.
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+11−1
@@ -40,7 +40,17 @@
"type": "object",
"properties": {}
}
}
},
"errors": [
{
"name": "JoinRequestNotFound",
"description": "No request from that account is waiting."
},
{
"name": "NotAssignable",
"description": "A role asked for is not the caller's to give."
}
]
}
}
}
lexicons/fyi/opensocial/cancelJoinRequest.json+7−1