chadtmiller.com/group-host
atmosphere group host
0
0
Spaces are kept under policies and changed through atproto's space methods
crates/group-host/src/actors.rs+2−4
| @@ -5,7 +5,7 @@ use crate::Host; | ||
use crate::api::{Params, page, param}; | ||
use crate::group::{members_space, meta_space}; | ||
use crate::group_api::{caller, group_of, signed_in}; | ||
use crate::rbac::{Access, NS}; | ||
use crate::rbac::NS; | ||
use crate::store::Store; | ||
use crate::xrpc::XrpcError; | ||
use atproto::did; | ||
| @@ -72,9 +72,7 @@ impl Host { | ||
} | ||
let roles = self.roles(group, viewer).map_err(XrpcError::internal)?; | ||
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, &meta).can_read(&roles, viewer) { | ||
if self.reads_space(&meta, &roles)? { | ||
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+45−20
| @@ -20,7 +20,7 @@ | ||
use crate::Host; | ||
use crate::index_api::capped; | ||
use crate::oauth_clients::pinned_client; | ||
use crate::rbac::{self, NS}; | ||
use crate::rbac::Policy; | ||
use crate::repo::invalid; | ||
use crate::space::NOTIFY_REPO_UPDATE; | ||
use crate::space_api::NOTIFY_REVOKED; | ||
| @@ -325,14 +325,14 @@ impl Host { | ||
} | ||
} | ||
| ||
/// Makes a space of `authority`'s, a group here, of `kind` at `skey`; | ||
/// open to any reader with `public_read`. Its URI. | ||
/// Makes a space of `authority`'s, a group here, of `kind` at `skey`, | ||
/// under `policy`. Its URI. | ||
pub fn create_space( | ||
&self, | ||
authority: &str, | ||
kind: &str, | ||
skey: &str, | ||
public_read: bool, | ||
policy: &Json, | ||
) -> Result<String, XrpcError> { | ||
let uri = format!("at://{authority}/space/{kind}/{skey}"); | ||
SpaceRef::parse(&uri).map_err(|e| invalid(e.to_string()))?; | ||
| @@ -342,7 +342,7 @@ impl Host { | ||
} | ||
let made = self | ||
.store | ||
.create_space(&uri, authority, public_read, now()) | ||
.create_space(&uri, authority, policy, now()) | ||
.map_err(XrpcError::internal)?; | ||
if !made { | ||
return Err(XrpcError::new( | ||
| @@ -354,6 +354,15 @@ impl Host { | ||
Ok(uri) | ||
} | ||
| ||
/// The policy of the space at `uri`, if it is one here. | ||
pub fn policy(&self, uri: &str) -> Result<Option<Policy>> { | ||
let Some(space) = self.store.space(uri)? else { | ||
return Ok(None); | ||
}; | ||
let at = SpaceRef::parse(uri)?; | ||
Ok(Some(Policy::of(&space.policy, &at))) | ||
} | ||
| ||
/// The space at `uri`, if its authority is a group here. | ||
pub fn hosted_space(&self, uri: &str) -> Result<Space, XrpcError> { | ||
let space = self.store.space(uri).map_err(XrpcError::internal)?; | ||
| @@ -399,23 +408,15 @@ impl Host { | ||
if user == space.authority { | ||
return Ok(true); | ||
} | ||
// 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.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), | ||
Access::Write => access.can_write_own(&roles, user), | ||
}; | ||
if by_record { | ||
return Ok(true); | ||
} | ||
} | ||
// Its policy decides, against the user's roles in the group; then | ||
// what the host keeps of each account beyond it, from a space | ||
// brought here with its members. | ||
let policy = Policy::of(&space.policy, &SpaceRef::parse(uri)?); | ||
let roles = self.roles(&space.authority, user)?; | ||
let granted = self.store.granted(uri, user)?; | ||
Ok(match access_kind { | ||
Access::Read => space.public_read || granted.is_some_and(|(read, _)| read), | ||
Access::Write => granted.is_some_and(|(_, write)| write), | ||
Access::Read => policy.can_read(&roles) || granted.is_some_and(|(read, _)| read), | ||
Access::Write => policy.writes_own(&roles) || granted.is_some_and(|(_, write)| write), | ||
}) | ||
} | ||
| ||
| @@ -472,6 +473,30 @@ impl Host { | ||
Ok(()) | ||
} | ||
| ||
/// Takes out of the writer set of `space` (at `uri`) each repo that | ||
/// may write there no more, as its policy and the roles it reads have | ||
/// it now; with `only`, that repo alone. | ||
pub fn prune_writers(&self, uri: &str, space: &Space, only: Option<&str>) -> Result<()> { | ||
for writer in self.store.writers(uri, None, u32::MAX)? { | ||
let other = only.is_some_and(|o| o != writer.did); | ||
if other || self.may(uri, space, Some(&writer.did), Access::Write)? { | ||
continue; | ||
} | ||
self.remove_writer(uri, &writer.did)?; | ||
} | ||
Ok(()) | ||
} | ||
| ||
/// Takes `member` out of the writer set of each of `group`'s spaces | ||
/// they may write in no more. | ||
pub fn prune_writer_of(&self, group: &str, member: &str) -> Result<()> { | ||
for uri in self.store.spaces_of(group)? { | ||
let space = self.store.space(&uri)?.context("a space of the group's")?; | ||
self.prune_writers(&uri, &space, Some(member))?; | ||
} | ||
Ok(()) | ||
} | ||
| ||
/// Asks the syncer endpoint `to` names to confirm it asked to be told | ||
/// of `space`: it echoes a challenge, within ten seconds, unredirected. | ||
pub(crate) async fn confirm_registration( | ||
crates/group-host/src/authorization.rs+5−7
| @@ -11,7 +11,7 @@ use crate::group_api::{group_of, signed_in}; | ||
use crate::mcp; | ||
use crate::oauth_scope::{concrete, set_of}; | ||
use crate::oauth_store::Request; | ||
use crate::rbac::{Access, NS}; | ||
use crate::rbac::NS; | ||
use crate::time::now_millis; | ||
use crate::xrpc::XrpcError; | ||
use axum::Json; | ||
| @@ -88,7 +88,7 @@ impl Host { | ||
let roles = self.roles(group, member).map_err(XrpcError::internal)?; | ||
let granted = match roles.is_empty() { | ||
true => Vec::new(), | ||
false => self.narrow(group, &roles, member, requested)?, | ||
false => self.narrow(group, &roles, requested)?, | ||
}; | ||
let withheld: Vec<String> = requested | ||
.iter() | ||
| @@ -102,10 +102,8 @@ impl Host { | ||
"granted": objects("scope", &granted), | ||
"withheld": objects("scope", &withheld), | ||
}); | ||
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, &meta).can_read(&roles, member) { | ||
let meta = meta_space(group); | ||
if self.reads_space(&meta, &roles)? { | ||
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") { | ||
| @@ -212,7 +210,7 @@ pub async fn approve_authorization( | ||
if roles.is_empty() { | ||
return Err(forbidden("you hold no role in this group")); | ||
} | ||
let granted = host.narrow(group, &roles, &me, &requested(&request))?; | ||
let granted = host.narrow(group, &roles, &requested(&request))?; | ||
let scope = concrete(&granted, group); | ||
let approved = host.approve_request(&request, group, &me, &scope); | ||
let redirect = approved.map_err(XrpcError::internal)?.ok_or_else(expired)?; | ||
crates/group-host/src/group.rs+42−50
| @@ -3,10 +3,10 @@ | ||
//! `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. | ||
//! space is its policy, against the reader's roles. | ||
| ||
use crate::Host; | ||
use crate::rbac::{ACTIONS, EVERY_ROLE, Grant, NS, PUBLIC, grants, roles_of}; | ||
use crate::rbac::{ACTIONS, EVERY_ROLE, Grant, NS, POLICY, grants, roles_of}; | ||
use crate::repo::{Write, invalid}; | ||
use crate::store::Record; | ||
use crate::time::{iso, now_millis}; | ||
| @@ -74,7 +74,8 @@ pub fn join_policy(asked: Option<&str>) -> Result<&'static str, XrpcError> { | ||
} | ||
| ||
/// A new group: its handle, who starts it and runs it beside them, its | ||
/// name and words, how people join, and who reads its meta space. | ||
/// name and words, how people join, and whether anyone reads its meta | ||
/// space. | ||
#[derive(Debug, Clone, Default)] | ||
pub struct NewGroup { | ||
pub handle: String, | ||
| @@ -83,9 +84,9 @@ pub struct NewGroup { | ||
pub display_name: String, | ||
pub description: Option<String>, | ||
pub join_policy: Option<String>, | ||
/// The roles that read the meta space, `public` for anyone signed in; | ||
/// `public` unless it says. | ||
pub meta_readable_by: Option<Vec<String>>, | ||
/// Whether anyone may read the meta space, beside its members: yes, | ||
/// unless it says. | ||
pub meta_public_read: Option<bool>, | ||
} | ||
| ||
/// A group made: its DID and its two spaces. | ||
| @@ -104,40 +105,38 @@ fn put(collection: &str, rkey: &str, value: Value) -> Write { | ||
} | ||
} | ||
| ||
/// 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); | ||
/// A new group's policy for its meta space, readable by anyone if | ||
/// `public`: its members read it, and admins read it and write its | ||
/// profile and rules as the group. | ||
fn meta_policy(public: bool) -> Value { | ||
let write = format!("space:{NS}.meta?collection={NS}.profile&collection={NS}.rule"); | ||
let mut policy = json!({"$type": POLICY, "grants": [ | ||
{"role": "member", "read": true}, | ||
{"role": "admin", "read": true, "scopes": [write]}, | ||
]}); | ||
if public { | ||
policy["publicRead"] = json!(true); | ||
} | ||
access | ||
policy | ||
} | ||
| ||
/// How a new group lets people in, who reads its meta, and who runs it. | ||
/// A new group's policy for its members space: its members read it, and | ||
/// write there, so that their acceptances sync. | ||
fn members_policy() -> Value { | ||
json!({"$type": POLICY, "grants": [{"role": "member", "read": true, "write": true}]}) | ||
} | ||
| ||
/// How a new group lets people in, whether anyone reads its meta, and who | ||
/// runs it. | ||
struct Shape { | ||
join: &'static str, | ||
readers: Vec<String>, | ||
public: bool, | ||
stewards: Vec<String>, | ||
} | ||
| ||
/// What `new` asks of a group's first day, checked. | ||
fn shape(new: &NewGroup) -> Result<Shape, XrpcError> { | ||
let join = join_policy(new.join_policy.as_deref())?; | ||
let readers = new | ||
.meta_readable_by | ||
.clone() | ||
.unwrap_or_else(|| vec!["public".into()]); | ||
let mut stewards = vec![new.founder.clone()]; | ||
for s in &new.stewards { | ||
if !stewards.contains(s) { | ||
| @@ -146,7 +145,7 @@ fn shape(new: &NewGroup) -> Result<Shape, XrpcError> { | ||
} | ||
Ok(Shape { | ||
join, | ||
readers, | ||
public: new.meta_public_read != Some(false), | ||
stewards, | ||
}) | ||
} | ||
| @@ -207,12 +206,13 @@ impl Host { | ||
async fn set_up(&self, did: &str, new: &NewGroup, shape: &Shape) -> Result<Made, XrpcError> { | ||
let Shape { | ||
join, | ||
readers, | ||
public, | ||
stewards, | ||
} = shape; | ||
let did = did.to_string(); | ||
let meta = self.create_space(&did, &format!("{NS}.meta"), "self", false)?; | ||
let members = self.create_space(&did, &format!("{NS}.members"), "self", false)?; | ||
let (meta_policy, members_policy) = (meta_policy(*public), members_policy()); | ||
let meta = self.create_space(&did, &format!("{NS}.meta"), "self", &meta_policy)?; | ||
let members = self.create_space(&did, &format!("{NS}.members"), "self", &members_policy)?; | ||
let at = iso(now_millis()); | ||
let c = |name: &str| format!("{NS}.{name}"); | ||
let mut profile = json!({ | ||
| @@ -227,18 +227,15 @@ impl Host { | ||
let meta_writes = [ | ||
put(&c("profile"), "self", profile), | ||
put(&c("labeler"), "self", labeler()), | ||
put(&c("access"), "self", meta_access(readers)), | ||
]; | ||
self.space_write(&did, &meta, &meta_writes).await?; | ||
// 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], &["*"]); | ||
// it, in its repo and in its spaces (so that they may give any | ||
// scope a space's policy may hold), and giving any role; everyone | ||
// else is a member. | ||
let mut admin = Grant::with("admin", &ACTIONS, &[EVERY_ROLE], &["*"]); | ||
admin.scopes.push("space:*?collection=*".into()); | ||
let mut members_writes = vec![ | ||
put( | ||
&c("access"), | ||
"self", | ||
json!({"$type": c("access"), "grants": [{"role": "member", "scopes": [format!("space:{}?action=read", c("members"))]}]}), | ||
), | ||
put( | ||
&c("role"), | ||
"admin", | ||
| @@ -250,14 +247,6 @@ impl Host { | ||
json!({"$type": c("role"), "displayName": "Member", "default": true, "createdAt": at}), | ||
), | ||
]; | ||
// The index of the group's spaces, which apps read to find them. | ||
for space in [&meta, &members] { | ||
members_writes.push(put( | ||
&c("space"), | ||
&self.clock.next(), | ||
json!({"$type": c("space"), "space": space, "createdAt": at}), | ||
)); | ||
} | ||
for steward in stewards { | ||
members_writes.push(put( | ||
&c("membership"), | ||
| @@ -266,8 +255,11 @@ impl Host { | ||
)); | ||
} | ||
self.space_write(&did, &members, &members_writes).await?; | ||
// Each policy published, and both spaces in the group's index. | ||
self.publish_policy(&did, &meta, &meta_policy).await?; | ||
self.publish_policy(&did, &members, &members_policy).await?; | ||
// Listed only if there is a face to show: a meta anyone may read. | ||
if readers.iter().any(|r| r == "public") { | ||
if *public { | ||
let declaration = json!({"$type": c("declaration"), "meta": meta, "createdAt": at}); | ||
self.write(&did, &[put(&c("declaration"), "self", declaration)])?; | ||
} | ||
crates/group-host/src/group_api.rs+22−26
| @@ -7,7 +7,7 @@ | ||
use crate::Host; | ||
use crate::api::{Params, page, param}; | ||
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::rbac::{NS, actions_for, listed, repo_collections_for, roles_of}; | ||
use crate::space_api::{service_caller, unauthorized}; | ||
use crate::xrpc::XrpcError; | ||
use axum::Json; | ||
| @@ -73,7 +73,7 @@ pub(crate) fn new_group(body: &Value, founder: String) -> Result<NewGroup, XrpcE | ||
display_name: text("displayName").expect("its lexicon requires it"), | ||
description: text("description"), | ||
join_policy: text("joinPolicy"), | ||
meta_readable_by: strings(body, "metaReadableBy", "role"), | ||
meta_public_read: body["metaPublicRead"].as_bool(), | ||
}) | ||
} | ||
| ||
| @@ -201,7 +201,7 @@ fn signed_out(did: &str, handle: String) -> Value { | ||
/// One group in full, as the caller may see it: what its meta space | ||
/// holds for whoever may read it, the caller's own standing, and for a | ||
/// member, how many are in it, its roles and spaces. To no one signed in, | ||
/// only its DID and handle, whatever its access record says. | ||
/// only its DID and handle, whatever its meta space's policy says. | ||
pub async fn get_group( | ||
State(host): State<Arc<Host>>, | ||
Query(p): Query<Params>, | ||
| @@ -230,10 +230,7 @@ pub async fn get_group( | ||
}; | ||
let (meta, members) = (meta_space(group), members_space(group)); | ||
let roles = host.roles(group, &me).map_err(XrpcError::internal)?; | ||
let reads = |space: &str| -> Result<bool, XrpcError> { | ||
let access = record(space, "access", "self")?; | ||
Ok(access.is_some_and(|a| Access::of(&a, space).can_read(&roles, &me))) | ||
}; | ||
let reads = |space: &str| host.reads_space(space, &roles); | ||
let reads_meta = reads(&meta)?; | ||
let reads_members = reads(&members)?; | ||
let granted = host.role_grants(group).map_err(XrpcError::internal)?; | ||
| @@ -308,23 +305,25 @@ pub async fn get_group( | ||
}) | ||
.collect(); | ||
let mut spaces = Vec::new(); | ||
for (_, entry) in records("space")? { | ||
let uri = entry["space"].as_str().unwrap_or_default(); | ||
// Those in its index, in its order, then those left out of it to | ||
// whoever reads them; each with its policy, to whoever reads the space. | ||
let mut uris: Vec<String> = records("space")? | ||
.into_iter() | ||
.filter_map(|(_, e)| e["space"].as_str().map(String::from)) | ||
.collect(); | ||
let unlisted = host.store.spaces_of(group).map_err(XrpcError::internal)?; | ||
let unlisted: Vec<String> = unlisted.into_iter().filter(|u| !uris.contains(u)).collect(); | ||
uris.extend(unlisted); | ||
for uri in uris { | ||
let kept = host.hosted_space(&uri)?; | ||
let readable = reads(&uri)?; | ||
if kept.policy["unlisted"] == true && !readable { | ||
continue; | ||
} | ||
let kind = uri.split('/').nth(4).unwrap_or_default(); | ||
let mut space = json!({"uri": uri, "spaceType": kind}); | ||
if let Some(name) = entry.get("name") { | ||
space["name"] = name.clone(); | ||
} | ||
// Its access record, to whoever it lets read the space. | ||
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, uri).can_read(&roles, &me)) { | ||
for key in ["public", "grants", "people", "writableBy"] { | ||
if let Some(v) = access.get(key) { | ||
space[key] = v.clone(); | ||
} | ||
} | ||
if readable { | ||
space["policy"] = kept.policy; | ||
} | ||
spaces.push(space); | ||
} | ||
| @@ -365,10 +364,7 @@ pub async fn list_members( | ||
let me = signed_in(&host, &headers, &format!("{NS}.listMembers")).await?; | ||
let members = members_space(group); | ||
let roles = host.roles(group, &me).map_err(XrpcError::internal)?; | ||
let access = host | ||
.group_record(group, &members, &format!("{NS}.access"), "self") | ||
.map_err(XrpcError::internal)?; | ||
if !access.is_some_and(|a| Access::of(&a, &members).can_read(&roles, &me)) { | ||
if !host.reads_space(&members, &roles)? { | ||
let closed = "only those who may read its members space see them"; | ||
return Err(XrpcError::new(StatusCode::FORBIDDEN, "Forbidden", closed)); | ||
} | ||
crates/group-host/src/group_config.rs+3−4
| @@ -9,7 +9,7 @@ use crate::Host; | ||
use crate::api::invalid; | ||
use crate::blobs::PROFILE_IMAGES; | ||
use crate::group::{join_policy, members_space, meta_space, rkey_did}; | ||
use crate::rbac::{Access, NS, actions_for, roles_of}; | ||
use crate::rbac::{NS, actions_for, roles_of}; | ||
use crate::repo::Write; | ||
use crate::xrpc::XrpcError; | ||
use atproto::Cid; | ||
| @@ -275,9 +275,8 @@ impl Host { | ||
let named = format!("a group's declaration names its meta space, {meta}"); | ||
return Err(invalid(named)); | ||
} | ||
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, &meta).public { | ||
let public = self.hosted_space(&meta)?.public_read; | ||
if !public { | ||
let hidden = "a group is declared only while anyone may read its meta space"; | ||
return Err(invalid(hidden)); | ||
} | ||
crates/group-host/src/group_spaces.rs+391−229
620 lines changed: not loaded until asked for.
crates/group-host/src/group_tokens.rs+53−28
| @@ -19,9 +19,9 @@ use crate::group_invites::{inviting_scope, is_inbox}; | ||
use crate::member_writes::own_scopes; | ||
use crate::oauth_resource::Refusal; | ||
use crate::oauth_scope::WRITES; | ||
use crate::oauth_scope::{labels_in, may_write, with_labels, writes_in}; | ||
use crate::oauth_scope::{may_write, with_labels}; | ||
use crate::oauth_store::{Grant, Tokens}; | ||
use crate::rbac::{Access, LABEL, NS}; | ||
use crate::rbac::{LABEL, NS, Policy}; | ||
use crate::time::{iso, now_millis}; | ||
use crate::xrpc::XrpcError; | ||
use atproto::jose; | ||
| @@ -64,18 +64,12 @@ impl Host { | ||
group: &str, | ||
roles: &[String], | ||
) -> Result<BTreeMap<String, BTreeSet<String>>, XrpcError> { | ||
let entries = self | ||
.group_records(group, &members_space(group), &format!("{NS}.space")) | ||
.map_err(XrpcError::internal)?; | ||
let spaces = self.store.spaces_of(group).map_err(XrpcError::internal)?; | ||
let mut out: BTreeMap<String, BTreeSet<String>> = BTreeMap::new(); | ||
for (_, entry) in entries { | ||
let uri = entry["space"].as_str().unwrap_or_default(); | ||
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 access = Access::of(&access, uri); | ||
let open = access.people.is_none(); | ||
for (collection, actions) in access.writes(roles).into_iter().filter(|_| open) { | ||
for uri in spaces { | ||
let policy = self.policy(&uri).map_err(XrpcError::internal)?; | ||
let policy = policy.expect("a space the group has"); | ||
for (collection, actions) in policy.writes(roles) { | ||
out.entry(collection).or_default().extend(actions); | ||
} | ||
} | ||
| @@ -139,9 +133,11 @@ type Writable = BTreeMap<String, BTreeSet<String>>; | ||
| ||
impl Host { | ||
/// What `member`'s roles in `group` may write as it in `space`, at | ||
/// `uri`: each kind of record with its writes, as the space's access | ||
/// record grants them and, in the members space, as the group grants | ||
/// them its own records there; and the scope of a token for them. | ||
/// `uri`: each kind of record with its writes, as the space's policy | ||
/// grants them and, in the members space, as the group grants them | ||
/// its own records there; and the scope of a token for them, and for | ||
/// what they may do to the space itself (making it, if it is not yet | ||
/// made, changing and ending it). | ||
pub(crate) fn group_scope( | ||
&self, | ||
group: &str, | ||
| @@ -150,33 +146,62 @@ impl Host { | ||
space: &SpaceRef, | ||
) -> Result<(Writable, Writable, String), XrpcError> { | ||
let roles = self.roles(group, member).map_err(XrpcError::internal)?; | ||
let access = self.group_record(group, uri, &format!("{NS}.access"), "self"); | ||
let access = access.map_err(XrpcError::internal)?.unwrap_or_default(); | ||
let everything = self.may_issue(group, member)?; | ||
let access = Access::of(&access, uri); | ||
let writes = writes_in(&access, &roles, member, everything); | ||
let policy = self.policy(uri).map_err(XrpcError::internal)?; | ||
let writes = policy | ||
.as_ref() | ||
.map(|p| p.writes(&roles)) | ||
.unwrap_or_default(); | ||
let mut own = match uri == members_space(group) { | ||
true => self.members_writes_of(group, &roles)?, | ||
false => BTreeMap::new(), | ||
}; | ||
// Labels, unless what the space grants holds them already. | ||
let labels = labels_in( | ||
&access, | ||
&roles, | ||
member, | ||
self.may_do(group, member, "label")?, | ||
); | ||
let labels = policy.is_some() && self.may_do(group, member, "label")?; | ||
if !WRITES.iter().all(|w| may_write(&writes, LABEL, w)) { | ||
with_labels(&mut own, labels); | ||
} | ||
if writes.is_empty() && own.is_empty() { | ||
let manage = self.manage_ops(group, member, &roles, policy.as_ref())?; | ||
if writes.is_empty() && own.is_empty() && manage.is_empty() { | ||
let none = "no role of yours may act as the group in this space"; | ||
return Err(forbidden(none)); | ||
} | ||
let mut scope = scopes_for(space, &writes); | ||
scope.extend(own_scopes(space, &own)); | ||
if !manage.is_empty() { | ||
let ops: Vec<String> = manage.iter().map(|op| format!("&manage={op}")).collect(); | ||
scope.push(format!( | ||
"space:{}?authority={}&skey={}&action=read{}", | ||
space.kind, | ||
space.authority, | ||
space.skey, | ||
ops.concat() | ||
)); | ||
} | ||
Ok((writes, own, scope.join(" "))) | ||
} | ||
| ||
/// What `member`, holding `roles`, may do to the space under `policy` | ||
/// itself, or, if there is none yet, make it: by their roles across | ||
/// the group, or the policy's grants. | ||
fn manage_ops( | ||
&self, | ||
group: &str, | ||
member: &str, | ||
roles: &[String], | ||
policy: Option<&Policy>, | ||
) -> Result<Vec<&'static str>, XrpcError> { | ||
let Some(policy) = policy else { | ||
let creates = self.may_do(group, member, "space.create")?; | ||
return Ok(creates.then_some("create").into_iter().collect()); | ||
}; | ||
let mut ops = Vec::new(); | ||
for (op, action) in [("update", "space.configure"), ("delete", "space.delete")] { | ||
if self.may_do(group, member, action)? || policy.manages(roles, op) { | ||
ops.push(op); | ||
} | ||
} | ||
Ok(ops) | ||
} | ||
} | ||
| ||
/// A token to act as the group in one of its spaces, for the caller's | ||
crates/group-host/src/import.rs+2−1
| @@ -573,7 +573,7 @@ impl Host { | ||
})?; | ||
let on = self.activate_arrived(did, &account.handle); | ||
on.map_err(XrpcError::internal)?; | ||
self.tell_spaces(did).await.map_err(XrpcError::internal)?; | ||
self.tell_spaces(did).await?; | ||
let group = NewGroup { | ||
handle: account.handle.clone(), | ||
founder: me.to_string(), | ||
| @@ -582,6 +582,7 @@ impl Host { | ||
..NewGroup::default() | ||
}; | ||
let made = self.make_group(did, &group).await?; | ||
self.open_spaces(did).await?; | ||
self.store.end_import(did).map_err(XrpcError::internal)?; | ||
let logged = self.record(did, me, None, "moved the account here as a group"); | ||
logged.map_err(XrpcError::internal)?; | ||
crates/group-host/src/import_space.rs+73−32
| @@ -10,11 +10,14 @@ | ||
//! (`com.atproto.space.getRepo`), checked against its commit's set hash. | ||
//! - `blob`: one of its files in a space, before the repos that hold it. | ||
//! | ||
//! A space's policy becomes this host's say over it: a memberspace's | ||
//! members their grants, and its public reading the space's. Anything | ||
//! this host would not do as the policy says (anyone writing, only some | ||
//! apps, a managing app) refuses the space rather than quietly widening | ||
//! or narrowing who uses it. | ||
//! A space's policy becomes this host's over it, `fyi.opensocial.policy`, | ||
//! left out of the group's index: a memberspace's public reading its | ||
//! `publicRead`, and its members, each kept as an account's grant beside | ||
//! the policy (reading, writing). Anything this host would not do as the | ||
//! policy says (anyone writing, only some apps, a managing app) refuses | ||
//! the space rather than quietly widening or narrowing who uses it. A | ||
//! space already under `fyi.opensocial.policy`, as a group moving between | ||
//! hosts brings its spaces, keeps its policy as it is. | ||
//! | ||
//! Its repos tell their spaces' authorities nothing while the account is | ||
//! switched off: an authority elsewhere would check the account's word | ||
| @@ -25,8 +28,9 @@ use crate::Host; | ||
use crate::api::{Params, invalid, param}; | ||
use crate::group::{members_space, meta_space}; | ||
use crate::group_api::signed_in; | ||
use crate::lexicons::lexicons; | ||
use crate::migration::create; | ||
use crate::rbac::NS; | ||
use crate::rbac::{NS, POLICY}; | ||
use crate::repo::{Asked, Write, record_cid}; | ||
use crate::store::{SpaceHead, Store}; | ||
use crate::xrpc::{XrpcError, read_body}; | ||
| @@ -48,6 +52,9 @@ pub const ARCHIVE_AT_MOST: u64 = 100 * 1024 * 1024; | ||
| ||
const PERSONAL: &str = "com.atproto.personalspace.policy"; | ||
const MEMBERS: &str = "com.atproto.memberspace.policy"; | ||
/// An account's grant in a space beside its policy, as a space meta | ||
/// archive's policy state keeps it. | ||
pub(crate) const MEMBER: &str = "com.atproto.memberspace.member"; | ||
const MEMBER_PREFIX: &str = "com.atproto.memberspace.member/"; | ||
const SPACE_REPOS: &str = "SELECT space, rev, state FROM space_repo WHERE did = ?1 ORDER BY space"; | ||
| ||
| @@ -83,17 +90,18 @@ pub fn record_key_to_did(rkey: &str) -> String { | ||
} | ||
} | ||
| ||
/// Who may do what in the space `meta` holds, as this host says it: whether | ||
/// anyone may read it, and each member's grant (reading, writing). | ||
fn access(meta: &SpaceMeta) -> Result<(bool, Vec<Grant>), XrpcError> { | ||
/// What this host keeps of the space `meta` holds: its policy, as ours, | ||
/// and each account's grant beside it (reading, writing). | ||
pub(crate) fn kept(meta: &SpaceMeta) -> Result<(serde_json::Value, Vec<Grant>), XrpcError> { | ||
let flag = |key: &str| meta.policy.get(key) == Some(&Value::Bool(true)); | ||
let kind = meta.policy.get("$type"); | ||
let members = match kind { | ||
Some(Value::String(t)) if t == MEMBERS => true, | ||
Some(Value::String(t)) if t == PERSONAL => false, | ||
let (ours, members) = match kind { | ||
Some(Value::String(t)) if t == POLICY => (true, true), | ||
Some(Value::String(t)) if t == MEMBERS => (false, true), | ||
Some(Value::String(t)) if t == PERSONAL => (false, false), | ||
_ => { | ||
return Err(unsupported( | ||
"a policy other than personalspace or memberspace", | ||
"a policy other than personalspace, memberspace or this host's own", | ||
)); | ||
} | ||
}; | ||
| @@ -116,21 +124,29 @@ fn access(meta: &SpaceMeta) -> Result<(bool, Vec<Grant>), XrpcError> { | ||
}; | ||
Ok((did, *read, *write)) | ||
}); | ||
Ok(( | ||
members && flag("publicRead"), | ||
grants.collect::<Result<_, _>>()?, | ||
)) | ||
let grants = grants.collect::<Result<_, _>>()?; | ||
let policy = Value::Map(meta.policy.clone()).to_json(); | ||
if ours { | ||
let checked = lexicons().validate(POLICY, &policy); | ||
checked.map_err(|e| refused("InvalidArchive", e.to_string()))?; | ||
return Ok((policy, grants)); | ||
} | ||
let mut policy = json!({"$type": POLICY, "unlisted": true, "grants": []}); | ||
if members && flag("publicRead") { | ||
policy["publicRead"] = json!(true); | ||
} | ||
Ok((policy, grants)) | ||
} | ||
| ||
impl Store { | ||
/// Keeps the space at `uri`, of `authority`'s, as an archive brought it, | ||
/// replacing what was kept for it: whether anyone may read it, `grants`, | ||
/// replacing what was kept for it: its policy, `grants` beside it, | ||
/// and `writers`, each with the space's revision it is kept at. | ||
pub fn import_space( | ||
&self, | ||
uri: &str, | ||
authority: &str, | ||
public_read: bool, | ||
policy: &serde_json::Value, | ||
grants: &[Grant], | ||
writers: &[Writer], | ||
now: i64, | ||
| @@ -138,9 +154,17 @@ impl Store { | ||
let mut conn = self.conn(); | ||
let tx = conn.transaction()?; | ||
tx.execute( | ||
"INSERT INTO space (uri, authority, public_read, created_at) VALUES (?1, ?2, ?3, ?4) | ||
ON CONFLICT (uri) DO UPDATE SET public_read = excluded.public_read", | ||
params![uri, authority, public_read, now], | ||
"INSERT INTO space (uri, authority, public_read, created_at, policy) | ||
VALUES (?1, ?2, ?3, ?4, ?5) | ||
ON CONFLICT (uri) DO UPDATE SET public_read = excluded.public_read, | ||
policy = excluded.policy", | ||
params![ | ||
uri, | ||
authority, | ||
policy["publicRead"] == true, | ||
now, | ||
policy.to_string() | ||
], | ||
)?; | ||
tx.execute("DELETE FROM space_grant WHERE space = ?1", [uri])?; | ||
tx.execute("DELETE FROM space_writer WHERE space = ?1", [uri])?; | ||
| @@ -183,10 +207,6 @@ impl Host { | ||
pub(crate) fn import_space_meta(&self, did: &str, bytes: &[u8]) -> Result<String, XrpcError> { | ||
let meta = read_space_meta(bytes); | ||
let meta = meta.map_err(|e| refused("InvalidArchive", e.to_string()))?; | ||
let space = SpaceRef::parse(&meta.space).expect("a space the archive's reader checked"); | ||
if space.authority != did { | ||
return Err(refused("NotSpaceOwner", "that space isn't the account's")); | ||
} | ||
// Its group makes these two as it is made. | ||
if [meta_space(did), members_space(did)].contains(&meta.space) { | ||
return Err(refused( | ||
| @@ -194,7 +214,17 @@ impl Host { | ||
format!("{} is the group's own, made with it", meta.space), | ||
)); | ||
} | ||
let (public_read, grants) = access(&meta)?; | ||
self.keep_space_meta(did, meta) | ||
} | ||
| ||
/// A space `did` governs, as `meta` holds it: kept here as this host | ||
/// would keep it, replacing what was kept of it. Its URI. | ||
pub(crate) fn keep_space_meta(&self, did: &str, meta: SpaceMeta) -> Result<String, XrpcError> { | ||
let space = SpaceRef::parse(&meta.space).expect("a space the archive's reader checked"); | ||
if space.authority != did { | ||
return Err(refused("NotSpaceOwner", "that space isn't the account's")); | ||
} | ||
let (policy, grants) = kept(&meta)?; | ||
// Its own repo there comes as a repo of its own, and is told to | ||
// the space as the account is switched on. | ||
let writers: Vec<_> = meta | ||
| @@ -206,7 +236,7 @@ impl Host { | ||
let now = crate::time::now_millis(); | ||
let kept = self | ||
.store | ||
.import_space(&meta.space, did, public_read, &grants, &writers, now); | ||
.import_space(&meta.space, did, &policy, &grants, &writers, now); | ||
kept.map_err(XrpcError::internal)?; | ||
Ok(meta.space) | ||
} | ||
| @@ -270,9 +300,10 @@ impl Host { | ||
} | ||
| ||
/// Tells each space `did` has a repo in of it, as `did` is switched on | ||
/// here, and reads the spaces it governs again. | ||
pub(crate) async fn tell_spaces(&self, did: &str) -> Result<()> { | ||
for (space, head) in self.store.space_repos(did)? { | ||
/// here. | ||
pub(crate) async fn tell_spaces(&self, did: &str) -> Result<(), XrpcError> { | ||
let repos = self.store.space_repos(did).map_err(XrpcError::internal)?; | ||
for (space, head) in repos { | ||
let parsed = SpaceRef::parse(&space).expect("a space the host keeps"); | ||
let data = LtHash::from_state(&head.state).expect("a state the host wrote"); | ||
let commit = Commit { | ||
| @@ -287,7 +318,17 @@ impl Host { | ||
tracing::warn!(space, repo = did, error, "telling the authority failed"); | ||
} | ||
} | ||
for space in self.store.spaces_of(did)? { | ||
Ok(()) | ||
} | ||
| ||
/// Publishes the policy of each space `did` governs, listing it in its | ||
/// index as the policy says, and reads it again: once its members | ||
/// space, which holds the index, is there. | ||
pub(crate) async fn open_spaces(&self, did: &str) -> Result<(), XrpcError> { | ||
let governed = self.store.spaces_of(did).map_err(XrpcError::internal)?; | ||
for space in governed { | ||
let policy = self.hosted_space(&space)?.policy; | ||
self.publish_policy(did, &space, &policy).await?; | ||
self.reindex(&space); | ||
} | ||
Ok(()) | ||
crates/group-host/src/index.rs+1−1
| @@ -1,6 +1,6 @@ | ||
//! The host's index of its groups' spaces: what each writer has written | ||
//! in each, read from wherever their repo is, so the host can answer for | ||
//! the space (`listSpaceRecords`) to whoever its access record lets read. | ||
//! the space (`listSpaceRecords`) to whoever its policy lets read. | ||
//! | ||
//! The host is each space's authority, so it knows its writer set: each | ||
//! writer's revision and digest as their host last said. When a writer's | ||
crates/group-host/src/index_api.rs+7−9
crates/group-host/src/lexicons.rs+9−4
crates/group-host/src/lib.rs+16−12
crates/group-host/src/mcp.rs+43−13
crates/group-host/src/member_writes.rs+7−2
crates/group-host/src/migration.rs+73−49
crates/group-host/src/oauth_scope.rs+69−62
crates/group-host/src/provision.rs+1−1
crates/group-host/src/rbac.rs+76−77
crates/group-host/src/scopes.rs+29−19
crates/group-host/src/store.rs+27−7
crates/group-host/src/token_writes.rs+18−16
crates/group-host/tests/common/oauth.rs+38−0
crates/group-host/tests/common/spaces.rs+10−0
crates/group-host/tests/actors.rs+11−1
crates/group-host/tests/authority.rs+16−9
crates/group-host/tests/authorization.rs+1−1
crates/group-host/tests/group_config.rs+14−11
crates/group-host/tests/group_spaces.rs+533−426
959 lines changed: not loaded until asked for.