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

Each role carries its own grant, and admins may give every role

Merged chadtmiller.com asked to merge into feature/proposal-nov from chadtmiller.com/group-host:roles/grants
crates/group-host/src/app_passwords.rs+3−12
@@ -15,13 +15,12 @@
use crate::Host;
use crate::api::{Params, invalid, param};
use crate::group::members_space;
use crate::group_api::{group_of, signed_in};
use crate::limits::{Client, SESSIONS, key};
use crate::oauth_dpop::hmac;
use crate::oauth_resource::{Acting, Refusal};
use crate::oauth_store::{AppPassword, Grant, Tokens, app_password_client};
use crate::rbac::{NS, grants, repo_collections_for};
use crate::rbac::{NS, repo_collections_for};
use crate::scopes::Permissions;
use crate::time::{iso, now_millis};
use crate::xrpc::XrpcError;
@@ -83,16 +82,8 @@ impl Host {
/// anything as it, every repo collection.
pub fn may_issue(&self, group: &str, member: &str) -> Result<bool, XrpcError> {
let roles = self.roles(group, member).map_err(XrpcError::internal)?;
let permissions = self.group_record(
group,
&members_space(group),
&format!("{NS}.permissions"),
"self",
);
let permissions = permissions
.map_err(XrpcError::internal)?
.unwrap_or_default();
Ok(repo_collections_for(&grants(&permissions), &roles).contains("*"))
let granted = self.role_grants(group).map_err(XrpcError::internal)?;
Ok(repo_collections_for(&granted, &roles).contains("*"))
}
/// Whether a session's app password still stands: there, and its
crates/group-host/src/group.rs+32−14
@@ -1,12 +1,12 @@
//! Groups: an account here with two spaces of its own, `meta` (its
//! profile, rules and labeler, for whoever it lets read them) and
//! `members` (its roles, what each may do, its memberships and the index
//! of its spaces, for its members). Everything a group is lives in those
//! records, written by the group; who may read or write each space is its
//! access record, against the reader's roles.
//! `members` (its roles, each with what it may do, its memberships and
//! the index of its spaces, for its members). Everything a group is lives
//! in those records, written by the group; who may read or write each
//! space is its access record, against the reader's roles.
use crate::Host;
use crate::rbac::{ACTIONS, Grant, NS, PUBLIC, roles_of};
use crate::rbac::{ACTIONS, EVERY_ROLE, Grant, NS, PUBLIC, grants, roles_of};
use crate::repo::{Write, invalid};
use crate::store::Record;
use crate::time::{iso, now_millis};
@@ -32,6 +32,22 @@ pub fn did_rkey(did: &str) -> String {
did.replace("%3A", ":")
}
/// The DID a record key made by [`did_rkey`] is of: a did:web whose host
/// is followed by a port, all digits, has it encoded again.
pub fn rkey_did(rkey: &str) -> String {
let Some((host, after)) = rkey
.strip_prefix("did:web:")
.and_then(|r| r.split_once(':'))
else {
return rkey.to_string();
};
let (port, path) = after.split_at(after.find(':').unwrap_or(after.len()));
if port.is_empty() || !port.bytes().all(|b| b.is_ascii_digit()) {
return rkey.to_string();
}
format!("did:web:{host}%3A{port}{path}")
}
/// What the labeler every group starts with says: the labels the host
/// acts on, and reports about accounts and records, appeals among them.
fn labeler(at: &str) -> Value {
@@ -224,8 +240,9 @@ impl Host {
put(&c("access"), "self", meta_access(readers)),
];
self.space_write(&did, &meta, &meta_writes).await?;
let admin = Grant::with("admin", &ACTIONS, &["admin", "member"], &["*"]);
let member = Grant::with("member", &[], &[], &[]);
// Its founders run it, holding every action, writing any record as
// it and giving any role; everyone else is a member.
let admin = Grant::with("admin", &ACTIONS, &[EVERY_ROLE], &["*"]);
let mut members_writes = vec![
put(
&c("access"),
@@ -235,18 +252,13 @@ impl Host {
put(
&c("role"),
"admin",
json!({"$type": c("role"), "displayName": "Admin", "description": "Runs the group.", "createdAt": at}),
json!({"$type": c("role"), "displayName": "Admin", "description": "Runs the group.", "scopes": admin.scopes, "assignable": admin.assignable, "createdAt": at}),
),
put(
&c("role"),
"member",
json!({"$type": c("role"), "displayName": "Member", "default": true, "createdAt": at}),
),
put(
&c("permissions"),
"self",
json!({"$type": c("permissions"), "grants": [admin.to_json(), member.to_json()], "createdAt": at}),
),
];
// The index of the group's spaces, which apps read to find them.
for space in [&meta, &members] {
@@ -260,7 +272,7 @@ impl Host {
members_writes.push(put(
&c("membership"),
&did_rkey(steward),
json!({"$type": c("membership"), "member": steward, "roles": ["admin", "member"], "createdAt": at}),
json!({"$type": c("membership"), "roles": ["admin", "member"], "createdAt": at}),
));
}
self.space_write(&did, &members, &members_writes).await?;
@@ -329,6 +341,12 @@ impl Host {
let membership = self.group_record(group, &members, &membership, &did_rkey(did))?;
Ok(membership.map(|m| roles_of(&m)).unwrap_or_default())
}
/// The group-wide grant of each of `group`'s roles, by its record.
pub fn role_grants(&self, group: &str) -> Result<Vec<Grant>> {
let roles = self.group_records(group, &members_space(group), &format!("{NS}.role"))?;
Ok(grants(&roles))
}
}
fn json_of(record: &Record) -> Value {
crates/group-host/src/group_api.rs+5−7
@@ -6,8 +6,8 @@
use crate::Host;
use crate::api::{Params, page, param};
use crate::group::{Made, NewGroup, members_space, meta_space};
use crate::rbac::{Access, NS, actions_for, grants, listed, repo_collections_for, roles_of};
use crate::group::{Made, NewGroup, members_space, meta_space, rkey_did};
use crate::rbac::{Access, NS, actions_for, listed, repo_collections_for, roles_of};
use crate::space_api::{service_caller, unauthorized};
use crate::xrpc::XrpcError;
use axum::Json;
@@ -236,8 +236,7 @@ pub async fn get_group(
};
let reads_meta = reads(&meta)?;
let reads_members = reads(&members)?;
let permissions = record(&members, "permissions", "self")?.unwrap_or_default();
let granted = grants(&permissions);
let granted = host.role_grants(group).map_err(XrpcError::internal)?;
let actions = actions_for(&granted, &roles);
let mut view = base(&host, group, &handle)?;
@@ -390,9 +389,8 @@ pub async fn list_members(
// read at once rather than in turn, until a page and one are found.
let mut found: Vec<(String, Value)> = Vec::new();
for some in left.chunks(limit + 1) {
let actors = some
.iter()
.map(|(_, m)| host.actor_view(m["member"].as_str().unwrap_or_default()));
let dids: Vec<String> = some.iter().map(|(k, _)| rkey_did(k)).collect();
let actors = dids.iter().map(|did| host.actor_view(did));
let actors = futures::future::join_all(actors).await;
for ((rkey, m), actor) in some.iter().zip(actors) {
let named = |at: &str| actor[at].as_str().unwrap_or_default().to_lowercase();
crates/group-host/src/group_config.rs+6−12
@@ -8,8 +8,8 @@
use crate::Host;
use crate::api::invalid;
use crate::blobs::PROFILE_IMAGES;
use crate::group::{join_policy, members_space, meta_space};
use crate::rbac::{Access, NS, actions_for, grants, roles_of};
use crate::group::{join_policy, members_space, meta_space, rkey_did};
use crate::rbac::{Access, NS, actions_for, roles_of};
use crate::repo::Write;
use crate::xrpc::XrpcError;
use atproto::Cid;
@@ -50,28 +50,22 @@ impl Host {
/// Whether `did`'s roles in `group` carry `action`.
pub fn may_do(&self, group: &str, did: &str, action: &str) -> Result<bool, XrpcError> {
let members = members_space(group);
let permissions = self
.group_record(group, &members, &format!("{NS}.permissions"), "self")
.map_err(XrpcError::internal)?;
let granted = self.role_grants(group).map_err(XrpcError::internal)?;
let roles = self.roles(group, did).map_err(XrpcError::internal)?;
Ok(actions_for(&grants(&permissions.unwrap_or_default()), &roles).contains(action))
Ok(actions_for(&granted, &roles).contains(action))
}
/// Everyone whose roles in `group` carry `group.configure`.
pub fn configurers(&self, group: &str) -> Result<Vec<String>, XrpcError> {
let members = members_space(group);
let permissions = self
.group_record(group, &members, &format!("{NS}.permissions"), "self")
.map_err(XrpcError::internal)?;
let granted = grants(&permissions.unwrap_or_default());
let granted = self.role_grants(group).map_err(XrpcError::internal)?;
let memberships = self
.group_records(group, &members, &format!("{NS}.membership"))
.map_err(XrpcError::internal)?;
Ok(memberships
.iter()
.filter(|(_, m)| actions_for(&granted, &roles_of(m)).contains("group.configure"))
.filter_map(|(_, m)| m["member"].as_str().map(String::from))
.map(|(k, _)| rkey_did(k))
.collect())
}
}
crates/group-host/src/group_members.rs+6−9
@@ -14,7 +14,7 @@ use crate::Host;
use crate::group::{did_rkey, members_space};
use crate::group_api::{group_of, signed_in};
use crate::group_config::put_in;
use crate::rbac::{Grant, NS, actions_for, actions_of, grants, roles_of};
use crate::rbac::{Grant, NS, actions_for, actions_of, roles_of};
use crate::repo::Write;
use crate::time::{iso, now_millis};
use crate::xrpc::XrpcError;
@@ -35,7 +35,7 @@ fn forbidden(message: impl Into<String>) -> XrpcError {
XrpcError::new(StatusCode::FORBIDDEN, "Forbidden", message)
}
/// A group's members space, its grants, and its records there.
/// A group's members space, its roles' grants, and its records there.
pub(crate) struct Members<'a> {
pub host: &'a Host,
pub group: String,
@@ -46,14 +46,12 @@ pub(crate) struct Members<'a> {
impl<'a> Members<'a> {
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")
.map_err(XrpcError::internal)?;
let grants = host.role_grants(group).map_err(XrpcError::internal)?;
Ok(Members {
host,
group: group.into(),
space,
grants: grants(&permissions.unwrap_or_default()),
grants,
})
}
@@ -111,7 +109,6 @@ impl<'a> Members<'a> {
}
let membership = json!({
"$type": format!("{NS}.membership"),
"member": did,
"roles": held,
"createdAt": iso(now_millis()),
});
@@ -136,8 +133,8 @@ impl<'a> Members<'a> {
.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))
let others = self.records("membership")?.into_iter().any(|(k, m)| {
k != did_rkey(who) && roles_of(&m).iter().any(|r| configuring.contains(r))
});
if others {
return Ok(());
crates/group-host/src/lexicons.rs+0−1
@@ -98,7 +98,6 @@ pub const FILES: &[&str] = &[
lexicon!("fyi/opensocial/migrateReceive"),
lexicon!("fyi/opensocial/moderate"),
lexicon!("fyi/opensocial/participate"),
lexicon!("fyi/opensocial/permissions"),
lexicon!("fyi/opensocial/profile"),
lexicon!("fyi/opensocial/provisionGroup"),
lexicon!("fyi/opensocial/putLabelDefinition"),
crates/group-host/src/mcp.rs+3−3
@@ -860,11 +860,11 @@ impl Host {
undo,
} => {
let members = crate::group::members_space(&who.group);
let collection = format!("{NS}.permissions");
let kept = self.group_record(&who.group, &members, &collection, "self");
let collection = format!("{NS}.role");
let kept = self.group_record(&who.group, &members, &collection, &role);
let kept = kept.map_err(XrpcError::internal).map_err(said)?;
let kept = kept.unwrap_or_default();
let write = group_host_mcp::regrant(&kept, &role, &scopes, &assignable, undo);
let write = group_host_mcp::regrant(&kept, &role, &scopes, &assignable, undo)?;
Box::pin(self.carry_out(who, write)).await
}
}
crates/group-host/src/member_writes.rs+114−157
@@ -1,15 +1,16 @@
//! The members space's records, written as the group with a token: its
//! roles, what each may do (the permissions record), and who holds which
//! roles, each with what it may do across the group, and who holds which
//! (memberships). The host makes each write only as it keeps the group
//! whole, and does what the write means.
//!
//! - A role is a key of 64 characters at most. It goes only once nobody
//! holds it and the permissions record grants it nothing.
//! - The permissions record is the configurers'. In it a writer changes
//! the grants only of roles they may assign, adds no scope their own
//! roles do not hold, and lets no role assign one they may not. A new
//! role, which nobody holds and no grant names, is theirs to grant and
//! to list.
//! holds it.
//! - Roles are the configurers'. In a role a writer changes the grant
//! (its scopes and `assignable`) only of a role they may assign, or one
//! the batch makes; adds no scope their own roles do not hold, a
//! permission set as the scopes it lists; and lets the role assign only
//! roles they may assign. `*` in `assignable` is every role, those made
//! later too, and only one who may assign every role may give it.
//! - Writing a membership for someone waiting to join admits them, with
//! roles the writer's `admit` grants may give, and their request goes.
//! Writing one for a member changes their roles, each one added or taken
@@ -29,17 +30,18 @@
use crate::Host;
use crate::api::invalid;
use crate::group::did_rkey;
use crate::group::{did_rkey, rkey_did};
use crate::group_members::Members;
use crate::moderation::Event;
use crate::oauth_resource::Acting;
use crate::oauth_scope::{scopes_of, set_of};
use crate::rbac::{Grant, NS, actions_for, actions_of, roles_of};
use crate::rbac::{EVERY_ROLE, Grant, NS, actions_for, actions_of, assigns, roles_of};
use crate::repo::Write;
use crate::scopes::covers;
use crate::time::now_millis;
use crate::xrpc::XrpcError;
use atproto::space::SpaceRef;
use atproto::syntax::is_did;
use axum::http::StatusCode;
use serde_json::Value;
use std::collections::{BTreeMap, BTreeSet};
@@ -56,23 +58,18 @@ const ROLE_KEY_AT_MOST: usize = 64;
fn kind(write: &Write) -> Option<&'static str> {
let (collection, _) = write.path();
let name = collection.strip_prefix(NS)?.strip_prefix('.')?;
["role", "permissions", "membership"]
.into_iter()
.find(|k| *k == name)
["role", "membership"].into_iter().find(|k| *k == name)
}
/// What a holder of `roles` may write in the members space, as the group,
/// by collection: roles and the permissions record if they configure the
/// group; memberships as they may admit (create), give roles (update) and
/// put out (delete).
/// by collection: roles if they configure the group; memberships as they
/// may admit (create), give roles (update) and put out (delete).
pub fn members_writes(grants: &[Grant], roles: &[String]) -> BTreeMap<String, BTreeSet<String>> {
let actions = actions_for(grants, roles);
let mut out: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
if actions.contains("group.configure") {
for c in ["role", "permissions"] {
let all = ["create", "update", "delete"].map(String::from);
out.insert(format!("{NS}.{c}"), all.into());
}
let all = ["create", "update", "delete"].map(String::from);
out.insert(format!("{NS}.role"), all.into());
}
let by = [
("admit", "create"),
@@ -109,74 +106,68 @@ pub(crate) fn own_scopes(
}
/// The roles holders of `roles` may give or take, for `action`, or for
/// any if none is named.
fn assignable(grants: &[Grant], roles: &[String], action: Option<&str>) -> BTreeSet<String> {
/// any if none is named: `*` among them for every role.
pub(crate) fn assignable(
grants: &[Grant],
roles: &[String],
action: Option<&str>,
) -> BTreeSet<String> {
let theirs = grants.iter().filter(|g| roles.contains(&g.role));
let doing = theirs.filter(|g| action.is_none_or(|a| actions_of(&g.scopes).contains(a)));
doing.flat_map(|g| g.assignable.iter().cloned()).collect()
}
/// The scopes `scope` is, a permission set of ours as those it lists.
fn expanded(scope: &str) -> Vec<String> {
pub(crate) fn expanded(scope: &str) -> Vec<String> {
match set_of(scope) {
Some(set) => scopes_of(set),
None => vec![scope.to_string()],
}
}
/// The scopes holders of `roles` hold across the group, each permission
/// set as the scopes it lists.
pub(crate) fn held(grants: &[Grant], roles: &[String]) -> Vec<String> {
let theirs = grants.iter().filter(|g| roles.contains(&g.role));
theirs
.flat_map(|g| g.scopes.iter().flat_map(|s| expanded(s)))
.collect()
}
/// The members space as the writes of a batch leave it.
#[derive(Clone)]
struct Book {
roles: BTreeSet<String>,
grants: Vec<Grant>,
/// Each membership by its key: whose it is, and their roles.
members: BTreeMap<String, (String, Vec<String>)>,
/// Each role by its key, and its grant.
roles: BTreeMap<String, Grant>,
/// Each membership by its key, its member's DID: their roles.
members: BTreeMap<String, Vec<String>>,
}
impl Book {
fn of(members: &Members) -> Result<Book, XrpcError> {
let roles = members.records("role")?.into_iter().map(|(k, _)| k);
let held = members.records("membership")?.into_iter().map(|(k, m)| {
let did = m["member"].as_str().unwrap_or_default().to_string();
(k, (did, roles_of(&m)))
});
let roles = members.grants.iter().map(|g| (g.role.clone(), g.clone()));
let held = members.records("membership")?.into_iter();
Ok(Book {
roles: roles.collect(),
grants: members.grants.clone(),
members: held.collect(),
members: held.map(|(k, m)| (k, roles_of(&m))).collect(),
})
}
/// Whether anyone holds a role that configures the group.
fn run(&self) -> bool {
let configuring: BTreeSet<&String> = self
.grants
.iter()
.filter(|g| actions_of(&g.scopes).contains("group.configure"))
.map(|g| &g.role)
.collect();
let holds = |roles: &Vec<String>| roles.iter().any(|r| configuring.contains(r));
self.members.values().any(|(_, roles)| holds(roles))
}
/// The roles defined that nobody holds and no grant names: new, and
/// so anyone's who configures the group to grant and to give.
fn fresh(&self) -> BTreeSet<String> {
let named = |r: &String| {
let granted = self
.grants
.iter()
.any(|g| &g.role == r || g.assignable.contains(r));
granted || self.members.values().any(|(_, roles)| roles.contains(r))
let configuring = |r: &String| {
let grant = self.roles.get(r);
grant.is_some_and(|g| actions_of(&g.scopes).contains("group.configure"))
};
self.roles.iter().filter(|r| !named(r)).cloned().collect()
let mut held = self.members.values().flatten();
held.any(configuring)
}
/// Refuses `roles` unless each is defined.
fn defined<'a>(&self, roles: impl IntoIterator<Item = &'a String>) -> Result<(), XrpcError> {
let undefined: Vec<&String> = roles
.into_iter()
.filter(|r| !self.roles.contains(*r))
.filter(|r| !self.roles.contains_key(*r))
.collect();
if !undefined.is_empty() {
return Err(invalid(format!("no such roles: {undefined:?}")));
@@ -195,10 +186,10 @@ struct Writer<'a> {
impl Writer<'_> {
/// Refuses a membership whose key is not its member's DID, or which
/// leaves out `member`.
/// leaves out `member`: their DID, and their roles.
fn membership(&self, rkey: &str, value: &Value) -> Result<(String, Vec<String>), XrpcError> {
let did = value["member"].as_str().unwrap_or_default().to_string();
if did_rkey(&did) != rkey {
let did = rkey_did(rkey);
if !is_did(&did) || did_rkey(&did) != rkey {
return Err(invalid("a membership is kept at its member's DID"));
}
let roles = roles_of(value);
@@ -219,7 +210,7 @@ impl Writer<'_> {
action: &str,
) -> Result<(), XrpcError> {
let mine = assignable(self.grants, self.roles, Some(action));
let blocked: Vec<&String> = changed.into_iter().filter(|r| !mine.contains(*r)).collect();
let blocked: Vec<&String> = changed.into_iter().filter(|r| !assigns(&mine, r)).collect();
if !blocked.is_empty() {
return Err(bad(
"NotAssignable",
@@ -229,72 +220,53 @@ impl Writer<'_> {
Ok(())
}
/// Refuses a new permissions record, in place of `was`, that changes a
/// grant of a role the writer may not assign, adds a scope their roles
/// do not hold, or lets a role assign one they may not.
fn permissions(
/// Refuses a write of the role `key`, its grant `was` before and `now`
/// after (none for none, as one made or deleted), that changes the
/// grant of a role the writer may not assign unless the batch makes
/// it (`new`), adds a scope their roles do not hold, or lets the role
/// assign one they may not. The roles it lets the role assign anew.
fn role(
&self,
was: &[Grant],
now: &[Grant],
fresh: &BTreeSet<String>,
key: &str,
was: Option<&Grant>,
now: Option<&Grant>,
new: bool,
) -> Result<Vec<String>, XrpcError> {
let mut seen = BTreeSet::new();
if let Some(twice) = now.iter().find(|g| !seen.insert(&g.role)) {
return Err(invalid(format!(
"one grant for each role: {} has two",
twice.role
)));
let none = Grant::of(key, &Value::Null);
let (before, after) = (was.unwrap_or(&none), now.unwrap_or(&none));
if (&before.scopes, &before.assignable) == (&after.scopes, &after.assignable) {
return Ok(Vec::new());
}
let union = assignable(self.grants, self.roles, None);
let mine = |r: &String| union.contains(r) || fresh.contains(r);
let held: Vec<String> = self
.grants
.iter()
.filter(|g| self.roles.contains(&g.role))
.flat_map(|g| g.scopes.iter().flat_map(|s| expanded(s)))
.collect();
let find = |grants: &[Grant], role: &str| grants.iter().find(|g| g.role == role).cloned();
let roles: BTreeSet<&String> = was.iter().chain(now).map(|g| &g.role).collect();
let mut named = Vec::new();
for role in roles {
let (before, after) = (find(was, role), find(now, role));
if before == after {
continue;
}
if !mine(role) {
if !new && !assigns(&union, key) {
return Err(bad(
"NotAssignable",
format!("not yours to change: {key}'s grant"),
));
}
let held = held(self.grants, self.roles);
let added = after.scopes.iter().filter(|s| !before.scopes.contains(s));
for scope in added {
let covered = expanded(scope).iter().all(|s| covers(&held, s, self.group));
if !covered {
return Err(bad(
"NotAssignable",
format!("not yours to change: {role}'s grant"),
"ScopeNotHeld",
format!("your roles do not hold {scope}, to give it"),
));
}
let Some(after) = after else { continue };
let before = before.unwrap_or(Grant {
role: role.clone(),
scopes: Vec::new(),
assignable: Vec::new(),
});
let added = after.scopes.iter().filter(|s| !before.scopes.contains(s));
for scope in added {
let covered = expanded(scope).iter().all(|s| covers(&held, s, self.group));
if !covered {
return Err(bad(
"ScopeNotHeld",
format!("your roles do not hold {scope}, to give it"),
));
}
}
let listed = after
.assignable
.iter()
.filter(|r| !before.assignable.contains(r));
let listed: Vec<&String> = listed.collect();
if let Some(r) = listed.iter().find(|r| !mine(r)) {
return Err(bad("NotAssignable", format!("not yours to give: {r}")));
}
named.push(role.clone());
named.extend(listed.into_iter().cloned());
}
Ok(named)
let listed = after.assignable.iter();
let listed: Vec<&String> = listed.filter(|r| !before.assignable.contains(r)).collect();
// Every role only from one who may give every role.
let mine = |r: &&String| match r.as_str() {
EVERY_ROLE => union.contains(EVERY_ROLE),
_ => assigns(&union, r),
};
if let Some(r) = listed.iter().find(|r| !mine(r)) {
return Err(bad("NotAssignable", format!("not yours to give: {r}")));
}
let named = listed.into_iter().filter(|r| *r != EVERY_ROLE);
Ok(named.cloned().collect())
}
}
@@ -334,35 +306,26 @@ impl Host {
let (_, rkey) = w.path();
match (kind(w), w) {
(Some("role"), Write::Delete { .. }) => {
book.roles.remove(rkey);
let was = book.roles.remove(rkey);
let new = !before.roles.contains_key(rkey);
writer.role(rkey, was.as_ref(), None, new)?;
}
(Some("role"), _) => {
(Some("role"), Write::Create { value, .. } | Write::Update { value, .. }) => {
if rkey.len() > ROLE_KEY_AT_MOST {
return Err(invalid(format!(
"a role is a key of {ROLE_KEY_AT_MOST} characters at most"
)));
}
book.roles.insert(rkey.to_string());
}
(Some("permissions"), Write::Delete { .. }) => {
return Err(invalid("the group keeps its permissions"));
}
(
Some("permissions"),
Write::Create { value, .. } | Write::Update { value, .. },
) => {
if rkey != "self" {
return Err(invalid("the permissions record is kept at self"));
}
let now = crate::rbac::grants(value);
let names = writer.permissions(&book.grants, &now, &book.fresh())?;
let now = Grant::of(rkey, value);
let new = !before.roles.contains_key(rkey);
let names = writer.role(rkey, book.roles.get(rkey), Some(&now), new)?;
named.extend(names);
book.grants = now;
book.roles.insert(rkey.to_string(), now);
}
// The rest are memberships: the members space takes no other
// record of ours (`guard`).
(_, Write::Delete { .. }) => {
let (_, theirs) = book.members.remove(rkey).unwrap_or_default();
let theirs = book.members.remove(rkey).unwrap_or_default();
writer.may_give(&theirs, "eject")?;
}
(_, Write::Create { value, .. }) => {
@@ -376,33 +339,29 @@ impl Host {
}
book.defined(&roles)?;
writer.may_give(&roles, "admit")?;
book.members.insert(rkey.to_string(), (did, roles));
book.members.insert(rkey.to_string(), roles);
}
(_, Write::Update { value, .. }) => {
let (did, roles) = writer.membership(rkey, value)?;
let (_, roles) = writer.membership(rkey, value)?;
book.defined(&roles)?;
let (_, current) = book.members.get(rkey).cloned().unwrap_or_default();
let current = book.members.get(rkey).cloned().unwrap_or_default();
let added = roles.iter().filter(|r| !current.contains(r));
let taken = current.iter().filter(|r| !roles.contains(r));
writer.may_give(added.chain(taken), "role.assign")?;
book.members.insert(rkey.to_string(), (did, roles));
book.members.insert(rkey.to_string(), roles);
}
}
}
// A role goes only once nothing holds or grants it.
for gone in before.roles.difference(&book.roles) {
let held = book.members.values().any(|(_, r)| r.contains(gone));
let granted = book.grants.iter().any(|g| &g.role == gone);
if held || granted {
let what = if held {
"someone holds it"
} else {
"it still has a grant"
};
return Err(bad("RoleInUse", format!("{gone} stays while {what}")));
// A role goes only once nobody holds it.
for gone in before.roles.keys().filter(|r| !book.roles.contains_key(*r)) {
if book.members.values().any(|r| r.contains(gone)) {
return Err(bad(
"RoleInUse",
format!("{gone} stays while someone holds it"),
));
}
}
// A grant changed is of a role defined, and gives roles defined.
// A role is let assign only roles defined.
book.defined(&named)?;
if before.run() && !book.run() {
return Err(bad(
@@ -431,11 +390,10 @@ impl Host {
for w in deletes.filter(|w| kind(w) == Some("membership")) {
let (collection, rkey) = w.path();
let record = self.group_record(group, uri, collection, rkey);
let Some(record) = record.map_err(XrpcError::internal)? else {
if record.map_err(XrpcError::internal)?.is_none() {
continue;
};
let did = record["member"].as_str().unwrap_or(rkey);
out.insert(rkey.to_string(), did.to_string());
}
out.insert(rkey.to_string(), rkey_did(rkey));
gone.push(w.clone());
}
// Asked of the deletes alone: the write asks again of them all.
@@ -474,9 +432,8 @@ impl Host {
let noted = self.store.moderate(group, member, &event);
noted.map_err(XrpcError::internal)?;
}
Write::Create { value, .. } | Write::Update { value, .. } => {
let did = value["member"].as_str().unwrap_or_default();
let decided = self.store.decide(group, did);
Write::Create { rkey, .. } | Write::Update { rkey, .. } => {
let decided = self.store.decide(group, &rkey_did(rkey));
decided.map_err(XrpcError::internal)?;
}
}
crates/group-host/src/oauth_scope.rs+2−11
@@ -12,7 +12,7 @@
use crate::Host;
use crate::group::members_space;
use crate::lexicons::lexicons;
use crate::rbac::{self, Access, LABEL, NS, actions_for, grants, repo_collections_for};
use crate::rbac::{self, Access, LABEL, NS, actions_for, repo_collections_for};
use crate::scopes::{decoded, is_blob, repo_collections};
use crate::xrpc::XrpcError;
use atproto::space::SpaceRef;
@@ -248,16 +248,7 @@ impl Host {
member: &str,
requested: &[String],
) -> Result<Vec<String>, XrpcError> {
let permissions = self
.group_record(
group,
&members_space(group),
&format!("{NS}.permissions"),
"self",
)
.map_err(XrpcError::internal)?
.unwrap_or_default();
let grants = grants(&permissions);
let grants = self.role_grants(group).map_err(XrpcError::internal)?;
let repo = repo_collections_for(&grants, roles);
let everything = repo.contains("*");
let held = actions_for(&grants, roles);
crates/group-host/src/rbac.rs+27−30
@@ -1,12 +1,12 @@
//! What a group's records let each of its people do, as pure functions
//! over those records: a space's access record says who reads it and who
//! writes in it; the permissions record grants each role OAuth scopes, and
//! each action the host's methods ask about is answered by one scope.
//! Roles compose by union: no deny, no precedence, no hierarchy.
//! writes in it; each role record grants its role OAuth scopes across the
//! group, and 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}`, `{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.
//! The records' lists are of objects (`{role}`, `{did}`), but for a
//! role's scopes and assignable roles, and a membership's roles, which
//! are strings alone, as the proposal has them.
use crate::scopes::{Permissions, decoded};
use atproto::space::SpaceRef;
@@ -293,8 +293,11 @@ pub fn actions_of(scopes: &[String]) -> BTreeSet<&'static str> {
out
}
/// A role's grant in the permissions record: its scopes and the roles its
/// holders may assign.
/// Every role, as a role's `assignable` names them: those made later too.
pub const EVERY_ROLE: &str = "*";
/// A role's group-wide grant, as its record has it: its scopes and the
/// roles its holders may assign.
#[derive(Debug, Clone, PartialEq)]
pub struct Grant {
pub role: String,
@@ -314,31 +317,25 @@ impl Grant {
}
}
/// As the permissions record keeps it (`defs#groupGrant`).
pub fn to_json(&self) -> Value {
serde_json::json!({
"role": self.role,
"scopes": self.scopes,
"assignable": self.assignable,
})
/// The grant of the role `role` keys, by its `record`.
pub fn of(role: &str, record: &Value) -> Grant {
Grant {
role: role.into(),
scopes: strings(&record["scopes"]),
assignable: strings(&record["assignable"]),
}
}
}
/// The grants a permissions record holds.
pub fn grants(permissions: &Value) -> Vec<Grant> {
permissions["grants"]
.as_array()
.map(|grants| {
grants
.iter()
.map(|g| Grant {
role: g["role"].as_str().unwrap_or_default().into(),
scopes: strings(&g["scopes"]),
assignable: strings(&g["assignable"]),
})
.collect()
})
.unwrap_or_default()
/// Whether `assignable`, a union of roles' lists, covers `role`: by
/// naming it, or every role.
pub fn assigns(assignable: &BTreeSet<String>, role: &str) -> bool {
assignable.contains(EVERY_ROLE) || assignable.contains(role)
}
/// The grants of a group's role records, each with its key.
pub fn grants(roles: &[(String, Value)]) -> Vec<Grant> {
roles.iter().map(|(key, r)| Grant::of(key, r)).collect()
}
/// Every action a holder of `roles` has, by union.
crates/group-host/src/token_writes.rs+11−19
crates/group-host/tests/common/members.rs+11−21
crates/group-host/tests/actors.rs+1−1
crates/group-host/tests/app_passwords.rs+7−16
crates/group-host/tests/authorization.rs+1−1
crates/group-host/tests/group_config.rs+1−1
crates/group-host/tests/group_spaces.rs+1−1
crates/group-host/tests/group_tokens.rs+5−5
crates/group-host/tests/groups.rs+30−6
crates/group-host/tests/index.rs+1−1
crates/group-host/tests/invites.rs+1−1
crates/group-host/tests/joining.rs+17−63
crates/group-host/tests/lifecycle.rs+1−1
crates/group-host/tests/mcp.rs+23−11
crates/group-host/tests/members.rs+185−201
crates/group-host/tests/moderation.rs+4−5
crates/group-host/tests/oauth.rs+1−1
crates/group-host/tests/oauth_scope.rs+22−37
crates/group-host/tests/rbac.rs+52−11
crates/group-host/tests/sites.rs+3−3
crates/group-host/tests/tokens.rs+1−11
crates/group-host-mcp/src/lib.rs+64−85
crates/group-host-mcp/tests/protocol.rs+47−42
crates/opensocial/src/lib.rs+20−54
crates/opensocial/tests/commands.rs+38−40
docs/design/groups.md+15−14
docs/design/mcp.md+3−3
docs/design/membership.md+32−33
docs/design/signing-in.md+9−10
docs/guides/shots/rules-create-role-dark.png+0−0
A binary file, not shown.
docs/guides/shots/rules-create-role.png+0−0
A binary file, not shown.
docs/guides/shots/rules-create-role.txt+2−0
docs/guides/shots/rules-give-dark.png+0−0
A binary file, not shown.
docs/guides/shots/rules-member-dark.png+0−0
A binary file, not shown.
docs/guides/rules-and-roles.md+7−5
docs/guides/signing-in-as-a-group.md+3−2
docs/reference/api.md+9−8
docs/reference/cli.md+5−5
docs/reference/mcp.md+4−4
examples/kicker/harness/seed.mjs+0−1
harness/look/seeds/nightshift-poster.mjs+3−5
harness/lexicons.mjs+19−11
lexicons/fyi/opensocial/configure.json+1−1
lexicons/fyi/opensocial/defs.json+1−41
lexicons/fyi/opensocial/members.json+1−2
lexicons/fyi/opensocial/membership.json+4−9
lexicons/fyi/opensocial/permissions.jsondeleted+0−32
lexicons/fyi/opensocial/role.json+24−2
web/src/lib/organisms/RolesEditor.svelte+8−3
web/src/lib/server/settings.ts+19−65
web/src/lib/actions.ts+2−2
web/src/lib/activity.ts+0−1
web/src/routes/g/[handle]/settings/roles/+page.svelte+8−1
web/src/routes/g/[handle]/+page.server.ts+1−1
web/src/routes/g/[handle]/+page.svelte+11−12