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

A group's profile, images and rules are changed by those who may configure it

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:host/group-config
crates/group-host/src/group_api.rs+7−3
@@ -45,7 +45,11 @@ pub(crate) async fn caller(
}
/// Who calls `lxm`, who must say.
async fn signed_in(host: &Host, headers: &HeaderMap, lxm: &str) -> Result<String, XrpcError> {
pub(crate) async fn signed_in(
host: &Host,
headers: &HeaderMap,
lxm: &str,
) -> Result<String, XrpcError> {
let who = caller(host, headers, lxm).await?;
who.ok_or_else(|| unauthorized("AuthMissing", "service auth is required"))
}
@@ -75,7 +79,7 @@ pub async fn create_group(
Ok(Json(json!({"did": did, "meta": meta, "members": members})))
}
fn not_found() -> XrpcError {
pub(crate) fn not_found() -> XrpcError {
XrpcError::new(
StatusCode::BAD_REQUEST,
"GroupNotFound",
@@ -84,7 +88,7 @@ fn not_found() -> XrpcError {
}
/// A group here: its handle, if `did` is one.
fn group_of(host: &Host, did: &str) -> Result<String, XrpcError> {
pub(crate) fn group_of(host: &Host, did: &str) -> Result<String, XrpcError> {
let account = host.store.account(did).map_err(XrpcError::internal)?;
let account = account.filter(|a| a.did == did).ok_or_else(not_found)?;
let space = host
crates/group-host/src/group_config.rsnew+319−0
@@ -0,0 +1,319 @@
//! Changing a group's face: its profile, its images and its rules. Each is
//! a record in its meta space, written by the group, so the host writes it
//! for a caller holding `group.configure`.
//!
//! As the prototype's `methods/profile.ts` and `methods/rules.ts`.
use crate::Host;
use crate::api::{Params, invalid, param};
use crate::group::{join_policy, members_space, meta_space};
use crate::group_api::{group_of, signed_in};
use crate::rbac::{NS, actions_for, grants};
use crate::repo::Write;
use crate::time::{iso, now_millis};
use crate::xrpc::XrpcError;
use axum::Json;
use axum::body::Bytes;
use axum::extract::{Query, State};
use axum::http::{HeaderMap, StatusCode, header};
use serde_json::{Value, json};
use std::sync::Arc;
type Answer = Result<Json<Value>, XrpcError>;
/// The most bytes an image may be, as the profile's lexicon has it.
pub const IMAGE_AT_MOST: usize = 1_000_000;
/// Where a group meets: the places `community.lexicon.location` has.
const PLACES: [&str; 4] = [
"community.lexicon.location.address",
"community.lexicon.location.geo",
"community.lexicon.location.fsq",
"community.lexicon.location.hthree",
];
fn forbidden() -> XrpcError {
XrpcError::new(
StatusCode::FORBIDDEN,
"Forbidden",
"missing group.configure",
)
}
/// The group a caller of `lxm` changes, once they hold `group.configure`
/// in it.
async fn configurer(
host: &Host,
headers: &HeaderMap,
group: &str,
lxm: &str,
) -> Result<String, XrpcError> {
let me = signed_in(host, headers, &format!("{NS}.{lxm}")).await?;
group_of(host, group)?;
let permissions = host
.group_record(
group,
&members_space(group),
&format!("{NS}.permissions"),
"self",
)
.map_err(XrpcError::internal)?;
let roles = host.roles(group, &me).map_err(XrpcError::internal)?;
let granted = grants(&permissions.unwrap_or_default());
if !actions_for(&granted, &roles).contains("group.configure") {
return Err(forbidden());
}
Ok(group.to_string())
}
/// Puts the group's record at `collection/rkey` in meta, made or replaced:
/// its URI and CID.
async fn put(host: &Host, group: &str, collection: &str, rkey: &str, value: Value) -> Answer {
let meta = meta_space(group);
let current = host
.group_record(group, &meta, collection, rkey)
.map_err(XrpcError::internal)?;
let (collection, rkey) = (collection.to_string(), rkey.to_string());
let write = match current {
Some(_) => Write::Update {
collection: collection.clone(),
rkey: rkey.clone(),
value,
},
None => Write::Create {
collection: collection.clone(),
rkey: rkey.clone(),
value,
},
};
host.space_write(group, &meta, &[write]).await?;
let kept = host
.store
.space_record(group, &meta, &collection, &rkey)
.map_err(XrpcError::internal)?
.expect("the record just written");
let uri = format!("{meta}/{group}/{collection}/{rkey}");
Ok(Json(json!({"uri": uri, "cid": kept.cid.to_string()})))
}
/// Words a profile lists, as `[{topic}]`: trimmed, each once, at most
/// `max`.
fn words(asked: &Value, field: &str, max: usize) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for item in asked.as_array().into_iter().flatten() {
let word = item[field].as_str().unwrap_or_default().trim().to_string();
if !word.is_empty() && !out.contains(&word) {
out.push(word);
}
}
out.truncate(max);
out
}
/// A BCP 47 tag, as the profile's languages are.
fn is_language(tag: &str) -> bool {
let mut parts = tag.split('-');
let first = parts.next().unwrap_or_default();
(2..=3).contains(&first.len())
&& first.chars().all(|c| c.is_ascii_alphabetic())
&& parts.all(|p| (1..=8).contains(&p.len()) && p.chars().all(|c| c.is_ascii_alphanumeric()))
}
/// A blob as a record holds it, `{$type, ref, mimeType, size}`, from what
/// `uploadImage` answered.
fn blob(asked: &Value) -> Option<Value> {
let link = asked["ref"]["$link"].as_str()?;
let mime = asked["mimeType"].as_str()?;
let size = asked["size"].as_u64()?;
Some(json!({"$type": "blob", "ref": {"$link": link}, "mimeType": mime, "size": size}))
}
/// Replaces the group's profile. What finds it (where it meets, online,
/// topics, languages) is as given, none when left out; an image left out
/// is kept, and `null` clears it; its first `createdAt` is kept.
pub async fn update_profile(
State(host): State<Arc<Host>>,
headers: HeaderMap,
Json(body): Json<Value>,
) -> Answer {
let group = body["group"]
.as_str()
.ok_or_else(|| invalid("group is required"))?;
let group = configurer(&host, &headers, group, "updateProfile").await?;
let name = body["displayName"].as_str().unwrap_or_default().trim();
if name.is_empty() {
return Err(invalid("displayName is required"));
}
let meta = meta_space(&group);
let collection = format!("{NS}.profile");
let current = host
.group_record(&group, &meta, &collection, "self")
.map_err(XrpcError::internal)?
.unwrap_or_default();
let join = match body["joinPolicy"].as_str() {
Some(asked) => join_policy(Some(asked))?.to_string(),
None => current["joinPolicy"]
.as_str()
.unwrap_or("approval")
.to_string(),
};
let mut profile = json!({
"$type": collection,
"displayName": name,
"joinPolicy": join,
"createdAt": current.get("createdAt").cloned().unwrap_or(json!(iso(now_millis()))),
});
let text = |k: &str| body[k].as_str().map(str::trim).filter(|t| !t.is_empty());
if let Some(d) = text("description") {
profile["description"] = json!(d);
}
// The site is kept, like the images: an edit of the name says nothing
// of it.
match text("url") {
Some(url) => profile["url"] = json!(url),
None => {
if let Some(url) = current.get("url") {
profile["url"] = url.clone();
}
}
}
if let Some(place) = body.get("location").filter(|l| !l.is_null()) {
let kind = place["$type"].as_str().unwrap_or_default();
if !PLACES.contains(&kind) {
return Err(invalid(format!("location is one of {}", PLACES.join(", "))));
}
profile["location"] = place.clone();
}
if body["online"].as_bool() == Some(true) {
profile["online"] = json!(true);
}
let topics: Vec<Value> = words(&body["topics"], "topic", 10)
.into_iter()
.map(|t| json!({"topic": t.chars().take(64).collect::<String>()}))
.collect();
if !topics.is_empty() {
profile["topics"] = json!(topics);
}
let languages: Vec<Value> = words(&body["languages"], "language", 5)
.into_iter()
.filter(|l| is_language(l))
.map(|l| json!({"language": l}))
.collect();
if !languages.is_empty() {
profile["languages"] = json!(languages);
}
for key in ["avatar", "banner"] {
let image = match body.get(key) {
Some(Value::Null) => None,
Some(asked) => Some(blob(asked).ok_or_else(|| invalid(format!("{key} is a blob")))?),
None => current.get(key).and_then(blob),
};
if let Some(image) = image {
profile[key] = image;
}
}
put(&host, &group, &collection, "self", profile).await
}
/// Keeps an image as the group's, for its profile: the blob to put there.
pub async fn upload_image(
State(host): State<Arc<Host>>,
Query(p): Query<Params>,
headers: HeaderMap,
bytes: Bytes,
) -> Answer {
let group = configurer(&host, &headers, param(&p, "group")?, "uploadImage").await?;
if bytes.is_empty() {
return Err(invalid("an empty upload"));
}
if bytes.len() > IMAGE_AT_MOST {
return Err(invalid(format!(
"an image is {IMAGE_AT_MOST} bytes at most"
)));
}
let mime = headers
.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.unwrap_or_default();
let blob = host.upload_blob(&group, &bytes, mime)?;
Ok(Json(json!({ "blob": blob })))
}
/// Makes or changes a rule. Its key stays as it is, so a label citing it
/// still does; a new one gets a key of its own, and goes last unless it
/// says where.
pub async fn put_rule(
State(host): State<Arc<Host>>,
headers: HeaderMap,
Json(body): Json<Value>,
) -> Answer {
let group = body["group"]
.as_str()
.ok_or_else(|| invalid("group is required"))?;
let group = configurer(&host, &headers, group, "putRule").await?;
let title = body["title"].as_str().unwrap_or_default().trim();
if title.is_empty() {
return Err(invalid("title is required"));
}
let rkey = match body["rkey"]
.as_str()
.map(str::trim)
.filter(|k| !k.is_empty())
{
Some(k) => k.to_string(),
None => host.clock.next(),
};
let collection = format!("{NS}.rule");
let rules = host
.group_records(&group, &meta_space(&group), &collection)
.map_err(XrpcError::internal)?;
let current = rules.iter().find(|(k, _)| *k == rkey).map(|(_, r)| r);
let last = rules.iter().filter_map(|(_, r)| r["order"].as_i64()).max();
let order = body["order"]
.as_i64()
.or_else(|| current.and_then(|r| r["order"].as_i64()))
.unwrap_or_else(|| last.map_or(0, |l| l + 1));
if order < 0 {
return Err(invalid("order is 0 or more"));
}
let created = current
.and_then(|r| r.get("createdAt").cloned())
.unwrap_or_else(|| json!(iso(now_millis())));
let rule = json!({
"$type": collection,
"title": title,
"text": body["text"].as_str().unwrap_or_default().trim(),
"order": order,
"createdAt": created,
});
put(&host, &group, &collection, &rkey, rule).await
}
/// Takes a rule away. A label citing it keeps its URI, which no longer
/// resolves: better than a citation taken out of history.
pub async fn delete_rule(
State(host): State<Arc<Host>>,
headers: HeaderMap,
Json(body): Json<Value>,
) -> Answer {
let group = body["group"]
.as_str()
.ok_or_else(|| invalid("group is required"))?;
let group = configurer(&host, &headers, group, "deleteRule").await?;
let rkey = body["rkey"]
.as_str()
.ok_or_else(|| invalid("rkey is required"))?;
let collection = format!("{NS}.rule");
let meta = meta_space(&group);
let current = host
.group_record(&group, &meta, &collection, rkey)
.map_err(XrpcError::internal)?;
if current.is_some() {
let delete = Write::Delete {
collection,
rkey: rkey.into(),
};
host.space_write(&group, &meta, &[delete]).await?;
}
Ok(Json(json!({})))
}
crates/group-host/src/lib.rs+14−0
@@ -11,6 +11,7 @@ pub mod config;
pub mod firehose;
pub mod group;
pub mod group_api;
pub mod group_config;
pub mod identity;
pub mod plc;
pub mod rbac;
@@ -166,6 +167,19 @@ pub fn router(host: Arc<Host>) -> Router {
"/xrpc/fyi.opensocial.listGroups",
get(group_api::list_groups),
)
.route(
"/xrpc/fyi.opensocial.updateProfile",
post(group_config::update_profile),
)
.route(
"/xrpc/fyi.opensocial.uploadImage",
post(group_config::upload_image),
)
.route("/xrpc/fyi.opensocial.putRule", post(group_config::put_rule))
.route(
"/xrpc/fyi.opensocial.deleteRule",
post(group_config::delete_rule),
)
.route("/.well-known/did.json", get(api::did_json))
.route("/.well-known/atproto-did", get(api::atproto_did))
.route("/xrpc/{nsid}", get(not_implemented).post(not_implemented))
crates/group-host/tests/common/groups.rsnew+76−0
@@ -0,0 +1,76 @@
//! Groups to test against: people elsewhere, signed in to this host, and
//! the groups they start.
#![allow(dead_code)]
use super::Running;
use super::spaces::{Authority, authority, now, read};
use atproto::service_auth::{self, Claims};
use serde_json::Value as Json;
pub const NS: &str = "fyi.opensocial";
/// Service auth from `who` for this host and `lxm`.
pub fn auth(h: &Running, who: &Authority, lxm: &str) -> (&'static str, String) {
auth_for(who, &h.host.config.service_did, lxm)
}
pub fn auth_for(who: &Authority, aud: &str, lxm: &str) -> (&'static str, String) {
let claims = Claims {
iss: who.did.clone(),
aud: aud.into(),
exp: now() + 60,
iat: Some(now()),
lxm: Some(lxm.into()),
jti: None,
};
(
"authorization",
format!("Bearer {}", service_auth::sign(&who.key, &claims)),
)
}
pub async fn post(h: &Running, nsid: &str, body: &Json, headers: &[(&str, String)]) -> (u16, Json) {
let mut req = h.http.post(format!("{}/xrpc/{nsid}", h.url)).json(body);
for (k, v) in headers {
req = req.header(*k, v);
}
let res = req.send().await.unwrap();
(
res.status().as_u16(),
res.json().await.unwrap_or(Json::Null),
)
}
pub async fn get(h: &Running, nsid: &str, query: &str, headers: &[(&str, String)]) -> (u16, Json) {
let got = read(h, nsid, query, headers).await;
(
got.status,
serde_json::from_slice(&got.body).unwrap_or(Json::Null),
)
}
/// A group started by `founder` with `body`: its DID.
pub async fn start_group(h: &Running, founder: &Authority, body: Json) -> String {
let lxm = format!("{NS}.createGroup");
let (status, made) = post(h, &lxm, &body, &[auth(h, founder, &lxm)]).await;
assert_eq!(status, 200, "{made}");
made["did"].as_str().unwrap().to_string()
}
/// Three people elsewhere.
pub async fn people(h: &Running) -> [Authority; 3] {
[
authority(h, false, true).await,
authority(h, false, true).await,
authority(h, false, true).await,
]
}
pub async fn view(h: &Running, group: &str, who: Option<&Authority>) -> Json {
let lxm = format!("{NS}.getGroup");
let headers: Vec<_> = who.map(|w| auth(h, w, &lxm)).into_iter().collect();
let (status, view) = get(h, &lxm, &format!("group={group}"), &headers).await;
assert_eq!(status, 200, "{view}");
view
}
crates/group-host/tests/common/mod.rs+1−0
@@ -3,6 +3,7 @@
#![allow(dead_code)]
pub mod groups;
pub mod net;
pub mod spaces;
crates/group-host/tests/group_config.rsnew+355−0
@@ -0,0 +1,355 @@
//! A group's face changed by those who may configure it: its profile, its
//! images and its rules.
mod common;
use common::groups::*;
use common::spaces::*;
use common::start;
use group_host::group::{members_space, meta_space};
use group_host::repo::Write;
use serde_json::{Value as Json, json};
const NS: &str = "fyi.opensocial";
/// A group Alice started, Bob a plain member of it, and Carol a stranger.
async fn group() -> (common::Running, String, [Authority; 3]) {
let h = start(&[], false).await;
let [alice, bob, carol] = people(&h).await;
let did = start_group(
&h,
&alice,
json!({"handle": RIDERS, "displayName": "Riders", "joinPolicy": "open"}),
)
.await;
h.host
.space_write(
&did,
&members_space(&did),
&[Write::Create {
collection: format!("{NS}.membership"),
rkey: bob.did.clone(),
value: json!({"$type": format!("{NS}.membership"), "member": bob.did, "roles": [{"role": "member"}], "createdAt": "2026-11-03T00:00:00Z"}),
}],
)
.await
.unwrap();
(h, did, [alice, bob, carol])
}
async fn call(h: &common::Running, who: &Authority, method: &str, body: Json) -> (u16, Json) {
let lxm = format!("{NS}.{method}");
post(h, &lxm, &body, &[auth(h, who, &lxm)]).await
}
fn profile(h: &common::Running, did: &str) -> Json {
h.host
.group_record(did, &meta_space(did), &format!("{NS}.profile"), "self")
.unwrap()
.unwrap()
}
async fn upload(
h: &common::Running,
who: &Authority,
did: &str,
bytes: Vec<u8>,
mime: &str,
) -> (u16, Json) {
let lxm = format!("{NS}.uploadImage");
let (k, v) = auth(h, who, &lxm);
let res = h
.http
.post(format!("{}/xrpc/{lxm}?group={did}", h.url))
.header(k, v)
.header("content-type", mime)
.body(bytes)
.send()
.await
.unwrap();
(
res.status().as_u16(),
res.json().await.unwrap_or(Json::Null),
)
}
#[tokio::test]
async fn an_admin_changes_the_profile() {
let (h, did, [alice, _, _]) = group().await;
let created = profile(&h, &did)["createdAt"].clone();
let (status, image) = upload(&h, &alice, &did, b"face".to_vec(), "image/png").await;
assert_eq!(status, 200, "{image}");
let avatar = image["blob"].clone();
assert_eq!(avatar["mimeType"], "image/png");
let (status, put) = call(
&h,
&alice,
"updateProfile",
json!({
"group": did,
"displayName": " Riders United ",
"description": "We ride.",
"url": "https://riders.example",
"location": {"$type": "community.lexicon.location.address", "locality": "Ljubljana", "country": "SI"},
"online": true,
"topics": [{"topic": "bikes"}, {"topic": " bikes "}, {"topic": ""}, {"topic": "x".repeat(80)}],
"languages": [{"language": "sl"}, {"language": "en-GB"}, {"language": "not a tag"}],
"avatar": avatar,
}),
)
.await;
assert_eq!(status, 200, "{put}");
assert_eq!(
put["uri"],
format!("{}/{did}/{NS}.profile/self", meta_space(&did))
);
let p = profile(&h, &did);
assert_eq!(p["displayName"], "Riders United");
assert_eq!(p["description"], "We ride.");
// Its join policy is kept when it is not named.
assert_eq!(p["joinPolicy"], "open");
assert_eq!(p["online"], true);
assert_eq!(
p["topics"],
json!([{"topic": "bikes"}, {"topic": "x".repeat(64)}])
);
assert_eq!(
p["languages"],
json!([{"language": "sl"}, {"language": "en-GB"}])
);
assert_eq!(p["avatar"]["ref"], avatar["ref"]);
assert_eq!(p["createdAt"], created);
assert_eq!(put["cid"].as_str().map(str::len), Some(59));
// A replace: what finds it, left out, is none; the images and site
// are kept; a policy named is taken.
let (status, _) = call(
&h,
&alice,
"updateProfile",
json!({"group": did, "displayName": "Riders", "joinPolicy": "fyi.opensocial.profile#invite"}),
)
.await;
assert_eq!(status, 200);
let p = profile(&h, &did);
assert_eq!(p.get("topics"), None);
assert_eq!(p.get("location"), None);
assert_eq!(p.get("description"), None);
assert_eq!(p["url"], "https://riders.example");
assert_eq!(p["avatar"]["ref"], avatar["ref"]);
assert_eq!(p["joinPolicy"], "invite");
// And `null` clears an image.
call(
&h,
&alice,
"updateProfile",
json!({"group": did, "displayName": "Riders", "avatar": null}),
)
.await;
assert_eq!(profile(&h, &did).get("avatar"), None);
}
#[tokio::test]
async fn refuses_a_profile_it_should_not_keep() {
let (h, did, [alice, bob, carol]) = group().await;
for (who, body, refused) in [
(
&bob,
json!({"group": did, "displayName": "Mine"}),
(403, "Forbidden"),
),
(
&carol,
json!({"group": did, "displayName": "Mine"}),
(403, "Forbidden"),
),
(
&alice,
json!({"displayName": "Riders"}),
(400, "InvalidRequest"),
),
(
&alice,
json!({"group": "did:plc:nobody", "displayName": "Riders"}),
(400, "GroupNotFound"),
),
(
&alice,
json!({"group": did, "displayName": " "}),
(400, "InvalidRequest"),
),
(
&alice,
json!({"group": did, "displayName": "Riders", "joinPolicy": "sometimes"}),
(400, "InvalidRequest"),
),
(
&alice,
json!({"group": did, "displayName": "Riders", "location": {"$type": "xyz.place"}}),
(400, "InvalidRequest"),
),
(
&alice,
json!({"group": did, "displayName": "Riders", "avatar": {"ref": "x"}}),
(400, "InvalidRequest"),
),
// An image that is not the group's.
(
&alice,
json!({"group": did, "displayName": "Riders", "avatar": {"$type": "blob", "ref": {"$link": "bafkreie5737gdxlw5i64vzichcalba3z2v5n6icifvx5xytvske7mr3hpm"}, "mimeType": "image/png", "size": 4}}),
(400, "InvalidRequest"),
),
] {
let said = call(&h, who, "updateProfile", body.clone()).await;
assert_eq!(
(said.0, said.1["error"].as_str().unwrap()),
refused,
"{body}"
);
}
let lxm = format!("{NS}.updateProfile");
let said = post(&h, &lxm, &json!({"group": did, "displayName": "X"}), &[]).await;
assert_eq!(said.0, 401);
for (who, bytes, refused) in [
(&bob, b"face".to_vec(), (403, "Forbidden")),
(&alice, vec![], (400, "InvalidRequest")),
(&alice, vec![0; 1_000_001], (400, "InvalidRequest")),
] {
let said = upload(&h, who, &did, bytes, "image/png").await;
assert_eq!((said.0, said.1["error"].as_str().unwrap()), refused);
}
let lxm = format!("{NS}.uploadImage");
let said = read(&h, &lxm, "", &[auth(&h, &alice, &lxm)]).await;
assert_eq!(said.status, 405);
}
#[tokio::test]
async fn an_admin_keeps_the_rules() {
let (h, did, [alice, bob, _]) = group().await;
let rule = |key: &str| {
h.host
.group_record(&did, &meta_space(&did), &format!("{NS}.rule"), key)
.unwrap()
};
let (status, first) = call(
&h,
&alice,
"putRule",
json!({"group": did, "title": "Be kind", "text": " Always. "}),
)
.await;
assert_eq!(status, 200, "{first}");
let first_key = first["uri"]
.as_str()
.unwrap()
.rsplit('/')
.next()
.unwrap()
.to_string();
let (_, second) = call(
&h,
&alice,
"putRule",
json!({"group": did, "title": "No spam"}),
)
.await;
let second_key = second["uri"]
.as_str()
.unwrap()
.rsplit('/')
.next()
.unwrap()
.to_string();
// A new rule goes last.
assert_eq!(rule(&first_key).unwrap()["order"], 0);
assert_eq!(rule(&first_key).unwrap()["text"], "Always.");
assert_eq!(rule(&second_key).unwrap()["order"], 1);
// Changed in place, it keeps its key, its place and when it was made.
let made = rule(&first_key).unwrap()["createdAt"].clone();
let (_, again) = call(
&h,
&alice,
"putRule",
json!({"group": did, "rkey": first_key, "title": "Be very kind"}),
)
.await;
assert_eq!(again["uri"], first["uri"]);
let changed = rule(&first_key).unwrap();
assert_eq!(
(changed["title"].clone(), changed["order"].clone()),
(json!("Be very kind"), json!(0))
);
assert_eq!(changed["createdAt"], made);
// Or moved.
call(
&h,
&alice,
"putRule",
json!({"group": did, "rkey": first_key, "title": "Be very kind", "order": 5}),
)
.await;
assert_eq!(rule(&first_key).unwrap()["order"], 5);
// Or put where it is named.
call(
&h,
&alice,
"putRule",
json!({"group": did, "rkey": "chosen", "title": "Chosen"}),
)
.await;
assert_eq!(rule("chosen").unwrap()["order"], 6);
let (status, _) = call(
&h,
&alice,
"deleteRule",
json!({"group": did, "rkey": second_key}),
)
.await;
assert_eq!(status, 200);
assert_eq!(rule(&second_key), None);
// Taking away one that is not there is no matter.
let (status, _) = call(
&h,
&alice,
"deleteRule",
json!({"group": did, "rkey": second_key}),
)
.await;
assert_eq!(status, 200);
for (method, body, refused) in [
(
"putRule",
json!({"group": did, "title": "Mine"}),
(403, "Forbidden"),
),
(
"deleteRule",
json!({"group": did, "rkey": "chosen"}),
(403, "Forbidden"),
),
] {
let said = call(&h, &bob, method, body).await;
assert_eq!((said.0, said.1["error"].as_str().unwrap()), refused);
}
for (method, body) in [
("putRule", json!({"group": did, "title": " "})),
(
"putRule",
json!({"group": did, "title": "Odd", "order": -1}),
),
("putRule", json!({"title": "Odd"})),
("deleteRule", json!({"group": did})),
("deleteRule", json!({"rkey": "x"})),
] {
let said = call(&h, &alice, method, body.clone()).await;
assert_eq!(
(said.0, said.1["error"].as_str().unwrap()),
(400, "InvalidRequest"),
"{body}"
);
}
}
crates/group-host/tests/groups.rs+2−69
@@ -4,83 +4,16 @@
mod common;
use atproto::service_auth::{self, Claims};
use atproto::{Curve, Keypair};
use common::groups::*;
use common::spaces::*;
use common::{Running, start};
use common::start;
use group_host::authority::Access;
use group_host::group::{members_space, meta_space};
use group_host::rbac::ACTIONS;
use group_host::repo::Write;
use serde_json::{Value as Json, json};
const NS: &str = "fyi.opensocial";
/// Service auth from `who` for this host and `lxm`.
fn auth(h: &Running, who: &Authority, lxm: &str) -> (&'static str, String) {
auth_for(who, &h.host.config.service_did, lxm)
}
fn auth_for(who: &Authority, aud: &str, lxm: &str) -> (&'static str, String) {
let claims = Claims {
iss: who.did.clone(),
aud: aud.into(),
exp: now() + 60,
iat: Some(now()),
lxm: Some(lxm.into()),
jti: None,
};
(
"authorization",
format!("Bearer {}", service_auth::sign(&who.key, &claims)),
)
}
async fn post(h: &Running, nsid: &str, body: &Json, headers: &[(&str, String)]) -> (u16, Json) {
let mut req = h.http.post(format!("{}/xrpc/{nsid}", h.url)).json(body);
for (k, v) in headers {
req = req.header(*k, v);
}
let res = req.send().await.unwrap();
(
res.status().as_u16(),
res.json().await.unwrap_or(Json::Null),
)
}
async fn get(h: &Running, nsid: &str, query: &str, headers: &[(&str, String)]) -> (u16, Json) {
let got = read(h, nsid, query, headers).await;
(
got.status,
serde_json::from_slice(&got.body).unwrap_or(Json::Null),
)
}
/// A group started by `founder` with `body`: its DID.
async fn start_group(h: &Running, founder: &Authority, body: Json) -> String {
let lxm = format!("{NS}.createGroup");
let (status, made) = post(h, &lxm, &body, &[auth(h, founder, &lxm)]).await;
assert_eq!(status, 200, "{made}");
made["did"].as_str().unwrap().to_string()
}
/// Three people elsewhere.
async fn people(h: &Running) -> [Authority; 3] {
[
authority(h, false, true).await,
authority(h, false, true).await,
authority(h, false, true).await,
]
}
async fn view(h: &Running, group: &str, who: Option<&Authority>) -> Json {
let lxm = format!("{NS}.getGroup");
let headers: Vec<_> = who.map(|w| auth(h, w, &lxm)).into_iter().collect();
let (status, view) = get(h, &lxm, &format!("group={group}"), &headers).await;
assert_eq!(status, 200, "{view}");
view
}
#[tokio::test]
async fn starts_a_group_with_its_spaces() {
let h = start(&[], false).await;
docs/design/groups.md+17−0
@@ -61,6 +61,23 @@ group for someone or lets them read it themselves.
- `fyi.opensocial.listGroups` is every group here, unauthenticated: by
handle, and for one whose meta anyone may read, its profile and rules.
## Changing its face
Its profile, images and rules are records in meta written by the group,
so the host writes them for a caller holding `group.configure`:
- `updateProfile` replaces the profile. Where it meets, whether online,
its topics and languages are as given, none when left out (topics
trimmed, each once, ten at most, 64 characters each; languages BCP 47
tags, five at most). Its site and images are kept when left out, and
`null` clears an image. Its first `createdAt` is kept.
- `uploadImage` keeps an image (1 MB at most) as the group's blob, for
the profile to reference: a blob in anyone else's repo would not
resolve for it.
- `putRule` makes or changes a rule. A rule keeps its key when changed,
so a label citing it still does; a new one goes last unless it says
where. `deleteRule` takes one away; a label citing it keeps the URI.
## From the prototype
As `bootstrap.ts` and `methods/groups.ts`, with these changes:
docs/design/README.md+2−2
@@ -80,8 +80,8 @@ says otherwise.
Then the
groups: `createGroup`, `getGroup`, `listGroups`, with their meta and
members spaces, access records and roles (`group.rs`, `group_api.rs`,
`rbac.rs`; done, see [groups](groups.md)), then
handles, profile, rules, activating and deleting; spaces made and
`rbac.rs`; done, see [groups](groups.md)), their profile, images and
rules (`group_config.rs`; done), then handles, activating and deleting; spaces made and
configured by members, `checkUserAccess`, and the space index:
`group.ts`, `bootstrap.ts`, `methods/{groups,handle,profile,rules,lifecycle,spaces,spaceRecords}.ts`,
`spaceIndex.ts`, `methods/checkUserAccess.ts`.