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

The host follows the opensocial proposal of 19 November

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:feature/proposal-nov
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/api.rs+10−0
@@ -31,6 +31,16 @@ pub(crate) fn invalid(message: impl Into<String>) -> XrpcError {
XrpcError::new(StatusCode::BAD_REQUEST, "InvalidRequest", message)
}
/// A cursor this host never gave, as a list whose lexicon names
/// `InvalidCursor` refuses it.
pub(crate) fn invalid_cursor() -> XrpcError {
XrpcError::new(
StatusCode::BAD_REQUEST,
"InvalidCursor",
"a cursor this host gave",
)
}
/// The parameter `name`, which the method needs.
pub(crate) fn param<'a>(params: &'a Params, name: &str) -> Result<&'a str, XrpcError> {
params
crates/group-host/src/app_passwords.rs+3−12
@@ -15,13 +15,12 @@
use crate::Host;
use crate::api::{Params, invalid, param};
use crate::group::members_space;
use crate::group_api::{group_of, signed_in};
use crate::limits::{Client, SESSIONS, key};
use crate::oauth_dpop::hmac;
use crate::oauth_resource::{Acting, Refusal};
use crate::oauth_store::{AppPassword, Grant, Tokens, app_password_client};
use crate::rbac::{NS, grants, repo_collections_for};
use crate::rbac::{NS, repo_collections_for};
use crate::scopes::Permissions;
use crate::time::{iso, now_millis};
use crate::xrpc::XrpcError;
@@ -83,16 +82,8 @@ impl Host {
/// anything as it, every repo collection.
pub fn may_issue(&self, group: &str, member: &str) -> Result<bool, XrpcError> {
let roles = self.roles(group, member).map_err(XrpcError::internal)?;
let permissions = self.group_record(
group,
&members_space(group),
&format!("{NS}.permissions"),
"self",
);
let permissions = permissions
.map_err(XrpcError::internal)?
.unwrap_or_default();
Ok(repo_collections_for(&grants(&permissions), &roles).contains("*"))
let granted = self.role_grants(group).map_err(XrpcError::internal)?;
Ok(repo_collections_for(&granted, &roles).contains("*"))
}
/// Whether a session's app password still stands: there, and its
crates/group-host/src/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+27−14
@@ -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") {
@@ -129,12 +127,17 @@ impl Host {
}
}
/// What each of this host's permission sets asked for is called, and
/// says it is for.
fn labels(requested: &[String]) -> Value {
let ours = requested.iter().filter_map(|s| Some((s, set_of(s)?)));
ours.map(|(s, set)| json!({"scope": s, "title": set["title"], "text": set["detail"]}))
.collect()
/// What each of this host's permission sets among `scopes` is called,
/// and says it is for, once each.
fn labels(scopes: &[&str]) -> Value {
let mut out: Vec<Value> = Vec::new();
for (i, s) in scopes.iter().enumerate() {
let set = set_of(s).filter(|_| !scopes[..i].contains(s));
out.extend(
set.map(|set| json!({"scope": s, "title": set["title"], "text": set["detail"]})),
);
}
out.into()
}
/// An app's pending request to sign in as a group, as the caller would
@@ -172,10 +175,20 @@ pub async fn get_authorization(
for group in &groups {
offered.push(host.offered(group, &me, &requested)?.0);
}
// Each set asked for, and any within it a group would give in its
// place.
let granted = offered
.iter()
.flat_map(|g| g["granted"].as_array().into_iter().flatten());
let named: Vec<&str> = requested
.iter()
.map(String::as_str)
.chain(granted.filter_map(|g| g["scope"].as_str()))
.collect();
let mut out = json!({
"client": client,
"requested": objects("scope", &requested),
"labels": labels(&requested),
"labels": labels(&named),
"groups": offered,
});
if let Some(hint) = request.parameters.get("login_hint") {
@@ -212,7 +225,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+83−75
@@ -1,12 +1,12 @@
//! Groups: an account here with two spaces of its own, `meta` (its
//! profile, rules and labeler, for whoever it lets read them) and
//! `members` (its roles, what each may do, its memberships and the index
//! of its spaces, for its members). Everything a group is lives in those
//! records, written by the group; who may read or write each space is its
//! access record, against the reader's roles.
//! `members` (its roles, each with what it may do, its memberships and
//! the index of its spaces, for its members). Everything a group is lives
//! in those records, written by the group; who may read or write each
//! space is its policy, against the reader's roles.
use crate::Host;
use crate::rbac::{ACTIONS, Grant, NS, PUBLIC, roles_of};
use crate::rbac::{EVERY_ROLE, Grant, NS, POLICY, grants, roles_of};
use crate::repo::{Write, invalid};
use crate::store::Record;
use crate::time::{iso, now_millis};
@@ -32,25 +32,31 @@ pub fn did_rkey(did: &str) -> String {
did.replace("%3A", ":")
}
/// The DID a record key made by [`did_rkey`] is of: a did:web whose host
/// is followed by a port, all digits, has it encoded again.
pub fn rkey_did(rkey: &str) -> String {
let Some((host, after)) = rkey
.strip_prefix("did:web:")
.and_then(|r| r.split_once(':'))
else {
return rkey.to_string();
};
let (port, path) = after.split_at(after.find(':').unwrap_or(after.len()));
if port.is_empty() || !port.bytes().all(|b| b.is_ascii_digit()) {
return rkey.to_string();
}
format!("did:web:{host}%3A{port}{path}")
}
/// What the labeler every group starts with says: the labels the host
/// acts on, and reports about accounts and records, appeals among them.
fn labeler(at: &str) -> Value {
let reasons = [
"Spam",
"Violation",
"Misleading",
"Sexual",
"Rude",
"Other",
"Appeal",
]
.map(|r| format!("com.atproto.moderation.defs#reason{r}"));
/// acts on, and reports about accounts and records, of every reason,
/// appeals among them.
fn labeler() -> Value {
json!({
"$type": format!("{NS}.labeler"),
"policies": {"labelValues": ["!hide", "!takedown"]},
"reasonTypes": reasons,
"reasonTypes": ["spam", "violation", "misleading", "nsfw", "rude", "other", "appeal"],
"subjectTypes": ["account", "record"],
"createdAt": at,
})
}
@@ -68,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,
@@ -77,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.
@@ -98,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
}
/// 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, who reads its meta, and who runs it.
/// 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) {
@@ -140,7 +145,7 @@ fn shape(new: &NewGroup) -> Result<Shape, XrpcError> {
}
Ok(Shape {
join,
readers,
public: new.meta_public_read != Some(false),
stewards,
})
}
@@ -201,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!({
@@ -220,52 +226,48 @@ impl Host {
}
let meta_writes = [
put(&c("profile"), "self", profile),
put(&c("labeler"), "self", labeler(&at)),
put(&c("access"), "self", meta_access(readers)),
put(&c("labeler"), "self", labeler()),
];
self.space_write(&did, &meta, &meta_writes).await?;
let admin = Grant::with("admin", &ACTIONS, &["admin", "member"], &["*"]);
let member = Grant::with("member", &[], &[], &[]);
// Its founders run it: administering it, labeling, making,
// changing and ending spaces, writing any record as 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 administers = format!("include:{NS}.authManageGroup");
let scopes = [
administers.as_str(),
"space:*?collection=com.atproto.label.record",
"space:*?manage=update",
"space:*?manage=create&manage=delete",
"space:*?collection=*",
"repo:*",
];
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",
json!({"$type": c("role"), "displayName": "Admin", "description": "Runs the group.", "createdAt": at}),
json!({"$type": c("role"), "displayName": "Admin", "description": "Runs the group.", "scopes": scopes, "assignable": [EVERY_ROLE], "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": ["admin", "member"], "createdAt": at}),
json!({"$type": c("membership"), "roles": ["admin", "member"], "createdAt": at}),
));
}
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)])?;
}
@@ -329,6 +331,12 @@ impl Host {
let membership = self.group_record(group, &members, &membership, &did_rkey(did))?;
Ok(membership.map(|m| roles_of(&m)).unwrap_or_default())
}
/// The group-wide grant of each of `group`'s roles, by its record.
pub fn role_grants(&self, group: &str) -> Result<Vec<Grant>> {
let roles = self.group_records(group, &members_space(group), &format!("{NS}.role"))?;
Ok(grants(&roles))
}
}
fn json_of(record: &Record) -> Value {
crates/group-host/src/group_api.rs+26−32
@@ -6,8 +6,8 @@
use crate::Host;
use crate::api::{Params, page, param};
use crate::group::{Made, NewGroup, members_space, meta_space};
use crate::rbac::{Access, NS, actions_for, grants, listed, repo_collections_for, roles_of};
use crate::group::{Made, NewGroup, members_space, meta_space, rkey_did};
use crate::rbac::{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,14 +230,10 @@ 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 permissions = record(&members, "permissions", "self")?.unwrap_or_default();
let granted = grants(&permissions);
let granted = host.role_grants(group).map_err(XrpcError::internal)?;
let actions = actions_for(&granted, &roles);
let mut view = base(&host, group, &handle)?;
@@ -309,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);
}
@@ -366,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));
}
@@ -390,9 +385,8 @@ pub async fn list_members(
// read at once rather than in turn, until a page and one are found.
let mut found: Vec<(String, Value)> = Vec::new();
for some in left.chunks(limit + 1) {
let actors = some
.iter()
.map(|(_, m)| host.actor_view(m["member"].as_str().unwrap_or_default()));
let dids: Vec<String> = some.iter().map(|(k, _)| rkey_did(k)).collect();
let actors = dids.iter().map(|did| host.actor_view(did));
let actors = futures::future::join_all(actors).await;
for ((rkey, m), actor) in some.iter().zip(actors) {
let named = |at: &str| actor[at].as_str().unwrap_or_default().to_lowercase();
crates/group-host/src/group_config.rs+8−15
@@ -8,8 +8,8 @@
use crate::Host;
use crate::api::invalid;
use crate::blobs::PROFILE_IMAGES;
use crate::group::{join_policy, members_space, meta_space};
use crate::rbac::{Access, NS, actions_for, grants, roles_of};
use crate::group::{join_policy, members_space, meta_space, rkey_did};
use crate::rbac::{NS, actions_for, roles_of};
use crate::repo::Write;
use crate::xrpc::XrpcError;
use atproto::Cid;
@@ -50,28 +50,22 @@ impl Host {
/// Whether `did`'s roles in `group` carry `action`.
pub fn may_do(&self, group: &str, did: &str, action: &str) -> Result<bool, XrpcError> {
let members = members_space(group);
let permissions = self
.group_record(group, &members, &format!("{NS}.permissions"), "self")
.map_err(XrpcError::internal)?;
let granted = self.role_grants(group).map_err(XrpcError::internal)?;
let roles = self.roles(group, did).map_err(XrpcError::internal)?;
Ok(actions_for(&grants(&permissions.unwrap_or_default()), &roles).contains(action))
Ok(actions_for(&granted, &roles).contains(action))
}
/// Everyone whose roles in `group` carry `group.configure`.
pub fn configurers(&self, group: &str) -> Result<Vec<String>, XrpcError> {
let members = members_space(group);
let permissions = self
.group_record(group, &members, &format!("{NS}.permissions"), "self")
.map_err(XrpcError::internal)?;
let granted = grants(&permissions.unwrap_or_default());
let granted = self.role_grants(group).map_err(XrpcError::internal)?;
let memberships = self
.group_records(group, &members, &format!("{NS}.membership"))
.map_err(XrpcError::internal)?;
Ok(memberships
.iter()
.filter(|(_, m)| actions_for(&granted, &roles_of(m)).contains("group.configure"))
.filter_map(|(_, m)| m["member"].as_str().map(String::from))
.map(|(k, _)| rkey_did(k))
.collect())
}
}
@@ -281,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_invites.rs+9−49
@@ -1,11 +1,13 @@
//! Invites. A group invites someone by writing an invite in its own repo
//! in the invitee's inbox: a space under the invitee's own DID, at their
//! PDS, which lets this host say who may write there
//! (`com.atproto.managedspace.checkAccess`). An app writes it as the
//! group, through `com.atproto.space.*` with a session for the group, and
//! takes it back by deleting it. The invitee's apps read it there; the
//! host keeps its own list of what it sent, which is what redeems an
//! invite, as the inbox is its owner's to read, not the group's.
//! PDS, which their app makes as a memberspace that tracks anyone's
//! writes and names no members, so any group may write there and only its
//! owner reads it. An app writes it as the group, through
//! `com.atproto.space.*` with a session for the group, and takes it back
//! by deleting it; each write is told to the invitee's PDS. The invitee's
//! apps read it there; the host keeps its own list of what it sent, which
//! is what redeems an invite, as the inbox is its owner's to read, not the
//! group's.
//!
//! An invite is redeemed by asking to join: admitted at once, whatever
//! the group's join policy, with its default roles.
@@ -13,7 +15,7 @@
use crate::Host;
use crate::api::{Params, invalid, page, param};
use crate::group::meta_space;
use crate::group_api::{caller, group_of, signed_in};
use crate::group_api::{group_of, signed_in};
use crate::group_members::{Members, acting};
use crate::lexicons::check_record;
use crate::mcp::McpGrant;
@@ -35,9 +37,6 @@ use std::sync::Arc;
type Answer = Result<Json<Value>, XrpcError>;
/// The method a space's authority asks this host what a repo may do.
pub const CHECK_ACCESS: &str = "com.atproto.managedspace.checkAccess";
fn bad(error: &'static str, message: impl Into<String>) -> XrpcError {
XrpcError::new(StatusCode::BAD_REQUEST, error, message)
}
@@ -472,42 +471,3 @@ pub async fn decline_invite(
host.take_back(&invite).await?;
Ok(Json(json!({})))
}
/// Whether an account may read or write a space this host manages for
/// its authority: someone's inbox, which its owner reads and groups here
/// write their invites in. Asked by the space's authority, with service
/// auth for this host (`<host DID>#opensocial`, the managing app an inbox
/// names).
pub async fn check_access(
State(host): State<Arc<Host>>,
Query(p): Query<Params>,
headers: HeaderMap,
) -> Answer {
let asker = caller(&host, &headers, CHECK_ACCESS).await?;
let asker = asker
.ok_or_else(|| crate::space_api::unauthorized("AuthMissing", "service auth is required"))?;
let space = SpaceRef::parse(param(&p, "space")?).map_err(|e| invalid(e.to_string()))?;
if asker != space.authority {
return Err(XrpcError::new(
StatusCode::FORBIDDEN,
"Forbidden",
"only the space's authority asks",
));
}
let inbox = space.kind == format!("{NS}.invites");
// Its owner reads it; a group here writes in it. Without a repo, no
// one is asking as anyone, and may do neither.
let (read, write) = match p.get("repo").filter(|_| inbox) {
Some(repo) => {
let group = host
.store
.account(repo)
.map_err(XrpcError::internal)?
.is_some_and(|a| &a.did == repo)
&& group_of(&host, repo).is_ok();
(repo == &space.authority, group)
}
None => (false, false),
};
Ok(Json(json!({ "read": read, "write": write })))
}
crates/group-host/src/group_join.rs+2−5
@@ -10,7 +10,7 @@
//! ask again and the group need not say.
use crate::Host;
use crate::api::{Params, invalid, page, param};
use crate::api::{Params, invalid_cursor, page, param};
use crate::group::meta_space;
use crate::group_api::{group_of, signed_in};
use crate::group_invites::invite_uri;
@@ -137,10 +137,7 @@ pub async fn list_join_requests(
let limit = page(&p, 50, 100)?;
let before = match p.get("cursor") {
None => None,
Some(c) => Some(
c.parse::<i64>()
.map_err(|_| invalid("a cursor this host gave"))?,
),
Some(c) => Some(c.parse::<i64>().map_err(|_| invalid_cursor())?),
};
let waiting = host
.store
crates/group-host/src/group_members.rs+6−9
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
crates/group-host/src/import.rs+2−1
crates/group-host/src/import_space.rs+73−32
crates/group-host/src/index.rs+1−1
crates/group-host/src/index_api.rs+32−15
crates/group-host/src/lexicons.rs+15−15
crates/group-host/src/lib.rs+23−22
crates/group-host/src/mcp.rs+46−16
crates/group-host/src/member_writes.rs+120−158
crates/group-host/src/migration.rs+73−49
crates/group-host/src/moderation.rs+33−60
crates/group-host/src/oauth_scope.rs+213−117
crates/group-host/src/provision.rs+1−1
crates/group-host/src/rbac.rs+125−111
crates/group-host/src/scopes.rs+29−19
crates/group-host/src/store.rs+27−7
crates/group-host/src/takedown.rsnew+108−0
crates/group-host/src/token_writes.rs+34−38
crates/group-host/tests/common/members.rs+12−23
crates/group-host/tests/common/oauth.rs+38−0
crates/group-host/tests/common/spaces.rs+10−0
crates/group-host/tests/actors.rs+12−2
crates/group-host/tests/app_passwords.rs+7−16
crates/group-host/tests/authority.rs+16−9
crates/group-host/tests/authorization.rs+49−8
crates/group-host/tests/group_config.rs+15−12
crates/group-host/tests/group_spaces.rs+534−427
961 lines changed: not loaded until asked for.
crates/group-host/tests/group_tokens.rs+43−64
crates/group-host/tests/groups.rs+79−37
crates/group-host/tests/import.rs+2−2
crates/group-host/tests/index.rs+8−12
crates/group-host/tests/interop.rs+8−5
crates/group-host/tests/invites.rs+2−80
crates/group-host/tests/joining.rs+18−64
crates/group-host/tests/lifecycle.rs+2−2
crates/group-host/tests/mcp.rs+33−16
crates/group-host/tests/members.rs+197−203
crates/group-host/tests/migration.rs+35−19
crates/group-host/tests/moderation.rs+278−130
408 lines changed: not loaded until asked for.
crates/group-host/tests/oauth.rs+1−1
crates/group-host/tests/oauth_scope.rs+249−191
440 lines changed: not loaded until asked for.
crates/group-host/tests/provision.rs+2−2
crates/group-host/tests/rbac.rs+131−97
crates/group-host/tests/sites.rs+3−3
crates/group-host/tests/tokens.rs+25−60
crates/group-host-mcp/src/lib.rs+113−130
crates/group-host-mcp/tests/protocol.rs+74−61
crates/opensocial/src/lib.rs+35−61
crates/opensocial/tests/cli.rs+12−5
crates/opensocial/tests/commands.rs+71−44
docs/design/groups.md+54−66
docs/design/mcp.md+3−3
docs/design/membership.md+68−54
docs/design/moderation.md+33−21
docs/design/moving.md+13−7
docs/design/signing-in.md+79−54
docs/design/sites.md+19−19
docs/design/spaces.md+102−38
docs/guides/shots/moderating-found-dark.png+0−0
A binary file, not shown.
docs/guides/shots/moderating-found.png+0−0
A binary file, not shown.
docs/guides/shots/moderating-found.txt+1−1
docs/guides/shots/moderating-label-dialog-dark.png+0−0
A binary file, not shown.
docs/guides/shots/moderating-label-dialog.png+0−0
A binary file, not shown.
docs/guides/shots/moderating-label-dialog.txt+1−1
docs/guides/shots/rules-create-role-dark.png+0−0
A binary file, not shown.
docs/guides/shots/rules-create-role.png+0−0
A binary file, not shown.
docs/guides/shots/rules-create-role.txt+2−0
docs/guides/shots/rules-give-dark.png+0−0
A binary file, not shown.
docs/guides/shots/rules-member-dark.png+0−0
A binary file, not shown.
docs/guides/moderating.md+4−4
docs/guides/rules-and-roles.md+7−5
docs/guides/signing-in-as-a-group.md+3−2
docs/reference/api.md+136−135
docs/reference/cli.md+83−83
docs/reference/mcp.md+52−52
docs/reference/sdk.md+2−2
docs/reference/site-kit.md+15−15
examples/kicker/harness/e2e/flows.spec.mjs+2−2
examples/kicker/harness/seed.mjs+12−16
examples/kicker/site/src/lib/organisms/ReportDialog.svelte+5−5
examples/kicker/site/src/lib/place.js+7−13
examples/kicker/README.md+14−14
harness/e2e/flows.spec.mjs+19−5
harness/e2e/pages.mjs+84−4
harness/look/seeds/moderating.mjs+7−19
harness/look/seeds/nightshift-poster.mjs+3−5
harness/look/seeds/reports.mjs+15−16
harness/alpha.sh+3−3
harness/lexicons.mjs+84−51
lexicons/fyi/opensocial/access.jsondeleted+0−51
lexicons/fyi/opensocial/authManageGroup.jsonnew+86−0
lexicons/fyi/opensocial/authManageProfile.jsonnew+31−0
lexicons/fyi/opensocial/authModerate.jsonnew+76−0
lexicons/fyi/opensocial/participate.json → lexicons/fyi/opensocial/authParticipate.jsonrenamed+20−7
lexicons/fyi/opensocial/configure.jsondeleted+0−32
lexicons/fyi/opensocial/createGroup.json+4−7
lexicons/fyi/opensocial/createReport.json+22−9
lexicons/fyi/opensocial/createSpace.jsondeleted+0−95
lexicons/fyi/opensocial/defs.json+42−226
lexicons/fyi/opensocial/deleteSpace.jsondeleted+0−48
lexicons/fyi/opensocial/getAuthorization.json+1−1
lexicons/fyi/opensocial/getGroupAuth.json+2−2
lexicons/fyi/opensocial/getSubjectHistory.json → lexicons/fyi/opensocial/getModSubjectHistory.jsonrenamed+6−2
lexicons/fyi/opensocial/invites.json+2−2
lexicons/fyi/opensocial/labeler.json+44−11
lexicons/fyi/opensocial/listJoinRequests.json+7−1
lexicons/fyi/opensocial/listSubjects.json → lexicons/fyi/opensocial/listModSubjects.jsonrenamed+9−3
lexicons/fyi/opensocial/listSpaceRecords.json+2−2
lexicons/fyi/opensocial/manageMembers.jsondeleted+0−42
lexicons/fyi/opensocial/manageSpaces.jsondeleted+0−32
lexicons/fyi/opensocial/members.json+3−5
lexicons/fyi/opensocial/membership.json+4−9
lexicons/fyi/opensocial/meta.json+2−3
lexicons/fyi/opensocial/migrateExport.json+1−1
lexicons/fyi/opensocial/moderate.jsondeleted+0−42
lexicons/fyi/opensocial/permissions.jsondeleted+0−32
lexicons/fyi/opensocial/policy.jsonnew+64−0
lexicons/fyi/opensocial/provisionGroup.json+4−6
lexicons/fyi/opensocial/resolveSubject.json → lexicons/fyi/opensocial/resolveModSubject.jsonrenamed+10−7
lexicons/fyi/opensocial/role.json+24−2
lexicons/fyi/opensocial/site.json+2−2
lexicons/fyi/opensocial/siteSpace.json+1−1
lexicons/fyi/opensocial/space.json+6−10
lexicons/fyi/opensocial/updateSpace.jsondeleted+0−63
lexicons/upstream/com/atproto/managedspace/checkAccess.jsondeleted+0−44
lexicons/upstream/com/atproto/memberspace/policy.jsonnew+40−0
lexicons/upstream/com/atproto/moderation/defs.jsondeleted+0−99
lexicons/upstream/com/atproto/personalspace/policy.jsonnew+11−0
lexicons/upstream/com/atproto/space/createSpace.jsonnew+58−0
lexicons/upstream/com/atproto/space/deleteSpace.jsonnew+31−0
lexicons/upstream/com/atproto/space/getSpace.jsonnew+43−0
lexicons/upstream/com/atproto/space/policy.jsonnew+26−0
lexicons/upstream/com/atproto/space/updateSpace.jsonnew+43−0
packages/sdk/src/group-client.test.ts+2−15
packages/sdk/package-lock.json+155−155
packages/sdk/package.json+3−3
packages/sdk/README.md+11−11
web/messages/en.json+8−6
web/src/lib/organisms/RolesEditor.svelte+8−3
web/src/lib/server/settings.ts+29−78
web/src/lib/actions.ts+8−7
web/src/lib/activity.ts+11−3
web/src/lib/reasons.ts+12−11
web/src/routes/g/[handle]/moderation/+page.server.ts+15−25
web/src/routes/g/[handle]/settings/roles/+page.svelte+8−1
web/src/routes/g/[handle]/+page.server.ts+1−1
web/src/routes/g/[handle]/+page.svelte+11−12
web/package-lock.json+239−266
505 lines changed: not loaded until asked for.
web/package.json+17−17