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

A group moderates its members' posts in their public repos

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:public-subjects
crates/group-host/src/moderation.rs+91−45
@@ -2,14 +2,15 @@
//!
//! - **Labels** are `com.atproto.label.label` records the group writes,
//! as any record of its own, beside their subject: a record's in the
//! space it is in, an account's in the members space by custom. Whoever
//! reads the content reads its labels. Deleting a label takes it back;
//! the queue keeps that it was written, and by whom.
//! space it is in, an account's, or a member's public record's, in the
//! members space by custom. Whoever reads the content reads its labels.
//! Deleting a label takes it back; the queue keeps that it was written,
//! and by whom.
//! - **The queue** (subjects, their status, what happened to each) is the
//! host's to keep, not the group's to publish.
//! - **Reports** come through `fyi.opensocial.createReport`, from whoever
//! can read what they report: an account in the group, or a record in
//! one of its spaces here.
//! can read what they report: an account in the group, a record in one
//! of its spaces here, or a member's record in their public repo.
use crate::Host;
use crate::api::{Params, invalid, page, param};
@@ -229,23 +230,39 @@ pub fn space_of(uri: &str) -> Option<(String, String)> {
/// another as long.
const REASON_TYPE_MAX: usize = 256;
/// The space a record subject's URI is in, one of `group`'s.
fn in_group(group: &str, uri: &str) -> Result<String, XrpcError> {
let space = space_of(uri).filter(|(_, authority)| authority == group);
let space = space.ok_or_else(|| invalid_subject("not a record in one of this group's spaces"));
Ok(space?.0)
/// The account a public record's URI is in, `at://<did>/<collection>/<rkey>`,
/// a record in no space, each of its parts what it says.
fn public_of(uri: &str) -> Option<&str> {
let parts: Vec<&str> = uri.strip_prefix("at://")?.split('/').collect();
let [did, collection, rkey] = parts[..] else {
return None;
};
let valid = syntax::is_did(did) && syntax::is_nsid(collection) && syntax::is_record_key(rkey);
valid.then_some(did)
}
/// Refuses a record subject's URI that is neither in one of `group`'s
/// spaces nor in a public repo.
fn record_in(group: &str, uri: &str) -> Result<(), XrpcError> {
let ours = space_of(uri).is_some_and(|(_, authority)| authority == group);
if !ours && public_of(uri).is_none() {
return Err(invalid_subject(
"not a record in one of this group's spaces, nor in a public repo",
));
}
Ok(())
}
/// A subject as the queue keys it (an account's DID, or a record's URI in
/// one of `group`'s spaces) and the version of a record it names, from
/// the union a caller sends.
/// one of `group`'s spaces or in a public repo) and the version of a
/// record it names, from the union a caller sends.
fn subject_in(group: &str, asked: &Value) -> Result<(String, Option<String>), XrpcError> {
let field = |key: &str| asked[key].as_str().map(String::from);
match asked["$type"].as_str() {
Some(ACCOUNT) => Ok((field("did").expect("its lexicon requires it"), None)),
Some(RECORD) => {
let uri = field("uri").expect("its lexicon requires it");
in_group(group, &uri)?;
record_in(group, &uri)?;
Ok((uri, field("cid")))
}
_ => Err(invalid_subject("a subject is an account or a record")),
@@ -261,24 +278,42 @@ fn subject_ref(key: &str) -> Value {
}
}
/// Refuses a label among `writes` in `space` whose subject is neither an
/// account nor a record in that same space: a label sits beside what it
/// is about, so exactly those who read the one read the other.
pub(crate) fn beside(space: &str, writes: &[Write]) -> Result<(), XrpcError> {
for write in writes {
let (collection, _) = write.path();
let Some(value) = write.value().filter(|_| collection == LABEL) else {
continue;
};
let subject = value["uri"].as_str().unwrap_or_default();
let here = space_of(subject).is_some_and(|(s, _)| s == space);
if !here && !syntax::is_did(subject) {
return Err(invalid(
"a label's uri is an account's DID, or a record's in the space it is written in",
));
impl Host {
/// Refuses a label among `writes` in `group`'s `space` whose subject is
/// neither an account nor a record in that same space, nor, in the
/// members space, a member's public record: a label sits beside what
/// it is about, so exactly those who read the one read the other.
pub(crate) fn beside(
&self,
group: &str,
space: &str,
writes: &[Write],
) -> Result<(), XrpcError> {
let members = space == members_space(group);
for write in writes {
let (collection, _) = write.path();
let Some(value) = write.value().filter(|_| collection == LABEL) else {
continue;
};
let subject = value["uri"].as_str().unwrap_or_default();
let here = space_of(subject).is_some_and(|(s, _)| s == space);
if here || syntax::is_did(subject) {
continue;
}
// A public record's author's roles, in the members space alone.
let roles = match public_of(subject).filter(|_| members) {
Some(did) => self.roles(group, did).map_err(XrpcError::internal)?,
None => Vec::new(),
};
if roles.is_empty() {
return Err(invalid(
"a label's uri is an account's DID, a record's in the space it is written in, \
or in the members space a member's public record",
));
}
}
Ok(())
}
Ok(())
}
impl Host {
@@ -369,10 +404,14 @@ fn present(mut value: Value) -> Value {
}
/// The account a subject is, or whose record it is: a record's repo, as
/// the queue keeps it, in a space.
fn account_of<'a>(key: &'a str) -> &'a str {
let repo = |path: &'a str| path.split('/').nth(4).expect("a record in a space");
key.strip_prefix("at://").map_or(key, repo)
/// the queue keeps it, in a space or a public repo.
fn account_of(key: &str) -> &str {
let Some(path) = key.strip_prefix("at://") else {
return key;
};
let parts: Vec<&str> = path.split('/').collect();
// A public record's repo comes first; one in a space's, after the space.
if parts.len() == 3 { parts[0] } else { parts[4] }
}
/// A subject as the queue answers it, with `actors`, the people it names
@@ -473,7 +512,7 @@ pub async fn get_subject_history(
.await?;
let subject = param(&p, "subject")?;
if !syntax::is_did(subject) {
in_group(group, subject)?;
record_in(group, subject)?;
}
let limit = page(&p, 50, 100)?;
let after = match p.get("cursor") {
@@ -544,7 +583,8 @@ fn accepts(labeler: &Value, key: &str, value: &str) -> bool {
}
/// A report, from one who can read its subject: an account in a group
/// here, or a record in one of its spaces, into that group's queue.
/// here, a record in one of its spaces, or a member's public record, into
/// that group's queue.
pub async fn create_report(
State(host): State<Arc<Host>>,
headers: HeaderMap,
@@ -575,23 +615,29 @@ pub async fn create_report(
"the group takes no reports of {reason_type}"
)));
}
// An account is reported in the members space, where its labels go;
// a record, in its own.
let (space, kind, collection) = match space_of(&subject) {
// A record in a space is reported in its own; an account, or a
// member's public record, in the members space, where its labels go.
let collection = subject
.strip_prefix("at://")
.map(|_| subject.rsplit('/').nth(1).expect("a record's URI"));
let kind = if collection.is_some() {
"record"
} else {
"account"
};
let space = match space_of(&subject) {
Some((space, _)) => space,
None => {
let roles = host.roles(group, &subject).map_err(XrpcError::internal)?;
let account = public_of(&subject).unwrap_or(&subject);
let roles = host.roles(group, account).map_err(XrpcError::internal)?;
if roles.is_empty() {
return Err(invalid_subject("not a member of this group"));
}
(members_space(group), "account", None)
}
Some((space, _)) => {
let collection = subject.rsplit('/').nth(1).map(String::from);
(space, "record", collection)
members_space(group)
}
};
let taken = accepts(&labeler, "subjectTypes", kind)
&& collection.is_none_or(|c| accepts(&labeler, "subjectCollections", &c));
&& collection.is_none_or(|c| accepts(&labeler, "subjectCollections", c));
if !taken {
return Err(invalid_subject("the group takes no reports of this kind"));
}
crates/group-host/src/token_writes.rs+1−2
@@ -21,7 +21,6 @@ use crate::group::{members_space, meta_space};
use crate::group_invites::is_inbox;
use crate::lexicons::{check_record, validation};
use crate::member_writes::members_writes;
use crate::moderation;
use crate::oauth_resource::{Acting, Refusal};
use crate::oauth_scope::{labels_in, may_write, writes_in};
use crate::rbac::{self, Access, LABEL, NS, actions_for, grants, repo_collections_for};
@@ -120,7 +119,7 @@ impl Host {
self.face(group, write)?;
}
}
moderation::beside(space, writes)
self.beside(group, space, writes)
}
}
crates/group-host/tests/moderation.rs+125−1
@@ -413,6 +413,130 @@ async fn holds_each_label_to_the_action_it_needs() {
assert_eq!(said.body["error"], "Forbidden");
}
/// 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]) {
let labeler = json!({
"$type": format!("{NS}.labeler"),
"policies": {"labelValues": ["!hide"]},
"subjectTypes": types,
"subjectCollections": collections,
"createdAt": "2026-11-04T00:00:00Z",
});
let write = Write::Update {
collection: format!("{NS}.labeler"),
rkey: "self".into(),
value: labeler,
};
h.host
.space_write(did, &meta_space(did), &[write])
.await
.unwrap();
}
#[tokio::test]
async fn moderates_a_members_public_post_as_its_own_subject() {
let h = start(&[], false).await;
let (did, space, _, [alice, bob, carol]) = group(&h).await;
// Bob's post in his own public repo, in no space of the group's.
let uri = format!("at://{}/app.bsky.feed.post/3mzjdd6rnfise", bob.did);
let subject = json!({"$type": RECORD, "uri": uri, "cid": CID});
let (status, said) = report(&h, &alice, &did, subject.clone()).await;
assert_eq!(status, 200, "{said}");
let (_, queue) = query(&h, &alice, "listSubjects", &format!("group={did}")).await;
assert_eq!(queue["subjects"].as_array().unwrap().len(), 1);
assert_eq!(queue["subjects"][0]["subject"], record(&uri));
assert_eq!(queue["subjects"][0]["reportCount"], 1);
assert_eq!(queue["subjects"][0]["actor"]["did"], bob.did.as_str());
// Its own subject, not its author's.
let q = format!("group={did}&subject={}", bob.did);
let (_, theirs) = query(&h, &alice, "getSubjectHistory", &q).await;
assert_eq!(theirs["events"], json!([]));
let q = format!("group={did}&subject={uri}&cid={CID}");
let (_, history) = query(&h, &alice, "getSubjectHistory", &q).await;
assert_eq!(kinds(&history), ["reportEvent"]);
assert_eq!(history["events"][0]["cid"], CID);
let resolve = json!({"group": did, "subject": record(&uri), "status": "resolved"});
let (status, view) = call(&h, &alice, "resolveSubject", resolve).await;
assert_eq!(status, 200, "{view}");
assert_eq!(view["status"], "resolved");
assert_eq!(view["actor"]["did"], bob.did.as_str());
let carols = format!("at://{}/app.bsky.feed.post/3mzjdd6rnfise", carol.did);
for (who, subject) in [
// Carol cannot read the members space.
(&carol, record(&uri)),
// Carol is not a member, nor is the group.
(&bob, record(&carols)),
(&bob, record(&format!("at://{did}/app.bsky.feed.post/x"))),
// A public record, by its DID, collection and key.
(
&bob,
record(&format!("at://{}/app.bsky.feed.post", bob.did)),
),
(&bob, record("at://bob.test/app.bsky.feed.post/x")),
] {
assert_eq!(
error(&report(&h, who, &did, subject.clone()).await),
(400, "InvalidSubject"),
"{subject}"
);
}
// The labeler's kinds and collections, as for any record.
takes(&h, &did, &["record"], &["app.bsky.feed.post"]).await;
assert_eq!(report(&h, &bob, &did, record(&uri)).await.0, 200);
for (types, collections) in [
(["account"], ["app.bsky.feed.post"]),
(["record"], ["com.example.event"]),
] {
takes(&h, &did, &types, &collections).await;
assert_eq!(
error(&report(&h, &bob, &did, record(&uri)).await),
(400, "InvalidSubject"),
"{types:?} {collections:?}"
);
}
// Labelled in the members space, where its author's labels go.
let members = members_space(&did);
let (status, made) = labelled(&h, &alice, &did, &members, label(&uri, "spam")).await;
assert_eq!(status, 200, "{made}");
let rkey = made["uri"].as_str().unwrap().rsplit('/').next().unwrap();
let nsid = "com.atproto.space.deleteRecord";
let (status, said) = as_group(&h, &alice, &did, &members, nsid, json!({"rkey": rkey})).await;
assert_eq!(status, 200, "{said}");
let q = format!("group={did}&subject={uri}");
let (_, history) = query(&h, &alice, "getSubjectHistory", &q).await;
assert_eq!(
kinds(&history),
[
"reportEvent",
"statusEvent",
"reportEvent",
"labelEvent",
"labelEvent"
]
);
let events = &history["events"];
assert_eq!(events[3]["event"]["uri"], made["uri"]);
assert_eq!(events[3]["event"]["val"], "spam");
assert_eq!(events[3]["event"]["deleted"], false);
assert_eq!(events[3]["createdBy"], alice.did.as_str());
assert_eq!(events[4]["event"]["uri"], made["uri"]);
assert_eq!(events[4]["event"]["deleted"], true);
assert_eq!(events[4]["createdBy"], alice.did.as_str());
// A non-member's public record, or one labelled in any other space.
for (at, subject) in [
(&members, &carols),
(&space, &uri),
(&meta_space(&did), &uri),
] {
let said = labelled(&h, &alice, &did, at, label(subject, "x")).await;
assert_eq!(error(&said), (400, "InvalidRequest"), "{at} {subject}");
}
}
#[tokio::test]
async fn resolves_and_escalates_with_a_note() {
let h = start(&[], false).await;
@@ -535,7 +659,7 @@ async fn resolves_and_escalates_with_a_note() {
),
(
&alice,
json!({"group": did, "subject": record(&format!("at://{did}/app.bsky.feed.post/x")), "status": "resolved"}),
json!({"group": did, "subject": record(&format!("at://did:plc:other/space/{CALENDAR}/rides/{}/c.d.e/f", bob.did)), "status": "resolved"}),
(400, "InvalidSubject"),
),
(
docs/design/moderation.md+24−12
@@ -56,8 +56,16 @@ A label has to be readable by the people who see its subject, and only
by them. So it goes where the subject lives. A record's label goes into
the space the record is in, in the group's own repo there; an account's
label goes into the group's members space. Whoever may read the space
may read its labels. The host refuses a label whose `uri` is neither a
DID nor a record in the space it is written in.
may read its labels.
A member also writes in their own public repo, outside the group's
spaces: a post an app such as a forum shows to the group's public
community. Such a record is labelled where its author's labels go, in
the members space, so a moderator can label one post rather than the
member who wrote it. The host refuses a label whose `uri` is neither a
DID nor a record in the space it is written in, nor, in the members
space, a record in the public repo of someone who holds a role in the
group.
A label is taken back by deleting it. The record is gone from the
space, but the queue keeps that it was written, when, and by whom.
@@ -89,7 +97,9 @@ those with `mod.read` see it.
A subject is an account, sent and answered as
`fyi.opensocial.defs#accountSubject` with its `did`, or a record, as
`fyi.opensocial.defs#recordSubject` with its `uri` and, optionally, the
`cid` of one version. The queue keeps a record as a whole, by its URI;
`cid` of one version. A record is one in a space, or one in a public
repo, `at://<did>/<collection>/<rkey>`, its own subject apart from its
author's account. The queue keeps a record as a whole, by its URI;
the version a report or label names stays on that event. A subject has a
status: `open`, `escalated` or `resolved`.
@@ -134,9 +144,9 @@ Deleting a group deletes its queue.
Details:
- A subject that is neither a DID nor a record in one of the group's
spaces is `InvalidSubject`. Resolving one never in the queue is
`SubjectNotFound`.
- A subject that is neither a DID, a record in one of the group's
spaces, nor a record in a public repo is `InvalidSubject`. Resolving
one never in the queue is `SubjectNotFound`.
- A page is 50 events or subjects unless `limit` says, 100 at most; the
`cursor` an answer gives asks for the next.
@@ -148,9 +158,10 @@ report arrives at `fyi.opensocial.createReport`, by service auth or the
console's session. It names the `group`, the subject, a `reasonType`,
and optionally a `reason` and the `rule` it cites. It needs no role.
The subject is an account that is a member of the group, or a record in
one of the group's spaces hosted here. The reporter must be able to read
the space the subject is in: a record's own space, or for an account the
The subject is an account that is a member of the group, a record in
one of the group's spaces hosted here, or a record in the public repo of
a member. The reporter must be able to read the space the subject is in:
a record's own space, or for an account or a member's public record the
members space, where its labels go. The report goes into the group's
queue as a `reportEvent`, and is answered with its `id` and `createdAt`.
Nobody is notified: the report waits in the queue for a moderator.
@@ -184,9 +195,10 @@ answers the definitions as `labels`, to whoever may read the meta space.
Details:
- A group not hosted here is `GroupNotFound`. A subject the reporter
cannot read, that is not in the group, or of a kind or collection the
labeler does not take, is `InvalidSubject`; a reason it does not take
is `InvalidRequest`.
cannot read, that is not in the group, a public record of someone not
a member, or of a kind or collection the labeler does not take, is
`InvalidSubject`; a reason it does not take is `InvalidRequest`. A
member's public record is a `record`, of its collection.
- A `rule` must be a record's URI in the group's meta space.
- The host does not check that the reported record exists or that its
CID matches.
docs/reference/api.md+2−2
@@ -170,7 +170,7 @@ An app signed in so, or with an app password, uses these as the group:
| `GET com.atproto.server.getSession` | the group a token acts as: its DID, handle, and whether it is switched on |
| `POST com.atproto.server.createSession`, `POST com.atproto.server.refreshSession`, `POST com.atproto.server.deleteSession` | an app password's sessions |
| `POST com.atproto.repo.createRecord`, `POST com.atproto.repo.putRecord`, `POST com.atproto.repo.deleteRecord`, `POST com.atproto.repo.applyWrites`, `POST com.atproto.repo.uploadBlob` | writes to the group's public repo |
| `POST com.atproto.space.createRecord`, `POST com.atproto.space.putRecord`, `POST com.atproto.space.deleteRecord`, `POST com.atproto.space.applyWrites` | writes to its repo in a space: one of its own, or someone's inbox, where it writes and deletes its invites to them (`AlreadyMember`, `InviteNotFound`). A label (`com.atproto.label.label`) is written, and deleted, in any of the group's spaces, beside its subject ([moderation](../design/moderation.md#labels)) |
| `POST com.atproto.space.createRecord`, `POST com.atproto.space.putRecord`, `POST com.atproto.space.deleteRecord`, `POST com.atproto.space.applyWrites` | writes to its repo in a space: one of its own, or someone's inbox, where it writes and deletes its invites to them (`AlreadyMember`, `InviteNotFound`). A label (`com.atproto.label.label`) is written, and deleted, in any of the group's spaces, beside its subject; a member's record in their public repo is labelled in the members space ([moderation](../design/moderation.md#labels)) |
A group's profile and rules, in `meta`, change only this way: an app
writes the records as the group, and the host keeps each only as its
@@ -196,7 +196,7 @@ its tools are in [MCP tools](mcp.md).
| Method | What it does |
| --- | --- |
| `POST fyi.opensocial.createReport` | reports a member or a record in one of the group's spaces here, from one who can read its space and as the group's labeler takes reports; answers the report's `id` and `createdAt`. A reason or note is 2,000 characters (20,000 bytes) at most |
| `POST fyi.opensocial.createReport` | reports a member, a record in one of the group's spaces here, or a member's record in their public repo, from one who can read its space (the members space for a member or their public record) and as the group's labeler takes reports; answers the report's `id` and `createdAt`. A reason or note is 2,000 characters (20,000 bytes) at most |
| `GET fyi.opensocial.listSubjects` | the moderation queue of one status, `open` unless asked |
| `GET fyi.opensocial.getSubjectHistory` | a subject's events, oldest first, a page at a time; with a `cid`, those about that version |
| `POST fyi.opensocial.resolveSubject` | sets a subject `resolved` or `escalated`, with an optional note; answers the subject |
lexicons/fyi/opensocial/createReport.json+2−2
@@ -4,7 +4,7 @@
"defs": {
"main": {
"type": "procedure",
"description": "Report an account or record in a group, opening or reopening it in the moderation queue. Uses service auth from the caller, who must be able to read the subject's space.",
"description": "Report an account or record in a group, or a member's record in their public repo, opening or reopening it in the moderation queue. Uses service auth from the caller, who must be able to read the subject's space: a record's own, or the members space for an account or a public record.",
"input": {
"encoding": "application/json",
"schema": {
@@ -72,7 +72,7 @@
},
{
"name": "InvalidSubject",
"description": "The subject isn't an account or record in this group."
"description": "The subject isn't an account or record in this group, nor a member's public record."
}
]
}
lexicons/fyi/opensocial/defs.json+1−1
@@ -837,7 +837,7 @@
"uri": {
"type": "string",
"format": "at-uri",
"description": "A record in one of the group's spaces."
"description": "A record in one of the group's spaces, or in a public repo."
},
"cid": {
"type": "string",
lexicons/fyi/opensocial/getSubjectHistory.json+1−1
@@ -62,7 +62,7 @@
"errors": [
{
"name": "InvalidSubject",
"description": "The subject isn't an account or record in this group."
"description": "The subject isn't an account, a record in this group, or a record in a public repo."
}
]
}
lexicons/fyi/opensocial/resolveSubject.json+1−1
@@ -52,7 +52,7 @@
"errors": [
{
"name": "InvalidSubject",
"description": "The subject isn't an account or record in this group."
"description": "The subject isn't an account, a record in this group, or a record in a public repo."
},
{
"name": "SubjectNotFound",