chadtmiller.com/group-host
atmosphere group host
0
0
Roles, permissions and memberships are written as the group
crates/group-host/src/assistants.rs+1−1
| @@ -719,7 +719,7 @@ impl Host { | ||
let group = &who.group; | ||
let uri = format!("at://{group}/space/{}/self", asked.space); | ||
let space = SpaceRef::parse(&uri).expect("a group's own space is a space"); | ||
let (_, scope) = self.group_scope(group, &who.member, &uri, &space)?; | ||
let (_, _, scope) = self.group_scope(group, &who.member, &uri, &space)?; | ||
let now = now_millis(); | ||
let grant = Grant { | ||
id: who.id.clone(), | ||
crates/group-host/src/group.rs+1−1
| @@ -216,7 +216,7 @@ impl Host { | ||
put(&c("access"), "self", meta_access(readers)), | ||
]; | ||
self.space_write(&did, &meta, &meta_writes).await?; | ||
let admin = Grant::with("admin", &ACTIONS, &["member"], &["*"]); | ||
let admin = Grant::with("admin", &ACTIONS, &["admin", "member"], &["*"]); | ||
let member = Grant::with("member", &[], &[], &[]); | ||
let mut members_writes = vec![ | ||
put( | ||
crates/group-host/src/group_api.rs+1−0
| @@ -279,6 +279,7 @@ pub async fn get_group( | ||
("displayName", "name"), | ||
("description", "description"), | ||
("bot", "bot"), | ||
("default", "default"), | ||
] { | ||
if let Some(v) = r.get(from) { | ||
role[to] = v.clone(); | ||
crates/group-host/src/group_join.rs+3−51
| @@ -1,7 +1,8 @@ | ||
//! 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`. | ||
//! `invite`. A request is granted by writing the asker's membership as | ||
//! the group (`member_writes.rs`), and turned down by `denyJoinRequest`. | ||
//! | ||
//! 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 | ||
| @@ -14,7 +15,7 @@ use crate::group::meta_space; | ||
use crate::group_api::{group_of, signed_in}; | ||
use crate::group_invites::invite_uri; | ||
use crate::group_members::{Members, acting}; | ||
use crate::rbac::{NS, listed}; | ||
use crate::rbac::NS; | ||
use crate::store::JoinRequest; | ||
use crate::time::{iso, now_millis}; | ||
use crate::xrpc::XrpcError; | ||
| @@ -152,55 +153,6 @@ pub async fn list_join_requests( | ||
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().expect("its lexicon requires it"); | ||
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")); | ||
} | ||
members.defined(&roles)?; | ||
// The roles an admitter may give are those their `admit` grants may. | ||
let assignable = members.assignable(&mine, "admit"); | ||
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>>, | ||
crates/group-host/src/group_members.rs+41−324
| @@ -1,24 +1,19 @@ | ||
//! A group's roles and who holds them: defining a role and what it may | ||
//! do, giving people roles, putting someone out, and leaving. | ||
//! A group's members space as the host reads it, and leaving a group. | ||
//! | ||
//! Roles and memberships are records in the members space, written by the | ||
//! group, so the host writes them for a caller whose roles allow it. A | ||
//! group never loses its last way to be run: the last role able to | ||
//! configure it keeps that, and its last holder may not leave. | ||
//! Roles and memberships are records in the members space, written as the | ||
//! group (`member_writes.rs` says how). The host writes a membership | ||
//! itself only for one who joins. A group never loses its last way to be | ||
//! run: the last member able to configure it may not leave. | ||
//! | ||
//! Someone who stops being a member reads its spaces no more: the | ||
//! credentials they hold are revoked, and the index forgets what they | ||
//! wrote there. | ||
//! credentials they hold are revoked, the apps they signed in as the group | ||
//! end, and the index forgets what they wrote there. | ||
| ||
use crate::Host; | ||
use crate::api::invalid; | ||
use crate::group::{did_rkey, members_space}; | ||
use crate::group_api::{group_of, signed_in}; | ||
use crate::group_config::put_in; | ||
use crate::moderation::Event; | ||
use crate::rbac::{ | ||
ACTIONS, Grant, NS, actions_for, actions_of, grants, listed, roles_of, scope_of, | ||
}; | ||
use crate::rbac::{Grant, NS, actions_for, actions_of, grants, roles_of}; | ||
use crate::repo::Write; | ||
use crate::time::{iso, now_millis}; | ||
use crate::xrpc::XrpcError; | ||
| @@ -85,15 +80,6 @@ impl<'a> Members<'a> { | ||
actions_for(&self.grants, roles).contains(action) | ||
} | ||
| ||
/// The roles holders of `roles` may give or take for `action`. | ||
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)) | ||
.flat_map(|g| g.assignable.iter().cloned()) | ||
.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> { | ||
| @@ -141,32 +127,18 @@ impl<'a> Members<'a> { | ||
Ok(written) | ||
} | ||
| ||
/// Refuses `roles` unless the group defines each. | ||
pub(crate) fn defined(&self, roles: &[String]) -> Result<(), XrpcError> { | ||
let defined: BTreeSet<String> = self.records("role")?.into_iter().map(|(k, _)| k).collect(); | ||
let undefined: Vec<&String> = roles.iter().filter(|r| !defined.contains(*r)).collect(); | ||
if !undefined.is_empty() { | ||
return Err(invalid(format!("no such roles: {undefined:?}"))); | ||
} | ||
Ok(()) | ||
} | ||
| ||
/// Whether any member holds one of `roles`. | ||
fn held(&self, roles: &BTreeSet<String>) -> Result<bool, XrpcError> { | ||
let memberships = self.records("membership")?; | ||
let holds = |m: &Value| roles_of(m).iter().any(|r| roles.contains(r)); | ||
Ok(memberships.iter().any(|(_, m)| holds(m))) | ||
} | ||
| ||
/// 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> { | ||
let configuring = self.configuring(); | ||
let theirs = roles.iter().any(|r| configuring.contains(r)); | ||
/// Refuses `who` leaving if nobody else could configure the group. | ||
fn keeps_a_configurer(&self, who: &str) -> Result<(), XrpcError> { | ||
let configuring: BTreeSet<String> = self | ||
.grants | ||
.iter() | ||
.filter(|g| actions_of(&g.scopes).contains("group.configure")) | ||
.map(|g| g.role.clone()) | ||
.collect(); | ||
let others = self.records("membership")?.into_iter().any(|(_, m)| { | ||
m["member"] != who && roles_of(&m).iter().any(|r| configuring.contains(r)) | ||
}); | ||
if theirs || others { | ||
if others { | ||
return Ok(()); | ||
} | ||
Err(bad( | ||
| @@ -174,20 +146,6 @@ impl<'a> Members<'a> { | ||
"nobody would be left who can run this group: give that to someone else first", | ||
)) | ||
} | ||
| ||
/// The roles whose grant lets their holders configure the group. | ||
pub(crate) fn configuring(&self) -> BTreeSet<String> { | ||
self.grants | ||
.iter() | ||
.filter(|g| actions_of(&g.scopes).contains("group.configure")) | ||
.map(|g| g.role.clone()) | ||
.collect() | ||
} | ||
| ||
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())}) | ||
} | ||
} | ||
| ||
/// The group a body names and its members space, once the caller of | ||
| @@ -212,243 +170,23 @@ pub(crate) async fn acting<'a>( | ||
Ok((members, me, roles)) | ||
} | ||
| ||
/// Defines a role, or changes one: its name, words, whether its people | ||
/// are bots or every new member gets it, and what it may do. For one | ||
/// holding `group.configure`. | ||
pub async fn put_role( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
Json(body): Json<Value>, | ||
) -> Answer { | ||
let (members, _, _) = | ||
acting(&host, &headers, &body, "putRole", Some("group.configure")).await?; | ||
let role = body["role"].as_str().unwrap_or_default().trim(); | ||
if role.is_empty() || role.len() > 64 || !atproto::syntax::is_record_key(role) { | ||
return Err(invalid("role is a key of 64 characters at most")); | ||
} | ||
let name = body["name"].as_str().expect("its lexicon requires it"); | ||
let description = body["description"].as_str(); | ||
let actions: Vec<String> = body["actions"] | ||
.as_array() | ||
.expect("its lexicon requires it") | ||
.iter() | ||
.map(|a| a.as_str().unwrap_or_default().to_string()) | ||
.collect(); | ||
let unknown: Vec<&String> = actions | ||
.iter() | ||
.filter(|a| !ACTIONS.contains(&a.as_str())) | ||
.collect(); | ||
if !unknown.is_empty() { | ||
return Err(invalid(format!("unknown actions: {unknown:?}"))); | ||
} | ||
// A role giving up configuring the group leaves someone who still | ||
// may, or nobody could run it again. | ||
let mut configuring = members.configuring(); | ||
let gives_up = !actions.iter().any(|a| a == "group.configure"); | ||
if gives_up && configuring.remove(role) && !members.held(&configuring)? { | ||
return Err(bad( | ||
"LastConfigurer", | ||
"nobody else holds a role that configures the group: give one to someone first", | ||
)); | ||
} | ||
// The roles it may give, as asked, or as they were: each one the group | ||
// defines, or this one. | ||
let previous = members.grants.iter().find(|g| g.role == role); | ||
let assignable = match body.get("assignable") { | ||
Some(_) => listed(&body, "assignable", "role"), | ||
None => previous.map(|g| g.assignable.clone()).unwrap_or_default(), | ||
}; | ||
let others: Vec<String> = assignable.iter().filter(|r| *r != role).cloned().collect(); | ||
members.defined(&others)?; | ||
let collection = format!("{NS}.role"); | ||
let was = members | ||
.records("role")? | ||
.into_iter() | ||
.find(|(k, _)| k == role) | ||
.map(|(_, r)| r) | ||
.unwrap_or_default(); | ||
let mut record = | ||
json!({"$type": collection, "displayName": name, "createdAt": iso(now_millis())}); | ||
if let Some(d) = description { | ||
record["description"] = json!(d); | ||
} | ||
// Left out, whether it is given on joining, and whether its people | ||
// are bots, stay as they were. | ||
for flag in ["default", "bot"] { | ||
let kept = body[flag].as_bool().or(was[flag].as_bool()); | ||
if kept == Some(true) { | ||
record[flag] = json!(true); | ||
} | ||
} | ||
// Its grant: the actions as their scopes, beside any other scope it | ||
// held; its public-repo collections as asked, or as they were. | ||
let kept = previous.map(|g| g.scopes.clone()).unwrap_or_default(); | ||
let asked_collections = body | ||
.get("repoCollections") | ||
.map(|_| listed(&body, "repoCollections", "collection")); | ||
let mut scopes: Vec<String> = kept | ||
.into_iter() | ||
.filter(|s| actions_of(std::slice::from_ref(s)).is_empty()) | ||
.filter(|s| asked_collections.is_none() || !s.starts_with("repo:")) | ||
.collect(); | ||
scopes.extend(actions.iter().filter_map(|a| scope_of(a))); | ||
scopes.extend( | ||
asked_collections | ||
.unwrap_or_default() | ||
.iter() | ||
.map(|c| format!("repo:{c}")), | ||
); | ||
let grant = Grant { | ||
role: role.into(), | ||
scopes, | ||
assignable, | ||
}; | ||
let mut granted: Vec<Grant> = members | ||
.grants | ||
.iter() | ||
.filter(|g| g.role != role) | ||
.cloned() | ||
.collect(); | ||
granted.push(grant); | ||
let space = members.space.clone(); | ||
let put = put_in(&host, &members.group, &space, &collection, role, record); | ||
let answer = put.await?; | ||
let permissions = members.permissions(&granted); | ||
let permissions_collection = format!("{NS}.permissions"); | ||
let put = put_in( | ||
&host, | ||
&members.group, | ||
&space, | ||
&permissions_collection, | ||
"self", | ||
permissions, | ||
); | ||
let _written = put.await?; | ||
Ok(answer) | ||
} | ||
| ||
/// Takes a role away, once nobody holds it. For one holding | ||
/// `group.configure`. | ||
pub async fn delete_role( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
Json(body): Json<Value>, | ||
) -> Answer { | ||
let (members, _, _) = acting( | ||
&host, | ||
&headers, | ||
&body, | ||
"deleteRole", | ||
Some("group.configure"), | ||
) | ||
.await?; | ||
let role = body["role"].as_str().expect("its lexicon requires it"); | ||
let configuring = members.configuring(); | ||
if configuring.len() == 1 && configuring.contains(role) { | ||
return Err(bad( | ||
"LastConfigurer", | ||
"the only role that configures the group stays", | ||
)); | ||
} | ||
let held = members | ||
.records("membership")? | ||
.iter() | ||
.any(|(_, m)| roles_of(m).iter().any(|r| r == role)); | ||
if held { | ||
return Err(bad( | ||
"RoleInUse", | ||
format!("someone holds {role}: give them another first"), | ||
)); | ||
} | ||
let granted: Vec<Grant> = members | ||
.grants | ||
.iter() | ||
.filter(|g| g.role != role) | ||
.cloned() | ||
.collect(); | ||
let defined = members.records("role")?.iter().any(|(k, _)| k == role); | ||
if defined { | ||
let gone = Write::Delete { | ||
collection: format!("{NS}.role"), | ||
rkey: role.into(), | ||
}; | ||
host.space_write(&members.group, &members.space, &[gone]) | ||
.await?; | ||
} | ||
let permissions = members.permissions(&granted); | ||
let space = members.space.clone(); | ||
let permissions_collection = format!("{NS}.permissions"); | ||
let put = put_in( | ||
&host, | ||
&members.group, | ||
&space, | ||
&permissions_collection, | ||
"self", | ||
permissions, | ||
); | ||
let _written = put.await?; | ||
Ok(Json(json!({}))) | ||
} | ||
| ||
/// Gives a member the roles named, in place of theirs: each one added or | ||
/// taken away one the caller may give. Everyone in a group holds `member`, | ||
/// which goes only when they do. | ||
pub async fn assign_roles( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
Json(body): Json<Value>, | ||
) -> Answer { | ||
let (members, _, mine) = | ||
acting(&host, &headers, &body, "assignRoles", Some("role.assign")).await?; | ||
let member = body["member"].as_str().expect("its lexicon requires it"); | ||
let roles = listed(&body, "roles", "role"); | ||
let current = members | ||
.membership(member)? | ||
.ok_or_else(|| bad("NotAMember", format!("{member} is not a member")))?; | ||
if current.iter().any(|r| r == "member") && !roles.iter().any(|r| r == "member") { | ||
return Err(bad( | ||
"MemberRole", | ||
"everyone in the group holds member: to put someone out, eject them", | ||
)); | ||
} | ||
members.defined(&roles)?; | ||
let assignable = members.assignable(&mine, "role.assign"); | ||
let changed = roles | ||
.iter() | ||
.filter(|r| !current.contains(r)) | ||
.chain(current.iter().filter(|r| !roles.contains(r))); | ||
let blocked: Vec<&String> = changed.filter(|r| !assignable.contains(*r)).collect(); | ||
if !blocked.is_empty() { | ||
return Err(bad( | ||
"NotAssignable", | ||
format!("not yours to give or take: {blocked:?}"), | ||
)); | ||
} | ||
members.keeps_a_configurer(member, &roles)?; | ||
members.put_membership(member, &roles).await?; | ||
Ok(Json(json!({}))) | ||
} | ||
| ||
impl Host { | ||
/// Takes `member` out of `group`: their membership goes, their | ||
/// credentials are revoked, and the index forgets what they wrote. | ||
async fn put_out(&self, group: &str, member: &str) -> Result<(), XrpcError> { | ||
// Their credentials first: if that fails, they are still in, and | ||
// it may be asked again. | ||
/// Ends what `member` holds of `group`: the credentials they hold are | ||
/// revoked, the apps they signed in as the group end, and their app | ||
/// passwords go. | ||
pub(crate) async fn cut_off(&self, group: &str, member: &str) -> Result<(), XrpcError> { | ||
let revoked = self.revoke_credentials(group, member).await; | ||
revoked.map_err(XrpcError::internal)?; | ||
// And the apps they signed in as the group. | ||
let ended = self.store.revoke_member_grants(group, member); | ||
ended.map_err(XrpcError::internal)?; | ||
let dropped = self.store.drop_members_app_passwords(group, member); | ||
dropped.map_err(XrpcError::internal)?; | ||
let gone = Write::Delete { | ||
collection: format!("{NS}.membership"), | ||
rkey: did_rkey(member), | ||
}; | ||
let (space, gone) = (members_space(group), [gone]); | ||
let written = self.space_write(group, &space, &gone); | ||
written.await?; | ||
Ok(()) | ||
} | ||
| ||
/// Forgets, in the index of each of `group`'s spaces, what `member` | ||
/// wrote there. | ||
pub(crate) fn unindex_member(&self, group: &str, member: &str) -> Result<(), XrpcError> { | ||
for space in self.store.spaces_of(group).map_err(XrpcError::internal)? { | ||
self.store | ||
.unindex(&space, member) | ||
| @@ -456,42 +194,21 @@ impl Host { | ||
} | ||
Ok(()) | ||
} | ||
} | ||
| ||
/// Puts a member out of the group, for one holding `eject` whose roles may | ||
/// give or take each of theirs. | ||
pub async fn eject_member( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
Json(body): Json<Value>, | ||
) -> Answer { | ||
let (members, me, mine) = acting(&host, &headers, &body, "ejectMember", Some("eject")).await?; | ||
let member = body["member"].as_str().expect("its lexicon requires it"); | ||
let reason = body["reason"].as_str(); | ||
let theirs = members | ||
.membership(member)? | ||
.ok_or_else(|| bad("NotAMember", format!("{member} is not a member")))?; | ||
let assignable = members.assignable(&mine, "eject"); | ||
let blocked: Vec<&String> = theirs.iter().filter(|r| !assignable.contains(*r)).collect(); | ||
if !blocked.is_empty() { | ||
return Err(bad( | ||
"NotAssignable", | ||
format!("cannot put out a holder of {blocked:?}"), | ||
)); | ||
/// Takes `member` out of `group`: what they hold of it ended first, so | ||
/// that if that fails they are still in and may ask again; then their | ||
/// membership, and what they wrote, forgotten. | ||
async fn put_out(&self, group: &str, member: &str) -> Result<(), XrpcError> { | ||
self.cut_off(group, member).await?; | ||
let gone = Write::Delete { | ||
collection: format!("{NS}.membership"), | ||
rkey: did_rkey(member), | ||
}; | ||
let (space, gone) = (members_space(group), [gone]); | ||
let written = self.space_write(group, &space, &gone); | ||
written.await?; | ||
self.unindex_member(group, member) | ||
} | ||
members.keeps_a_configurer(member, &[])?; | ||
host.put_out(&members.group, member).await?; | ||
// Kept in the group's queue, on them, for its moderators to read. | ||
let event = Event { | ||
kind: "eject".into(), | ||
actor: Some(me), | ||
reason: reason.map(str::to_string), | ||
created_at: now_millis(), | ||
..Event::default() | ||
}; | ||
let noted = host.store.moderate(&members.group, member, &event); | ||
noted.map_err(XrpcError::internal)?; | ||
Ok(Json(json!({}))) | ||
} | ||
| ||
/// Leaves the group. Its last member able to configure it may not: nobody | ||
| @@ -505,7 +222,7 @@ pub async fn leave_group( | ||
if members.membership(&me)?.is_none() { | ||
return Err(bad("NotAMember", "you are not a member")); | ||
} | ||
members.keeps_a_configurer(&me, &[])?; | ||
members.keeps_a_configurer(&me)?; | ||
host.put_out(&members.group, &me).await?; | ||
Ok(Json(json!({}))) | ||
} | ||
crates/group-host/src/group_tokens.rs+20−9
| @@ -16,6 +16,7 @@ use crate::api::{Params, invalid, param}; | ||
use crate::group::members_space; | ||
use crate::group_api::{group_of, signed_in}; | ||
use crate::group_invites::{inviting_scope, is_inbox}; | ||
use crate::member_writes::own_scopes; | ||
use crate::oauth_resource::Refusal; | ||
use crate::oauth_scope::writes_in; | ||
use crate::oauth_store::{Grant, Tokens}; | ||
| @@ -84,9 +85,10 @@ impl Host { | ||
/// `member`: its scope, and the kinds of record it writes there and in | ||
/// the group's repo. | ||
fn space_auth(&self, group: &str, member: &str, space: &SpaceRef) -> Authed { | ||
let (writes, scope) = self.group_scope(group, member, &space.to_string(), space)?; | ||
let collections: Vec<String> = writes.keys().cloned().collect(); | ||
Ok((scope, collections.clone(), collections)) | ||
let (writes, own, scope) = self.group_scope(group, member, &space.to_string(), space)?; | ||
let published: Vec<String> = writes.keys().cloned().collect(); | ||
let collections = published.iter().chain(own.keys()).cloned().collect(); | ||
Ok((scope, collections, published)) | ||
} | ||
| ||
/// What a group token for `inbox`, someone's, carries for `member`: | ||
| @@ -131,28 +133,37 @@ fn scopes_for(space: &SpaceRef, writes: &BTreeMap<String, BTreeSet<String>>) -> | ||
out | ||
} | ||
| ||
/// Kinds of record, each with the writes that may be made of it. | ||
type Writable = BTreeMap<String, BTreeSet<String>>; | ||
| ||
impl Host { | ||
/// What `member`'s roles in `group` may write as it in `space`, at | ||
/// `uri`: each kind of record with its writes, and the scope of a | ||
/// token for them. | ||
/// `uri`: each kind of record with its writes, as the space's access | ||
/// record grants them and, in the members space, as the group grants | ||
/// them its own records there; and the scope of a token for them. | ||
pub(crate) fn group_scope( | ||
&self, | ||
group: &str, | ||
member: &str, | ||
uri: &str, | ||
space: &SpaceRef, | ||
) -> Result<(BTreeMap<String, BTreeSet<String>>, String), XrpcError> { | ||
) -> Result<(Writable, Writable, String), XrpcError> { | ||
let roles = self.roles(group, member).map_err(XrpcError::internal)?; | ||
let access = self.group_record(group, uri, &format!("{NS}.access"), "self"); | ||
let access = access.map_err(XrpcError::internal)?.unwrap_or_default(); | ||
let everything = self.may_issue(group, member)?; | ||
let writes = writes_in(&Access::of(&access, uri), &roles, member, everything); | ||
if writes.is_empty() { | ||
let own = match uri == members_space(group) { | ||
true => self.members_writes_of(group, &roles)?, | ||
false => BTreeMap::new(), | ||
}; | ||
if writes.is_empty() && own.is_empty() { | ||
let none = "no role of yours may act as the group in this space"; | ||
return Err(forbidden(none)); | ||
} | ||
let scope = scopes_for(space, &writes).join(" "); | ||
Ok((writes, scope)) | ||
let mut scope = scopes_for(space, &writes); | ||
scope.extend(own_scopes(space, &own)); | ||
Ok((writes, own, scope.join(" "))) | ||
} | ||
} | ||
| ||
crates/group-host/src/lexicons.rs+0−5
| @@ -32,10 +32,8 @@ pub const FILES: &[&str] = &[ | ||
lexicon!("fyi/opensocial/access"), | ||
lexicon!("fyi/opensocial/activateGroup"), | ||
lexicon!("fyi/opensocial/addRecoveryKey"), | ||
lexicon!("fyi/opensocial/admitMember"), | ||
lexicon!("fyi/opensocial/applyLabel"), | ||
lexicon!("fyi/opensocial/approveAuthorization"), | ||
lexicon!("fyi/opensocial/assignRoles"), | ||
lexicon!("fyi/opensocial/cancelAccountMove"), | ||
lexicon!("fyi/opensocial/cancelJoinRequest"), | ||
lexicon!("fyi/opensocial/checkAddress"), | ||
| @@ -53,10 +51,8 @@ pub const FILES: &[&str] = &[ | ||
lexicon!("fyi/opensocial/declineInvite"), | ||
lexicon!("fyi/opensocial/defs"), | ||
lexicon!("fyi/opensocial/deleteGroup"), | ||
lexicon!("fyi/opensocial/deleteRole"), | ||
lexicon!("fyi/opensocial/deleteSpace"), | ||
lexicon!("fyi/opensocial/denyJoinRequest"), | ||
lexicon!("fyi/opensocial/ejectMember"), | ||
lexicon!("fyi/opensocial/finishAccountMove"), | ||
lexicon!("fyi/opensocial/getAccountMove"), | ||
lexicon!("fyi/opensocial/getActor"), | ||
| @@ -101,7 +97,6 @@ pub const FILES: &[&str] = &[ | ||
lexicon!("fyi/opensocial/permissions"), | ||
lexicon!("fyi/opensocial/profile"), | ||
lexicon!("fyi/opensocial/provisionGroup"), | ||
lexicon!("fyi/opensocial/putRole"), | ||
lexicon!("fyi/opensocial/removeRecoveryKey"), | ||
lexicon!("fyi/opensocial/requestJoin"), | ||
lexicon!("fyi/opensocial/resolveSubject"), | ||
crates/group-host/src/lib.rs+1−20
| @@ -32,6 +32,7 @@ pub mod index; | ||
pub mod index_api; | ||
pub mod lexicons; | ||
pub mod lifecycle; | ||
pub mod member_writes; | ||
pub mod migration; | ||
pub mod moderation; | ||
pub mod move_host; | ||
| @@ -252,22 +253,6 @@ 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), | ||
| @@ -284,10 +269,6 @@ pub fn router(host: Arc<Host>) -> Router { | ||
"/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), | ||
crates/group-host/src/member_writes.rsnew+484−0
484 lines changed: not loaded until asked for.
crates/group-host/src/oauth_scope.rs+7−2
| @@ -172,11 +172,16 @@ impl Host { | ||
.map_err(XrpcError::internal)? | ||
.unwrap_or_default(); | ||
let access = Access::of(&access, uri); | ||
let mut writable = writes_in(&access, roles, member, everything); | ||
// The members space's own records, as the group grants them. | ||
if uri == members_space(group) { | ||
writable.extend(self.members_writes_of(group, roles)?); | ||
} | ||
rooms.push(Room { | ||
kind: space.kind, | ||
skey: space.skey, | ||
readable: access.can_read(roles, member), | ||
writable: writes_in(&access, roles, member, everything), | ||
writable, | ||
}); | ||
} | ||
Ok(rooms) | ||
| @@ -395,7 +400,7 @@ pub fn concrete(granted: &[String], group: &str) -> String { | ||
| ||
/// The scopes a permission set lists: a space permission as a space | ||
/// scope, and an rpc one as a scope for each of its methods. | ||
fn scopes_of(set: &Value) -> Vec<String> { | ||
pub(crate) fn scopes_of(set: &Value) -> Vec<String> { | ||
let mut out = Vec::new(); | ||
for p in set["permissions"].as_array().into_iter().flatten() { | ||
let text = |k: &str| p[k].as_str().unwrap_or_default().to_string(); | ||
crates/group-host/src/rbac.rs+49−21
| @@ -4,9 +4,9 @@ | ||
//! each action the host's methods ask about is answered by one scope. | ||
//! Roles compose by union: no deny, no precedence, no hierarchy. | ||
//! | ||
//! The records' lists are of objects (`{role}`, `{scope}`), but for an | ||
//! access record's grants, whose scopes are strings, and a membership's | ||
//! roles, which are role ids alone, as the proposal has them. | ||
//! The records' lists are of objects (`{role}`, `{did}`), but for the | ||
//! scopes and assignable roles of a grant, and a membership's roles, | ||
//! which are strings alone, as the proposal has them. | ||
| ||
use crate::scopes::{Permissions, decoded}; | ||
use atproto::space::SpaceRef; | ||
| @@ -177,10 +177,7 @@ fn query_of(scope: &str, name: &str) -> Vec<String> { | ||
} | ||
| ||
/// The actions a host method's `rpc:` scope grants, by method. | ||
const BY_METHOD: [(&str, &str); 6] = [ | ||
("assignRoles", "role.assign"), | ||
("ejectMember", "eject"), | ||
("admitMember", "admit"), | ||
const BY_METHOD: [(&str, &str); 3] = [ | ||
("listSubjects", "mod.read"), | ||
("resolveSubject", "mod.resolve"), | ||
("applyLabel", "label"), | ||
| @@ -189,15 +186,18 @@ const BY_METHOD: [(&str, &str); 6] = [ | ||
/// The scope that grants each action. | ||
pub fn scope_of(action: &str) -> Option<String> { | ||
let rpc = |method: &str| format!("rpc:{NS}.{method}?aud=*"); | ||
let membership = |write: &str| { | ||
format!("space:{NS}.members?skey=self&collection={NS}.membership&action={write}") | ||
}; | ||
Some(match action { | ||
"group.configure" => format!("include:{NS}.configure"), | ||
"space.create" => "space:*?manage=create".into(), | ||
"space.delete" => "space:*?manage=delete".into(), | ||
"space.configure" => format!("space:*?collection={NS}.access"), | ||
"role.assign" => rpc("assignRoles"), | ||
"eject" => rpc("ejectMember"), | ||
"admit" => membership("create"), | ||
"role.assign" => membership("update"), | ||
"eject" => membership("delete"), | ||
"invite" => format!("space:{NS}.invites?authority=*&collection={NS}.invite"), | ||
"admit" => rpc("admitMember"), | ||
"mod.read" => rpc("listSubjects"), | ||
"mod.resolve" => rpc("resolveSubject"), | ||
"label" => rpc("applyLabel"), | ||
| @@ -216,13 +216,47 @@ fn query<'a>(scope: &'a str, name: &str) -> Vec<&'a str> { | ||
.collect() | ||
} | ||
| ||
/// What a space scope lets its holder do of writing memberships: `admit` | ||
/// for making one, `role.assign` for changing one, `eject` for deleting | ||
/// one, in the members space or in every space. | ||
fn membership_actions(scope: &str, out: &mut BTreeSet<&'static str>) { | ||
let Some(rest) = scope.strip_prefix("space:") else { | ||
return; | ||
}; | ||
let kind = rest.split('?').next().unwrap_or_default(); | ||
let members = kind == "*" || kind == format!("{NS}.members"); | ||
if !members || !query(scope, "manage").is_empty() { | ||
return; | ||
} | ||
let collections = query(scope, "collection"); | ||
let membership = format!("{NS}.membership"); | ||
let any = collections.is_empty() || collections.contains(&"*"); | ||
if !any && !collections.contains(&membership.as_str()) { | ||
return; | ||
} | ||
let named = query(scope, "action"); | ||
let writes = [ | ||
("create", "admit"), | ||
("update", "role.assign"), | ||
("delete", "eject"), | ||
]; | ||
for (write, action) in writes { | ||
if named.is_empty() || named.contains(&write) { | ||
out.insert(action); | ||
} | ||
} | ||
} | ||
| ||
/// What these scopes let their holder do. A scope that is none of the | ||
/// host's grants nothing. | ||
pub fn actions_of(scopes: &[String]) -> BTreeSet<&'static str> { | ||
let mut out = BTreeSet::new(); | ||
for scope in scopes { | ||
membership_actions(scope, &mut out); | ||
if *scope == format!("include:{NS}.configure") { | ||
out.insert("group.configure"); | ||
} else if *scope == format!("include:{NS}.manageMembers") { | ||
out.extend(["admit", "eject", "role.assign", "invite"]); | ||
} else if let Some(rpc) = scope.strip_prefix("rpc:") { | ||
let method = rpc.split('?').next().unwrap_or_default(); | ||
let action = BY_METHOD | ||
| @@ -282,18 +316,12 @@ impl Grant { | ||
} | ||
} | ||
| ||
/// As the permissions record keeps it. | ||
/// As the permissions record keeps it (`defs#groupGrant`). | ||
pub fn to_json(&self) -> Value { | ||
let objects = |field: &str, items: &[String]| -> Value { | ||
items | ||
.iter() | ||
.map(|i| serde_json::json!({ field: i })) | ||
.collect() | ||
}; | ||
serde_json::json!({ | ||
"role": self.role, | ||
"scopes": objects("scope", &self.scopes), | ||
"assignable": objects("role", &self.assignable), | ||
"scopes": self.scopes, | ||
"assignable": self.assignable, | ||
}) | ||
} | ||
} | ||
| @@ -307,8 +335,8 @@ pub fn grants(permissions: &Value) -> Vec<Grant> { | ||
.iter() | ||
.map(|g| Grant { | ||
role: g["role"].as_str().unwrap_or_default().into(), | ||
scopes: listed(g, "scopes", "scope"), | ||
assignable: listed(g, "assignable", "role"), | ||
scopes: strings(&g["scopes"]), | ||
assignable: strings(&g["assignable"]), | ||
}) | ||
.collect() | ||
}) | ||
crates/group-host/src/scopes.rs+87−0
crates/group-host/src/token_writes.rs+32−27
crates/group-host/tests/common/members.rsnew+155−0
crates/group-host/tests/common/mod.rs+1−0
crates/group-host/tests/app_passwords.rs+1−1
crates/group-host/tests/assistants.rs+84−14
crates/group-host/tests/group_tokens.rs+36−0
crates/group-host/tests/groups.rs+5−2
crates/group-host/tests/joining.rs+133−161
crates/group-host/tests/members.rs+520−317
837 lines changed: not loaded until asked for.