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

A moderation role labels only in the spaces its scopes reach

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:rbac/label-spaces
crates/group-host/src/group_api.rs+23−1
@@ -9,7 +9,8 @@ use crate::api::{Params, page, param};
use crate::group::{Made, NewGroup, members_space, meta_space, rkey_did};
use crate::member_writes::{expanded, held};
use crate::rbac::{
ACTIONS, Grant, NS, actions_for, actions_of, listed, repo_collections_for, roles_of, scope_of,
ACTIONS, Grant, NS, actions_for, actions_of, label_writes_in, listed, repo_collections_for,
roles_of, scope_of,
};
use crate::scopes::covers;
use crate::space_api::{service_caller, unauthorized};
@@ -276,6 +277,7 @@ pub async fn get_group(
if member {
viewer["accepted"] = json!(accepted(&host, &members, &me).map_err(XrpcError::internal)?);
viewer["grantable"] = json!(grantable(&granted, &roles, group));
viewer["labelSpaces"] = json!(label_spaces(&host, group, &roles, &granted)?);
}
// Their own request, while it waits.
let asked = host.store.asked(group, &me).map_err(XrpcError::internal)?;
@@ -436,3 +438,23 @@ fn accepted(host: &Host, members: &str, did: &str) -> anyhow::Result<bool> {
let writers = host.store.writers(members, None, u32::MAX)?;
Ok(writers.iter().any(|w| w.did == did && w.data != empty))
}
/// The spaces of `group`'s where a holder of `roles` may write a label as
/// it, by their roles' scopes across the group or the space's policy.
fn label_spaces(
host: &Host,
group: &str,
roles: &[String],
grants: &[Grant],
) -> Result<Vec<Value>, XrpcError> {
let spaces = host.store.spaces_of(group).map_err(XrpcError::internal)?;
let mut out = Vec::new();
for uri in spaces {
let policy = host.policy(&uri).map_err(XrpcError::internal)?;
let policy = policy.expect("a space the group has");
if label_writes_in(grants, roles, &policy).contains("create") {
out.push(json!({ "space": uri }));
}
}
Ok(out)
}
crates/group-host/src/group_tokens.rs+8−6
@@ -18,10 +18,9 @@ use crate::group_api::{group_of, signed_in};
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::{may_write, with_labels};
use crate::oauth_store::{Grant, Tokens};
use crate::rbac::{LABEL, NS, Policy};
use crate::rbac::{LABEL, NS, Policy, label_writes};
use crate::time::{iso, now_millis};
use crate::xrpc::XrpcError;
use atproto::jose;
@@ -155,10 +154,13 @@ impl Host {
true => self.members_writes_of(group, &roles)?,
false => BTreeMap::new(),
};
// Labels, unless what the space grants holds them already.
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);
// Labels, as far as what the space grants does not hold them.
if policy.is_some() {
let grants = self.role_grants(group).map_err(XrpcError::internal)?;
let labels = label_writes(&grants, &roles, group, space);
if !labels.iter().all(|w| may_write(&writes, LABEL, w)) {
with_labels(&mut own, labels);
}
}
let manage = self.manage_ops(group, member, &roles, policy.as_ref())?;
if writes.is_empty() && own.is_empty() && manage.is_empty() {
crates/group-host/src/oauth_scope.rs+15−10
@@ -13,7 +13,7 @@
use crate::Host;
use crate::group::{members_space, meta_space};
use crate::lexicons::lexicons;
use crate::rbac::{self, LABEL, NS, actions_for, repo_collections_for};
use crate::rbac::{self, LABEL, NS, actions_for, label_writes, repo_collections_for};
use crate::scopes::{decoded, is_blob, repo_collections};
use crate::xrpc::XrpcError;
use serde_json::Value;
@@ -124,11 +124,11 @@ fn manages(want: &SpaceScope, actions: &BTreeSet<&'static str>, rooms: &[Room])
})
}
/// `writable` with labels, if `labels` and it does not hold every write
/// of them already.
pub fn with_labels(writable: &mut BTreeMap<String, BTreeSet<String>>, labels: bool) {
if labels && !WRITES.iter().all(|w| may_write(writable, LABEL, w)) {
writable.insert(LABEL.into(), WRITES.map(String::from).into());
/// `writable` with the label writes `labels`, if it does not hold each of
/// them already.
pub fn with_labels(writable: &mut BTreeMap<String, BTreeSet<String>>, labels: BTreeSet<String>) {
if !labels.iter().all(|w| may_write(writable, LABEL, w)) {
writable.entry(LABEL.into()).or_default().extend(labels);
}
}
@@ -176,11 +176,13 @@ fn managing(actions: &BTreeSet<&'static str>) -> BTreeSet<&'static str> {
impl Host {
/// The group's spaces, each with what a holder of `roles`, holding
/// `actions`, may read and write there as the group, and do to it.
/// `actions` by `grants`, may read and write there as the group, and
/// do to it.
fn rooms(
&self,
group: &str,
roles: &[String],
grants: &[rbac::Grant],
actions: &BTreeSet<&'static str>,
) -> Result<Vec<Room>, XrpcError> {
let spaces = self.store.spaces_of(group).map_err(XrpcError::internal)?;
@@ -197,7 +199,10 @@ impl Host {
if uri == members_space(group) {
writable.extend(self.members_writes_of(group, roles)?);
}
with_labels(&mut writable, actions.contains("label"));
with_labels(
&mut writable,
label_writes(grants, roles, group, &policy.space),
);
let mut manages = managing(actions);
for op in ["update", "delete"] {
if policy.manages(roles, op) {
@@ -228,7 +233,7 @@ impl Host {
if !repo.is_empty() || actions.contains("group.configure") {
return Ok(true);
}
let rooms = self.rooms(group, roles, &actions)?;
let rooms = self.rooms(group, roles, grants, &actions)?;
Ok(rooms.iter().any(|r| !r.writable.is_empty()))
}
@@ -264,7 +269,7 @@ impl Host {
let repo = repo_collections_for(&grants, roles);
let everything = repo.contains("*");
let held = actions_for(&grants, roles);
let rooms = self.rooms(group, roles, &held)?;
let rooms = self.rooms(group, roles, &grants, &held)?;
let invite = format!("{NS}.invite");
// What each scope asked for gives, in the order asked.
let mut each: Vec<Vec<String>> = Vec::new();
crates/group-host/src/rbac.rs+40−4
@@ -9,6 +9,7 @@
//! role's scopes and assignable roles, and a membership's roles, which
//! are strings alone, as the proposal has them.
use crate::oauth_scope::concrete;
use crate::scopes::{Permissions, decoded};
use atproto::space::SpaceRef;
use serde_json::Value;
@@ -183,14 +184,15 @@ const BY_METHOD: [(&str, &str); 2] = [
];
/// The actions holding `fyi.opensocial.authModerate` gives, as its
/// permissions do: memberships, invites, labels, join requests and the
/// moderation methods. `authManageGroup` gives them, and
/// permissions do: memberships, invites, join requests and the
/// moderation methods. Its labels are the meta and members spaces' alone
/// ([`label_writes`]), so it gives no `label`, which is labels in every
/// space. `authManageGroup` gives them, and
/// `group.configure`; `authManageProfile` none, as who writes the
/// profile and rules is the meta space's policy's to say.
pub const MODERATES: [&str; 7] = [
pub const MODERATES: [&str; 6] = [
"mod.read",
"mod.resolve",
"label",
"invite",
"admit",
"eject",
@@ -375,3 +377,37 @@ pub fn repo_collections_for(grants: &[Grant], roles: &[String]) -> BTreeSet<Stri
.map(|c| c.split('?').next().unwrap_or_default().to_string())
.collect()
}
/// The writes of labels a holder of `roles` may make as `group` in
/// `space` by their roles' scopes across the group: those of the
/// moderation sets in its meta and members spaces, as the sets'
/// permissions name them; in any of its spaces, by a space scope naming
/// labels or every collection. A space's policy may grant more there.
pub fn label_writes(
grants: &[Grant],
roles: &[String],
group: &str,
space: &SpaceRef,
) -> BTreeSet<String> {
let scopes: Vec<String> = grants
.iter()
.filter(|g| roles.contains(&g.role))
.flat_map(|g| g.scopes.clone())
.collect();
let held = Permissions::new(&concrete(&scopes, group), group);
let writes = WRITES
.into_iter()
.filter(|w| held.space(space, Some(LABEL), w));
writes.map(String::from).collect()
}
/// The label writes of [`label_writes`], and those `policy`, the
/// space's, grants `roles` there.
pub fn label_writes_in(grants: &[Grant], roles: &[String], policy: &Policy) -> BTreeSet<String> {
let space = &policy.space;
let mut out = label_writes(grants, roles, &space.authority, space);
let granted = policy.writes(roles);
let any = ["*", LABEL].iter().filter_map(|c| granted.get(*c));
out.extend(any.flatten().cloned());
out
}
crates/group-host/src/token_writes.rs+3−3
@@ -25,7 +25,7 @@ use crate::lexicons::{check_record, validation};
use crate::member_writes::members_writes;
use crate::oauth_resource::{Acting, Refusal};
use crate::oauth_scope::{may_write, meta_writes};
use crate::rbac::{self, LABEL, NS, actions_for, repo_collections_for};
use crate::rbac::{self, LABEL, NS, actions_for, label_writes, repo_collections_for};
use crate::repo::{Asked, Write, record_cid};
use crate::xrpc::XrpcError;
use atproto::space::SpaceRef;
@@ -468,7 +468,7 @@ impl Host {
if uri == meta_space(group) {
writable.extend(meta_writes(&held));
}
let labels = held.contains("label");
let labels = label_writes(&grants, &roles, group, space);
for w in writes {
let (collection, _) = w.path();
if !acting.permissions.space(space, Some(collection), action(w)) {
@@ -479,7 +479,7 @@ impl Host {
)));
}
let still = match collection {
LABEL => labels,
LABEL => labels.contains(action(w)) || may_write(&writable, LABEL, action(w)),
_ if uri == members_space(group) => {
may_write(&members_writes(&grants, &roles), collection, action(w))
}
crates/group-host/tests/groups.rs+0−1
@@ -179,7 +179,6 @@ async fn shows_a_group_as_each_viewer_may_see_it() {
"admit",
"eject",
"invite",
"label",
"mod.read",
"mod.resolve",
"role.assign",
crates/group-host/tests/moderation.rs+80−0
@@ -551,6 +551,86 @@ async fn holds_each_label_to_the_action_it_needs() {
assert_eq!(said.body["error"], "Forbidden");
}
/// The spaces `getGroup` says `who` may label in, as the group, in order.
async fn label_spaces(h: &Running, who: &Authority, did: &str) -> Vec<String> {
let (status, view) = query(h, who, "getGroup", &format!("group={did}")).await;
assert_eq!(status, 200, "{view}");
let spaces = view["group"]["viewer"]["labelSpaces"].as_array().unwrap();
let uri = |s: &Json| s["space"].as_str().unwrap().to_string();
let mut spaces: Vec<String> = spaces.iter().map(uri).collect();
spaces.sort();
spaces
}
#[tokio::test]
async fn labels_only_in_the_spaces_the_roles_scopes_reach() {
let h = start(&[], false).await;
let (did, space, post, [alice, bob, _]) = group(&h).await;
let uri = post["uri"].as_str().unwrap();
let (meta, members) = (meta_space(&did), members_space(&did));
use common::members::{granting, keep};
let moderate = format!("include:{NS}.authModerate");
let moderator = granting(&h, &did, "moderator", &[&moderate], &[]);
keep(&h, &did, "role", "moderator", moderator).await;
membership(&h, &did, &bob.did, &["member", "moderator"]).await;
// The moderation set labels in the meta and members spaces, as its
// permissions say.
let rule = format!("{meta}/{did}/{NS}.rule/r");
let (status, said) = labelled(&h, &bob, &did, &meta, label(&rule, "x")).await;
assert_eq!(status, 200, "{said}");
let (status, said) = labelled(&h, &bob, &did, &members, label(&alice.did, "x")).await;
assert_eq!(status, 200, "{said}");
assert_eq!(
label_spaces(&h, &bob, &did).await,
[members.clone(), meta.clone()]
);
// Not in the calendar: no token for it, nothing else being theirs
// there.
let app = App::new("console");
let said = group_token(&h, &app, &bob, &did, &space).await;
assert_eq!(said.status, 403, "{}", said.body);
// With labels in every space, there too, of any value.
let every = format!("space:*?collection={LABEL}");
let moderator = granting(&h, &did, "moderator", &[&moderate, &every], &[]);
keep(&h, &did, "role", "moderator", moderator).await;
let token = app.token_for(&h, &bob, &did, &space).await;
let write = |val: &str| json!({"repo": did, "space": space, "collection": LABEL, "record": label(uri, val)});
let nsid = "com.atproto.space.createRecord";
for val in ["spam", "!takedown"] {
let said = app.call(&h, nsid, &token, Some(&write(val))).await;
assert_eq!(said.status, 200, "{val}: {}", said.body);
}
let spaces = label_spaces(&h, &bob, &did).await;
assert_eq!(spaces.len(), 3);
assert!(spaces.contains(&space), "{spaces:?}");
// Taken away, the token writes there no more.
let moderator = granting(&h, &did, "moderator", &[&moderate], &[]);
keep(&h, &did, "role", "moderator", moderator).await;
let said = app.call(&h, nsid, &token, Some(&write("spam"))).await;
assert_eq!(said.status, 403, "{}", said.body);
assert_eq!(said.body["error"], "Forbidden");
// A space whose policy grants moderators labels: there, and only
// there.
let policy = json!({"$type": "fyi.opensocial.policy", "grants": [
{"role": "member", "read": true},
{"role": "moderator", "read": true, "scopes": [every]},
]});
let board = "com.example.board";
let board = common::oauth::make_space(&h, &alice, &did, board, "swaps", policy).await;
let pinned = format!("{board}/{}/com.example.post/p", alice.did);
let (status, said) = labelled(&h, &bob, &did, &board, label(&pinned, "x")).await;
assert_eq!(status, 200, "{said}");
let said = group_token(&h, &app, &bob, &did, &space).await;
assert_eq!(said.status, 403, "{}", said.body);
let spaces = label_spaces(&h, &bob, &did).await;
assert_eq!(spaces.len(), 3);
assert!(spaces.contains(&board), "{spaces:?}");
// Those who run the group label in every space.
assert_eq!(label_spaces(&h, &alice, &did).await.len(), 4);
}
/// Sets the group's labeler to take reports of `types` of subject, of
/// records in `collections`.
async fn takes(h: &Running, did: &str, types: &[&str], collections: &[&str]) {
crates/group-host/tests/oauth_scope.rs+54−0
@@ -480,6 +480,60 @@ async fn keeps_of_a_permission_set_what_the_roles_grant() {
}
}
#[tokio::test]
async fn keeps_labels_only_in_the_spaces_the_roles_label_in() {
let h = start(&[], false).await;
let (did, calendar_uri, _) = group(&h).await;
let moderate = format!("include:{NS}.authModerate");
let label = "com.atproto.label.record";
let every = format!("space:*?collection={label}");
define(
&h,
&did,
Grant {
role: "moderator".into(),
scopes: vec![moderate.clone()],
assignable: vec![],
},
)
.await;
define(
&h,
&did,
Grant {
role: "labeller".into(),
scopes: vec![moderate, every.clone()],
assignable: vec![],
},
)
.await;
let narrow =
|r: &[&str], scopes: &[&str]| h.host.narrow(&did, &roles(r), &asked(scopes)).unwrap();
let named = format!("space:{CALENDAR}?collection={label}");
// The moderation set's labels are the meta and members spaces'.
let moderator = narrow(&["member", "moderator"], &[&every]);
for kind in ["meta", "members"] {
let there = |s: &String| s.contains(&format!("{NS}.{kind}?")) && s.contains(label);
assert!(moderator.iter().any(there), "{kind}: {moderator:?}");
}
assert_eq!(calendar(moderator), Vec::<String>::new());
assert_eq!(narrow(&["moderator"], &[&named]), Vec::<String>::new());
// Labels in every space reach the calendar.
let labeller = narrow(&["member", "labeller"], &[&every]);
assert_eq!(calendar(labeller).len(), 1);
let kept = narrow(&["labeller"], &[&named]);
assert_eq!(kept, std::slice::from_ref(&named));
// As does a grant of them in its policy, there only.
let policy = json!({"$type": "fyi.opensocial.policy", "grants": [
{"role": "member", "read": true},
{"role": "moderator", "read": true, "scopes": [every]},
]});
h.host.store.set_policy(&calendar_uri, &policy).unwrap();
let moderator = narrow(&["member", "moderator"], &[&every]);
assert_eq!(calendar(moderator).len(), 1);
assert_eq!(narrow(&["moderator"], &[&named]), [named]);
}
#[tokio::test]
async fn a_profile_writer_keeps_the_profile_with_what_it_approved() {
let h = start(&[], false).await;
crates/group-host/tests/rbac.rs+5−4
@@ -150,14 +150,15 @@ fn answers_each_action_by_its_scope() {
none
);
assert_eq!(of("space:fyi.opensocial.members?manage=create"), none);
// The tiered sets: moderating gives memberships, invites, labels and
// the moderation methods; administering, those and configuring; the
// profile, nothing, as the meta space's policy says who writes it.
// The tiered sets: moderating gives memberships, invites and the
// moderation methods, and labels in the meta and members spaces alone,
// not `label`, which is labels in every space; administering, those
// and configuring; the profile, nothing, as the meta space's policy
// says who writes it.
let moderates = [
"admit",
"eject",
"invite",
"label",
"mod.read",
"mod.resolve",
"role.assign",
crates/group-host-mcp/src/lib.rs+3−2
@@ -500,8 +500,9 @@ const TOOLS: &[(&str, &[&str], &str, Made)] = &[
"mod_label",
&["subject", "val"],
"Labels a subject as the group, with a label record (com.atproto.label.record) beside \
it: a record's in its space, an account's in the members space. With undo, takes the \
label back by deleting it.",
it: a record's in its space, an account's in the members space; where the member's \
roles write labels, as getGroup's labelSpaces lists. With undo, takes the label back \
by deleting it.",
Made::Label,
),
];
docs/design/membership.md+5−1
docs/design/moderation.md+19−5
docs/design/signing-in.md+12−1
docs/guides/shots/rules-change-role-dark.png+0−0
A binary file, not shown.
docs/guides/shots/rules-change-role.png+0−0
A binary file, not shown.
docs/guides/shots/rules-change-role.txt+2−2
docs/guides/shots/rules-delete-dark.png+0−0
A binary file, not shown.
docs/guides/shots/rules-give-dark.png+0−0
A binary file, not shown.
docs/guides/shots/rules-give.png+0−0
A binary file, not shown.
docs/guides/shots/rules-given-dark.png+0−0
A binary file, not shown.
docs/guides/shots/rules-given.png+0−0
A binary file, not shown.
docs/guides/shots/rules-menu-dark.png+0−0
A binary file, not shown.
docs/guides/shots/rules-menu.png+0−0
A binary file, not shown.
docs/guides/rules-and-roles.md+5−4
docs/reference/api.md+1−1
docs/reference/cli.md+1−1
docs/reference/mcp.md+1−1
lexicons/fyi/opensocial/defs.json+21−0
web/src/lib/organisms/ModerationQueue.svelte+8−6
web/src/lib/actions.ts+2−1
web/src/lib/moderation.ts+12−0
web/src/routes/g/[handle]/moderation/+page.server.ts+2−12
web/src/routes/g/[handle]/moderation/+page.svelte+5−2