chadtmiller.com/group-host
atmosphere group host
0
0
Permission sets, limits and shapes are the opensocial proposal's
crates/group-host/src/authorization.rs+5−9
| @@ -9,7 +9,7 @@ use crate::api::{Params, param}; | ||
use crate::assistants; | ||
use crate::group::meta_space; | ||
use crate::group_api::{group_of, signed_in}; | ||
use crate::oauth_scope::{concrete, configure}; | ||
use crate::oauth_scope::{concrete, set_of}; | ||
use crate::oauth_store::Request; | ||
use crate::rbac::{Access, NS}; | ||
use crate::time::now_millis; | ||
| @@ -125,15 +125,11 @@ impl Host { | ||
} | ||
} | ||
| ||
/// What the configure permission set says it is for. | ||
/// What each of this host's permission sets asked for says it is for. | ||
fn labels(requested: &[String]) -> Value { | ||
let lexicon: Value = serde_json::from_str(include_str!( | ||
"../../../lexicons/fyi/opensocial/configure.json" | ||
)) | ||
.expect("the configure lexicon is JSON"); | ||
let text = &lexicon["defs"]["main"]["detail"]; | ||
let ours = requested.iter().filter(|s| **s == configure()); | ||
ours.map(|s| json!({"scope": s, "text": text})).collect() | ||
let ours = requested.iter().filter_map(|s| Some((s, set_of(s)?))); | ||
ours.map(|(s, set)| json!({"scope": s, "text": set["detail"]})) | ||
.collect() | ||
} | ||
| ||
/// An app's pending request to sign in as a group, as the caller would | ||
crates/group-host/src/group.rs+7−12
| @@ -6,7 +6,7 @@ | ||
//! access record, against the reader's roles. | ||
| ||
use crate::Host; | ||
use crate::rbac::{ACTIONS, Grant, NS, PUBLIC, listed}; | ||
use crate::rbac::{ACTIONS, Grant, NS, PUBLIC, roles_of}; | ||
use crate::repo::{Write, invalid}; | ||
use crate::store::Record; | ||
use crate::time::{iso, now_millis}; | ||
| @@ -46,14 +46,11 @@ fn labeler(at: &str) -> Value { | ||
}) | ||
} | ||
| ||
/// How a new group lets people in, as its profile says it: `open`, | ||
/// `approval` or `invite`, from either the profile's words or | ||
/// `createGroup`'s (`fyi.opensocial.profile#request`, …); `approval` | ||
/// unless it says. | ||
/// How a group lets people in, as its profile says it (`defs#joinPolicy`): | ||
/// `open`, `approval` or `invite`; `approval` unless it says. | ||
pub fn join_policy(asked: Option<&str>) -> Result<&'static str, XrpcError> { | ||
let word = asked.map(|a| a.rsplit('#').next().unwrap_or(a)); | ||
match word { | ||
None | Some("approval") | Some("request") => Ok("approval"), | ||
match asked { | ||
None | Some("approval") => Ok("approval"), | ||
Some("open") => Ok("open"), | ||
Some("invite") => Ok("invite"), | ||
Some(other) => Err(invalid(format!( | ||
| @@ -255,7 +252,7 @@ impl Host { | ||
members_writes.push(put( | ||
&c("membership"), | ||
&did_rkey(steward), | ||
json!({"$type": c("membership"), "member": steward, "roles": [{"role": "admin"}, {"role": "member"}], "createdAt": at}), | ||
json!({"$type": c("membership"), "member": steward, "roles": ["admin", "member"], "createdAt": at}), | ||
)); | ||
} | ||
self.space_write(&did, &members, &members_writes).await?; | ||
| @@ -322,9 +319,7 @@ impl Host { | ||
pub fn roles(&self, group: &str, did: &str) -> Result<Vec<String>> { | ||
let (members, membership) = (members_space(group), format!("{NS}.membership")); | ||
let membership = self.group_record(group, &members, &membership, &did_rkey(did))?; | ||
Ok(membership | ||
.map(|m| listed(&m, "roles", "role")) | ||
.unwrap_or_default()) | ||
Ok(membership.map(|m| roles_of(&m)).unwrap_or_default()) | ||
} | ||
} | ||
| ||
crates/group-host/src/group_api.rs+2−2
| @@ -7,7 +7,7 @@ | ||
use crate::Host; | ||
use crate::api::{Params, param}; | ||
use crate::group::{Made, NewGroup, members_space, meta_space}; | ||
use crate::rbac::{Access, NS, actions_for, grants, listed, repo_collections_for}; | ||
use crate::rbac::{Access, NS, actions_for, grants, listed, repo_collections_for, roles_of}; | ||
use crate::space_api::{service_caller, unauthorized}; | ||
use crate::xrpc::XrpcError; | ||
use axum::Json; | ||
| @@ -265,7 +265,7 @@ pub async fn get_group( | ||
out["members"] = memberships | ||
.iter() | ||
.zip(actors) | ||
.map(|((_, m), actor)| json!({"actor": actor, "roles": objects("role", listed(m, "roles", "role"))})) | ||
.map(|((_, m), actor)| json!({"actor": actor, "roles": objects("role", roles_of(m))})) | ||
.collect(); | ||
out["roles"] = records("role")? | ||
.into_iter() | ||
crates/group-host/src/group_config.rs+3−5
| @@ -7,7 +7,7 @@ use crate::api::{Params, invalid, param}; | ||
use crate::blobs::PROFILE_IMAGES; | ||
use crate::group::{join_policy, members_space, meta_space}; | ||
use crate::group_api::{group_of, signed_in}; | ||
use crate::rbac::{NS, actions_for, grants, listed}; | ||
use crate::rbac::{NS, actions_for, grants, roles_of}; | ||
use crate::repo::Write; | ||
use crate::time::{iso, now_millis}; | ||
use crate::xrpc::XrpcError; | ||
| @@ -22,7 +22,7 @@ use std::sync::Arc; | ||
type Answer = Result<Json<Value>, XrpcError>; | ||
| ||
/// The most bytes an image may be, as the profile's lexicon has it. | ||
pub const IMAGE_AT_MOST: usize = 1_000_000; | ||
pub const IMAGE_AT_MOST: usize = 2_000_000; | ||
| ||
/// Where a group meets: the places `community.lexicon.location` has. | ||
const PLACES: [&str; 4] = [ | ||
| @@ -84,9 +84,7 @@ impl Host { | ||
.map_err(XrpcError::internal)?; | ||
Ok(memberships | ||
.iter() | ||
.filter(|(_, m)| { | ||
actions_for(&granted, &listed(m, "roles", "role")).contains("group.configure") | ||
}) | ||
.filter(|(_, m)| actions_for(&granted, &roles_of(m)).contains("group.configure")) | ||
.filter_map(|(_, m)| m["member"].as_str().map(String::from)) | ||
.collect()) | ||
} | ||
crates/group-host/src/group_invites.rs+5−4
| @@ -41,7 +41,8 @@ pub fn inbox_of(did: &str) -> String { | ||
format!("at://{did}/space/{NS}.invites/self") | ||
} | ||
| ||
fn uri_of(invite: &Invite) -> String { | ||
/// Where `invite` is: the group's record in the invitee's inbox. | ||
pub(crate) fn invite_uri(invite: &Invite) -> String { | ||
format!( | ||
"{}/{}/{NS}.invite/{}", | ||
inbox_of(&invite.invitee), | ||
| @@ -52,7 +53,7 @@ fn uri_of(invite: &Invite) -> String { | ||
| ||
fn view(invite: &Invite) -> Value { | ||
let mut view = json!({ | ||
"uri": uri_of(invite), | ||
"uri": invite_uri(invite), | ||
"invitee": invite.invitee, | ||
"createdAt": iso(invite.created_at), | ||
}); | ||
| @@ -212,7 +213,7 @@ pub async fn create_invite( | ||
// One waiting is the one answered; one lapsed is taken back, and a | ||
// fresh one written. | ||
if let Some(waiting) = host.waiting_invite(&group, invitee).await? { | ||
return Ok(Json(json!({ "uri": uri_of(&waiting) }))); | ||
return Ok(Json(json!({ "uri": invite_uri(&waiting) }))); | ||
} | ||
let invite = Invite { | ||
seq: 0, | ||
| @@ -240,7 +241,7 @@ pub async fn create_invite( | ||
let written = host.space_write(&group, &inbox, std::slice::from_ref(&write)); | ||
written.await?; | ||
host.store.invite(&invite).map_err(XrpcError::internal)?; | ||
Ok(Json(json!({ "uri": uri_of(&invite) }))) | ||
Ok(Json(json!({ "uri": invite_uri(&invite) }))) | ||
} | ||
| ||
/// The group's invites waiting, newest first, for one holding `invite`. | ||
crates/group-host/src/group_join.rs+33−17
| @@ -12,6 +12,7 @@ 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_invites::invite_uri; | ||
use crate::group_members::{Members, acting}; | ||
use crate::rbac::{NS, listed}; | ||
use crate::store::JoinRequest; | ||
| @@ -33,18 +34,30 @@ fn no_request() -> XrpcError { | ||
bad("JoinRequestNotFound", "no request from them is waiting") | ||
} | ||
| ||
/// A request as a view shows it. | ||
/// A request as the lexicons' `joinRequest` has it. | ||
pub fn request_view(r: &JoinRequest) -> Value { | ||
let mut view = json!({"did": r.did, "createdAt": iso(r.created_at)}); | ||
let mut view = json!({"member": r.did, "createdAt": iso(r.created_at)}); | ||
if let Some(message) = &r.message { | ||
view["message"] = json!(message); | ||
} | ||
view | ||
} | ||
| ||
/// `did` admitted to `group` with its default roles, a request they made | ||
/// before waiting no more: the answer, naming their membership. | ||
async fn admitted(members: &Members<'_>, did: &str) -> Answer { | ||
let roles = members.default_roles()?; | ||
let membership = members.put_membership(did, &roles).await?; | ||
let decided = members.host.store.decide(&members.group, did); | ||
decided.map_err(XrpcError::internal)?; | ||
Ok(Json( | ||
json!({"status": "admitted", "membership": membership}), | ||
)) | ||
} | ||
| ||
/// 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. | ||
/// invites them. An invite admits them whatever the policy. | ||
pub async fn request_join( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
| @@ -58,35 +71,38 @@ pub async fn request_join( | ||
if members.membership(&me)?.is_some() { | ||
return Err(bad("AlreadyMember", "you are a member already")); | ||
} | ||
let waiting = host.waiting_invite(group, &me).await?; | ||
if let Some(named) = body["invite"].as_str() | ||
&& waiting.as_ref().is_none_or(|w| invite_uri(w) != named) | ||
{ | ||
return Err(bad( | ||
"InvalidInvite", | ||
"that invite is not one from this group to you, waiting", | ||
)); | ||
} | ||
// An invite is pre-approval: redeemed, whatever the policy. It is | ||
// taken back once they are a member, so a membership not written | ||
// leaves it waiting. | ||
if let Some(invite) = host.waiting_invite(group, &me).await? { | ||
let roles = members.default_roles()?; | ||
members.put_membership(&me, &roles).await?; | ||
if let Some(invite) = waiting { | ||
let answer = admitted(&members, &me).await?; | ||
host.take_back(&invite).await?; | ||
host.store.decide(group, &me).map_err(XrpcError::internal)?; | ||
return Ok(Json(json!({"status": "admitted"}))); | ||
return Ok(answer); | ||
} | ||
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")), | ||
Some("open") => admitted(&members, &me).await, | ||
Some("invite") => Err(bad("JoinClosed", "this group joins by invite")), | ||
_ => { | ||
let message = body["message"].as_str(); | ||
host.store | ||
.ask(group, &me, message, now_millis()) | ||
.map_err(XrpcError::internal)?; | ||
Ok(Json(json!({"status": "pending"}))) | ||
let asked = host.store.asked(group, &me).map_err(XrpcError::internal)?; | ||
let request = request_view(&asked.expect("the request just made")); | ||
Ok(Json(json!({"status": "pending", "request": request}))) | ||
} | ||
} | ||
} | ||
crates/group-host/src/group_members.rs+13−17
| @@ -16,7 +16,9 @@ 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, scope_of}; | ||
use crate::rbac::{ | ||
ACTIONS, Grant, NS, actions_for, actions_of, grants, listed, roles_of, scope_of, | ||
}; | ||
use crate::repo::Write; | ||
use crate::time::{iso, now_millis}; | ||
use crate::xrpc::XrpcError; | ||
| @@ -76,7 +78,7 @@ impl<'a> Members<'a> { | ||
&did_rkey(did), | ||
) | ||
.map_err(XrpcError::internal)?; | ||
Ok(record.map(|m| listed(&m, "roles", "role"))) | ||
Ok(record.map(|m| roles_of(&m))) | ||
} | ||
| ||
pub(crate) fn can(&self, roles: &[String], action: &str) -> bool { | ||
| @@ -109,12 +111,13 @@ impl<'a> Members<'a> { | ||
} | ||
| ||
/// Writes `did`'s membership, holding `roles`, and `member` among them | ||
/// whatever they name: everyone in the group holds it. | ||
/// whatever they name: everyone in the group holds it. Its `uri` and | ||
/// `cid`, as a strong reference names it. | ||
pub(crate) async fn put_membership( | ||
&self, | ||
did: &str, | ||
roles: &[String], | ||
) -> Result<(), XrpcError> { | ||
) -> Result<Value, XrpcError> { | ||
let mut held = roles.to_vec(); | ||
if !held.iter().any(|r| r == "member") { | ||
held.insert(0, "member".into()); | ||
| @@ -122,7 +125,7 @@ impl<'a> Members<'a> { | ||
let membership = json!({ | ||
"$type": format!("{NS}.membership"), | ||
"member": did, | ||
"roles": objects("role", &held), | ||
"roles": held, | ||
"createdAt": iso(now_millis()), | ||
}); | ||
let (collection, key) = (format!("{NS}.membership"), did_rkey(did)); | ||
| @@ -134,8 +137,8 @@ impl<'a> Members<'a> { | ||
&key, | ||
membership, | ||
); | ||
let _written = put.await?; | ||
Ok(()) | ||
let Json(written) = put.await?; | ||
Ok(written) | ||
} | ||
| ||
/// Refuses `roles` unless the group defines each. | ||
| @@ -151,7 +154,7 @@ impl<'a> Members<'a> { | ||
/// 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| listed(m, "roles", "role").iter().any(|r| roles.contains(r)); | ||
let holds = |m: &Value| roles_of(m).iter().any(|r| roles.contains(r)); | ||
Ok(memberships.iter().any(|(_, m)| holds(m))) | ||
} | ||
| ||
| @@ -161,10 +164,7 @@ impl<'a> Members<'a> { | ||
let configuring = self.configuring(); | ||
let theirs = roles.iter().any(|r| configuring.contains(r)); | ||
let others = self.records("membership")?.into_iter().any(|(_, m)| { | ||
m["member"] != who | ||
&& listed(&m, "roles", "role") | ||
.iter() | ||
.any(|r| configuring.contains(r)) | ||
m["member"] != who && roles_of(&m).iter().any(|r| configuring.contains(r)) | ||
}); | ||
if theirs || others { | ||
return Ok(()); | ||
| @@ -212,10 +212,6 @@ pub(crate) async fn acting<'a>( | ||
Ok((members, me, roles)) | ||
} | ||
| ||
fn objects(field: &str, items: &[String]) -> Value { | ||
items.iter().map(|i| json!({ field: i })).collect() | ||
} | ||
| ||
/// 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`. | ||
| @@ -357,7 +353,7 @@ pub async fn delete_role( | ||
let held = members | ||
.records("membership")? | ||
.iter() | ||
.any(|(_, m)| listed(m, "roles", "role").iter().any(|r| r == role)); | ||
.any(|(_, m)| roles_of(m).iter().any(|r| r == role)); | ||
if held { | ||
return Err(bad( | ||
"RoleInUse", | ||
crates/group-host/src/lexicons.rs+4−0
| @@ -87,6 +87,8 @@ pub const FILES: &[&str] = &[ | ||
lexicon!("fyi/opensocial/listRecoveryKeys"), | ||
lexicon!("fyi/opensocial/listSpaceRecords"), | ||
lexicon!("fyi/opensocial/listSubjects"), | ||
lexicon!("fyi/opensocial/manageMembers"), | ||
lexicon!("fyi/opensocial/manageSpaces"), | ||
lexicon!("fyi/opensocial/members"), | ||
lexicon!("fyi/opensocial/membership"), | ||
lexicon!("fyi/opensocial/meta"), | ||
| @@ -95,7 +97,9 @@ pub const FILES: &[&str] = &[ | ||
lexicon!("fyi/opensocial/migrateExport"), | ||
lexicon!("fyi/opensocial/migratePrepare"), | ||
lexicon!("fyi/opensocial/migrateReceive"), | ||
lexicon!("fyi/opensocial/moderate"), | ||
lexicon!("fyi/opensocial/negateLabel"), | ||
lexicon!("fyi/opensocial/participate"), | ||
lexicon!("fyi/opensocial/permissions"), | ||
lexicon!("fyi/opensocial/profile"), | ||
lexicon!("fyi/opensocial/provisionGroup"), | ||
crates/group-host/src/oauth_scope.rs+63−40
| @@ -3,13 +3,15 @@ | ||
//! group, then made concrete, so the token never depends on how a scope | ||
//! is read later. | ||
//! | ||
//! No lexicon is resolved: the only permission set a token keeps is this host's own | ||
//! (`fyi.opensocial.configure`), read from its lexicon here, and a space | ||
//! scope naming no collection keeps every one, which narrowing allowed | ||
//! only to roles that may write every one there. | ||
//! No lexicon is resolved: the only permission sets a token keeps are | ||
//! this host's own for a group's session (`fyi.opensocial.configure`, | ||
//! `manageMembers`, `manageSpaces`, `moderate`), read from their lexicons | ||
//! here, and a space scope naming no collection keeps every one, which | ||
//! narrowing allowed only to roles that may write every one there. | ||
| ||
use crate::Host; | ||
use crate::group::members_space; | ||
use crate::lexicons::lexicons; | ||
use crate::rbac::{self, Access, NS, actions_for, grants, repo_collections_for}; | ||
use crate::scopes::{decoded, is_blob, repo_collections}; | ||
use crate::xrpc::XrpcError; | ||
| @@ -19,9 +21,31 @@ use std::collections::{BTreeMap, BTreeSet}; | ||
| ||
pub use crate::rbac::WRITES; | ||
| ||
/// The permission set that lets an app configure the group. | ||
pub fn configure() -> String { | ||
format!("include:{NS}.configure") | ||
/// This host's permission sets for a group's session, each by its name, | ||
/// with the actions a member's roles must hold, every one, to give it. | ||
pub const SETS: [(&str, &[&str]); 4] = [ | ||
("configure", &["group.configure"]), | ||
( | ||
"manageMembers", | ||
&["admit", "eject", "role.assign", "invite"], | ||
), | ||
("manageSpaces", &["space.configure"]), | ||
("moderate", &["mod.read", "mod.resolve", "label"]), | ||
]; | ||
| ||
/// The permission set of this host's that `scope` includes, from its | ||
/// lexicon, if it is one: `include:fyi.opensocial.manageMembers`. | ||
pub fn set_of(scope: &str) -> Option<&'static Value> { | ||
let name = scope.strip_prefix(&format!("include:{NS}."))?; | ||
let set = lexicons().def(&format!("{NS}.{name}")); | ||
set.filter(|d| d["type"] == "permission-set") | ||
} | ||
| ||
/// The actions a member's roles must hold to give an app `scope`, if it | ||
/// is one of [`SETS`]. | ||
fn needs(scope: &str) -> Option<&'static [&'static str]> { | ||
let name = scope.strip_prefix(&format!("include:{NS}."))?; | ||
SETS.iter().find(|(n, _)| *n == name).map(|(_, a)| *a) | ||
} | ||
| ||
/// The parts of a `space:` scope that decide whether a role may have it. | ||
| @@ -179,7 +203,8 @@ impl Host { | ||
/// may give an app acting as the group: | ||
/// | ||
/// - `atproto`, always; | ||
/// - the configure permission set, for roles that configure the group; | ||
/// - one of this host's permission sets for a group's session, for | ||
/// roles holding every action it needs ([`SETS`]); | ||
/// - `repo:C`, for roles whose grants hold `repo:C` or `repo:*`; | ||
/// - `rpc:M`, a method of another service, for roles with `repo:*`, | ||
/// never one of this host's own; | ||
| @@ -210,15 +235,15 @@ impl Host { | ||
let grants = grants(&permissions); | ||
let repo = repo_collections_for(&grants, roles); | ||
let everything = repo.contains("*"); | ||
let configures = actions_for(&grants, roles).contains("group.configure"); | ||
let held = actions_for(&grants, roles); | ||
let rooms = self.rooms(group, roles, member, everything)?; | ||
let (mut kept, mut made) = (Vec::new(), Vec::new()); | ||
for s in requested { | ||
let space = SpaceScope::parse(s).filter(|w| w.for_group(group)); | ||
let keep = if s == "atproto" { | ||
true | ||
} else if *s == configure() { | ||
configures | ||
} else if let Some(needs) = needs(s) { | ||
needs.iter().all(|a| held.contains(a)) | ||
} else if let Some(named) = repo_collections(s) { | ||
let each = !named.is_empty() && named.iter().all(|c| repo.contains(c)); | ||
everything || each | ||
| @@ -238,7 +263,7 @@ impl Host { | ||
} | ||
} | ||
let writes = |s: &String| { | ||
*s == configure() | ||
needs(s).is_some() | ||
|| repo_collections(s).is_some() | ||
|| SpaceScope::parse(s).is_some_and(|w| !w.read_only) | ||
}; | ||
| @@ -330,16 +355,15 @@ fn any_kind(group: &str, want: &SpaceScope, rooms: &[Room]) -> Vec<String> { | ||
out | ||
} | ||
| ||
/// A granted scope as the token carries it: the configure set as the | ||
/// space scopes its lexicon lists, `authority=self` as the group, and a | ||
/// A granted scope as the token carries it: a permission set of ours as | ||
/// the scopes its lexicon lists, `authority=self` as the group, and a | ||
/// space scope naming no collection as naming every one. | ||
pub fn concrete(granted: &[String], group: &str) -> String { | ||
let mut out: Vec<String> = Vec::new(); | ||
for s in granted { | ||
let scopes = if *s == configure() { | ||
configure_scopes() | ||
} else { | ||
vec![s.clone()] | ||
let scopes = match set_of(s) { | ||
Some(set) => scopes_of(set), | ||
None => vec![s.clone()], | ||
}; | ||
for s in scopes { | ||
let mut s = s.replace("authority=self", &format!("authority={group}")); | ||
| @@ -358,28 +382,27 @@ pub fn concrete(granted: &[String], group: &str) -> String { | ||
out.join(" ") | ||
} | ||
| ||
/// The space scopes the configure permission set lists, from its lexicon. | ||
fn configure_scopes() -> Vec<String> { | ||
let lexicon: Value = serde_json::from_str(include_str!( | ||
"../../../lexicons/fyi/opensocial/configure.json" | ||
)) | ||
.expect("the configure lexicon is JSON"); | ||
let permissions = lexicon["defs"]["main"]["permissions"] | ||
.as_array() | ||
.into_iter() | ||
.flatten(); | ||
permissions | ||
.map(|p| { | ||
let text = |k: &str| p[k].as_str().unwrap_or_default().to_string(); | ||
let mut q = vec![ | ||
format!("authority={}", text("authority")), | ||
format!("skey={}", text("skey")), | ||
]; | ||
q.extend(strings(&p["collection"]).map(|c| format!("collection={c}"))); | ||
q.extend(strings(&p["action"]).map(|a| format!("action={a}"))); | ||
format!("space:{}?{}", text("spaceType"), q.join("&")) | ||
}) | ||
.collect() | ||
/// 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> { | ||
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(); | ||
if p["resource"] == "rpc" { | ||
let aud = text("aud"); | ||
out.extend(strings(&p["lxm"]).map(|m| format!("rpc:{m}?aud={aud}"))); | ||
continue; | ||
} | ||
let mut q = vec![ | ||
format!("authority={}", text("authority")), | ||
format!("skey={}", text("skey")), | ||
]; | ||
for key in ["collection", "action", "manage"] { | ||
q.extend(strings(&p[key]).map(|v| format!("{key}={v}"))); | ||
} | ||
out.push(format!("space:{}?{}", text("spaceType"), q.join("&"))); | ||
} | ||
out | ||
} | ||
| ||
fn strings(value: &Value) -> impl Iterator<Item = &str> { | ||
crates/group-host/src/rbac.rs+9−1
| @@ -5,7 +5,8 @@ | ||
//! 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. | ||
//! access record's grants, whose scopes are strings, and a membership's | ||
//! roles, which are role ids alone, as the proposal has them. | ||
| ||
use crate::scopes::{Permissions, decoded}; | ||
use atproto::space::SpaceRef; | ||
| @@ -46,6 +47,13 @@ pub fn listed(record: &Value, key: &str, field: &str) -> Vec<String> { | ||
.unwrap_or_default() | ||
} | ||
| ||
/// The roles a membership record gives, each by its id, as the | ||
/// opensocial proposal lists them: `["member", "admin"]`. | ||
pub fn roles_of(membership: &Value) -> Vec<String> { | ||
let roles = membership["roles"].as_array().into_iter().flatten(); | ||
roles.filter_map(Value::as_str).map(String::from).collect() | ||
} | ||
| ||
/// A role's grant in a space's access record: the OAuth scopes it holds | ||
/// there, which count only in that space. | ||
#[derive(Debug, Clone, PartialEq)] | ||