chadtmiller.com/group-host
atmosphere group host
0
0
Moderators see what the group took down, where they review it
crates/group-host/src/blobs.rs+14−5
| @@ -8,8 +8,9 @@ | ||
//! `/img/{did}/{cid}`, to whoever may see a record that holds it: anyone, | ||
//! for a record in its public repo; for one in a space, whoever signed in | ||
//! to the console that space lets read, a group's listed profile being for | ||
//! anyone signed in. Served as an image and nothing more, and kept for | ||
//! good, as a CID names its bytes. | ||
//! anyone signed in; but none a takedown of the group's takes out of the | ||
//! space (`takedown.rs`), to anyone. Served as an image and nothing more, | ||
//! and kept for good, as a CID names its bytes. | ||
| ||
use crate::Host; | ||
use crate::authority::Access; | ||
| @@ -181,7 +182,8 @@ impl Host { | ||
/// Whether `who` (none, for someone not signed in) may see `did`'s blob | ||
/// `cid`: a record holding it is one they may read. Someone not signed | ||
/// in sees only what the public repo holds, as of a group they learn | ||
/// no more than its DID and handle. | ||
/// no more than its DID and handle. In a space, none the group took | ||
/// down (`takedown.rs`), to anyone, as `getSpaceBlob` serves it. | ||
pub fn may_see(&self, did: &str, cid: &Cid, who: Option<&str>) -> Result<bool> { | ||
if self.store.deactivation(did)?.is_some() { | ||
return Ok(false); | ||
| @@ -194,8 +196,15 @@ impl Host { | ||
}; | ||
for space in self.store.holding_spaces(did, cid)? { | ||
let hosted = self.store.space(&space)?; | ||
let may = hosted.map(|h| self.may(&space, &h, Some(who), Access::Read)); | ||
if may.transpose()?.unwrap_or(false) { | ||
let may = hosted | ||
.as_ref() | ||
.map(|h| self.may(&space, h, Some(who), Access::Read)); | ||
if !may.transpose()?.unwrap_or(false) { | ||
continue; | ||
} | ||
let group = &hosted.expect("a space they read is hosted").authority; | ||
let down = self.taken_down(group, &space)?; | ||
if !self.file_taken_down(&down, &space, did, cid)? { | ||
return Ok(true); | ||
} | ||
} | ||
crates/group-host/src/index_api.rs+9−3
| @@ -23,7 +23,7 @@ use serde_json::{Value, json}; | ||
use std::sync::Arc; | ||
| ||
/// How long a list waits on the index to read the space's writers. | ||
const SYNC_AT_MOST: std::time::Duration = std::time::Duration::from_secs(5); | ||
pub(crate) const SYNC_AT_MOST: std::time::Duration = std::time::Duration::from_secs(5); | ||
| ||
/// The most bytes a file is fetched from its writer's PDS for. | ||
pub const FILE_AT_MOST: usize = 5 * 1024 * 1024; | ||
| @@ -185,6 +185,12 @@ pub async fn get_space_blob( | ||
} | ||
let fetched = host.space_blob(&group, &space, repo, &cid).await; | ||
let (mime, bytes) = fetched.ok_or_else(|| not_found("no such file in this space"))?; | ||
Ok(served(mime, bytes)) | ||
} | ||
| ||
/// A file of a space's, as the host serves it: its own type, and nothing | ||
/// in it run, kept by the browser that asked and no cache between. | ||
pub(crate) fn served(mime: String, bytes: Vec<u8>) -> Response { | ||
let headers = [ | ||
(header::CONTENT_TYPE, mime), | ||
(header::X_CONTENT_TYPE_OPTIONS, "nosniff".to_string()), | ||
| @@ -194,14 +200,14 @@ pub async fn get_space_blob( | ||
), | ||
(header::CACHE_CONTROL, "private, max-age=3600".to_string()), | ||
]; | ||
Ok((headers, bytes).into_response()) | ||
(headers, bytes).into_response() | ||
} | ||
| ||
impl Host { | ||
/// `repo`'s blob `cid` in `space`, a group's here: from the store for | ||
/// a repo here, else from the repo's PDS, with a credential the group | ||
/// issues itself. Its type and bytes. | ||
async fn space_blob( | ||
pub(crate) async fn space_blob( | ||
&self, | ||
group: &str, | ||
space: &str, | ||
crates/group-host/src/lexicons.rs+1−0
| @@ -67,6 +67,7 @@ pub const FILES: &[&str] = &[ | ||
lexicon!("fyi/opensocial/getGroupAuth"), | ||
lexicon!("fyi/opensocial/getJoinRequest"), | ||
lexicon!("fyi/opensocial/getLogs"), | ||
lexicon!("fyi/opensocial/getModSubjectBlob"), | ||
lexicon!("fyi/opensocial/getModSubjectHistory"), | ||
lexicon!("fyi/opensocial/getSpaceBlob"), | ||
lexicon!("fyi/opensocial/getStats"), | ||
crates/group-host/src/lib.rs+4−0
| @@ -348,6 +348,10 @@ pub(crate) fn routes(host: Arc<Host>) -> Router { | ||
"/xrpc/fyi.opensocial.getModSubjectHistory", | ||
get(moderation::get_mod_subject_history), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.getModSubjectBlob", | ||
get(moderation::get_mod_subject_blob), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.resolveModSubject", | ||
post(moderation::resolve_mod_subject), | ||
crates/group-host/src/moderation.rs+48−3
| @@ -15,18 +15,22 @@ | ||
use crate::Host; | ||
use crate::api::{Params, invalid, invalid_cursor, page, param}; | ||
use crate::authority::Access; | ||
use crate::blobs::blob_refs; | ||
use crate::group::{members_space, meta_space}; | ||
use crate::group_api::{group_of, signed_in}; | ||
use crate::index_api::served; | ||
use crate::rbac::{LABEL, NS}; | ||
use crate::repo::Write; | ||
use crate::store::Store; | ||
use crate::takedown::Reviewed; | ||
use crate::time::{iso, now_millis}; | ||
use crate::xrpc::XrpcError; | ||
use anyhow::Result; | ||
use atproto::syntax; | ||
use atproto::{Cid, drisl, syntax}; | ||
use axum::Json; | ||
use axum::extract::{Query, State}; | ||
use axum::http::{HeaderMap, StatusCode}; | ||
use axum::response::Response; | ||
use rusqlite::{OptionalExtension, Row, params}; | ||
use serde_json::{Value, json}; | ||
use std::collections::HashMap; | ||
| @@ -487,14 +491,15 @@ pub async fn list_mod_subjects( | ||
} | ||
| ||
/// What happened to a subject in the group's queue, oldest first, a page | ||
/// at a time. | ||
/// at a time; and a record subject itself, as a moderator reviews it. | ||
pub async fn get_mod_subject_history( | ||
State(host): State<Arc<Host>>, | ||
Query(p): Query<Params>, | ||
headers: HeaderMap, | ||
) -> Answer { | ||
let group = param(&p, "group")?; | ||
host.moderator(&headers, "getModSubjectHistory", group, "mod.read") | ||
let me = host | ||
.moderator(&headers, "getModSubjectHistory", group, "mod.read") | ||
.await?; | ||
let subject = param(&p, "subject")?; | ||
subject_of(group, subject)?; | ||
| @@ -517,9 +522,49 @@ pub async fn get_mod_subject_history( | ||
{ | ||
out["cursor"] = json!(last.seq.to_string()); | ||
} | ||
let reviewed = host.reviewed(group, subject, &me).await; | ||
if let Some(r) = reviewed.map_err(XrpcError::internal)? { | ||
out["record"] = json!({ | ||
"uri": subject, | ||
"cid": r.record.cid.to_string(), | ||
"value": value_of(&r), | ||
"createdAt": iso(r.record.indexed_at), | ||
"takenDown": r.taken_down, | ||
}); | ||
} | ||
Ok(Json(out)) | ||
} | ||
| ||
/// A reviewed record's value, as JSON. | ||
fn value_of(r: &Reviewed) -> Value { | ||
let value = drisl::decode(&r.record.value).expect("a record the host indexed"); | ||
value.to_json() | ||
} | ||
| ||
/// A file a record subject holds, for a moderator reviewing it, whom its | ||
/// space lets read it: served though the group took the record down. | ||
pub async fn get_mod_subject_blob( | ||
State(host): State<Arc<Host>>, | ||
Query(p): Query<Params>, | ||
headers: HeaderMap, | ||
) -> Result<Response, XrpcError> { | ||
let group = param(&p, "group")?; | ||
let me = host | ||
.moderator(&headers, "getModSubjectBlob", group, "mod.read") | ||
.await?; | ||
let subject = param(&p, "subject")?; | ||
subject_of(group, subject)?; | ||
let cid = Cid::parse(param(&p, "cid")?).map_err(|e| invalid(format!("cid: {e}")))?; | ||
let gone = || XrpcError::new(StatusCode::BAD_REQUEST, "NotFound", "no such file here"); | ||
let reviewed = host.reviewed(group, subject, &me).await; | ||
let reviewed = reviewed.map_err(XrpcError::internal)?; | ||
let holds = |r: &Reviewed| blob_refs(&value_of(r)).contains(&cid); | ||
let r = reviewed.filter(holds).ok_or_else(gone)?; | ||
let fetched = host.space_blob(group, &r.space, &r.record.did, &cid).await; | ||
let (mime, bytes) = fetched.ok_or_else(gone)?; | ||
Ok(served(mime, bytes)) | ||
} | ||
| ||
/// Resolves or escalates a subject, with a note if one is given; setting | ||
/// the status it has keeps the note. | ||
pub async fn resolve_mod_subject( | ||
crates/group-host/src/oauth_scope.rs+2−1
| @@ -27,12 +27,13 @@ pub const TIERS: [&str; 3] = ["authManageProfile", "authModerate", "authManageGr | ||
| ||
/// The action each of the host's methods a permission set lists asks of | ||
/// the member who signed the app in. | ||
const ASKS: [(&str, &str); 6] = [ | ||
const ASKS: [(&str, &str); 7] = [ | ||
("listJoinRequests", "admit"), | ||
("denyJoinRequest", "admit"), | ||
("listInvites", "invite"), | ||
("listModSubjects", "mod.read"), | ||
("getModSubjectHistory", "mod.read"), | ||
("getModSubjectBlob", "mod.read"), | ||
("resolveModSubject", "mod.resolve"), | ||
]; | ||
| ||
crates/group-host/src/takedown.rs+49−1
| @@ -10,18 +10,66 @@ | ||
//! where an account's labels go, in every space of the group. Deleting | ||
//! the label, or its lapsing (`exp`), puts it all back. Only the group's | ||
//! own labels count: one anyone else writes takes nothing down. What is | ||
//! taken down stays in its writer's repo; the host only stops serving it. | ||
//! taken down stays in its writer's repo; the host only stops serving it, | ||
//! but to a moderator reviewing it (`getModSubjectHistory`, | ||
//! `getModSubjectBlob`) whom the space lets read it, as it was. | ||
| ||
use crate::Host; | ||
use crate::authority::Access; | ||
use crate::blobs::blob_refs; | ||
use crate::group::members_space; | ||
use crate::group_invites::millis_of; | ||
use crate::index_api::SYNC_AT_MOST; | ||
use crate::moderation::space_of; | ||
use crate::rbac::LABEL; | ||
use crate::store::Indexed; | ||
use crate::time::now_millis; | ||
use anyhow::Result; | ||
use atproto::{Cid, drisl, syntax}; | ||
use std::collections::HashSet; | ||
| ||
/// A record subject as a moderator reviews it: the space it is in, the | ||
/// version the index holds, and whether the group took that down. | ||
pub struct Reviewed { | ||
pub space: String, | ||
pub record: Indexed, | ||
pub taken_down: bool, | ||
} | ||
| ||
impl Host { | ||
/// The record `subject` names in one of `group`'s spaces, as the index | ||
/// holds it, for `me`, a moderator whom the space's policy lets read | ||
/// it: taken down or not. None for an account or a public record, nor | ||
/// for one `me` may not read or the index does not hold. | ||
pub async fn reviewed(&self, group: &str, subject: &str, me: &str) -> Result<Option<Reviewed>> { | ||
let Some((space, _)) = space_of(subject) else { | ||
return Ok(None); | ||
}; | ||
let Some(hosted) = self.store.space(&space)? else { | ||
return Ok(None); | ||
}; | ||
if !self.may(&space, &hosted, Some(me), Access::Read)? { | ||
return Ok(None); | ||
} | ||
// Read as a list of the space is: what the index has not read yet | ||
// first, for a few seconds at most. | ||
let synced = tokio::time::timeout(SYNC_AT_MOST, self.sync_space(&space)).await; | ||
tracing::debug!(space, ?synced, "read before reviewing"); | ||
let rest = &subject[space.len() + 1..]; | ||
let (repo, path) = rest.split_once('/').expect("a repo, then a path"); | ||
let Some(record) = self.store.indexed_one(&space, repo, path)? else { | ||
return Ok(None); | ||
}; | ||
let down = self.taken_down(group, &space)?; | ||
let taken_down = down.hides(subject, repo, &record.cid.to_string()); | ||
Ok(Some(Reviewed { | ||
space, | ||
record, | ||
taken_down, | ||
})) | ||
} | ||
} | ||
| ||
/// The label that takes content down. | ||
pub const TAKEDOWN: &str = "!takedown"; | ||
| ||
crates/group-host/tests/moderation.rs+146−0
| @@ -1188,3 +1188,149 @@ async fn takes_out_of_the_space_what_the_group_takes_down() { | ||
assert!(events(&h, &bob, &did, &space, None).await.is_empty()); | ||
assert_eq!(the_map().await.error(), (400, "NotFound".into())); | ||
} | ||
| ||
/// How the console's `/img` answers `who`, signed in to it, for `did`'s | ||
/// picture `cid`: by its status. | ||
async fn picture(h: &Running, who: &Authority, did: &str, cid: &str) -> u16 { | ||
let now = std::time::SystemTime::now() | ||
.duration_since(std::time::UNIX_EPOCH) | ||
.unwrap() | ||
.as_millis() as i64; | ||
let cookie = h.host.session_cookie(&who.did, now); | ||
let name = h.host.cookie_name(group_host::console_login::COOKIE); | ||
let req = h.http.get(format!("{}/img/{did}/{cid}", h.url)); | ||
let res = req | ||
.header("cookie", format!("{name}={cookie}")) | ||
.send() | ||
.await; | ||
res.unwrap().status().as_u16() | ||
} | ||
| ||
/// A subject's history, as `who` reviews it in Riders' queue. | ||
async fn reviewed(h: &Running, who: &Authority, did: &str, subject: &str) -> (u16, Json) { | ||
let q = format!("group={did}&subject={}", urlencode(subject)); | ||
query(h, who, "getModSubjectHistory", &q).await | ||
} | ||
| ||
/// The file `cid` of the record `subject`, as `who` reviews it. | ||
async fn reviewed_file(h: &Running, who: &Authority, did: &str, subject: &str, cid: &str) -> Read { | ||
let lxm = format!("{NS}.getModSubjectBlob"); | ||
let q = format!("group={did}&subject={}&cid={cid}", urlencode(subject)); | ||
read(h, &lxm, &q, &[auth(h, who, &lxm)]).await | ||
} | ||
| ||
#[tokio::test] | ||
async fn shows_a_moderator_what_was_taken_down_where_they_review_it() { | ||
let h = start(&[], false).await; | ||
let (did, space, _, [alice, bob, carol]) = group(&h).await; | ||
// Dan, an account here and a member, posts a ride with a map, which | ||
// the group takes down; and a picnic with a flyer, which it leaves. | ||
let dan = h.host.create_account("dan.groups.test").await.unwrap(); | ||
membership(&h, &did, &dan, &["member"]).await; | ||
let map = h.host.upload_blob(&dan, b"a map", "image/png").unwrap(); | ||
let flyer = h.host.upload_blob(&dan, b"a flyer", "image/png").unwrap(); | ||
let event = |rkey: &str, value: Json| Write::Create { | ||
collection: "com.example.event".into(), | ||
rkey: rkey.into(), | ||
value, | ||
}; | ||
let ride_value = json!({"$type": "com.example.event", "text": "Ride", "map": map}); | ||
let picnic_value = json!({"$type": "com.example.event", "text": "Picnic", "flyer": flyer}); | ||
let writes = [ | ||
event("ride", ride_value.clone()), | ||
event("picnic", picnic_value), | ||
]; | ||
h.host.space_write(&dan, &space, &writes).await.unwrap(); | ||
let ride = format!("{space}/{dan}/com.example.event/ride"); | ||
let picnic = format!("{space}/{dan}/com.example.event/picnic"); | ||
let (status, made) = labelled(&h, &alice, &did, &space, label(&ride, "!takedown")).await; | ||
assert_eq!(status, 200, "{made}"); | ||
let map = map["ref"]["$link"].as_str().unwrap(); | ||
let flyer = flyer["ref"]["$link"].as_str().unwrap(); | ||
| ||
// Read as anyone reads the space, it is gone for a member and for the | ||
// moderator alike, and its map with it, as a file and as a picture; | ||
// the picnic's flyer, which nothing taken down holds, is not. | ||
for who in [&bob, &alice] { | ||
assert_eq!(events(&h, who, &did, &space, None).await, [picnic.as_str()]); | ||
let lxm = format!("{NS}.getSpaceBlob"); | ||
let q = format!("group={did}&space={space}&repo={dan}&cid={map}"); | ||
let file = read(&h, &lxm, &q, &[auth(&h, who, &lxm)]).await; | ||
assert_eq!(file.error(), (400, "NotFound".into())); | ||
assert_eq!(picture(&h, who, &dan, map).await, 404); | ||
assert_eq!(picture(&h, who, &dan, flyer).await, 200); | ||
} | ||
| ||
// Reviewed, the moderator sees it as the index holds it, said to be | ||
// taken down, and its map. | ||
let (status, seen) = reviewed(&h, &alice, &did, &ride).await; | ||
assert_eq!(status, 200, "{seen}"); | ||
let record = &seen["record"]; | ||
assert_eq!(record["uri"], ride.as_str()); | ||
assert_eq!(record["value"], ride_value); | ||
assert_eq!(record["takenDown"], true); | ||
assert!(record["cid"].is_string()); | ||
assert!(record["createdAt"].is_string()); | ||
assert_eq!(kinds(&seen), ["labelEvent"]); | ||
let got = reviewed_file(&h, &alice, &did, &ride, map).await; | ||
assert_eq!(got.status, 200); | ||
assert_eq!(got.body, b"a map"); | ||
assert_eq!(got.header("content-type"), Some("image/png")); | ||
assert_eq!( | ||
got.header("content-security-policy"), | ||
Some("default-src 'none'; sandbox") | ||
); | ||
| ||
// What is not taken down is shown as well, said to be up; only the | ||
// files the record holds are served, not another of the writer's. | ||
let (_, seen) = reviewed(&h, &alice, &did, &picnic).await; | ||
assert_eq!(seen["record"]["takenDown"], false); | ||
assert!(seen["events"].as_array().unwrap().is_empty()); | ||
assert_eq!( | ||
reviewed_file(&h, &alice, &did, &picnic, flyer).await.status, | ||
200 | ||
); | ||
let not_its = reviewed_file(&h, &alice, &did, &ride, flyer).await; | ||
assert_eq!(not_its.error(), (400, "NotFound".into())); | ||
| ||
// An account, a record the index does not hold, a public record, and | ||
// one in a space not hosted here carry no record, and serve no file. | ||
let gone = format!("{space}/{dan}/com.example.event/gone"); | ||
let public = format!("at://{dan}/com.example.event/ride"); | ||
let nowhere = format!("at://{did}/space/{CALENDAR}/nowhere/{dan}/com.example.event/ride"); | ||
for subject in [dan.as_str(), &gone, &public, &nowhere] { | ||
let (status, seen) = reviewed(&h, &alice, &did, subject).await; | ||
assert_eq!(status, 200, "{seen}"); | ||
assert!(seen.get("record").is_none(), "{seen}"); | ||
let none = reviewed_file(&h, &alice, &did, subject, map).await; | ||
assert_eq!(none.error(), (400, "NotFound".into())); | ||
} | ||
let bad = reviewed_file(&h, &alice, &did, &ride, "bafynotacid").await; | ||
assert_eq!(bad.error(), (400, "InvalidRequest".into())); | ||
let elsewhere = "at://did:plc:x/space/a.b/c/did:plc:y/a.b/c"; | ||
let elsewhere = reviewed_file(&h, &alice, &did, elsewhere, map).await; | ||
assert_eq!(elsewhere.error(), (400, "InvalidSubject".into())); | ||
| ||
// A plain member is refused both. | ||
assert_eq!(reviewed(&h, &bob, &did, &ride).await.0, 403); | ||
let refused = reviewed_file(&h, &bob, &did, &ride, map).await; | ||
assert_eq!(refused.error(), (403, "Forbidden".into())); | ||
| ||
// A moderator the space does not let read sees the history, and | ||
// neither the record nor its files. | ||
let role = json!({"$type": format!("{NS}.role"), "displayName": "Moderator", "scopes": [format!("rpc:{NS}.listModSubjects?aud=*")], "createdAt": "2026-11-03T00:00:00Z"}); | ||
let write = Write::Create { | ||
collection: format!("{NS}.role"), | ||
rkey: "moderator".into(), | ||
value: role, | ||
}; | ||
let members = members_space(&did); | ||
h.host.space_write(&did, &members, &[write]).await.unwrap(); | ||
membership(&h, &did, &carol.did, &["moderator"]).await; | ||
let (status, seen) = reviewed(&h, &carol, &did, &ride).await; | ||
assert_eq!(status, 200, "{seen}"); | ||
assert_eq!(kinds(&seen), ["labelEvent"]); | ||
assert!(seen.get("record").is_none(), "{seen}"); | ||
let unread = reviewed_file(&h, &carol, &did, &ride, map).await; | ||
assert_eq!(unread.error(), (400, "NotFound".into())); | ||
} | ||
crates/group-host/tests/oauth_scope.rs+1−0
| @@ -578,6 +578,7 @@ fn makes_a_permission_set_concrete() { | ||
format!("rpc:{NS}.listInvites?aud=*"), | ||
format!("rpc:{NS}.listModSubjects?aud=*"), | ||
format!("rpc:{NS}.getModSubjectHistory?aud=*"), | ||
format!("rpc:{NS}.getModSubjectBlob?aud=*"), | ||
format!("rpc:{NS}.resolveModSubject?aud=*"), | ||
] | ||
); | ||
docs/design/groups.md+2−1
| @@ -197,7 +197,8 @@ The host serves images at `/img/{did}/{cid}` to anyone who may see a | ||
record holding them. For the public repo that's anyone. Otherwise it's | ||
anyone signed in to the console who may read the space. For `meta` while | ||
the group is declared, that's anyone signed in. A switched-off group's | ||
images aren't served. | ||
images aren't served, nor is an image the group has taken down in a | ||
space ([moderation](moderation.md#labels)). | ||
| ||
A rule is kept at a TID, so a label citing it keeps its URI however the | ||
rule changes. When a new rule is written with no key, the host's clock | ||
docs/design/moderation.md+31−5
docs/design/signing-in.md+4−3
docs/design/spaces.md+1−1
docs/guides/shots/moderating-post-takedown-dark.pngnew+0−0
A binary file, not shown.
docs/guides/shots/moderating-post-takedown.pngnew+0−0
A binary file, not shown.