chadtmiller.com/group-host
atmosphere group host
0
0
A group's page shows its members a page at a time, and how to join
crates/group-host/src/group_api.rs+70−16
| @@ -5,7 +5,7 @@ | ||
//! and the method: their own PDS signs it for them. | ||
| ||
use crate::Host; | ||
use crate::api::{Params, param}; | ||
use crate::api::{Params, page, param}; | ||
use crate::group::{Made, NewGroup, members_space, meta_space}; | ||
use crate::rbac::{Access, NS, actions_for, grants, listed, repo_collections_for, roles_of}; | ||
use crate::space_api::{service_caller, unauthorized}; | ||
| @@ -120,6 +120,7 @@ fn profile_view(profile: &Value) -> Value { | ||
"description", | ||
"joinPolicy", | ||
"url", | ||
"links", | ||
"location", | ||
"online", | ||
"topics", | ||
| @@ -194,8 +195,8 @@ fn signed_out(did: &str, handle: String) -> Value { | ||
| ||
/// One group in full, as the caller may see it: what its meta space | ||
/// holds for whoever may read it, the caller's own standing, and for a | ||
/// member, its members, roles and spaces. To no one signed in, only its | ||
/// DID and handle, whatever its access record says. | ||
/// member, how many are in it, its roles and spaces. To no one signed in, | ||
/// only its DID and handle, whatever its access record says. | ||
pub async fn get_group( | ||
State(host): State<Arc<Host>>, | ||
Query(p): Query<Params>, | ||
| @@ -252,25 +253,15 @@ pub async fn get_group( | ||
viewer["request"] = crate::group_join::request_view(&request); | ||
} | ||
view["viewer"] = viewer; | ||
let mut out = json!({ "group": view }); | ||
if !reads_members { | ||
return Ok(Json(out)); | ||
return Ok(Json(json!({ "group": view }))); | ||
} | ||
let records = |collection: &str| { | ||
host.group_records(group, &members, &format!("{NS}.{collection}")) | ||
.map_err(XrpcError::internal) | ||
}; | ||
// Each named by their document, read at once rather than in turn. | ||
let memberships = records("membership")?; | ||
let actors = memberships | ||
.iter() | ||
.map(|(_, m)| host.actor_view(m["member"].as_str().unwrap_or_default())); | ||
let actors = futures::future::join_all(actors).await; | ||
out["members"] = memberships | ||
.iter() | ||
.zip(actors) | ||
.map(|((_, m), actor)| json!({"actor": actor, "roles": objects("role", roles_of(m))})) | ||
.collect(); | ||
view["memberCount"] = json!(records("membership")?.len()); | ||
let mut out = json!({ "group": view }); | ||
out["roles"] = records("role")? | ||
.into_iter() | ||
.map(|(key, r)| { | ||
| @@ -344,6 +335,69 @@ pub async fn get_group( | ||
Ok(Json(out)) | ||
} | ||
| ||
/// A group's members, each with their roles, to one who may read its | ||
/// members space: a page at a time, in the order of their DIDs (the keys | ||
/// of their memberships), those after `cursor`; with `q`, only those | ||
/// whose handle or DID holds it, in any case. The cursor is there while | ||
/// more are. | ||
pub async fn list_members( | ||
State(host): State<Arc<Host>>, | ||
Query(p): Query<Params>, | ||
headers: HeaderMap, | ||
) -> Answer { | ||
let group = param(&p, "group")?; | ||
group_of(&host, group)?; | ||
let me = signed_in(&host, &headers, &format!("{NS}.listMembers")).await?; | ||
let members = members_space(group); | ||
let roles = host.roles(group, &me).map_err(XrpcError::internal)?; | ||
let access = host | ||
.group_record(group, &members, &format!("{NS}.access"), "self") | ||
.map_err(XrpcError::internal)?; | ||
if !access.is_some_and(|a| Access::of(&a, &members).can_read(&roles, &me)) { | ||
let closed = "only those who may read its members space see them"; | ||
return Err(XrpcError::new(StatusCode::FORBIDDEN, "Forbidden", closed)); | ||
} | ||
let limit = page(&p, 50, 100)? as usize; | ||
let after = p.get("cursor").cloned().unwrap_or_default(); | ||
let q = p | ||
.get("q") | ||
.map(|q| q.trim().to_lowercase()) | ||
.unwrap_or_default(); | ||
let memberships = host | ||
.group_records(group, &members, &format!("{NS}.membership")) | ||
.map_err(XrpcError::internal)?; | ||
let left: Vec<(String, Value)> = memberships | ||
.into_iter() | ||
.filter(|(rkey, _)| *rkey > after) | ||
.collect(); | ||
// Named by their documents a page and one more at a time, each page | ||
// read at once rather than in turn, until a page and one are found. | ||
let mut found: Vec<(String, Value)> = Vec::new(); | ||
for some in left.chunks(limit + 1) { | ||
let actors = some | ||
.iter() | ||
.map(|(_, m)| host.actor_view(m["member"].as_str().unwrap_or_default())); | ||
let actors = futures::future::join_all(actors).await; | ||
for ((rkey, m), actor) in some.iter().zip(actors) { | ||
let named = |at: &str| actor[at].as_str().unwrap_or_default().to_lowercase(); | ||
if named("did").contains(&q) || named("handle").contains(&q) { | ||
let view = json!({"actor": actor, "roles": objects("role", roles_of(m))}); | ||
found.push((rkey.clone(), view)); | ||
} | ||
} | ||
if found.len() > limit { | ||
break; | ||
} | ||
} | ||
let more = found.len() > limit; | ||
found.truncate(limit); | ||
let mut out = json!({ "members": found.iter().map(|(_, v)| v).collect::<Vec<_>>() }); | ||
if let Some((last, _)) = found.last().filter(|_| more) { | ||
out["cursor"] = json!(last); | ||
} | ||
Ok(Json(out)) | ||
} | ||
| ||
/// Whether `did` has written their own acceptance in the members space: | ||
/// their repo there holds anything. | ||
fn accepted(host: &Host, members: &str, did: &str) -> anyhow::Result<bool> { | ||
crates/group-host/src/group_config.rs+14−8
| @@ -141,15 +141,21 @@ fn place(profile: &Value) -> Result<(), XrpcError> { | ||
Ok(()) | ||
} | ||
| ||
/// Refuses a site that is not on the web. | ||
fn site(profile: &Value) -> Result<(), XrpcError> { | ||
let Some(url) = profile.get("url") else { | ||
return Ok(()); | ||
}; | ||
/// Whether `url` is an address on the web. | ||
fn on_the_web(url: &Value) -> bool { | ||
let url = url.as_str().unwrap_or_default(); | ||
if !url.starts_with("https://") && !url.starts_with("http://") { | ||
url.starts_with("https://") || url.starts_with("http://") | ||
} | ||
| ||
/// Refuses a site, or a link, that is not on the web. | ||
fn site(profile: &Value) -> Result<(), XrpcError> { | ||
if profile.get("url").is_some_and(|url| !on_the_web(url)) { | ||
return Err(invalid("url is an http or https address")); | ||
} | ||
let links = profile["links"].as_array().into_iter().flatten(); | ||
if links.into_iter().any(|link| !on_the_web(&link["url"])) { | ||
return Err(invalid("each link's url is an http or https address")); | ||
} | ||
Ok(()) | ||
} | ||
| ||
| @@ -179,8 +185,8 @@ impl Host { | ||
} | ||
| ||
/// 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 | ||
/// join policy the host does not know, a place that is none, a site or | ||
/// link 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"]) { | ||
crates/group-host/src/lexicons.rs+1−0
| @@ -78,6 +78,7 @@ pub const FILES: &[&str] = &[ | ||
lexicon!("fyi/opensocial/listGroupTokens"), | ||
lexicon!("fyi/opensocial/listInvites"), | ||
lexicon!("fyi/opensocial/listJoinRequests"), | ||
lexicon!("fyi/opensocial/listMembers"), | ||
lexicon!("fyi/opensocial/listRecoveryKeys"), | ||
lexicon!("fyi/opensocial/listSpaceRecords"), | ||
lexicon!("fyi/opensocial/listSubjects"), | ||
crates/group-host/src/lib.rs+4−0
| @@ -209,6 +209,10 @@ pub fn router(host: Arc<Host>) -> Router { | ||
post(group_api::create_group), | ||
) | ||
.route("/xrpc/fyi.opensocial.getGroup", get(group_api::get_group)) | ||
.route( | ||
"/xrpc/fyi.opensocial.listMembers", | ||
get(group_api::list_members), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.listGroups", | ||
get(group_api::list_groups), | ||
crates/group-host/tests/actors.rs+1−1
| @@ -167,7 +167,7 @@ async fn names_by_did_alone_someone_whose_document_it_cannot_read() { | ||
) | ||
.await; | ||
join(&h, &riders, "did:plc:nobodynobodynobodyxx").await; | ||
let lxm = format!("{NS}.getGroup"); | ||
let lxm = format!("{NS}.listMembers"); | ||
let (_, view) = get( | ||
&h, | ||
&lxm, | ||
crates/group-host/tests/assistants.rs+5−0
| @@ -265,6 +265,11 @@ async fn acts_as_the_member_in_the_group_they_chose() { | ||
group.as_str(), | ||
"{got}" | ||
); | ||
// Who is in it, found by part of their DID. | ||
let got = tool(&h, access, "listMembers", json!({"q": &alice.did[8..]})).await; | ||
let found = &got["structuredContent"]["members"]; | ||
assert_eq!(found[0]["actor"]["did"], alice.did.as_str(), "{got}"); | ||
assert_eq!(found.as_array().unwrap().len(), 1, "{got}"); | ||
let got = tool( | ||
&h, | ||
access, | ||
crates/group-host/tests/group_config.rs+15−0
| @@ -87,6 +87,14 @@ async fn an_admin_changes_the_profile() { | ||
"displayName": "Riders United", | ||
"description": "We ride.", | ||
"url": "https://riders.example", | ||
// As many links as a profile holds, a title as long as one may be. | ||
"links": [ | ||
{"url": "https://chat.riders.example", "title": "Our chat"}, | ||
{"url": "http://calendar.riders.example/rides"}, | ||
{"url": "https://a.example", "title": "x".repeat(64)}, | ||
{"url": "https://b.example", "title": "B"}, | ||
{"url": "https://c.example", "title": "C"}, | ||
], | ||
"joinPolicy": "invite", | ||
"location": {"$type": "community.lexicon.location.address", "locality": "Ljubljana", "country": "SI"}, | ||
"online": true, | ||
| @@ -113,6 +121,7 @@ async fn an_admin_changes_the_profile() { | ||
let shown = view(&h, &did, Some(&alice)).await; | ||
assert_eq!(shown["group"]["displayName"], "Riders United"); | ||
assert_eq!(shown["group"]["joinPolicy"], "invite"); | ||
assert_eq!(shown["group"]["links"], record["links"]); | ||
| ||
// Replaced whole: what is left out goes, pictures and all. | ||
let said = app | ||
| @@ -155,6 +164,12 @@ async fn refuses_a_profile_it_should_not_keep() { | ||
riders(json!({"joinPolicy": "fyi.opensocial.profile#invite"})), | ||
riders(json!({"location": {"$type": "xyz.place"}})), | ||
riders(json!({"url": "ftp://riders.example"})), | ||
riders( | ||
json!({"links": [{"url": "https://riders.example"}, {"url": "ftp://riders.example"}]}), | ||
), | ||
riders(json!({"links": [{"title": "Nowhere"}]})), | ||
riders(json!({"links": [{"url": "https://riders.example", "title": "x".repeat(65)}]})), | ||
riders(json!({"links": vec![json!({"url": "https://riders.example"}); 6]})), | ||
riders(json!({"topics": [{"topic": "bikes"}, {"topic": " bikes "}]})), | ||
riders(json!({"topics": [{"topic": " "}]})), | ||
riders(json!({"languages": [{"language": "sl"}, {"language": "sl"}]})), | ||
crates/group-host/tests/groups.rs+3−16
| @@ -149,22 +149,9 @@ async fn shows_a_group_as_each_viewer_may_see_it() { | ||
every.sort(); | ||
assert_eq!(viewer["actions"], json!(every)); | ||
assert_eq!(viewer["accepted"], false); | ||
let members: Vec<&str> = mine["members"] | ||
.as_array() | ||
.unwrap() | ||
.iter() | ||
.map(|m| m["actor"]["did"].as_str().unwrap()) | ||
.collect(); | ||
assert_eq!(members.len(), 2); | ||
assert!(members.contains(&alice.did.as_str()) && members.contains(&bob.did.as_str())); | ||
// Each by the handle their DID document names. | ||
assert!( | ||
mine["members"] | ||
.as_array() | ||
.unwrap() | ||
.iter() | ||
.all(|m| m["actor"]["handle"] == "authority.test") | ||
); | ||
// How many are in it, she and her steward; listMembers names them. | ||
assert_eq!(group["memberCount"], 2); | ||
assert_eq!(mine.get("members"), None); | ||
assert_eq!( | ||
mine["roles"], | ||
json!([ | ||
crates/group-host/tests/members.rs+107−0
| @@ -793,3 +793,110 @@ async fn one_whose_credentials_cannot_be_revoked_stays_in() { | ||
.is_empty() | ||
); | ||
} | ||
| ||
/// What `listMembers` answers `who` for `query`, past `group=`. | ||
async fn listed(h: &Running, who: Option<&Authority>, group: &str, query: &str) -> (u16, Json) { | ||
let lxm = format!("{NS}.listMembers"); | ||
let headers: Vec<_> = who.map(|w| auth(h, w, &lxm)).into_iter().collect(); | ||
get(h, &lxm, &format!("group={group}{query}"), &headers).await | ||
} | ||
| ||
/// Each member a page names, by their DID. | ||
fn dids(page: &Json) -> Vec<String> { | ||
let members = page["members"].as_array().unwrap().iter(); | ||
members | ||
.map(|m| m["actor"]["did"].as_str().unwrap().to_string()) | ||
.collect() | ||
} | ||
| ||
#[tokio::test] | ||
async fn members_are_listed_a_page_at_a_time() { | ||
let h = start(&[], false).await; | ||
let (did, [alice, bob, carol]) = group(&h).await; | ||
// Seven more, whom no DID document names. | ||
let nobodies: Vec<String> = ('a'..='g') | ||
.map(|c| format!("did:plc:nobodynobodynobody{c}")) | ||
.collect(); | ||
for n in &nobodies { | ||
join(&h, &did, n, &["member"]).await; | ||
} | ||
| ||
// getGroup counts them, and lists none. | ||
let shown = view(&h, &did, Some(&bob)).await; | ||
assert_eq!(shown["group"]["memberCount"], 9); | ||
assert_eq!(shown.get("members"), None); | ||
| ||
// All of them, in pages of four, each once, in the order of their DIDs. | ||
let mut seen: Vec<String> = Vec::new(); | ||
let mut cursor = String::new(); | ||
let mut pages = 0; | ||
loop { | ||
let (status, page) = listed(&h, Some(&bob), &did, &format!("&limit=4{cursor}")).await; | ||
assert_eq!(status, 200, "{page}"); | ||
pages += 1; | ||
seen.extend(dids(&page)); | ||
let Some(next) = page["cursor"].as_str() else { | ||
break; | ||
}; | ||
cursor = format!("&cursor={next}"); | ||
} | ||
assert_eq!(pages, 3); | ||
let mut every: Vec<String> = nobodies.clone(); | ||
every.extend([alice.did.clone(), bob.did.clone()]); | ||
every.sort(); | ||
assert_eq!(seen, every); | ||
// A page holding the last of them says there are no more. | ||
let (_, whole) = listed(&h, Some(&bob), &did, "&limit=9").await; | ||
assert_eq!(dids(&whole).len(), 9); | ||
assert_eq!(whole.get("cursor"), None); | ||
| ||
// Each with their roles, and named as their DID document names them. | ||
let (_, all) = listed(&h, Some(&alice), &did, "").await; | ||
let of = |who: &str| { | ||
let members = all["members"].as_array().unwrap(); | ||
members | ||
.iter() | ||
.find(|m| m["actor"]["did"] == who) | ||
.unwrap() | ||
.clone() | ||
}; | ||
assert_eq!( | ||
of(&alice.did)["roles"], | ||
json!([{"role": "admin"}, {"role": "member"}]) | ||
); | ||
assert_eq!(of(&alice.did)["actor"]["handle"], "authority.test"); | ||
assert_eq!( | ||
of(&nobodies[0]), | ||
json!({"actor": {"did": nobodies[0]}, "roles": [{"role": "member"}]}) | ||
); | ||
| ||
// Narrowed to those whose handle or DID holds `q`, whatever its case. | ||
let (_, named) = listed(&h, Some(&bob), &did, "&q=AUTHORITY").await; | ||
let mut both = vec![alice.did.clone(), bob.did.clone()]; | ||
both.sort(); | ||
assert_eq!(dids(&named), both); | ||
let (_, one) = listed(&h, Some(&bob), &did, "&q=nobodyc").await; | ||
assert_eq!(dids(&one), [nobodies[2].clone()]); | ||
let (_, none) = listed(&h, Some(&bob), &did, "&q=nobody.else").await; | ||
assert_eq!(none, json!({"members": []})); | ||
// And a page at a time still. | ||
let (_, first) = listed(&h, Some(&bob), &did, "&q=nobody&limit=5").await; | ||
assert_eq!(dids(&first), nobodies[..5]); | ||
let next = first["cursor"].as_str().unwrap(); | ||
let rest = format!("&q=nobody&limit=5&cursor={next}"); | ||
let (_, rest) = listed(&h, Some(&bob), &did, &rest).await; | ||
assert_eq!(dids(&rest), nobodies[5..]); | ||
assert_eq!(rest.get("cursor"), None); | ||
| ||
// Only to whoever may read its members space. | ||
assert_eq!( | ||
error(&listed(&h, Some(&carol), &did, "").await), | ||
(403, "Forbidden") | ||
); | ||
assert_eq!(listed(&h, None, &did, "").await.0, 401); | ||
let lost = listed(&h, Some(&bob), "did:plc:nobody", "").await; | ||
assert_eq!(error(&lost), (400, "GroupNotFound")); | ||
// Nor does one not in it learn how many are. | ||
let theirs = view(&h, &did, Some(&carol)).await; | ||
assert_eq!(theirs["group"].get("memberCount"), None); | ||
} | ||
crates/group-host-mcp/src/lib.rs+1−0
| @@ -35,6 +35,7 @@ macro_rules! lexicon { | ||
/// The methods an assistant may call, by their lexicons. | ||
const METHODS: &[(&str, &str)] = &[ | ||
lexicon!("getGroup"), | ||
lexicon!("listMembers"), | ||
lexicon!("listJoinRequests"), | ||
lexicon!("denyJoinRequest"), | ||
lexicon!("listInvites"), | ||