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

Groups are started, read and listed

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:host/groups
crates/group-host/src/authority.rs+17−3
@@ -12,6 +12,7 @@
//! or a day has passed, as pds.js's `outbox.js` does.
use crate::Host;
use crate::rbac::{self, NS};
use crate::repo::invalid;
use crate::space::NOTIFY_WRITE;
use crate::store::{Notice, Space};
@@ -135,17 +136,30 @@ impl Host {
uri: &str,
space: &Space,
user: Option<&str>,
access: Access,
access_kind: Access,
) -> Result<bool> {
let Some(user) = user else {
return Ok(access == Access::Read && space.public_read);
return Ok(access_kind == Access::Read && space.public_read);
};
// The authority never locks itself out of its own space.
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.as_ref().map(rbac::Access::of) {
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);
}
}
let granted = self.store.granted(uri, user)?;
Ok(match access {
Ok(match access_kind {
Access::Read => space.public_read || granted.is_some_and(|(read, _)| read),
Access::Write => granted.is_some_and(|(_, write)| write),
})
crates/group-host/src/authority_api.rs+21−14
@@ -59,16 +59,27 @@ pub async fn get_space_credential(
if !matches!(PublicKey::from_did_key(kid), Ok(PublicKey::P256(_))) {
return Err(invalid("credentialKid is a P-256 did:key"));
}
let user = match body["delegationToken"].as_str() {
let delegation = match body["delegationToken"].as_str() {
Some(token) => Some(delegated(&host, token, &space).await?),
None => None,
};
let user = delegation.as_ref().map(|d| d.iss.as_str());
let hosted = host.store.space(uri).map_err(XrpcError::internal)?;
let hosted = hosted.ok_or_else(not_found)?;
let may = host.may(uri, &hosted, user.as_deref(), Access::Read);
let may = host.may(uri, &hosted, user, Access::Read);
if !may.map_err(XrpcError::internal)? {
return Err(not_found());
}
// Spent once it buys a credential: one token, one credential.
if let Some(d) = &delegation {
let spent = host.store.spend(&d.iss, &d.jti, d.exp as i64, now() as i64);
if !spent.map_err(XrpcError::internal)? {
return Err(bad(
"InvalidDelegationToken",
"the delegation token was used already",
));
}
}
let authority = host
.store
.account(&hosted.authority)
@@ -85,9 +96,13 @@ pub async fn get_space_credential(
Ok(Json(json!({ "credential": credential })))
}
/// The user a delegation token speaks for: signed by them, for this
/// space's authority and this space, and not spent before.
async fn delegated(host: &Host, token: &str, space: &SpaceRef) -> Result<String, XrpcError> {
/// What a delegation token says, once it is signed by the user it names,
/// for this space's authority and this space.
async fn delegated(
host: &Host,
token: &str,
space: &SpaceRef,
) -> Result<space_auth::Token, XrpcError> {
let refused = |m: String| bad("InvalidDelegationToken", m);
let (_, claims) = space_auth::parse(Kind::Delegation, token).map_err(|e| refused(e.message))?;
let aud = space_host_aud(&space.authority);
@@ -99,15 +114,7 @@ async fn delegated(host: &Host, token: &str, space: &SpaceRef) -> Result<String,
let check = |key: &PublicKey| space_auth::verify(Kind::Delegation, token, key, &expect, now());
let checked = host.identity.with_key(&claims.iss, check).await;
let checked = checked.ok_or_else(|| refused(format!("no signing key for {}", claims.iss)))?;
let claims = checked.map_err(|e| refused(e.message))?;
let spent = host
.store
.spend(&claims.iss, &claims.jti, claims.exp as i64, now() as i64)
.map_err(XrpcError::internal)?;
if !spent {
return Err(refused("the delegation token was used already".into()));
}
Ok(claims.iss)
checked.map_err(|e| refused(e.message))
}
/// A repo host says a repo of one of its accounts was written in a space
crates/group-host/src/config.rs+14−6
@@ -24,6 +24,9 @@ pub struct Config {
/// How a `did:web`'s document is read, `DID_WEB_SCHEME`: `https`, or
/// `http` for a network of test servers.
pub did_web_scheme: String,
/// Who this host starts groups for, `GROUP_FOUNDERS`, comma-separated
/// DIDs: anyone when it names none.
pub group_founders: Vec<String>,
/// The relays told of this host's news, `PDS_CRAWLERS`, comma-separated.
pub crawlers: Vec<String>,
/// The most bytes one blob may be, `BLOB_UPLOAD_LIMIT`.
@@ -61,12 +64,16 @@ impl Config {
if !["https", "http"].contains(&did_web_scheme.as_str()) {
bail!("DID_WEB_SCHEME is https or http, not {did_web_scheme}");
}
let crawlers = var("PDS_CRAWLERS").unwrap_or_default();
let crawlers = crawlers
.split(',')
.map(|c| c.trim().trim_end_matches('/').to_string())
.filter(|c| !c.is_empty())
.collect();
let list = |name: &str| -> Vec<String> {
var(name)
.unwrap_or_default()
.split(',')
.map(|c| c.trim().trim_end_matches('/').to_string())
.filter(|c| !c.is_empty())
.collect()
};
let group_founders = list("GROUP_FOUNDERS");
let crawlers = list("PDS_CRAWLERS");
let blob_upload_limit = match var("BLOB_UPLOAD_LIMIT") {
Some(l) => l
.parse()
@@ -81,6 +88,7 @@ impl Config {
data_dir,
plc_url,
did_web_scheme,
group_founders,
crawlers,
blob_upload_limit,
})
crates/group-host/src/group.rsnew+261−0
@@ -0,0 +1,261 @@
//! Groups: an account here with two spaces of its own, `meta` (its
//! profile, rules and labeler, for whoever it lets read them) and
//! `members` (its roles, what each may do, its memberships and the index
//! of its spaces, for its members). Everything a group is lives in those
//! records, written by the group; who may read or write each space is its
//! access record, against the reader's roles.
//!
//! As the prototype's `bootstrap.ts` makes one, and `group.ts` reads it.
use crate::Host;
use crate::rbac::{ACTIONS, Grant, NS, listed};
use crate::repo::{Write, invalid};
use crate::store::Record;
use crate::time::{iso, now_millis};
use crate::xrpc::XrpcError;
use anyhow::Result;
use atproto::drisl;
use axum::http::StatusCode;
use serde_json::{Value, json};
/// A group's meta space, at `did`.
pub fn meta_space(did: &str) -> String {
format!("at://{did}/space/{NS}.meta/self")
}
/// A group's members space, at `did`.
pub fn members_space(did: &str) -> String {
format!("at://{did}/space/{NS}.members/self")
}
/// A DID as a record key: a record key holds no `%`, so a did:web's
/// encoded port is written plain.
pub fn did_rkey(did: &str) -> String {
did.replace("%3A", ":")
}
/// What the labeler every group starts with says: the labels the host
/// acts on, and reports about records.
fn labeler(at: &str) -> Value {
let reasons = ["Spam", "Violation", "Misleading", "Sexual", "Rude", "Other"]
.map(|r| format!("com.atproto.moderation.defs#reason{r}"));
json!({
"$type": format!("{NS}.labeler"),
"policies": {"labelValues": ["!hide", "!takedown"]},
"reasonTypes": reasons,
"subjectTypes": ["record"],
"createdAt": at,
})
}
/// 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.
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"),
Some("open") => Ok("open"),
Some("invite") => Ok("invite"),
Some(other) => Err(invalid(format!(
"joinPolicy is open, approval or invite, not {other}"
))),
}
}
/// 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.
#[derive(Debug, Clone, Default)]
pub struct NewGroup {
pub handle: String,
pub founder: String,
pub stewards: Vec<String>,
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>>,
}
/// A group made: its DID and its two spaces.
#[derive(Debug, Clone, PartialEq)]
pub struct Made {
pub did: String,
pub meta: String,
pub members: String,
}
fn put(collection: &str, rkey: &str, value: Value) -> Write {
Write::Create {
collection: collection.into(),
rkey: rkey.into(),
value,
}
}
fn audience(roles: &[String]) -> Value {
roles.iter().map(|r| json!({ "role": r })).collect()
}
impl Host {
/// Whether this host starts groups for `did`: anyone, unless
/// `GROUP_FOUNDERS` names who.
pub fn may_found(&self, did: &str) -> bool {
let founders = &self.config.group_founders;
founders.is_empty() || founders.iter().any(|f| f == did)
}
/// Makes a group: its account, its two spaces and what they hold from
/// its first day, and its declaration if anyone may read its meta.
pub async fn create_group(&self, new: &NewGroup) -> Result<Made, XrpcError> {
if !self.may_found(&new.founder) {
return Err(XrpcError::new(
StatusCode::FORBIDDEN,
"NotAllowed",
"this host is not starting groups for you",
));
}
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 !atproto::syntax::is_did(s) {
return Err(invalid(format!("steward {s} is no DID")));
}
if !stewards.contains(s) {
stewards.push(s.clone());
}
}
let did = self.create_account(&new.handle).await.map_err(|e| {
if e.error == "HandleNotAvailable" {
XrpcError::new(e.status, "HandleTaken", e.message)
} else {
e
}
})?;
let meta = self.create_space(&did, &format!("{NS}.meta"), "self", false)?;
let members = self.create_space(&did, &format!("{NS}.members"), "self", false)?;
let at = iso(now_millis());
let c = |name: &str| format!("{NS}.{name}");
let mut profile = json!({
"$type": c("profile"),
"displayName": new.display_name,
"joinPolicy": join,
"createdAt": at,
});
if let Some(d) = &new.description {
profile["description"] = json!(d);
}
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,
}),
),
];
self.space_write(&did, &meta, &meta_writes).await?;
let admin = Grant::with("admin", &ACTIONS, &["member"], &["*"]);
let member = Grant::with("member", &[], &[], &[]);
let mut members_writes = vec![
put(
&c("access"),
"self",
json!({"$type": c("access"), "readableBy": [{"role": "member"}], "createdAt": at}),
),
put(
&c("role"),
"admin",
json!({"$type": c("role"), "displayName": "Admin", "description": "Runs the group.", "createdAt": at}),
),
put(
&c("role"),
"member",
json!({"$type": c("role"), "displayName": "Member", "default": true, "createdAt": at}),
),
put(
&c("permissions"),
"self",
json!({"$type": c("permissions"), "grants": [admin.to_json(), member.to_json()], "createdAt": at}),
),
];
// The index of the group's spaces, which apps read to find them.
for space in [&meta, &members] {
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"),
&did_rkey(steward),
json!({"$type": c("membership"), "member": steward, "roles": [{"role": "admin"}, {"role": "member"}], "createdAt": at}),
));
}
self.space_write(&did, &members, &members_writes).await?;
// Listed only if there is a face to show: a meta anyone may read.
if readers.iter().any(|r| r == "public") {
let declaration = json!({"$type": c("declaration"), "meta": meta, "createdAt": at});
self.write(&did, &[put(&c("declaration"), "self", declaration)])?;
}
Ok(Made { did, meta, members })
}
/// The group's own record in `space`, as JSON.
pub fn group_record(
&self,
group: &str,
space: &str,
collection: &str,
rkey: &str,
) -> Result<Option<Value>> {
let found = self.store.space_record(group, space, collection, rkey)?;
Ok(found.map(|r| json_of(&r)))
}
/// Every record of `collection` in the group's own repo in `space`,
/// with its key, in key order.
pub fn group_records(
&self,
group: &str,
space: &str,
collection: &str,
) -> Result<Vec<(String, Value)>> {
let records =
self.store
.space_list(group, space, Some(collection), None, u32::MAX, true)?;
Ok(records
.iter()
.map(|r| (r.rkey.clone(), json_of(r)))
.collect())
}
/// The roles `did` holds in `group`: none for one not a member.
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())
}
}
fn json_of(record: &Record) -> Value {
drisl::decode(&record.value)
.expect("a record the host wrote")
.to_json()
}
crates/group-host/src/group_api.rsnew+342−0
@@ -0,0 +1,342 @@
//! The `fyi.opensocial.*` methods that make and read groups: starting
//! one, a group as its viewer may see it, and every group here.
//!
//! A caller is who their service auth says, for this host (`SERVICE_DID`)
//! and the method: their own PDS signs it for them.
use crate::Host;
use crate::api::{Params, invalid, 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::space_api::{service_caller, unauthorized};
use crate::xrpc::XrpcError;
use axum::Json;
use axum::extract::{Query, State};
use axum::http::{HeaderMap, StatusCode, header};
use serde_json::{Value, json};
use std::sync::Arc;
type Answer = Result<Json<Value>, XrpcError>;
/// Who calls `lxm`, by their service auth for this host; none without
/// any.
pub(crate) async fn caller(
host: &Host,
headers: &HeaderMap,
lxm: &str,
) -> Result<Option<String>, XrpcError> {
if !headers.contains_key(header::AUTHORIZATION) {
return Ok(None);
}
let claims = service_caller(host, headers, lxm).await?;
let ours = &host.config.service_did;
let for_us = claims.aud == *ours
|| claims
.aud
.strip_prefix(ours.as_str())
.is_some_and(|f| f.starts_with('#'));
if !for_us {
return Err(unauthorized(
"BadJwtAudience",
format!("a token for {}, not this host", claims.aud),
));
}
Ok(Some(claims.account().to_string()))
}
/// Who calls `lxm`, who must say.
async fn signed_in(host: &Host, headers: &HeaderMap, lxm: &str) -> Result<String, XrpcError> {
let who = caller(host, headers, lxm).await?;
who.ok_or_else(|| unauthorized("AuthMissing", "service auth is required"))
}
fn strings(body: &Value, key: &str, field: &str) -> Option<Vec<String>> {
body.get(key).map(|_| listed(body, key, field))
}
/// Starts a group, the caller its founder and first admin.
pub async fn create_group(
State(host): State<Arc<Host>>,
headers: HeaderMap,
Json(body): Json<Value>,
) -> Answer {
let founder = signed_in(&host, &headers, &format!("{NS}.createGroup")).await?;
let text = |k: &str| body[k].as_str().map(String::from);
let new = NewGroup {
handle: text("handle").ok_or_else(|| invalid("handle is required"))?,
founder,
stewards: strings(&body, "stewards", "did").unwrap_or_default(),
display_name: text("displayName").ok_or_else(|| invalid("displayName is required"))?,
description: text("description"),
join_policy: text("joinPolicy"),
meta_readable_by: strings(&body, "metaReadableBy", "role"),
};
let Made { did, meta, members } = host.create_group(&new).await?;
Ok(Json(json!({"did": did, "meta": meta, "members": members})))
}
fn not_found() -> XrpcError {
XrpcError::new(
StatusCode::BAD_REQUEST,
"GroupNotFound",
"no such group here",
)
}
/// A group here: its handle, if `did` is one.
fn group_of(host: &Host, did: &str) -> Result<String, XrpcError> {
let account = host.store.account(did).map_err(XrpcError::internal)?;
let account = account.filter(|a| a.did == did).ok_or_else(not_found)?;
let space = host
.store
.space(&members_space(did))
.map_err(XrpcError::internal)?;
space.map(|_| account.handle).ok_or_else(not_found)
}
/// The CID a blob reference names.
fn cid_of(blob: &Value) -> Option<&str> {
blob["ref"]["$link"].as_str()
}
/// What a group's profile shows of it.
fn profile_view(profile: &Value) -> Value {
let mut view = json!({});
for key in [
"displayName",
"description",
"joinPolicy",
"url",
"location",
"online",
"topics",
"languages",
] {
if let Some(v) = profile.get(key) {
view[key] = v.clone();
}
}
for key in ["avatar", "banner"] {
if let Some(cid) = cid_of(&profile[key]) {
view[key] = json!(cid);
}
}
view
}
/// The group's rules in the order they are presented: by `order`, then as
/// written, then by key.
fn rules(host: &Host, group: &str) -> Result<Vec<Value>, XrpcError> {
let mut rules = host
.group_records(group, &meta_space(group), &format!("{NS}.rule"))
.map_err(XrpcError::internal)?;
rules.sort_by(|(ak, a), (bk, b)| {
let order = |r: &Value| r["order"].as_i64().unwrap_or(i64::MAX);
let at = |r: &Value| r["createdAt"].as_str().unwrap_or_default().to_string();
(order(a), at(a), ak).cmp(&(order(b), at(b), bk))
});
Ok(rules
.into_iter()
.map(|(rkey, r)| {
let mut rule = json!({"rkey": rkey, "title": r["title"]});
for key in ["text", "createdAt"] {
if let Some(v) = r.get(key) {
rule[key] = v.clone();
}
}
rule
})
.collect())
}
fn base(did: &str, handle: &str) -> Value {
json!({
"did": did,
"handle": handle,
"address": handle,
"meta": meta_space(did),
"members": members_space(did),
})
}
fn merge(into: &mut Value, from: Value) {
if let (Some(into), Value::Object(from)) = (into.as_object_mut(), from) {
into.extend(from);
}
}
fn objects(field: &str, items: impl IntoIterator<Item = impl Into<String>>) -> Value {
items
.into_iter()
.map(|i| json!({ field: i.into() }))
.collect()
}
/// 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, its members, roles and spaces.
pub async fn get_group(
State(host): State<Arc<Host>>,
Query(p): Query<Params>,
headers: HeaderMap,
) -> Answer {
let group = param(&p, "group")?;
let handle = group_of(&host, group)?;
let me = caller(&host, &headers, &format!("{NS}.getGroup")).await?;
let record = |space: &str, collection: &str, rkey: &str| {
host.group_record(group, space, &format!("{NS}.{collection}"), rkey)
.map_err(XrpcError::internal)
};
let (meta, members) = (meta_space(group), members_space(group));
let roles = match &me {
Some(me) => host.roles(group, me).map_err(XrpcError::internal)?,
None => Vec::new(),
};
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)))
};
let reads_meta = reads(&meta)?;
let reads_members = me.is_some() && reads(&members)?;
let permissions = record(&members, "permissions", "self")?.unwrap_or_default();
let granted = grants(&permissions);
let actions = actions_for(&granted, &roles);
let mut view = base(group, &handle);
if reads_meta {
if let Some(profile) = record(&meta, "profile", "self")? {
merge(&mut view, profile_view(&profile));
}
view["rules"] = json!(rules(&host, group)?);
}
if let Some(me) = &me {
let member = !roles.is_empty();
let mut viewer = json!({
"member": member,
"roles": objects("role", roles.clone()),
"actions": actions,
});
if member {
viewer["accepted"] = json!(accepted(&host, &members, me).map_err(XrpcError::internal)?);
}
view["viewer"] = viewer;
}
let mut out = json!({ "group": view });
if !reads_members {
return Ok(Json(out));
}
let records = |collection: &str| {
host.group_records(group, &members, &format!("{NS}.{collection}"))
.map_err(XrpcError::internal)
};
out["members"] = records("membership")?
.into_iter()
.map(|(_, m)| json!({"actor": {"did": m["member"]}, "roles": objects("role", listed(&m, "roles", "role"))}))
.collect();
out["roles"] = records("role")?
.into_iter()
.map(|(key, r)| {
let mut role = json!({"key": key});
for (from, to) in [
("displayName", "name"),
("description", "description"),
("bot", "bot"),
] {
if let Some(v) = r.get(from) {
role[to] = v.clone();
}
}
role
})
.collect();
out["bindings"] = granted
.iter()
.map(|g| {
let one = std::slice::from_ref(&g.role);
json!({
"role": g.role,
"actions": actions_for(&granted, one),
"assignable": objects("role", g.assignable.clone()),
"repoCollections": objects("collection", repo_collections_for(&granted, one)),
"scopes": objects("scope", g.scopes.clone()),
})
})
.collect();
let mut spaces = Vec::new();
for (_, entry) in records("space")? {
let uri = entry["space"].as_str().unwrap_or_default();
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).can_read(&roles, me_or)) {
for key in ["readableBy", "people", "writableBy", "credentialScopes"] {
if let Some(v) = access.get(key) {
space[key] = v.clone();
}
}
}
spaces.push(space);
}
out["spaces"] = json!(spaces);
Ok(Json(out))
}
/// Whether `did` has written their own acceptance in the members space:
/// their repo there holds anything.
fn accepted(host: &Host, members: &str, did: &str) -> anyhow::Result<bool> {
let empty = atproto::space::LtHash::default().digest();
let writers = host.store.writers(members, None, u32::MAX)?;
Ok(writers.iter().any(|w| w.did == did && w.data != empty))
}
/// Every group here: its handle and spaces, and for one whose meta anyone
/// may read, its profile and rules. Unauthenticated.
pub async fn list_groups(State(host): State<Arc<Host>>) -> Answer {
let mut groups = Vec::new();
let mut cursor: Option<String> = None;
loop {
let page = host
.store
.accounts(cursor.as_deref(), 100)
.map_err(XrpcError::internal)?;
for (did, _) in &page {
let Ok(handle) = group_of(&host, did) else {
continue;
};
let mut view = base(did, &handle);
let meta = meta_space(did);
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))
{
let profile = host
.group_record(did, &meta, &format!("{NS}.profile"), "self")
.map_err(XrpcError::internal)?;
if let Some(profile) = profile {
merge(&mut view, profile_view(&profile));
}
view["rules"] = rules(&host, did)?
.into_iter()
.map(|mut r| {
r.as_object_mut().map(|o| o.remove("createdAt"));
r
})
.collect();
}
groups.push(view);
}
if page.len() < 100 {
break;
}
cursor = page.last().map(|(did, _)| did.clone());
}
Ok(Json(json!({ "groups": groups })))
}
crates/group-host/src/lib.rs+12−0
@@ -9,8 +9,11 @@ pub mod authority_api;
pub mod blobs;
pub mod config;
pub mod firehose;
pub mod group;
pub mod group_api;
pub mod identity;
pub mod plc;
pub mod rbac;
pub mod repo;
pub mod secrets;
pub mod space;
@@ -154,6 +157,15 @@ pub fn router(host: Arc<Host>) -> Router {
"/xrpc/com.atproto.space.unregisterNotify",
post(authority_api::unregister_notify),
)
.route(
"/xrpc/fyi.opensocial.createGroup",
post(group_api::create_group),
)
.route("/xrpc/fyi.opensocial.getGroup", get(group_api::get_group))
.route(
"/xrpc/fyi.opensocial.listGroups",
get(group_api::list_groups),
)
.route("/.well-known/did.json", get(api::did_json))
.route("/.well-known/atproto-did", get(api::atproto_did))
.route("/xrpc/{nsid}", get(not_implemented).post(not_implemented))
crates/group-host/src/rbac.rsnew+249−0
@@ -0,0 +1,249 @@
//! What a group's records let each of its people do, as pure functions
//! over those records: a space's access record says who reads it and who
//! writes in it; the permissions record grants each role OAuth scopes, and
//! each action the host's methods ask about is answered by one scope.
//! Roles compose by union: no deny, no precedence, no hierarchy.
//!
//! As the prototype's `access.ts` and `roles.ts` have them, over this
//! host's records, whose lists are of objects (`{role}`, `{scope}`).
use serde_json::Value;
use std::collections::BTreeSet;
pub const NS: &str = "fyi.opensocial";
/// Anyone signed in, as an audience.
pub const PUBLIC: &str = "public";
/// The actions the host's methods ask about.
pub const ACTIONS: [&str; 12] = [
"mod.read",
"mod.resolve",
"label",
"takedown",
"invite",
"admit",
"eject",
"role.assign",
"space.create",
"space.configure",
"space.delete",
"group.configure",
];
/// The values of `field` in each object of the list at `key`, as
/// `[{role: "admin"}]` holds `admin`.
pub fn listed(record: &Value, key: &str, field: &str) -> Vec<String> {
record[key]
.as_array()
.map(|items| {
items
.iter()
.filter_map(|i| i[field].as_str().map(String::from))
.collect()
})
.unwrap_or_default()
}
/// A space's access record, as read.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Access {
pub readable_by: Vec<String>,
/// 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.
pub writable_by: Option<Vec<String>>,
}
impl Access {
pub fn of(record: &Value) -> Access {
let maybe = |key: &str, field: &str| record.get(key).map(|_| listed(record, key, field));
Access {
readable_by: listed(record, "readableBy", "role"),
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.
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));
}
self.readable_by
.iter()
.any(|r| r == PUBLIC || roles.contains(r))
}
/// May `did`, holding `roles`, write in the space in their own name?
/// Any member, 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(),
Some(by) => by.iter().any(|r| r == PUBLIC || roles.contains(r)),
}
}
}
/// The actions a host method's `rpc:` scope grants, by method.
const BY_METHOD: [(&str, &str); 7] = [
("assignRoles", "role.assign"),
("ejectMember", "eject"),
("createInvite", "invite"),
("admitMember", "admit"),
("listSubjects", "mod.read"),
("resolveSubject", "mod.resolve"),
("applyLabel", "label"),
];
/// The scope that grants each action.
pub fn scope_of(action: &str) -> Option<String> {
let rpc = |method: &str| format!("rpc:{NS}.{method}?aud=*");
Some(match action {
"group.configure" => format!("include:{NS}.configure"),
"space.create" => "space:*?manage=create".into(),
"space.delete" => "space:*?manage=delete".into(),
"space.configure" => format!("space:*?collection={NS}.access"),
"role.assign" => rpc("assignRoles"),
"eject" => rpc("ejectMember"),
"invite" => rpc("createInvite"),
"admit" => rpc("admitMember"),
"mod.read" => rpc("listSubjects"),
"mod.resolve" => rpc("resolveSubject"),
"label" => rpc("applyLabel"),
"takedown" => format!("space:*?collection={NS}.label"),
_ => return None,
})
}
/// The values of `name` in a scope's query.
fn query<'a>(scope: &'a str, name: &str) -> Vec<&'a str> {
let q = scope.split_once('?').map_or("", |(_, q)| q);
q.split('&')
.filter_map(|kv| kv.split_once('='))
.filter(|(k, _)| *k == name)
.map(|(_, v)| v)
.collect()
}
/// What these scopes let their holder do. A scope that is none of the
/// host's grants nothing.
pub fn actions_of(scopes: &[String]) -> BTreeSet<&'static str> {
let mut out = BTreeSet::new();
for scope in scopes {
if *scope == format!("include:{NS}.configure") {
out.insert("group.configure");
} else if let Some(rpc) = scope.strip_prefix("rpc:") {
let method = rpc.split('?').next().unwrap_or_default();
let action = BY_METHOD
.iter()
.find(|(m, _)| method == format!("{NS}.{m}"));
if let Some((_, action)) = action {
out.insert(*action);
}
} else if scope.starts_with("space:*") {
let manage = query(scope, "manage");
if manage.contains(&"create") {
out.insert("space.create");
}
if manage.contains(&"delete") {
out.insert("space.delete");
}
if !manage.is_empty() {
continue;
}
let collections = query(scope, "collection");
let every = collections.is_empty() || collections.contains(&"*");
if every || collections.contains(&format!("{NS}.access").as_str()) {
out.insert("space.configure");
}
if every || collections.contains(&format!("{NS}.label").as_str()) {
out.insert("label");
out.insert("takedown");
}
}
}
out
}
/// A role's grant in the permissions record: its scopes and the roles its
/// holders may assign.
#[derive(Debug, Clone, PartialEq)]
pub struct Grant {
pub role: String,
pub scopes: Vec<String>,
pub assignable: Vec<String>,
}
impl Grant {
/// A grant of `actions` and the public-repo `collections`.
pub fn with(role: &str, actions: &[&str], assignable: &[&str], collections: &[&str]) -> Grant {
let mut scopes: Vec<String> = actions.iter().filter_map(|a| scope_of(a)).collect();
scopes.extend(collections.iter().map(|c| format!("repo:{c}")));
Grant {
role: role.into(),
scopes,
assignable: assignable.iter().map(|r| r.to_string()).collect(),
}
}
/// As the permissions record keeps it.
pub fn to_json(&self) -> Value {
let objects = |field: &str, items: &[String]| -> Value {
items
.iter()
.map(|i| serde_json::json!({ field: i }))
.collect()
};
serde_json::json!({
"role": self.role,
"scopes": objects("scope", &self.scopes),
"assignable": objects("role", &self.assignable),
})
}
}
/// The grants a permissions record holds.
pub fn grants(permissions: &Value) -> Vec<Grant> {
permissions["grants"]
.as_array()
.map(|grants| {
grants
.iter()
.map(|g| Grant {
role: g["role"].as_str().unwrap_or_default().into(),
scopes: listed(g, "scopes", "scope"),
assignable: listed(g, "assignable", "role"),
})
.collect()
})
.unwrap_or_default()
}
/// Every action a holder of `roles` has, by union.
pub fn actions_for(grants: &[Grant], roles: &[String]) -> BTreeSet<&'static str> {
let scopes: Vec<String> = grants
.iter()
.filter(|g| roles.contains(&g.role))
.flat_map(|g| g.scopes.clone())
.collect();
actions_of(&scopes)
}
/// The public-repo collections a holder of `roles` may write as the group.
pub fn repo_collections_for(grants: &[Grant], roles: &[String]) -> BTreeSet<String> {
grants
.iter()
.filter(|g| roles.contains(&g.role))
.flat_map(|g| g.scopes.iter())
.filter_map(|s| s.strip_prefix("repo:"))
.map(|c| c.split('?').next().unwrap_or_default().to_string())
.collect()
}
crates/group-host/tests/config.rs+3−0
@@ -20,6 +20,7 @@ fn defaults_serve_localhost() {
assert_eq!(c.handle_domain, ".test");
assert_eq!(c.data_dir, std::path::PathBuf::from("data"));
assert_eq!(c.did_web_scheme, "https");
assert!(c.group_founders.is_empty());
}
#[test]
@@ -39,8 +40,10 @@ fn the_environment_names_the_host() {
let c = config(&[
("SERVICE_DID", "did:web:other.example"),
("DID_WEB_SCHEME", "http"),
("GROUP_FOUNDERS", "did:plc:a, did:plc:b,"),
])
.unwrap();
assert_eq!(c.group_founders, ["did:plc:a", "did:plc:b"]);
assert_eq!(c.service_did, "did:web:other.example");
assert_eq!(c.did_web_scheme, "http");
}
crates/group-host/tests/groups.rsnew+580−0
580 lines changed: not loaded until asked for.
crates/group-host/tests/rbac.rsnew+135−0
@@ -0,0 +1,135 @@
//! What a group's records let each of its people do.
use group_host::group::join_policy;
use group_host::rbac::{
ACTIONS, Access, Grant, actions_for, actions_of, grants, listed, repo_collections_for, scope_of,
};
use serde_json::json;
fn roles(names: &[&str]) -> Vec<String> {
names.iter().map(|r| r.to_string()).collect()
}
#[test]
fn reads_and_writes_by_the_access_record() {
let members = Access::of(&json!({"readableBy": [{"role": "member"}]}));
assert!(members.can_read(&roles(&["member"]), "did:plc:a"));
assert!(!members.can_read(&[], "did:plc:a"));
// Any member writes, unless it says who.
assert!(members.can_write_own(&roles(&["member"]), "did:plc:a"));
assert!(!members.can_write_own(&[], "did:plc:a"));
let public = Access::of(
&json!({"readableBy": [{"role": "public"}], "writableBy": [{"role": "public"}]}),
);
assert!(public.can_read(&[], "did:plc:a"));
assert!(public.can_write_own(&[], "did:plc:a"));
let mods = Access::of(&json!({"readableBy": [], "writableBy": [{"role": "mod"}]}));
assert!(mods.can_write_own(&roles(&["mod"]), "did:plc:a"));
assert!(!mods.can_write_own(&roles(&["member"]), "did:plc:a"));
// For chosen people: them while they are members, and its reviewers.
let chosen = Access::of(&json!({
"readableBy": [{"role": "public"}],
"people": [{"did": "did:plc:a"}],
"reviewers": [{"role": "admin"}],
}));
assert!(chosen.can_read(&roles(&["member"]), "did:plc:a"));
assert!(!chosen.can_read(&[], "did:plc:a"));
assert!(!chosen.can_read(&roles(&["member"]), "did:plc:b"));
assert!(chosen.can_read(&roles(&["admin"]), "did:plc:b"));
assert!(chosen.can_write_own(&roles(&["member"]), "did:plc:a"));
assert!(!chosen.can_write_own(&roles(&["admin"]), "did:plc:b"));
assert_eq!(Access::of(&json!({})), Access::default());
assert_eq!(
listed(&json!({"x": [{"role": 1}, {"role": "a"}]}), "x", "role"),
["a"]
);
}
#[test]
fn answers_each_action_by_its_scope() {
for action in ACTIONS {
let scope = scope_of(action).unwrap();
assert!(
actions_of(std::slice::from_ref(&scope)).contains(action),
"{action} by {scope}"
);
}
assert_eq!(scope_of("fly"), None);
let none: [&str; 0] = [];
for nothing in [
"rpc:fyi.opensocial.fly?aud=*",
"rpc:com.example.thing",
"repo:*",
"blob:*/*",
] {
assert_eq!(
actions_of(&[nothing.into()])
.into_iter()
.collect::<Vec<_>>(),
none,
"{nothing}"
);
}
// A space scope over every collection labels, takes down and
// configures; one managing makes and deletes spaces.
let every = actions_of(&["space:*".into()]);
assert_eq!(
every.into_iter().collect::<Vec<_>>(),
["label", "space.configure", "takedown"]
);
let star = actions_of(&["space:*?collection=*".into()]);
assert_eq!(star.len(), 3);
let manage = actions_of(&["space:*?manage=create&manage=delete".into()]);
assert_eq!(
manage.into_iter().collect::<Vec<_>>(),
["space.create", "space.delete"]
);
let other = actions_of(&["space:*?collection=xyz.task".into()]);
assert!(other.is_empty());
}
#[test]
fn roles_compose_by_union() {
let record = json!({"grants": [
Grant::with("admin", &["invite", "admit"], &["member"], &["*"]).to_json(),
Grant::with("mod", &["label"], &[], &["xyz.post?action=create"]).to_json(),
{"role": "odd"},
]});
let granted = grants(&record);
assert_eq!(granted.len(), 3);
assert_eq!(granted[0].assignable, ["member"]);
assert_eq!(granted[2].scopes, Vec::<String>::new());
let both = roles(&["admin", "mod"]);
assert_eq!(
actions_for(&granted, &both).into_iter().collect::<Vec<_>>(),
["admit", "invite", "label"]
);
assert_eq!(
repo_collections_for(&granted, &both)
.into_iter()
.collect::<Vec<_>>(),
["*", "xyz.post"]
);
assert!(actions_for(&granted, &[]).is_empty());
assert!(grants(&json!({})).is_empty());
}
#[test]
fn reads_a_join_policy_in_either_words() {
assert_eq!(join_policy(None).unwrap(), "approval");
assert_eq!(
join_policy(Some("fyi.opensocial.profile#request")).unwrap(),
"approval"
);
assert_eq!(join_policy(Some("approval")).unwrap(), "approval");
assert_eq!(
join_policy(Some("fyi.opensocial.profile#open")).unwrap(),
"open"
);
assert_eq!(join_policy(Some("invite")).unwrap(), "invite");
assert_eq!(
join_policy(Some("sometimes")).unwrap_err().message,
"joinPolicy is open, approval or invite, not sometimes"
);
}
crates/group-host/tests/serve.rs+2−2
@@ -50,8 +50,8 @@ async fn answers_health_and_refuses_unknown_methods() {
assert_eq!(health["version"], env!("CARGO_PKG_VERSION"));
for req in [
http.get(format!("{}/xrpc/fyi.opensocial.getGroup", host.1)),
http.post(format!("{}/xrpc/fyi.opensocial.createGroup", host.1)),
http.get(format!("{}/xrpc/fyi.opensocial.listInvites", host.1)),
http.post(format!("{}/xrpc/fyi.opensocial.assignRoles", host.1)),
] {
let res = req.send().await.unwrap();
assert_eq!(res.status(), 501);
docs/design/groups.mdnew+78−0
docs/design/README.md+5−3
docs/reference/config.md+1−0
docs/README.md+1−1