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

A group's profile and rules are written as the group

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:proposal/writes-meta
crates/group-host/src/assistants.rs+97−2
@@ -21,18 +21,23 @@
use crate::Host;
use crate::api::{Params, param};
use crate::group_api::{group_of, signed_in};
use crate::oauth_resource::Acting;
use crate::oauth_store::Grant;
use crate::rbac::NS;
use crate::repo::{Write, record_cid};
use crate::scopes::Permissions;
use crate::store::Store;
use crate::time::{iso, now_millis};
use crate::xrpc::XrpcError;
use anyhow::Result;
use atproto::jose;
use atproto::space::SpaceRef;
use axum::body::Body;
use axum::extract::{Query, State};
use axum::http::{HeaderMap, Request, StatusCode, header};
use axum::response::{IntoResponse, Redirect, Response};
use axum::{Form, Json};
use group_host_mcp::Tool;
use group_host_mcp::{Kind, Tool};
use rusqlite::{OptionalExtension, Row, params};
use serde_json::{Value, json};
use std::collections::HashMap;
@@ -690,7 +695,82 @@ fn query_of(args: &Value) -> Vec<(String, String)> {
out
}
/// A record tool's write: the record's kind, the type of the group's
/// space it is kept in, the one key it is kept at if one, and whether it
/// goes.
struct RecordAsked<'a> {
collection: &'a str,
space: &'a str,
literal: Option<&'a str>,
delete: bool,
}
impl Host {
/// Writes the record `asked` names, its key and value `args`, as the
/// group, in `who`'s group: what a group session `who`'s member
/// approved for that space would write, its scope what their roles
/// there grant now, kept to the same rules.
async fn record_as(
&self,
who: &Connected,
asked: &RecordAsked<'_>,
mut args: Value,
) -> Result<Value, XrpcError> {
let group = &who.group;
let uri = format!("at://{group}/space/{}/self", asked.space);
let space = SpaceRef::parse(&uri).expect("a group's own space is a space");
let (_, scope) = self.group_scope(group, &who.member, &uri, &space)?;
let now = now_millis();
let grant = Grant {
id: who.id.clone(),
group: group.clone(),
member: who.member.clone(),
client_id: who.client_id.clone(),
client_auth: json!({"method": "none"}),
scope: scope.clone(),
dpop_jkt: String::new(),
access_expires: now,
expires_at: now,
created_at: now,
source: "mcp".into(),
used_at: None,
};
let acting = Acting {
permissions: Permissions::new(&scope, group),
grant,
};
let fields = args
.as_object_mut()
.expect("a tool's arguments are an object");
let named = fields.remove("rkey");
let rkey = match (asked.literal, named.as_ref().and_then(Value::as_str)) {
(Some(key), _) => key.to_string(),
(None, Some(key)) => key.to_string(),
(None, None) => self.clock.next(),
};
let collection = asked.collection.to_string();
let write = match asked.delete {
true => Write::Delete { collection, rkey },
false => {
fields.insert("$type".into(), json!(collection));
Write::Update {
collection,
rkey,
value: args.clone(),
}
}
};
let writes = std::slice::from_ref(&write);
let written = self.write_as(&acting, &uri, &space, writes, true);
written.await?;
let (collection, rkey) = write.path();
let mut out = json!({"uri": format!("{uri}/{group}/{collection}/{rkey}")});
if !asked.delete {
out["cid"] = json!(record_cid(collection, &args)?.to_string());
}
Ok(out)
}
/// Calls `tool` with `args` as `who`, in their group: as the console
/// does, the host asking itself as them. A tool that writes an invite
/// makes the write their own session for the group would.
@@ -700,6 +780,21 @@ impl Host {
tool: Tool,
mut args: Value,
) -> Result<Value, String> {
if let Kind::Record {
space,
literal,
delete,
} = &tool.kind
{
let asked = RecordAsked {
collection: &tool.nsid,
space,
literal: literal.as_deref(),
delete: *delete,
};
let written = self.record_as(who, &asked, args).await;
return written.map_err(|e| format!("{}: {}", e.error, e.message));
}
if tool.nsid.starts_with("com.atproto.space.") {
let made = self.invite_as(who, &tool.name, &args).await;
return made.map_err(|e| format!("{}: {}", e.error, e.message));
@@ -708,7 +803,7 @@ impl Host {
let cookie = self.session_cookie(&who.member, now_millis());
let cookie = format!("{}={cookie}", crate::console_login::COOKIE);
let path = format!("/xrpc/{}", tool.nsid);
let request = match tool.procedure {
let request = match tool.kind == Kind::Procedure {
true => Request::post(path)
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(args.to_string())),
crates/group-host/src/group_config.rs+141−240
@@ -1,28 +1,27 @@
//! 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`.
//! A group's face: its profile, its pictures and its rules, each a record
//! in its meta space that the group writes, and its declaration, in its
//! public repo, which lists it while anyone may read that space. An app
//! writes them as the group, with a token a member approved
//! (`token_writes`); here is what each must be for the host to keep it,
//! beyond what its lexicon says, and who may configure the group.
use crate::Host;
use crate::api::{Params, invalid, param};
use crate::api::invalid;
use crate::blobs::PROFILE_IMAGES;
use crate::group::{join_policy, members_space, meta_space};
use crate::group_api::{group_of, signed_in};
use crate::rbac::{NS, actions_for, grants, roles_of};
use crate::rbac::{Access, NS, actions_for, grants, roles_of};
use crate::repo::Write;
use crate::time::{iso, now_millis};
use crate::xrpc::XrpcError;
use atproto::Cid;
use atproto::syntax::is_tid;
use axum::Json;
use axum::body::Bytes;
use axum::extract::{Query, State};
use axum::http::{HeaderMap, StatusCode, header};
use axum::http::StatusCode;
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 = 2_000_000;
/// The most bytes a profile's picture may be, as its lexicon has it.
pub const IMAGE_AT_MOST: i64 = 2_000_000;
/// Where a group meets: the places `community.lexicon.location` has.
const PLACES: [&str; 4] = [
@@ -40,22 +39,6 @@ pub(crate) fn forbidden() -> XrpcError {
)
}
/// 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)?;
if !host.may_configure(group, &me)? {
return Err(forbidden());
}
Ok(group.to_string())
}
impl Host {
/// Whether `did` holds `group.configure` in `group`, by its records now.
pub fn may_configure(&self, group: &str, did: &str) -> Result<bool, XrpcError> {
@@ -90,24 +73,18 @@ impl Host {
}
}
/// 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 {
put_in(host, group, &meta_space(group), collection, rkey, value).await
}
/// Puts the group's record at `collection/rkey` in `space`, made or
/// replaced: its URI and CID.
pub(crate) async fn put_in(
host: &Host,
group: &str,
meta: &str,
space: &str,
collection: &str,
rkey: &str,
value: Value,
) -> Answer {
let current = host
.group_record(group, meta, collection, rkey)
.group_record(group, space, collection, rkey)
.map_err(XrpcError::internal)?;
let (collection, rkey) = (collection.to_string(), rkey.to_string());
let write = match current {
@@ -122,234 +99,158 @@ pub(crate) async fn put_in(
value,
},
};
host.space_write(group, meta, &[write]).await?;
host.space_write(group, space, &[write]).await?;
let kept = host
.store
.space_record(group, meta, &collection, &rkey)
.space_record(group, space, &collection, &rkey)
.map_err(XrpcError::internal)?
.expect("the record just written");
let uri = format!("{meta}/{group}/{collection}/{rkey}");
let uri = format!("{space}/{group}/{collection}/{rkey}");
Ok(Json(json!({"uri": uri, "cid": kept.cid.to_string()})))
}
/// Words a profile lists, as `[{topic}]`: trimmed, cut to `longest`
/// characters, each once, at most `max`.
fn words(asked: &Value, field: &str, longest: usize, max: usize) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for item in asked.as_array().into_iter().flatten() {
/// Whether `text` says something: more than spaces.
fn said(text: &Value) -> bool {
text.as_str().is_some_and(|t| !t.trim().is_empty())
}
/// Refuses the words a profile lists at `key`, as `[{field}]`, if one is
/// blank or listed twice.
fn words(profile: &Value, key: &str, field: &str) -> Result<(), XrpcError> {
let mut seen: Vec<&str> = Vec::new();
for item in profile[key].as_array().into_iter().flatten() {
let word = item[field].as_str().unwrap_or_default().trim();
let word: String = word.chars().take(longest).collect();
if !word.is_empty() && !out.contains(&word) {
out.push(word);
if word.is_empty() || seen.contains(&word) {
let once = format!("{key} lists each {field} once, and none blank");
return Err(invalid(once));
}
seen.push(word);
}
out.truncate(max);
out
Ok(())
}
/// 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}))
}
/// The image `asked` names, as the group's profile holds it: one of its
/// own uploads, of a kind of image a page is given, its type and size as
/// the host kept them rather than as the caller says.
fn image(host: &Host, group: &str, key: &str, asked: &Value) -> Result<Value, XrpcError> {
let not_one = invalid(format!("{key} is an image uploadImage answered"));
let link = asked["ref"]["$link"].as_str().unwrap_or_default();
let Ok(cid) = Cid::parse(link) else {
return Err(not_one);
/// Refuses a place the profile says it meets that is none of [`PLACES`].
fn place(profile: &Value) -> Result<(), XrpcError> {
let Some(place) = profile.get("location") else {
return Ok(());
};
let kept = host.store.blob(group, &cid).map_err(XrpcError::internal)?;
let kept = kept.filter(|b| PROFILE_IMAGES.contains(&b.mime_type.as_str()));
let kept = kept.ok_or(not_one)?;
let (mime, size) = (kept.mime_type, kept.size);
Ok(json!({"$type": "blob", "ref": {"$link": link}, "mimeType": mime, "size": size}))
let kind = place["$type"].as_str().unwrap_or_default();
if !PLACES.contains(&kind) {
return Err(invalid(format!("location is one of {}", PLACES.join(", "))));
}
Ok(())
}
/// 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 `removeAvatar` or `removeBanner` 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().expect("its lexicon requires it");
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(),
/// Refuses a site that is not on the web.
fn site(profile: &Value) -> Result<(), XrpcError> {
let Some(url) = profile.get("url") else {
return Ok(());
};
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 replaced, as the description is: left out, it goes.
if let Some(url) = text("url") {
profile["url"] = json!(url);
}
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", 64, 10)
.into_iter()
.map(|t| json!({ "topic": t }))
.collect();
if !topics.is_empty() {
profile["topics"] = json!(topics);
let url = url.as_str().unwrap_or_default();
if !url.starts_with("https://") && !url.starts_with("http://") {
return Err(invalid("url is an http or https address"));
}
let languages: Vec<Value> = words(&body["languages"], "language", usize::MAX, 5)
.into_iter()
.map(|l| json!({"language": l}))
.collect();
if !languages.is_empty() {
profile["languages"] = json!(languages);
}
for (key, remove) in [("avatar", "removeAvatar"), ("banner", "removeBanner")] {
let image = match body.get(key) {
_ if body[remove] == true => None,
Some(asked) => Some(image(&host, &group, key, asked)?),
None => current.get(key).and_then(blob),
Ok(())
}
impl Host {
/// Refuses a picture a profile names at `key`, unless it is one of the
/// group's own uploads, of a kind of image a page is given and no
/// larger than a profile takes, with the type and size the host kept.
fn picture(&self, group: &str, profile: &Value, key: &str) -> Result<(), XrpcError> {
let Some(asked) = profile.get(key) else {
return Ok(());
};
let not_one = || {
invalid(format!(
"{key} is a PNG, JPEG or WebP image of at most {IMAGE_AT_MOST} bytes, as the group's uploadBlob answered it"
))
};
if let Some(image) = image {
profile[key] = image;
let link = asked["ref"]["$link"].as_str().unwrap_or_default();
let cid = Cid::parse(link).map_err(|_| not_one())?;
let kept = self.store.blob(group, &cid).map_err(XrpcError::internal)?;
let kept = kept.ok_or_else(not_one)?;
let image = PROFILE_IMAGES.contains(&kept.mime_type.as_str());
let as_kept = asked["mimeType"] == kept.mime_type && asked["size"] == kept.size;
if !image || kept.size > IMAGE_AT_MOST || !as_kept {
return Err(not_one());
}
Ok(())
}
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();
if !PROFILE_IMAGES.contains(&mime) {
return Err(invalid(format!(
"an image is one of {}",
PROFILE_IMAGES.join(", ")
)));
/// Refuses a profile the group should not keep: one with no name, a
/// join policy the host does not know, a place that is none, a site
/// not on the web, words blank or listed twice, or a picture that is
/// not one of its own.
fn profile(&self, group: &str, profile: &Value) -> Result<(), XrpcError> {
if !said(&profile["displayName"]) {
return Err(invalid("displayName is required"));
}
if let Some(policy) = profile["joinPolicy"].as_str() {
join_policy(Some(policy))?;
}
place(profile)?;
site(profile)?;
words(profile, "topics", "topic")?;
words(profile, "languages", "language")?;
self.picture(group, profile, "avatar")?;
self.picture(group, profile, "banner")
}
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().expect("its lexicon requires it");
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 text = body["text"].as_str().unwrap_or_default().trim();
let collection = format!("{NS}.rule");
let rules = host
.group_records(&group, &meta_space(&group), &collection)
.map_err(XrpcError::internal)?;
// A key names a rule there is; a new one is keyed by the clock, as
// rules are.
let (rkey, current) = match body["rkey"].as_str() {
Some(k) => {
let found = rules.iter().find(|(key, _)| key == k);
let none = invalid(format!("no rule {k}: a new one is given no rkey"));
let found = found.ok_or(none)?;
(k.to_string(), Some(&found.1))
/// Refuses a write of the group's profile or one of its rules, in its
/// meta space, that the host should not keep: a profile as `profile`
/// has it, kept at `self` and never deleted; a rule with a title, at a
/// TID, so that a label citing it keeps its URI however it changes.
pub(crate) fn face(&self, group: &str, write: &Write) -> Result<(), XrpcError> {
let (collection, rkey) = write.path();
let value = match write {
Write::Create { value, .. } | Write::Update { value, .. } => Some(value),
Write::Delete { .. } => None,
};
if collection == format!("{NS}.profile") {
if rkey != "self" {
return Err(invalid(format!("{collection} is kept at self")));
}
let kept = || invalid("the group keeps its profile");
return self.profile(group, value.ok_or_else(kept)?);
}
None => (host.clock.next(), None),
};
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));
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": text,
"order": order,
"createdAt": created,
});
put(&host, &group, &collection, &rkey, rule).await
}
if let Some(rule) = value.filter(|_| collection == format!("{NS}.rule")) {
if !is_tid(rkey) {
return Err(invalid("a rule is kept at a TID"));
}
if !said(&rule["title"]) {
return Err(invalid("title is required"));
}
}
Ok(())
}
/// 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().expect("its lexicon requires it");
let group = configurer(&host, &headers, group, "deleteRule").await?;
let rkey = body["rkey"].as_str().expect("its lexicon requires it");
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(),
/// Refuses a write of the group's declaration, in its public repo,
/// that does not follow who may read its meta space: it is kept at
/// `self`, names that space, and is made only while anyone may read
/// it. Taking it away is always the group's to do.
pub(crate) fn declaration(&self, group: &str, write: &Write) -> Result<(), XrpcError> {
let (collection, rkey) = write.path();
if collection != format!("{NS}.declaration") {
return Ok(());
}
if rkey != "self" {
return Err(invalid(format!("{collection} is kept at self")));
}
let (Write::Create { value, .. } | Write::Update { value, .. }) = write else {
return Ok(());
};
host.space_write(&group, &meta, &[delete]).await?;
let meta = meta_space(group);
if value["meta"] != meta.as_str() {
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 hidden = "a group is declared only while anyone may read its meta space";
return Err(invalid(hidden));
}
Ok(())
}
Ok(Json(json!({})))
}
crates/group-host/src/group_tokens.rs+26−10
@@ -84,17 +84,8 @@ impl Host {
/// `member`: its scope, and the kinds of record it writes there and in
/// the group's repo.
fn space_auth(&self, group: &str, member: &str, space: &SpaceRef) -> Authed {
let uri = space.to_string();
let roles = self.roles(group, member).map_err(XrpcError::internal)?;
let access = self.group_record(group, &uri, &format!("{NS}.access"), "self");
let access = access.map_err(XrpcError::internal)?.unwrap_or_default();
let everything = self.may_issue(group, member)?;
let writes = writes_in(&Access::of(&access, &uri), &roles, member, everything);
if writes.is_empty() {
return Err(forbidden("no role of yours may act as the group in this space").into());
}
let (writes, scope) = self.group_scope(group, member, &space.to_string(), space)?;
let collections: Vec<String> = writes.keys().cloned().collect();
let scope = scopes_for(space, &writes).join(" ");
Ok((scope, collections.clone(), collections))
}
@@ -140,6 +131,31 @@ fn scopes_for(space: &SpaceRef, writes: &BTreeMap<String, BTreeSet<String>>) ->
out
}
impl Host {
/// What `member`'s roles in `group` may write as it in `space`, at
/// `uri`: each kind of record with its writes, and the scope of a
/// token for them.
pub(crate) fn group_scope(
&self,
group: &str,
member: &str,
uri: &str,
space: &SpaceRef,
) -> Result<(BTreeMap<String, BTreeSet<String>>, String), XrpcError> {
let roles = self.roles(group, member).map_err(XrpcError::internal)?;
let access = self.group_record(group, uri, &format!("{NS}.access"), "self");
let access = access.map_err(XrpcError::internal)?.unwrap_or_default();
let everything = self.may_issue(group, member)?;
let writes = writes_in(&Access::of(&access, uri), &roles, member, everything);
if writes.is_empty() {
let none = "no role of yours may act as the group in this space";
return Err(forbidden(none));
}
let scope = scopes_for(space, &writes).join(" ");
Ok((writes, scope))
}
}
/// A token to act as the group in one of its spaces, for the caller's
/// DPoP key, as far as their roles there let them write.
pub async fn get_group_auth(
crates/group-host/src/lexicons.rs+0−4
@@ -54,7 +54,6 @@ pub const FILES: &[&str] = &[
lexicon!("fyi/opensocial/defs"),
lexicon!("fyi/opensocial/deleteGroup"),
lexicon!("fyi/opensocial/deleteRole"),
lexicon!("fyi/opensocial/deleteRule"),
lexicon!("fyi/opensocial/deleteSpace"),
lexicon!("fyi/opensocial/denyJoinRequest"),
lexicon!("fyi/opensocial/ejectMember"),
@@ -103,7 +102,6 @@ pub const FILES: &[&str] = &[
lexicon!("fyi/opensocial/profile"),
lexicon!("fyi/opensocial/provisionGroup"),
lexicon!("fyi/opensocial/putRole"),
lexicon!("fyi/opensocial/putRule"),
lexicon!("fyi/opensocial/removeRecoveryKey"),
lexicon!("fyi/opensocial/requestJoin"),
lexicon!("fyi/opensocial/resolveSubject"),
@@ -115,9 +113,7 @@ pub const FILES: &[&str] = &[
lexicon!("fyi/opensocial/space"),
lexicon!("fyi/opensocial/startAccountMove"),
lexicon!("fyi/opensocial/updateGroupHandle"),
lexicon!("fyi/opensocial/updateProfile"),
lexicon!("fyi/opensocial/updateSpace"),
lexicon!("fyi/opensocial/uploadImage"),
lexicon!("upstream/com/atproto/admin/defs"),
lexicon!("upstream/com/atproto/identity/resolveHandle"),
lexicon!("upstream/com/atproto/label/defs"),
crates/group-host/src/lib.rs+0−13
@@ -212,19 +212,6 @@ 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(
"/xrpc/fyi.opensocial.deactivateGroup",
post(group_lifecycle::deactivate_group),
crates/group-host/src/token_writes.rs+44−34
@@ -4,19 +4,20 @@
//! reaches, and blobs for them.
//!
//! In the group's own meta and members spaces, a token writes only what
//! the configure set is for, and only as the host's methods would: the
//! profile (with a name and a join policy it knows) and the labeler, kept
//! at `self` and never deleted; rules; and roles, one taken away only once
//! nothing grants it. Who holds which role, what each may do, and who may
//! read a space change only through the host's methods, which check that
//! nobody gives themselves more than they hold.
//! the configure set is for, and only as the host would keep it: the
//! profile, its pictures and the rules, as `group_config` has them; the
//! labeler, kept at `self` and never deleted; and roles, one taken away
//! only once nothing grants it. The group's declaration, in its public
//! repo, follows who may read its meta space. Who holds which role, what
//! each may do, and who may read a space change only through the host's
//! methods, which check that nobody gives themselves more than they hold.
//!
//! In someone's inbox, a token writes the group's invite to them, as
//! `group_invites` has it.
use crate::Host;
use crate::api::invalid;
use crate::group::{join_policy, members_space, meta_space};
use crate::group::{members_space, meta_space};
use crate::group_invites::is_inbox;
use crate::lexicons::{check_record, validation};
use crate::oauth_resource::{Acting, Refusal};
@@ -104,7 +105,7 @@ impl Host {
"{collection} changes through the host's methods, not as a record"
)));
}
if [c("profile"), c("labeler")].iter().any(|x| x == collection) {
if collection == c("labeler") {
if rkey != "self" {
return Err(invalid(format!("{collection} is kept at self")));
}
@@ -112,16 +113,8 @@ impl Host {
return Err(invalid(format!("the group keeps its {collection}")));
}
}
if let Write::Create { value, .. } | Write::Update { value, .. } = write
&& collection == c("profile")
{
let named = value["displayName"]
.as_str()
.is_some_and(|n| !n.trim().is_empty());
if !named {
return Err(invalid("displayName is required"));
}
join_policy(value["joinPolicy"].as_str())?;
if space == meta_space(group) {
self.face(group, write)?;
}
if matches!(write, Write::Delete { .. }) && collection == c("role") {
let permissions = self.group_record(group, space, &c("permissions"), "self");
@@ -285,6 +278,7 @@ impl Host {
if !granted && !may_write(&publishable, collection, action(w)) {
return Err(no_longer(collection));
}
self.declaration(&acting.grant.group, w)?;
}
checked(writes)
}
@@ -506,8 +500,35 @@ fn space_uri(space: &str, group: &str, collection: &str, rkey: &str) -> String {
format!("{space}/{group}/{collection}/{rkey}")
}
/// Makes `writes` in the space a body names, as `put` has them: its
/// commit, if any.
impl Host {
/// Makes `writes` in `space`, at `uri`, as `acting`, as `put` has
/// them, each as far as its scope and its member's roles reach and as
/// the host would keep it: whether a commit was made.
pub(crate) async fn write_as(
&self,
acting: &Acting,
uri: &str,
space: &SpaceRef,
writes: &[Write],
put: bool,
) -> Result<bool, XrpcError> {
let allow = |w: &[Write]| self.may_space(acting, uri, space, w);
let asked = Asked {
put,
allow: Some(&allow),
..Asked::default()
};
let group = &acting.grant.group;
let made = self.space_write_asked(group, uri, writes, &asked).await?;
if let Some((_, made)) = &made {
self.wrote(acting, Some(uri), made)?;
}
Ok(made.is_some())
}
}
/// Makes `writes` in the space a body names, as `put` has them: the
/// space, the group, the writes, and whether a commit was made.
async fn space_writes(
host: &Host,
nsid: &str,
@@ -518,26 +539,15 @@ async fn space_writes(
) -> Result<(String, String, Vec<Write>, bool), Refusal> {
let acting = host.writer(headers, nsid, body)?;
let (uri, space) = space_of(body)?;
let group = acting.grant.group.clone();
let writes = writes(host)?;
let group = acting.grant.group.clone();
// Someone's inbox, where the group writes invites, is theirs.
if is_inbox(&space) {
let made = host.write_invites(&acting, &space, writes).await?;
return Ok((uri, group, made, true));
}
let allow = |w: &[Write]| host.may_space(&acting, &uri, &space, w);
let asked = Asked {
put,
allow: Some(&allow),
..Asked::default()
};
let made = host
.space_write_asked(&group, &uri, &writes, &asked)
.await?;
if let Some((_, made)) = &made {
host.wrote(&acting, Some(&uri), made)?;
}
Ok((uri, group, writes, made.is_some()))
let made = host.write_as(&acting, &uri, &space, &writes, put).await?;
Ok((uri, group, writes, made))
}
/// The one write a put or delete body asks for.
crates/group-host/tests/common/oauth.rs+79−0
@@ -296,6 +296,85 @@ pub async fn group_token(
app.said(send()).await
}
impl App {
/// A group token for `group`'s `space`, as `who`: the console's way
/// to write as the group.
pub async fn token_for(
&self,
h: &Running,
who: &Authority,
group: &str,
space: &str,
) -> String {
let said = group_token(h, self, who, group, space).await;
assert_eq!(said.status, 200, "{}", said.body);
said.body["accessJwt"].as_str().unwrap().to_string()
}
/// Uploads `bytes`, of the type `mime`, with `token`.
pub async fn upload(&self, h: &Running, token: &str, bytes: Vec<u8>, mime: &str) -> Said {
let nsid = "com.atproto.repo.uploadBlob";
let send = || {
h.http
.post(format!("{}/xrpc/{nsid}", h.url))
.header("authorization", format!("DPoP {token}"))
.header("dpop", self.resource_proof(h, "POST", nsid, token))
.header("content-type", mime)
.body(bytes.clone())
};
let said = self.said(send()).await;
let stale = said
.headers
.get("www-authenticate")
.is_some_and(|v| v.to_str().unwrap().contains("use_dpop_nonce"));
if !stale {
return said;
}
self.said(send()).await
}
/// Puts `record` as the group in `space`, at `collection/rkey`, with
/// `token`.
pub async fn put(
&self,
h: &Running,
token: &str,
space: &str,
collection: &str,
rkey: &str,
record: Json,
) -> Said {
let group = space.split('/').nth(2).unwrap();
let body = json!({"repo": group, "space": space, "collection": collection, "rkey": rkey, "record": record});
self.call(h, "com.atproto.space.putRecord", token, Some(&body))
.await
}
}
/// Gives `group` a PNG of `bytes` for its avatar, as `who` does from the
/// console, its profile named `name`: the blob.
pub async fn give_avatar(
h: &Running,
who: &Authority,
group: &str,
name: &str,
bytes: &[u8],
) -> Json {
let app = App::new("console");
let meta = format!("at://{group}/space/{NS}.meta/self");
let token = app.token_for(h, who, group, &meta).await;
let said = app.upload(h, &token, bytes.to_vec(), "image/png").await;
assert_eq!(said.status, 200, "{}", said.body);
let blob = said.body["blob"].clone();
let profile = json!({"$type": format!("{NS}.profile"), "displayName": name, "joinPolicy": "approval", "avatar": blob});
let collection = format!("{NS}.profile");
let said = app
.put(h, &token, &meta, &collection, "self", profile)
.await;
assert_eq!(said.status, 200, "{}", said.body);
blob
}
/// `nsid`, a write as `group` in the inbox `inbox`, made for `who` with a
/// group token for it, `body` given its repo and, unless it names one,
/// its space: what it answered, or why there was no token.
crates/group-host/tests/actors.rs+3−19
@@ -3,6 +3,7 @@
mod common;
use common::groups::*;
use common::oauth::give_avatar;
use common::spaces::*;
use common::{Running, start};
use group_host::group::members_space;
@@ -150,26 +151,9 @@ async fn shows_a_groups_picture() {
json!({"handle": RIDERS, "displayName": "Riders"}),
)
.await;
let lxm = format!("{NS}.uploadImage");
let (k, v) = auth(&h, &alice, &lxm);
let res = h
.http
.post(format!("{}/xrpc/{lxm}?group={riders}", h.url))
.header(k, v)
.header("content-type", "image/png")
.body(b"face".to_vec())
.send()
.await
.unwrap();
let image: Json = res.json().await.unwrap();
let lxm = format!("{NS}.updateProfile");
let body = json!({"group": riders, "displayName": "Riders", "avatar": image["blob"]});
assert_eq!(
post(&h, &lxm, &body, &[auth(&h, &alice, &lxm)]).await.0,
200
);
let avatar = give_avatar(&h, &alice, &riders, "Riders", b"face").await;
let (_, mine) = groups_of(&h, &alice, &format!("actor={}", alice.did)).await;
assert_eq!(mine["groups"][0]["avatar"], image["blob"]["ref"]["$link"]);
assert_eq!(mine["groups"][0]["avatar"], avatar["ref"]["$link"]);
}
#[tokio::test]
crates/group-host/tests/assistants.rs+85−0
@@ -332,6 +332,91 @@ async fn acts_as_the_member_in_the_group_they_chose() {
assert_eq!(got["structuredContent"]["group"]["did"], group.as_str());
}
#[tokio::test]
async fn writes_the_groups_profile_and_rules_as_the_group() {
let h = start(&[], false).await;
let [alice, ..] = people(&h).await;
let group = start_group(
&h,
&alice,
json!({"handle": RIDERS, "displayName": "Riders"}),
)
.await;
let (client, tokens) = connect(&h, &alice, &group).await;
let access = tokens["access_token"].as_str().unwrap();
let meta = group_host::group::meta_space(&group);
let kept = |collection: &str, rkey: &str| {
let c = format!("{NS}.{collection}");
h.host.group_record(&group, &meta, &c, rkey).unwrap()
};
// The profile, at its one key, replaced whole.
let profile = json!({"displayName": "Riders United", "joinPolicy": "open"});
let got = tool(&h, access, "putProfile", profile).await;
assert!(got.get("isError").is_none(), "{got}");
let uri = format!("{meta}/{group}/{NS}.profile/self");
assert_eq!(got["structuredContent"]["uri"], uri);
assert!(got["structuredContent"]["cid"].is_string());
let written = kept("profile", "self").unwrap();
assert_eq!(
written,
json!({"$type": format!("{NS}.profile"), "displayName": "Riders United", "joinPolicy": "open"})
);
// A new rule, keyed by the clock; changed at its key; taken away.
let got = tool(
&h,
access,
"putRule",
json!({"title": "Be kind", "text": ""}),
)
.await;
assert!(got.get("isError").is_none(), "{got}");
let made = got["structuredContent"]["uri"].as_str().unwrap();
let rkey = made.rsplit('/').next().unwrap().to_string();
assert_eq!(kept("rule", &rkey).unwrap()["title"], "Be kind");
let again = json!({"rkey": rkey, "title": "Be very kind", "text": "Always."});
let got = tool(&h, access, "putRule", again).await;
assert_eq!(got["structuredContent"]["uri"], made, "{got}");
assert_eq!(kept("rule", &rkey).unwrap()["title"], "Be very kind");
let got = tool(&h, access, "deleteRule", json!({"rkey": rkey})).await;
assert_eq!(got["structuredContent"], json!({"uri": made}), "{got}");
assert_eq!(kept("rule", &rkey), None);
// Held to what the host keeps, as any write as the group is.
let got = tool(
&h,
access,
"putProfile",
json!({"displayName": " ", "joinPolicy": "open"}),
)
.await;
assert_eq!(got["isError"], true, "{got}");
let text = got["content"][0]["text"].as_str().unwrap();
assert!(text.starts_with("InvalidRequest: "), "{text}");
let got = tool(
&h,
access,
"putRule",
json!({"rkey": "chosen", "title": "x", "text": ""}),
)
.await;
assert_eq!(got["isError"], true, "{got}");
// What it did is in the group's log, as the assistant's.
let lxm = format!("{NS}.listGroupTokens");
let (_, listed) = get(
&h,
&lxm,
&format!("group={group}"),
&[auth(&h, &alice, &lxm)],
)
.await;
let by = &listed["activity"][0];
assert_eq!(by["clientId"], client.as_str(), "{listed}");
assert_eq!(by["member"], alice.did.as_str());
}
#[tokio::test]
async fn does_only_what_the_members_roles_allow() {
let h = start(&[], false).await;
crates/group-host/tests/authorization.rs+2−21
@@ -186,32 +186,13 @@ async fn offers_only_the_group_the_app_named_even_to_one_without_a_role() {
async fn shows_the_groups_picture() {
let h = start(&[], false).await;
let (riders, _, [alice, ..]) = groups(&h).await;
let lxm = format!("{NS}.uploadImage");
let (k, v) = auth(&h, &alice, &lxm);
let res = h
.http
.post(format!("{}/xrpc/{lxm}?group={riders}", h.url))
.header(k, v)
.header("content-type", "image/png")
.body(b"face".to_vec())
.send()
.await
.unwrap();
let image: Json = res.json().await.unwrap();
let (status, put) = call(
&h,
&alice,
"updateProfile",
json!({"group": riders, "displayName": "Riders", "avatar": image["blob"]}),
)
.await;
assert_eq!(status, 200, "{put}");
let image = give_avatar(&h, &alice, &riders, "Riders", b"face").await;
let request_uri = App::loopback(SCOPE)
.push(&h, &[("login_hint", RIDERS)])
.await;
let (_, offered) = offer(&h, &alice, &request_uri).await;
let avatar = offered["groups"][0]["avatar"].as_str().unwrap();
let cid = image["blob"]["ref"]["$link"].as_str().unwrap();
let cid = image["ref"]["$link"].as_str().unwrap();
assert_eq!(param(avatar, "cid").unwrap(), cid);
// Where any file in the space is served, to whoever may read it.
let query = avatar
crates/group-host/tests/group_config.rs+283−357
640 lines changed: not loaded until asked for.
crates/group-host/tests/lexicons.rs+15−5
crates/group-host/tests/migration.rs+14−23
crates/group-host/tests/tokens.rs+27−1
crates/group-host-mcp/src/lib.rs+115−26
crates/group-host-mcp/tests/protocol.rs+60−8
crates/opensocial/src/lib.rs+7−2
crates/opensocial/tests/commands.rs+12−0
docs/design/groups.md+40−29
docs/design/signing-in.md+15−1
docs/reference/api.md+4−4
docs/reference/mcp.md+23−8
harness/lexicons.mjs+6−2
lexicons/fyi/opensocial/deleteRule.jsondeleted+0−38
lexicons/fyi/opensocial/putRule.jsondeleted+0−61
lexicons/fyi/opensocial/rule.json+2−2
lexicons/fyi/opensocial/updateProfile.jsondeleted+0−126
lexicons/fyi/opensocial/uploadImage.jsondeleted+0−36
web/src/lib/organisms/RulesEditor.svelte+1−1
web/src/lib/asGroup.ts+69−17
web/src/routes/g/[handle]/settings/+page.server.ts+59−25