chadtmiller.com/group-host
atmosphere group host
0
0
A space's access record grants each role scopes there
crates/group-host/src/actors.rs+1−1
| @@ -55,7 +55,7 @@ impl Host { | ||
let meta = meta_space(group); | ||
let access = self.group_record(group, &meta, &format!("{NS}.access"), "self"); | ||
let access = access.map_err(XrpcError::internal)?.unwrap_or_default(); | ||
if Access::of(&access).can_read(&roles, viewer) { | ||
if Access::of(&access, &meta).can_read(&roles, viewer) { | ||
let profile = self.group_record(group, &meta, &format!("{NS}.profile"), "self"); | ||
let profile = profile.map_err(XrpcError::internal)?.unwrap_or_default(); | ||
if let Some(name) = profile.get("displayName") { | ||
crates/group-host/src/authority.rs+1−1
| @@ -156,7 +156,7 @@ impl Host { | ||
// A group's space with an access record: the record decides, | ||
// against the user's roles in the group. | ||
let access = self.group_record(&space.authority, uri, &format!("{NS}.access"), "self")?; | ||
if let Some(access) = access.as_ref().map(rbac::Access::of) { | ||
if let Some(access) = access.map(|a| rbac::Access::of(&a, uri)) { | ||
let roles = self.roles(&space.authority, user)?; | ||
let by_record = match access_kind { | ||
Access::Read => access.can_read(&roles, user), | ||
crates/group-host/src/authorization.rs+1−1
| @@ -101,7 +101,7 @@ impl Host { | ||
let (meta, access) = (meta_space(group), format!("{NS}.access")); | ||
let access = self.group_record(group, &meta, &access, "self"); | ||
let access = access.map_err(XrpcError::internal)?.unwrap_or_default(); | ||
if Access::of(&access).can_read(&roles, member) { | ||
if Access::of(&access, &meta).can_read(&roles, member) { | ||
let profile = self.group_record(group, &meta, &format!("{NS}.profile"), "self"); | ||
let profile = profile.map_err(XrpcError::internal)?.unwrap_or_default(); | ||
if let Some(name) = profile.get("displayName") { | ||
crates/group-host/src/group.rs+21−15
| @@ -6,7 +6,7 @@ | ||
//! access record, against the reader's roles. | ||
| ||
use crate::Host; | ||
use crate::rbac::{ACTIONS, Grant, NS, listed}; | ||
use crate::rbac::{ACTIONS, Grant, NS, PUBLIC, listed}; | ||
use crate::repo::{Write, invalid}; | ||
use crate::store::Record; | ||
use crate::time::{iso, now_millis}; | ||
| @@ -93,8 +93,24 @@ fn put(collection: &str, rkey: &str, value: Value) -> Write { | ||
} | ||
} | ||
| ||
fn audience(roles: &[String]) -> Value { | ||
roles.iter().map(|r| json!({ "role": r })).collect() | ||
/// The meta space's access record for `readers`, roles or `public` for | ||
/// anyone signed in: each role reading it, and admins writing its profile | ||
/// and rules as the group. | ||
fn meta_access(readers: &[String]) -> Value { | ||
let meta = format!("{NS}.meta"); | ||
let read = format!("space:{meta}?action=read"); | ||
let write = format!("space:{meta}?collection={NS}.profile&collection={NS}.rule"); | ||
let mut grants: Vec<Value> = readers | ||
.iter() | ||
.filter(|r| *r != PUBLIC && *r != "admin") | ||
.map(|r| json!({"role": r, "scopes": [read]})) | ||
.collect(); | ||
grants.push(json!({"role": "admin", "scopes": [write]})); | ||
let mut access = json!({"$type": format!("{NS}.access"), "grants": grants}); | ||
if readers.iter().any(|r| r == PUBLIC) { | ||
access["public"] = json!(true); | ||
} | ||
access | ||
} | ||
| ||
/// How a new group lets people in, who reads its meta, and who runs it. | ||
| @@ -200,17 +216,7 @@ impl Host { | ||
let meta_writes = [ | ||
put(&c("profile"), "self", profile), | ||
put(&c("labeler"), "self", labeler(&at)), | ||
// Admins write the profile and rules as the group. | ||
put( | ||
&c("access"), | ||
"self", | ||
json!({ | ||
"$type": c("access"), | ||
"readableBy": audience(readers), | ||
"credentialScopes": [{"role": "admin", "scopes": [{"collection": c("profile")}, {"collection": c("rule")}]}], | ||
"createdAt": at, | ||
}), | ||
), | ||
put(&c("access"), "self", meta_access(readers)), | ||
]; | ||
self.space_write(&did, &meta, &meta_writes).await?; | ||
let admin = Grant::with("admin", &ACTIONS, &["member"], &["*"]); | ||
| @@ -219,7 +225,7 @@ impl Host { | ||
put( | ||
&c("access"), | ||
"self", | ||
json!({"$type": c("access"), "readableBy": [{"role": "member"}], "createdAt": at}), | ||
json!({"$type": c("access"), "grants": [{"role": "member", "scopes": [format!("space:{}?action=read", c("members"))]}]}), | ||
), | ||
put( | ||
&c("role"), | ||
crates/group-host/src/group_api.rs+5−6
| @@ -7,7 +7,7 @@ | ||
use crate::Host; | ||
use crate::api::{Params, param}; | ||
use crate::group::{Made, NewGroup, members_space, meta_space}; | ||
use crate::rbac::{self, Access, NS, actions_for, grants, listed, repo_collections_for}; | ||
use crate::rbac::{Access, NS, actions_for, grants, listed, repo_collections_for}; | ||
use crate::space_api::{service_caller, unauthorized}; | ||
use crate::xrpc::XrpcError; | ||
use axum::Json; | ||
| @@ -216,7 +216,7 @@ pub async fn get_group( | ||
let me_or = me.as_deref().unwrap_or_default(); | ||
let reads = |space: &str| -> Result<bool, XrpcError> { | ||
let access = record(space, "access", "self")?; | ||
Ok(access.is_some_and(|a| Access::of(&a).can_read(&roles, me_or))) | ||
Ok(access.is_some_and(|a| Access::of(&a, space).can_read(&roles, me_or))) | ||
}; | ||
let reads_meta = reads(&meta)?; | ||
let reads_members = me.is_some() && reads(&members)?; | ||
| @@ -308,8 +308,8 @@ pub async fn get_group( | ||
let access = host | ||
.group_record(group, uri, &format!("{NS}.access"), "self") | ||
.map_err(XrpcError::internal)?; | ||
if let Some(access) = access.filter(|a| Access::of(a).can_read(&roles, me_or)) { | ||
for key in ["readableBy", "people", "writableBy", "credentialScopes"] { | ||
if let Some(access) = access.filter(|a| Access::of(a, uri).can_read(&roles, me_or)) { | ||
for key in ["public", "grants", "people", "writableBy"] { | ||
if let Some(v) = access.get(key) { | ||
space[key] = v.clone(); | ||
} | ||
| @@ -371,8 +371,7 @@ pub async fn list_groups(State(host): State<Arc<Host>>) -> Answer { | ||
let access = host | ||
.group_record(did, &meta, &format!("{NS}.access"), "self") | ||
.map_err(XrpcError::internal)?; | ||
if access.is_some_and(|a| Access::of(&a).readable_by.iter().any(|r| r == rbac::PUBLIC)) | ||
{ | ||
if access.is_some_and(|a| Access::of(&a, &meta).public) { | ||
let profile = host | ||
.group_record(did, &meta, &format!("{NS}.profile"), "self") | ||
.map_err(XrpcError::internal)?; | ||
crates/group-host/src/group_spaces.rs+154−115
| @@ -1,8 +1,9 @@ | ||
//! The spaces a group's members make beside its two own: a calendar, a | ||
//! forum, a channel. Each is the group's, with its access record saying | ||
//! who reads it, who writes in it in their own name, and which roles | ||
//! write in it as the group; and an entry in the members space's index, | ||
//! which apps read to find it. | ||
//! forum, a channel. Each is the group's, with its access record granting | ||
//! each role scopes in it (`read` among them, which lets a member write | ||
//! there in their own name too), or making it public; and, unless it is | ||
//! left out, an entry in the members space's index, which apps read to | ||
//! find it. | ||
//! | ||
//! Deleting a space ends it, as its authority, as well as taking it out | ||
//! of the index. | ||
| @@ -12,7 +13,8 @@ use crate::api::invalid; | ||
use crate::group::{members_space, meta_space}; | ||
use crate::group_api::{group_of, signed_in}; | ||
use crate::group_config::put_in; | ||
use crate::rbac::{Access, NS, PUBLIC}; | ||
use crate::oauth_scope::SpaceScope; | ||
use crate::rbac::{Access, NS, SpaceGrant}; | ||
use crate::repo::Write; | ||
use crate::time::{iso, now_millis}; | ||
use crate::xrpc::XrpcError; | ||
| @@ -21,6 +23,7 @@ use axum::Json; | ||
use axum::extract::State; | ||
use axum::http::{HeaderMap, StatusCode}; | ||
use serde_json::{Value, json}; | ||
use std::collections::BTreeSet; | ||
use std::sync::Arc; | ||
| ||
type Answer = Result<Json<Value>, XrpcError>; | ||
| @@ -50,28 +53,73 @@ async fn acting( | ||
Ok(group.to_string()) | ||
} | ||
| ||
/// An audience list as given, `[{role}]`, if it is one. | ||
fn audience(body: &Value, key: &str) -> Result<Option<Vec<Value>>, XrpcError> { | ||
let Some(given) = body.get(key) else { | ||
return Ok(None); | ||
}; | ||
let roles = given | ||
/// The access record `config` (an `accessConfig`) asks for in the space | ||
/// at `uri`, checked: one grant a role, each of a role the group has and | ||
/// of space scopes, and someone besides the group to read the space. | ||
fn access_record(host: &Host, group: &str, uri: &str, config: &Value) -> Result<Value, XrpcError> { | ||
let grants = config["grants"] | ||
.as_array() | ||
.expect("its lexicon has it a list of {role}"); | ||
Ok(Some(roles.clone())) | ||
.expect("its lexicon requires it"); | ||
let roles = host.group_records(group, &members_space(group), &format!("{NS}.role")); | ||
let roles = roles.map_err(XrpcError::internal)?; | ||
let mut seen = BTreeSet::new(); | ||
for grant in grants { | ||
let role = grant["role"].as_str().expect("its lexicon requires it"); | ||
if !seen.insert(role) { | ||
return Err(invalid(format!("{role} has more than one grant"))); | ||
} | ||
if !roles.iter().any(|(r, _)| r == role) { | ||
return Err(refused( | ||
"UnknownRole", | ||
format!("the group has no role {role}"), | ||
)); | ||
} | ||
let scopes = grant["scopes"].as_array().expect("its lexicon requires it"); | ||
for scope in scopes.iter().filter_map(Value::as_str) { | ||
if SpaceScope::parse(scope).is_none() { | ||
return Err(refused( | ||
"InvalidScope", | ||
format!("{scope} is no space scope"), | ||
)); | ||
} | ||
} | ||
} | ||
let mut record = json!({"$type": format!("{NS}.access"), "grants": grants}); | ||
if config["public"] == true { | ||
record["public"] = json!(true); | ||
} | ||
let writers = config["writableBy"].as_array().filter(|w| !w.is_empty()); | ||
if let Some(writers) = writers { | ||
record["writableBy"] = json!(writers); | ||
} | ||
let access = Access::of(&record, uri); | ||
let read = |g: &SpaceGrant| access.reads(std::slice::from_ref(&g.role)); | ||
if !access.public && !access.grants.iter().any(read) { | ||
return Err(invalid("nobody but the group would read the space")); | ||
} | ||
Ok(record) | ||
} | ||
| ||
/// The group's index entries of its spaces: key and record. | ||
fn index(host: &Host, group: &str) -> Result<Vec<(String, Value)>, XrpcError> { | ||
host.group_records(group, &members_space(group), &format!("{NS}.space")) | ||
.map_err(XrpcError::internal) | ||
/// A record of the group's just written in `space`, as a strong reference. | ||
fn strong_ref( | ||
host: &Host, | ||
group: &str, | ||
space: &str, | ||
collection: &str, | ||
rkey: &str, | ||
) -> Result<Value, XrpcError> { | ||
let kept = host.store.space_record(group, space, collection, rkey); | ||
let kept = kept.map_err(XrpcError::internal)?; | ||
let cid = kept.expect("the record just written").cid.to_string(); | ||
let uri = format!("{space}/{group}/{collection}/{rkey}"); | ||
Ok(json!({"uri": uri, "cid": cid})) | ||
} | ||
| ||
/// The key of `space`'s entry in the group's index. | ||
fn entry_of(host: &Host, group: &str, space: &str) -> Result<(String, Value), XrpcError> { | ||
let entries = index(host, group)?; | ||
let entry = entries.into_iter().find(|(_, e)| e["space"] == space); | ||
entry.ok_or_else(|| refused("SpaceNotFound", "the space is not in the group's index")) | ||
/// `space`'s entry in the group's index, if it has one: key and record. | ||
fn entry_of(host: &Host, group: &str, space: &str) -> Result<Option<(String, Value)>, XrpcError> { | ||
let entries = host.group_records(group, &members_space(group), &format!("{NS}.space")); | ||
let entries = entries.map_err(XrpcError::internal)?; | ||
Ok(entries.into_iter().find(|(_, e)| e["space"] == space)) | ||
} | ||
| ||
/// The space a body names, the group's, and its access record: refused | ||
| @@ -86,7 +134,7 @@ fn own_space(host: &Host, group: &str, body: &Value) -> Result<(String, Value), | ||
.group_record(group, space, &format!("{NS}.access"), "self") | ||
.map_err(XrpcError::internal)?; | ||
let access = access.ok_or_else(|| refused("SpaceNotFound", "no such space"))?; | ||
if Access::of(&access).people.is_some() { | ||
if Access::of(&access, space).people.is_some() { | ||
return Err(forbidden( | ||
"that space is for chosen people: only they change it", | ||
)); | ||
| @@ -94,77 +142,87 @@ fn own_space(host: &Host, group: &str, body: &Value) -> Result<(String, Value), | ||
Ok((space.to_string(), access)) | ||
} | ||
| ||
/// Adds a space to the group, for one holding `space.create`. | ||
/// Refused for the meta and members spaces, which every group has. | ||
fn reserved_space() -> XrpcError { | ||
refused( | ||
"ReservedSpace", | ||
"the meta and members spaces come and go with the group", | ||
) | ||
} | ||
| ||
/// Adds a space to the group, for one holding `space.create`: with its | ||
/// access record, and an entry in the group's index unless `index` is | ||
/// false. | ||
pub async fn create_space( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
Json(body): Json<Value>, | ||
) -> Answer { | ||
let group = acting(&host, &headers, &body, "createSpace", "space.create").await?; | ||
let kind = body["spaceType"].as_str().expect("its lexicon requires it"); | ||
let readers = audience(&body, "readableBy")?.unwrap_or_default(); | ||
if readers.is_empty() { | ||
return Err(invalid("readableBy names who reads the space")); | ||
let kind = body["type"].as_str().expect("its lexicon requires it"); | ||
if [format!("{NS}.meta"), format!("{NS}.members")].contains(&kind.to_string()) { | ||
return Err(reserved_space()); | ||
} | ||
let writers = audience(&body, "writableBy")?; | ||
let skey = match body["skey"].as_str() { | ||
Some(skey) => skey.to_string(), | ||
None => host.clock.next(), | ||
}; | ||
let uri = format!("at://{group}/space/{kind}/{skey}"); | ||
let access = access_record(&host, &group, &uri, &body["access"])?; | ||
let uri = host.create_space(&group, kind, &skey, false)?; | ||
// A space without its access record or its entry could be neither | ||
// changed nor deleted, and its key never made again: it is made whole | ||
// or not at all. | ||
let furnished = furnish(&host, &group, &uri, &body, readers, writers).await; | ||
if let Err(e) = furnished { | ||
host.end_space(&group, &uri).map_err(XrpcError::internal)?; | ||
return Err(e); | ||
// A space without its access record could be neither changed nor | ||
// deleted, and its key never made again: it is made whole or not at | ||
// all. | ||
match furnish(&host, &group, &uri, &body, access).await { | ||
Ok(made) => Ok(Json(made)), | ||
Err(e) => { | ||
host.end_space(&group, &uri).map_err(XrpcError::internal)?; | ||
Err(e) | ||
} | ||
} | ||
Ok(Json(json!({ "uri": uri }))) | ||
} | ||
| ||
/// Writes a space just made its access record, and its entry in the | ||
/// group's index, as `body` has them. | ||
/// group's index unless `body` says not: what was written, as | ||
/// `createSpace` answers it. | ||
async fn furnish( | ||
host: &Host, | ||
group: &str, | ||
uri: &str, | ||
body: &Value, | ||
readers: Vec<Value>, | ||
writers: Option<Vec<Value>>, | ||
) -> Result<(), XrpcError> { | ||
let at = iso(now_millis()); | ||
let mut access = | ||
json!({"$type": format!("{NS}.access"), "readableBy": readers, "createdAt": at}); | ||
if let Some(writers) = writers.filter(|w| !w.is_empty()) { | ||
access["writableBy"] = json!(writers); | ||
} | ||
if let Some(scopes) = body.get("credentialScopes") { | ||
access["credentialScopes"] = scopes.clone(); | ||
} | ||
access: Value, | ||
) -> Result<Value, XrpcError> { | ||
let collection = format!("{NS}.access"); | ||
let access_write = Write::Create { | ||
collection: format!("{NS}.access"), | ||
collection: collection.clone(), | ||
rkey: "self".into(), | ||
value: access, | ||
}; | ||
host.space_write(group, uri, &[access_write]).await?; | ||
let access = strong_ref(host, group, uri, &collection, "self")?; | ||
let mut made = json!({"space": uri, "access": access}); | ||
if body["index"] == false { | ||
return Ok(made); | ||
} | ||
let at = iso(now_millis()); | ||
let mut entry = json!({"$type": format!("{NS}.space"), "space": uri, "createdAt": at}); | ||
if let Some(name) = body["name"].as_str() { | ||
entry["name"] = json!(name); | ||
} | ||
let (members, rkey) = (members_space(group), host.clock.next()); | ||
let collection = format!("{NS}.space"); | ||
let indexed = Write::Create { | ||
collection: format!("{NS}.space"), | ||
rkey: host.clock.next(), | ||
collection: collection.clone(), | ||
rkey: rkey.clone(), | ||
value: entry, | ||
}; | ||
host.space_write(group, &members_space(group), &[indexed]) | ||
.await?; | ||
Ok(()) | ||
host.space_write(group, &members, &[indexed]).await?; | ||
made["index"] = strong_ref(host, group, &members, &collection, &rkey)?; | ||
Ok(made) | ||
} | ||
| ||
/// Changes a space: its name, who reads it, who writes in it in their own | ||
/// name, and which roles write in it as the group. For one holding | ||
/// `space.configure`. | ||
/// Changes a space: its name, in its index entry, and its access record, | ||
/// replaced whole. For one holding `space.configure`. | ||
pub async fn update_space( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
| @@ -172,60 +230,43 @@ pub async fn update_space( | ||
) -> Answer { | ||
let group = acting(&host, &headers, &body, "updateSpace", "space.configure").await?; | ||
let (access_collection, space_collection) = (format!("{NS}.access"), format!("{NS}.space")); | ||
let (space, current) = own_space(&host, &group, &body)?; | ||
let (space, _) = own_space(&host, &group, &body)?; | ||
let (meta, members) = (meta_space(&group), members_space(&group)); | ||
let readers = audience(&body, "readableBy")?; | ||
if readers.as_ref().is_some_and(Vec::is_empty) { | ||
return Err(invalid("readableBy names who reads the space")); | ||
} | ||
let writers = audience(&body, "writableBy")?; | ||
let name = body["name"].as_str(); | ||
let names = |list: &[Value]| -> Vec<String> { | ||
list.iter() | ||
.filter_map(|r| r["role"].as_str().map(String::from)) | ||
.collect() | ||
let access = match body.get("access") { | ||
Some(config) => Some(access_record(&host, &group, &space, config)?), | ||
None => None, | ||
}; | ||
if let Some(readers) = &readers { | ||
if let Some(access) = access.as_ref().filter(|_| space == members) { | ||
// The members space unreadable by members would lock the group out | ||
// of its own roster, whoever changes it included. | ||
if space == members && !names(readers).iter().any(|r| r == "member") { | ||
if !Access::of(access, &members).reads(&["member".into()]) { | ||
return Err(invalid("the members space stays readable by member")); | ||
} | ||
} | ||
// Writing in the members space in one's own name is joining: who may | ||
// stays as it is. | ||
if writers.is_some() && space == members { | ||
return Err(invalid("who may write in the members space is fixed")); | ||
// Writing in the members space in one's own name is joining: who | ||
// may stays as it is. | ||
if access.get("writableBy").is_some() { | ||
return Err(invalid("who may write in the members space is fixed")); | ||
} | ||
} | ||
// The entry is found before anything is written, so a change refused | ||
// for want of it changes nothing. | ||
let named = match name { | ||
Some(name) => Some((name, entry_of(&host, &group, &space)?)), | ||
let named = match body["name"].as_str() { | ||
Some(name) => { | ||
let entry = entry_of(&host, &group, &space)?; | ||
let unlisted = || refused("SpaceNotFound", "the space is not in the group's index"); | ||
Some((name, entry.ok_or_else(unlisted)?)) | ||
} | ||
None => None, | ||
}; | ||
if readers.is_some() || writers.is_some() || body.get("credentialScopes").is_some() { | ||
let mut access = current.clone(); | ||
if let Some(readers) = &readers { | ||
access["readableBy"] = json!(readers); | ||
} | ||
if let Some(writers) = writers { | ||
let fields = access.as_object_mut().expect("an access record"); | ||
fields.remove("writableBy"); | ||
if !writers.is_empty() { | ||
fields.insert("writableBy".into(), json!(writers)); | ||
} | ||
} | ||
if let Some(scopes) = body.get("credentialScopes") { | ||
access["credentialScopes"] = scopes.clone(); | ||
} | ||
if let Some(access) = access { | ||
let public = access["public"] == true; | ||
let put = put_in(&host, &group, &space, &access_collection, "self", access); | ||
let _written = put.await?; | ||
} | ||
// Meta's readers are the group's visibility: it is declared only while | ||
// anyone may read it, once the access record says so. | ||
if let Some(readers) = readers.as_ref().filter(|_| space == meta) { | ||
let declared = host.declare(&group, names(readers).iter().any(|r| r == PUBLIC)); | ||
declared.await?; | ||
// Meta's readers are the group's visibility: it is declared only | ||
// while anyone may read it. | ||
if space == meta { | ||
host.declare(&group, public).await?; | ||
} | ||
} | ||
if let Some((name, (rkey, mut entry))) = named { | ||
entry["name"] = json!(name); | ||
| @@ -235,10 +276,10 @@ pub async fn update_space( | ||
Ok(Json(json!({}))) | ||
} | ||
| ||
/// Ends a space, for one holding `space.delete`: the services syncing it | ||
/// are told, and its authority's state and the group's own repo in it go. | ||
/// What members wrote there is theirs, at their own PDSes. Meta and | ||
/// members stay: nothing works without them. | ||
/// Ends a space, for one holding `space.delete`: it leaves the index if it | ||
/// is there, the services syncing it are told, and its authority's state | ||
/// and the group's own repo in it go. What members wrote there is theirs, | ||
/// at their own PDSes. Meta and members stay: nothing works without them. | ||
pub async fn delete_space( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
| @@ -247,18 +288,16 @@ pub async fn delete_space( | ||
let group = acting(&host, &headers, &body, "deleteSpace", "space.delete").await?; | ||
let (space, _) = own_space(&host, &group, &body)?; | ||
if space == meta_space(&group) || space == members_space(&group) { | ||
return Err(refused( | ||
"WellKnownSpace", | ||
"the meta and members spaces stay", | ||
)); | ||
return Err(reserved_space()); | ||
} | ||
if let Some((rkey, _)) = entry_of(&host, &group, &space)? { | ||
let unindexed = Write::Delete { | ||
collection: format!("{NS}.space"), | ||
rkey, | ||
}; | ||
host.space_write(&group, &members_space(&group), &[unindexed]) | ||
.await?; | ||
} | ||
let (rkey, _) = entry_of(&host, &group, &space)?; | ||
let unindexed = Write::Delete { | ||
collection: format!("{NS}.space"), | ||
rkey, | ||
}; | ||
host.space_write(&group, &members_space(&group), &[unindexed]) | ||
.await?; | ||
host.end_space(&group, &space) | ||
.map_err(XrpcError::internal)?; | ||
Ok(Json(json!({}))) | ||
crates/group-host/src/group_tokens.rs+7−6
| @@ -3,8 +3,8 @@ | ||
//! `getGroupAuth` gives a member, signed in as themselves, a short-lived | ||
//! token for the group, bound to their DPoP key, to write in one of its | ||
//! spaces what their roles there may write as the group, and the same | ||
//! kinds of record in its public repo, as the access record's | ||
//! `credentialScopes` say a role may publish what it writes. No group | ||
//! kinds of record in its public repo, as a role that may write a kind of | ||
//! record as the group in a space, by its grant there, may publish it. No group | ||
//! password is involved, and there is nothing to refresh. | ||
//! | ||
//! `listGroupTokens` shows a group's configurers every grant that acts as | ||
| @@ -16,7 +16,7 @@ use crate::api::{Params, invalid, param}; | ||
use crate::group::members_space; | ||
use crate::group_api::{group_of, signed_in}; | ||
use crate::oauth_resource::Refusal; | ||
use crate::oauth_scope::{writes_for, writes_in}; | ||
use crate::oauth_scope::writes_in; | ||
use crate::oauth_store::{Grant, Tokens}; | ||
use crate::rbac::{Access, NS}; | ||
use crate::time::{iso, now_millis}; | ||
| @@ -66,8 +66,9 @@ impl Host { | ||
let access = self.group_record(group, uri, &format!("{NS}.access"), "self"); | ||
let access = access.map_err(XrpcError::internal)?.unwrap_or_default(); | ||
// A space for chosen people is theirs, not the group's to publish. | ||
let open = Access::of(&access).people.is_none(); | ||
for (collection, actions) in writes_for(&access, roles).into_iter().filter(|_| open) { | ||
let access = Access::of(&access, uri); | ||
let open = access.people.is_none(); | ||
for (collection, actions) in access.writes(roles).into_iter().filter(|_| open) { | ||
out.entry(collection).or_default().extend(actions); | ||
} | ||
} | ||
| @@ -129,7 +130,7 @@ pub async fn get_group_auth( | ||
let access = host.group_record(group, uri, &format!("{NS}.access"), "self"); | ||
let access = access.map_err(XrpcError::internal)?.unwrap_or_default(); | ||
let everything = host.may_issue(group, &me)?; | ||
let writes = writes_in(&access, &roles, &me, everything); | ||
let writes = writes_in(&Access::of(&access, uri), &roles, &me, everything); | ||
if writes.is_empty() { | ||
return Err(forbidden("no role of yours may act as the group in this space").into()); | ||
} | ||
crates/group-host/src/index_api.rs+1−1
| @@ -55,7 +55,7 @@ async fn readable( | ||
Some(me) => host.roles(group, me).map_err(XrpcError::internal)?, | ||
None => Vec::new(), | ||
}; | ||
if !Access::of(&access).can_read(&roles, me.as_deref().unwrap_or_default()) { | ||
if !Access::of(&access, space).can_read(&roles, me.as_deref().unwrap_or_default()) { | ||
return Err(XrpcError::new( | ||
StatusCode::UNAUTHORIZED, | ||
"NotAuthorized", | ||
crates/group-host/src/oauth_scope.rs+9−36
| @@ -10,15 +10,14 @@ | ||
| ||
use crate::Host; | ||
use crate::group::members_space; | ||
use crate::rbac::{self, Access, NS, actions_for, grants, listed, repo_collections_for}; | ||
use crate::rbac::{self, Access, NS, actions_for, grants, repo_collections_for}; | ||
use crate::scopes::{decoded, is_blob, repo_collections}; | ||
use crate::xrpc::XrpcError; | ||
use atproto::space::SpaceRef; | ||
use serde_json::Value; | ||
use std::collections::{BTreeMap, BTreeSet}; | ||
| ||
/// The writes a space scope may name. | ||
pub const WRITES: [&str; 3] = ["create", "update", "delete"]; | ||
pub use crate::rbac::WRITES; | ||
| ||
/// The permission set that lets an app configure the group. | ||
pub fn configure() -> String { | ||
| @@ -79,50 +78,23 @@ impl SpaceScope { | ||
} | ||
} | ||
| ||
/// What a holder of `roles` may write as the group in a space, by | ||
/// collection (`*` for every one), by the union of their grants in its | ||
/// access record's `credentialScopes`. | ||
pub fn writes_for(access: &Value, roles: &[String]) -> BTreeMap<String, BTreeSet<String>> { | ||
let mut out: BTreeMap<String, BTreeSet<String>> = BTreeMap::new(); | ||
let scopes = access["credentialScopes"].as_array().into_iter().flatten(); | ||
for grant in scopes.filter(|g| roles.iter().any(|r| g["role"] == r.as_str())) { | ||
for scope in listed(grant, "scopes", "collection") { | ||
let (collection, query) = scope.split_once('?').unwrap_or((&scope, "")); | ||
let named: Vec<&str> = query | ||
.split('&') | ||
.filter_map(|kv| kv.strip_prefix("action=")) | ||
.filter(|a| WRITES.contains(a)) | ||
.collect(); | ||
let actions = if named.is_empty() { | ||
WRITES.to_vec() | ||
} else { | ||
named | ||
}; | ||
let has = out.entry(collection.into()).or_default(); | ||
has.extend(actions.iter().map(|a| a.to_string())); | ||
} | ||
} | ||
out | ||
} | ||
| ||
/// What a holder of `roles`, `member`, may write as the group in a space | ||
/// whose access record is `access`, by collection, `everything` being | ||
/// whether they may do anything as the group. A space for chosen people | ||
/// is written as the group by those of them who may do anything as it; | ||
/// any other, as its `credentialScopes` say. | ||
/// any other, as its grants say. | ||
pub fn writes_in( | ||
access: &Value, | ||
access: &Access, | ||
roles: &[String], | ||
member: &str, | ||
everything: bool, | ||
) -> BTreeMap<String, BTreeSet<String>> { | ||
let rules = Access::of(access); | ||
match rules.people { | ||
Some(_) if everything && rules.can_read(roles, member) => { | ||
match access.people { | ||
Some(_) if everything && access.can_read(roles, member) => { | ||
BTreeMap::from([("*".into(), WRITES.map(String::from).into())]) | ||
} | ||
Some(_) => BTreeMap::new(), | ||
None => writes_for(access, roles), | ||
None => access.writes(roles), | ||
} | ||
} | ||
| ||
| @@ -175,10 +147,11 @@ impl Host { | ||
.group_record(group, uri, &format!("{NS}.access"), "self") | ||
.map_err(XrpcError::internal)? | ||
.unwrap_or_default(); | ||
let access = Access::of(&access, uri); | ||
rooms.push(Room { | ||
kind: space.kind, | ||
skey: space.skey, | ||
readable: Access::of(&access).can_read(roles, member), | ||
readable: access.can_read(roles, member), | ||
writable: writes_in(&access, roles, member, everything), | ||
}); | ||
} | ||
crates/group-host/src/rbac.rs+95−18
| @@ -4,10 +4,13 @@ | ||
//! 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}`). | ||
//! The records' lists are of objects (`{role}`, `{scope}`), but for an | ||
//! access record's grants, whose scopes are strings. | ||
| ||
use crate::scopes::{Permissions, decoded}; | ||
use atproto::space::SpaceRef; | ||
use serde_json::Value; | ||
use std::collections::BTreeSet; | ||
use std::collections::{BTreeMap, BTreeSet}; | ||
| ||
pub const NS: &str = "fyi.opensocial"; | ||
/// Anyone signed in, as an audience. | ||
| @@ -43,54 +46,128 @@ pub fn listed(record: &Value, key: &str, field: &str) -> Vec<String> { | ||
.unwrap_or_default() | ||
} | ||
| ||
/// A space's access record, as read. | ||
/// 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)] | ||
pub struct SpaceGrant { | ||
pub role: String, | ||
pub scopes: Vec<String>, | ||
} | ||
| ||
/// A space's access record, as read, for the space it is in. | ||
#[derive(Debug, Clone, Default, PartialEq)] | ||
pub struct Access { | ||
pub readable_by: Vec<String>, | ||
/// The space it is the record of; a grant counts in no other. | ||
pub space: Option<SpaceRef>, | ||
/// Whether anyone signed in reads it, member or not. | ||
pub public: bool, | ||
pub grants: Vec<SpaceGrant>, | ||
/// The people it is for, by DID, when it is for chosen people. | ||
pub people: Option<Vec<String>>, | ||
/// The roles that may read a space for chosen people, to decide on it. | ||
pub reviewers: Vec<String>, | ||
/// Who may write in it in their own name; absent is any member. | ||
/// Who may write in it in their own name, when not every member whose | ||
/// roles grant `read`. | ||
pub writable_by: Option<Vec<String>>, | ||
} | ||
| ||
impl Access { | ||
pub fn of(record: &Value) -> Access { | ||
/// The access record `record` of the space at `space`. | ||
pub fn of(record: &Value, space: &str) -> Access { | ||
let maybe = |key: &str, field: &str| record.get(key).map(|_| listed(record, key, field)); | ||
let grants = record["grants"].as_array().into_iter().flatten(); | ||
Access { | ||
readable_by: listed(record, "readableBy", "role"), | ||
space: SpaceRef::parse(space).ok(), | ||
public: record["public"] == true, | ||
grants: grants | ||
.map(|g| SpaceGrant { | ||
role: g["role"].as_str().unwrap_or_default().into(), | ||
scopes: strings(&g["scopes"]), | ||
}) | ||
.collect(), | ||
people: maybe("people", "did"), | ||
reviewers: listed(record, "reviewers", "role"), | ||
writable_by: maybe("writableBy", "role"), | ||
} | ||
} | ||
| ||
/// May `did`, holding `roles`, read the space? One for chosen people is | ||
/// for them while they are members, and its reviewers. | ||
/// The scopes a holder of `roles` is granted here, by union. | ||
pub fn scopes(&self, roles: &[String]) -> Vec<String> { | ||
let mine = self.grants.iter().filter(|g| roles.contains(&g.role)); | ||
mine.flat_map(|g| g.scopes.clone()).collect() | ||
} | ||
| ||
/// Whether `scopes` let their holder `action` here, on `collection` | ||
/// for a write. | ||
fn lets(&self, scopes: &[String], collection: Option<&str>, action: &str) -> bool { | ||
let Some(space) = &self.space else { | ||
return false; | ||
}; | ||
let held = Permissions::new(&scopes.join(" "), &space.authority); | ||
held.space(space, collection, action) | ||
} | ||
| ||
/// Whether `roles` are granted `read` here. | ||
pub fn reads(&self, roles: &[String]) -> bool { | ||
self.lets(&self.scopes(roles), None, "read") | ||
} | ||
| ||
/// What a holder of `roles` may write here as the group, by collection | ||
/// (`*` for every one): the writes of each collection their scopes | ||
/// name. | ||
pub fn writes(&self, roles: &[String]) -> BTreeMap<String, BTreeSet<String>> { | ||
let mut out: BTreeMap<String, BTreeSet<String>> = BTreeMap::new(); | ||
for scope in self.scopes(roles) { | ||
let one = [scope.clone()]; | ||
for collection in query_of(&decoded(&scope), "collection") { | ||
for action in WRITES { | ||
if self.lets(&one, Some(&collection), action) { | ||
out.entry(collection.clone()) | ||
.or_default() | ||
.insert(action.into()); | ||
} | ||
} | ||
} | ||
} | ||
out | ||
} | ||
| ||
/// May `did`, holding `roles`, read the space? Anyone signed in, if it | ||
/// is public; else those whose roles grant `read`. One for chosen | ||
/// people is for them while they are members, and those whose roles | ||
/// grant `read`. | ||
pub fn can_read(&self, roles: &[String], did: &str) -> bool { | ||
if let Some(people) = &self.people { | ||
let theirs = !roles.is_empty() && people.iter().any(|p| p == did); | ||
return theirs || roles.iter().any(|r| self.reviewers.contains(r)); | ||
return theirs || self.reads(roles); | ||
} | ||
self.readable_by | ||
.iter() | ||
.any(|r| r == PUBLIC || roles.contains(r)) | ||
self.public || self.reads(roles) | ||
} | ||
| ||
/// May `did`, holding `roles`, write in the space in their own name? | ||
/// Any member, unless the record names who. | ||
/// A member whose roles grant `read`, unless the record names who. | ||
pub fn can_write_own(&self, roles: &[String], did: &str) -> bool { | ||
if let Some(people) = &self.people { | ||
return !roles.is_empty() && people.iter().any(|p| p == did); | ||
} | ||
match &self.writable_by { | ||
None => !roles.is_empty(), | ||
None => !roles.is_empty() && self.reads(roles), | ||
Some(by) => by.iter().any(|r| r == PUBLIC || roles.contains(r)), | ||
} | ||
} | ||
} | ||
| ||
/// The writes a space scope may name. | ||
pub const WRITES: [&str; 3] = ["create", "update", "delete"]; | ||
| ||
/// The strings in a list of them. | ||
fn strings(value: &Value) -> Vec<String> { | ||
let items = value.as_array().into_iter().flatten(); | ||
items.filter_map(|s| s.as_str().map(String::from)).collect() | ||
} | ||
| ||
/// The values of `name` in a scope's query, owned. | ||
fn query_of(scope: &str, name: &str) -> Vec<String> { | ||
query(scope, name).into_iter().map(String::from).collect() | ||
} | ||
| ||
/// The actions a host method's `rpc:` scope grants, by method. | ||
const BY_METHOD: [(&str, &str); 7] = [ | ||
("assignRoles", "role.assign"), | ||