chadtmiller.com/group-host
atmosphere group host
0
0
profile set and role grant change only what they are given
crates/group-host/src/mcp.rs+20−2
| @@ -781,13 +781,31 @@ impl Host { | ||
let written = self.invite_as(who, &person, record).await; | ||
written.map_err(said) | ||
} | ||
Plan::Grant { role, grant } => { | ||
Plan::Edit { | ||
space, | ||
collection, | ||
rkey, | ||
fields, | ||
} => { | ||
let uri = format!("at://{}/space/{space}/self", who.group); | ||
let kept = self.group_record(&who.group, &uri, &collection, &rkey); | ||
let kept = kept.map_err(XrpcError::internal).map_err(said)?; | ||
let kept = kept.unwrap_or_default(); | ||
let write = group_host_mcp::edited(&kept, space, collection, rkey, fields); | ||
Box::pin(self.carry_out(who, write)).await | ||
} | ||
Plan::Grant { | ||
role, | ||
scopes, | ||
assignable, | ||
undo, | ||
} => { | ||
let members = crate::group::members_space(&who.group); | ||
let collection = format!("{NS}.permissions"); | ||
let kept = self.group_record(&who.group, &members, &collection, "self"); | ||
let kept = kept.map_err(XrpcError::internal).map_err(said)?; | ||
let kept = kept.unwrap_or_default(); | ||
let write = group_host_mcp::regrant(&kept, &role, grant); | ||
let write = group_host_mcp::regrant(&kept, &role, &scopes, &assignable, undo); | ||
Box::pin(self.carry_out(who, write)).await | ||
} | ||
} | ||
crates/group-host/tests/mcp.rs+13−14
| @@ -442,18 +442,23 @@ async fn writes_the_groups_profile_and_rules_as_the_group() { | ||
h.host.group_record(&group, &meta, &c, rkey).unwrap() | ||
}; | ||
| ||
// The profile, at its one key, replaced whole. | ||
let profile = json!({"display_name": "Riders United", "join_policy": "open"}); | ||
// The profile, at its one key, changed in what is given. | ||
let before = kept("profile", "self").unwrap(); | ||
let profile = json!({"display_name": "Riders United", "description": "Bikes"}); | ||
let got = tool(&h, access, "profile_set", 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"}) | ||
); | ||
let mut want = before.clone(); | ||
want["displayName"] = json!("Riders United"); | ||
want["description"] = json!("Bikes"); | ||
assert_eq!(kept("profile", "self").unwrap(), want); | ||
// Given empty, a field is taken away; the rest stay. | ||
let got = tool(&h, access, "profile_set", json!({"description": ""})).await; | ||
assert!(got.get("isError").is_none(), "{got}"); | ||
want.as_object_mut().unwrap().remove("description"); | ||
assert_eq!(kept("profile", "self").unwrap(), want); | ||
| ||
// A new rule, keyed by the clock; changed at its key; taken away. | ||
let got = tool( | ||
| @@ -476,13 +481,7 @@ async fn writes_the_groups_profile_and_rules_as_the_group() { | ||
assert_eq!(kept("rule", &rkey), None); | ||
| ||
// Held to what the host keeps, as any write as the group is. | ||
let got = tool( | ||
&h, | ||
access, | ||
"profile_set", | ||
json!({"display_name": " ", "join_policy": "open"}), | ||
) | ||
.await; | ||
let got = tool(&h, access, "profile_set", json!({"display_name": " "})).await; | ||
assert_eq!(got["isError"], true, "{got}"); | ||
let text = got["content"][0]["text"].as_str().unwrap(); | ||
assert!(text.starts_with("InvalidRequest: "), "{text}"); | ||
crates/group-host-mcp/src/lib.rs+150−35
| @@ -76,8 +76,6 @@ const MEMBERS: &str = "fyi.opensocial.members"; | ||
/// Where a record a tool writes is kept in its space. | ||
#[derive(Debug, Clone, PartialEq)] | ||
pub enum Key { | ||
/// At this one key, as its lexicon has it: `self`. | ||
Literal(String), | ||
/// At the key this argument names, which the tool requires. | ||
Named(String), | ||
/// At the key this field of the record names, which the tool | ||
| @@ -108,6 +106,13 @@ pub enum Action { | ||
key: Key, | ||
stamp: bool, | ||
}, | ||
/// Changes the fields given of the record of the kind `collection` at | ||
/// `rkey` in the group's space of the type `space`, keeping the rest. | ||
Edit { | ||
collection: String, | ||
space: String, | ||
rkey: String, | ||
}, | ||
/// Deletes one. | ||
Delete { | ||
collection: String, | ||
| @@ -117,8 +122,8 @@ pub enum Action { | ||
/// Writes an invite as the group in the invitee's inbox; with `undo`, | ||
/// takes back the one waiting. | ||
Invite, | ||
/// Sets a role's grant in the permissions record; with `undo`, drops | ||
/// it. | ||
/// Adds to a role's grant in the permissions record; with `undo`, | ||
/// takes away from it. | ||
Grant, | ||
} | ||
| ||
| @@ -275,8 +280,6 @@ const DEPTH: u8 = 6; | ||
| ||
/// Where a record a tool writes is kept, as `TOOLS` says it. | ||
enum At { | ||
/// At this one key. | ||
Literal(&'static str), | ||
/// At the key this argument names, which is not the record's own. | ||
Named(&'static str), | ||
/// At the key this field of the record names: a membership's member. | ||
| @@ -291,6 +294,8 @@ enum Made { | ||
Method(&'static str, Option<&'static str>), | ||
/// A record of ours put, or deleted, in the group's space of a type. | ||
Put(&'static str, &'static str, At), | ||
/// A record of ours at its one key, changed in the fields given. | ||
Edit(&'static str, &'static str, &'static str), | ||
Delete(&'static str, &'static str, At), | ||
Invite, | ||
Grant, | ||
| @@ -308,9 +313,9 @@ const TOOLS: &[(&str, &[&str], &str, Made)] = &[ | ||
( | ||
"profile_set", | ||
&[], | ||
"Replaces the group's profile as the group, whole: a field not given is dropped, and a \ | ||
picture is kept only by naming a blob the group holds.", | ||
Made::Put("profile", META, At::Literal("self")), | ||
"Changes the group's profile as the group. Changes only the fields given, keeping the \ | ||
rest; a field given empty, or null, is taken away.", | ||
Made::Edit("profile", META, "self"), | ||
), | ||
( | ||
"rule_set", | ||
| @@ -339,8 +344,9 @@ const TOOLS: &[(&str, &[&str], &str, Made)] = &[ | ||
( | ||
"role_grant", | ||
&["role"], | ||
"Sets what a role may do, as the group: its scopes, and the roles its holders may assign, \ | ||
in place of its grant in the permissions record; with undo, drops its grant.", | ||
"Adds to what a role may do, as the group: the scopes given, and the roles given that its \ | ||
holders may assign, to what its grant in the permissions record has; with undo, takes \ | ||
them away, or with none given drops its grant.", | ||
Made::Grant, | ||
), | ||
( | ||
| @@ -547,7 +553,6 @@ impl Docs { | ||
}; | ||
let stamp = drop(&mut input, "createdAt"); | ||
let key = match at { | ||
At::Literal(k) => Key::Literal(k.to_string()), | ||
At::Named(n) => { | ||
let said = format!("Which {kind}: its record's key."); | ||
add(&mut input, n, rkey(said), true); | ||
| @@ -582,6 +587,19 @@ impl Docs { | ||
}; | ||
(action, input, main["description"].as_str()) | ||
} | ||
Made::Edit(kind, space, rkey) => { | ||
let collection = format!("{NS}.{kind}"); | ||
let main = self.main(&collection); | ||
let mut input = self.object(&collection, &main["record"], DEPTH); | ||
drop(&mut input, "createdAt"); | ||
input["required"] = json!([]); | ||
let action = Action::Edit { | ||
collection, | ||
space: space.to_string(), | ||
rkey: rkey.to_string(), | ||
}; | ||
(action, input, main["description"].as_str()) | ||
} | ||
Made::Invite => { | ||
let nsid = format!("{NS}.invite"); | ||
let main = self.main(&nsid); | ||
| @@ -657,9 +675,24 @@ pub enum Plan { | ||
person: String, | ||
record: Option<Value>, | ||
}, | ||
/// Set `role`'s grant in the permissions record to `grant`; with none, | ||
/// drop it. `regrant` makes the write, from the record as it is. | ||
Grant { role: String, grant: Option<Value> }, | ||
/// Change the record of the kind `collection` at `rkey` in the | ||
/// group's space of the type `space` in the `fields` given, keeping | ||
/// the rest. `edited` makes the write, from the record as it is. | ||
Edit { | ||
space: String, | ||
collection: String, | ||
rkey: String, | ||
fields: Map<String, Value>, | ||
}, | ||
/// Add `scopes` and `assignable` to `role`'s grant in the permissions | ||
/// record; with `undo`, take them away, or with none drop its grant. | ||
/// `regrant` makes the write, from the record as it is. | ||
Grant { | ||
role: String, | ||
scopes: Vec<String>, | ||
assignable: Vec<String>, | ||
undo: bool, | ||
}, | ||
} | ||
| ||
/// What calling `tool` with `args` comes to, `now` the time a record it | ||
| @@ -725,7 +758,6 @@ pub fn plan(tool: &Tool, args: &Value, now: &str) -> Result<Plan, String> { | ||
key, | ||
} => { | ||
let rkey = match key { | ||
Key::Literal(k) => Some(k.clone()), | ||
Key::Named(n) => Some(given(&mut input, n)?), | ||
Key::Field(n) => { | ||
let named = given(&mut input, n)?; | ||
| @@ -749,6 +781,16 @@ pub fn plan(tool: &Tool, args: &Value, now: &str) -> Result<Plan, String> { | ||
record, | ||
} | ||
} | ||
Action::Edit { | ||
collection, | ||
space, | ||
rkey, | ||
} => Plan::Edit { | ||
space: space.clone(), | ||
collection: collection.clone(), | ||
rkey: rkey.clone(), | ||
fields: input, | ||
}, | ||
Action::Invite => { | ||
let person = given(&mut input, "person")?; | ||
let record = (!undo).then(|| stamped(input, &format!("{NS}.invite"))); | ||
| @@ -756,43 +798,80 @@ pub fn plan(tool: &Tool, args: &Value, now: &str) -> Result<Plan, String> { | ||
} | ||
Action::Grant => { | ||
let role = given(&mut input, "role")?; | ||
let list = |input: &Map<String, Value>, name: &str| { | ||
input.get(name).cloned().unwrap_or(json!([])) | ||
let list = |name: &str| -> Vec<String> { | ||
let items = input.get(name).and_then(Value::as_array).into_iter(); | ||
let items = items.flatten().filter_map(Value::as_str); | ||
items.map(String::from).collect() | ||
}; | ||
let grant = json!({ | ||
"role": role, | ||
"scopes": list(&input, "scopes"), | ||
"assignable": list(&input, "assignable"), | ||
}); | ||
Plan::Grant { | ||
role, | ||
grant: (!undo).then_some(grant), | ||
scopes: list("scopes"), | ||
assignable: list("assignable"), | ||
undo, | ||
} | ||
} | ||
}) | ||
} | ||
| ||
/// The write that sets `role`'s grant to `grant`, or with none drops it, | ||
/// in `permissions`, the group's permissions record as it is (none if it | ||
/// has none): each other role's grant as it was. | ||
pub fn regrant(permissions: &Value, role: &str, grant: Option<Value>) -> Plan { | ||
/// The write that adds `scopes` and `assignable` to `role`'s grant, or | ||
/// with `undo` takes them away, in `permissions`, the group's permissions | ||
/// record as it is (none if it has none): the grant dropped if nothing is | ||
/// named to take away, or nothing is left; each other role's as it was. | ||
pub fn regrant( | ||
permissions: &Value, | ||
role: &str, | ||
scopes: &[String], | ||
assignable: &[String], | ||
undo: bool, | ||
) -> Plan { | ||
let mut record = match permissions { | ||
Value::Object(_) => permissions.clone(), | ||
_ => json!({}), | ||
}; | ||
let old = record["grants"].as_array().cloned().unwrap_or_default(); | ||
let had = |field: &str| -> Vec<String> { | ||
let theirs = old.iter().filter(|g| g["role"] == role); | ||
let items = theirs.flat_map(|g| g[field].as_array().cloned().unwrap_or_default()); | ||
let mut out: Vec<String> = Vec::new(); | ||
for item in items.filter_map(|i| i.as_str().map(String::from)) { | ||
if !out.contains(&item) { | ||
out.push(item); | ||
} | ||
} | ||
out | ||
}; | ||
let changed = |mut list: Vec<String>, named: &[String]| { | ||
match undo { | ||
true => list.retain(|i| !named.contains(i)), | ||
false => list.extend( | ||
named | ||
.iter() | ||
.filter(|n| !list.contains(n)) | ||
.cloned() | ||
.collect::<Vec<_>>(), | ||
), | ||
} | ||
list | ||
}; | ||
let scopes_now = changed(had("scopes"), scopes); | ||
let assignable_now = changed(had("assignable"), assignable); | ||
let named = !scopes.is_empty() || !assignable.is_empty(); | ||
let gone = undo && (!named || (scopes_now.is_empty() && assignable_now.is_empty())); | ||
let grant = | ||
(!gone).then(|| json!({"role": role, "scopes": scopes_now, "assignable": assignable_now})); | ||
let mut grants = Vec::new(); | ||
let mut replaced = false; | ||
for old in record["grants"].as_array().into_iter().flatten() { | ||
match old["role"] == role { | ||
true if !replaced => { | ||
replaced = true; | ||
let mut placed = false; | ||
for g in old { | ||
match g["role"] == role { | ||
true if !placed => { | ||
placed = true; | ||
grants.extend(grant.clone()); | ||
} | ||
true => {} | ||
false => grants.push(old.clone()), | ||
false => grants.push(g), | ||
} | ||
} | ||
if !replaced { | ||
if !placed { | ||
grants.extend(grant); | ||
} | ||
record["$type"] = json!(format!("{NS}.permissions")); | ||
| @@ -805,6 +884,42 @@ pub fn regrant(permissions: &Value, role: &str, grant: Option<Value>) -> Plan { | ||
} | ||
} | ||
| ||
/// The write that changes `kept`, the record of the kind `collection` at | ||
/// `rkey` in the group's space of the type `space` as it is (none if there | ||
/// is none), in the `fields` given: each set, or taken away if given | ||
/// empty, an empty list, or null; the rest as they were. | ||
pub fn edited( | ||
kept: &Value, | ||
space: String, | ||
collection: String, | ||
rkey: String, | ||
fields: Map<String, Value>, | ||
) -> Plan { | ||
let mut record = match kept { | ||
Value::Object(o) => o.clone(), | ||
_ => Map::new(), | ||
}; | ||
for (name, value) in fields { | ||
let empty = match &value { | ||
Value::Null => true, | ||
Value::String(s) => s.is_empty(), | ||
Value::Array(a) => a.is_empty(), | ||
_ => false, | ||
}; | ||
match empty { | ||
true => record.remove(&name), | ||
false => record.insert(name, value), | ||
}; | ||
} | ||
record.insert("$type".into(), json!(collection)); | ||
Plan::Write { | ||
space, | ||
collection, | ||
rkey: Some(rkey), | ||
record: Some(Value::Object(record)), | ||
} | ||
} | ||
| ||
fn error(id: &Value, code: i64, message: &str) -> Value { | ||
json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message}}) | ||
} | ||
crates/group-host-mcp/tests/protocol.rs+105−30
| @@ -2,7 +2,7 @@ | ||
//! the server answers each message an MCP client sends. | ||
| ||
use group_host_mcp::{ | ||
Action, Key, PROTOCOL_VERSIONS, Plan, Tool, answer, camel, plan, regrant, snake, tools, | ||
Action, Key, PROTOCOL_VERSIONS, Plan, Tool, answer, camel, edited, plan, regrant, snake, tools, | ||
}; | ||
use serde_json::{Value, json}; | ||
| ||
| @@ -103,14 +103,17 @@ fn makes_each_schema_from_the_lexicons() { | ||
assert_eq!(eject.input_schema["required"], json!(["member"])); | ||
assert_eq!(eject.input_schema["properties"]["member"]["format"], "did"); | ||
| ||
// The profile, at its one key: none to say, nor when it was made. | ||
// The profile, at its one key: none to say, nor when it was made; | ||
// each field changed only if given. | ||
let profile = tool("profile_set"); | ||
let fields = &profile.input_schema["properties"]; | ||
assert_eq!(fields["display_name"]["maxLength"], 640); | ||
assert!(fields.get("rkey").is_none() && fields.get("created_at").is_none()); | ||
assert_eq!( | ||
profile.input_schema["required"], | ||
json!(["display_name", "join_policy"]) | ||
assert_eq!(profile.input_schema["required"], json!([])); | ||
assert!( | ||
profile | ||
.description | ||
.contains("Changes only the fields given") | ||
); | ||
let said = fields["join_policy"]["description"].as_str().unwrap(); | ||
assert!(said.contains("One of: "), "{said}"); | ||
| @@ -231,20 +234,21 @@ fn plans_a_record_written_as_the_group() { | ||
rkey: rkey.map(String::from), | ||
record, | ||
}; | ||
// In snake case, written in the lexicon's own case. | ||
// In snake case, in the lexicon's own case: the fields to change. | ||
assert_eq!( | ||
planned( | ||
"profile_set", | ||
json!({"display_name": "Riders", "join_policy": "open"}) | ||
json!({"display_name": "Riders", "description": ""}) | ||
), | ||
Ok(write( | ||
"meta", | ||
"profile", | ||
Some("self"), | ||
Some( | ||
json!({"$type": "fyi.opensocial.profile", "displayName": "Riders", "joinPolicy": "open"}) | ||
) | ||
)) | ||
Ok(Plan::Edit { | ||
space: "fyi.opensocial.meta".into(), | ||
collection: "fyi.opensocial.profile".into(), | ||
rkey: "self".into(), | ||
fields: json!({"displayName": "Riders", "description": ""}) | ||
.as_object() | ||
.unwrap() | ||
.clone(), | ||
}) | ||
); | ||
let rule = json!({"$type": "fyi.opensocial.rule", "title": "Be kind", "text": ""}); | ||
assert_eq!( | ||
| @@ -332,14 +336,21 @@ fn plans_an_invite_and_a_grant() { | ||
planned("role_grant", json!({"role": "leader", "scopes": ["rpc:x"]})), | ||
Ok(Plan::Grant { | ||
role: "leader".into(), | ||
grant: Some(json!({"role": "leader", "scopes": ["rpc:x"], "assignable": []})), | ||
scopes: vec!["rpc:x".into()], | ||
assignable: vec![], | ||
undo: false, | ||
}) | ||
); | ||
assert_eq!( | ||
planned("role_grant", json!({"role": "leader", "undo": true})), | ||
planned( | ||
"role_grant", | ||
json!({"role": "leader", "assignable": ["member"], "undo": true}) | ||
), | ||
Ok(Plan::Grant { | ||
role: "leader".into(), | ||
grant: None | ||
scopes: vec![], | ||
assignable: vec!["member".into()], | ||
undo: true, | ||
}) | ||
); | ||
assert!(planned("role_grant", json!({})).is_err()); | ||
| @@ -347,8 +358,7 @@ fn plans_an_invite_and_a_grant() { | ||
| ||
#[test] | ||
fn regrants_one_role_keeping_the_rest() { | ||
let grant = | ||
|role: &str, scope: &str| json!({"role": role, "scopes": [scope], "assignable": []}); | ||
let grant = |role: &str, scopes: &[&str], assignable: &[&str]| json!({"role": role, "scopes": scopes, "assignable": assignable}); | ||
let written = |plan: Plan| match plan { | ||
Plan::Write { | ||
space, | ||
| @@ -368,23 +378,88 @@ fn regrants_one_role_keeping_the_rest() { | ||
} | ||
other => panic!("{other:?}"), | ||
}; | ||
let kept = json!({"$type": "fyi.opensocial.permissions", "grants": [grant("admin", "a"), grant("leader", "b"), grant("leader", "c")], "createdAt": NOW}); | ||
// In its place, once; the rest as they were. | ||
let record = written(regrant(&kept, "leader", Some(grant("leader", "d")))); | ||
let names = |n: &[&str]| n.iter().map(|s| s.to_string()).collect::<Vec<_>>(); | ||
let kept = json!({"$type": "fyi.opensocial.permissions", "grants": [grant("admin", &["a"], &[]), grant("leader", &["b"], &["member"]), grant("leader", &["c"], &[])], "createdAt": NOW}); | ||
// What is named is added to what the role had, once, in its place; | ||
// the rest as they were. | ||
let record = written(regrant(&kept, "leader", &names(&["d", "b"]), &[], false)); | ||
assert_eq!( | ||
record["grants"], | ||
json!([grant("admin", "a"), grant("leader", "d")]) | ||
json!([ | ||
grant("admin", &["a"], &[]), | ||
grant("leader", &["b", "c", "d"], &["member"]) | ||
]) | ||
); | ||
assert_eq!(record["createdAt"], NOW); | ||
let record = written(regrant(&kept, "leader", None)); | ||
assert_eq!(record["grants"], json!([grant("admin", "a")])); | ||
let record = written(regrant(&kept, "mod", Some(grant("mod", "e")))); | ||
assert_eq!(record["grants"].as_array().unwrap().len(), 4); | ||
// With undo, what is named is taken away; with nothing named, or | ||
// nothing left, the grant goes. | ||
let record = written(regrant(&kept, "leader", &names(&["b"]), &[], true)); | ||
assert_eq!( | ||
record["grants"], | ||
json!([ | ||
grant("admin", &["a"], &[]), | ||
grant("leader", &["c"], &["member"]) | ||
]) | ||
); | ||
let record = written(regrant(&kept, "leader", &[], &[], true)); | ||
assert_eq!(record["grants"], json!([grant("admin", &["a"], &[])])); | ||
let record = written(regrant(&kept, "admin", &names(&["a"]), &[], true)); | ||
let roles: Vec<&Value> = record["grants"] | ||
.as_array() | ||
.unwrap() | ||
.iter() | ||
.map(|g| &g["role"]) | ||
.collect(); | ||
assert_eq!(roles, ["leader", "leader"]); | ||
let record = written(regrant(&kept, "mod", &names(&["e"]), &[], false)); | ||
assert_eq!(record["grants"][3], grant("mod", &["e"], &[])); | ||
// A group with none yet has one. | ||
let record = written(regrant(&Value::Null, "mod", Some(grant("mod", "e")))); | ||
let record = written(regrant(&Value::Null, "mod", &names(&["e"]), &[], false)); | ||
assert_eq!( | ||
record, | ||
json!({"$type": "fyi.opensocial.permissions", "grants": [grant("mod", &["e"], &[])]}) | ||
); | ||
} | ||
| ||
#[test] | ||
fn edits_a_record_keeping_what_is_not_given() { | ||
let avatar = | ||
json!({"$type": "blob", "ref": {"$link": "bafy"}, "mimeType": "image/png", "size": 3}); | ||
let kept = json!({"$type": "fyi.opensocial.profile", "displayName": "Riders", "description": "Bikes", "avatar": avatar, "links": [{"url": "https://a.test"}], "joinPolicy": "open"}); | ||
let fields = json!({"displayName": "Riders United", "description": "", "links": [], "url": null, "online": false}); | ||
let plan = edited( | ||
&kept, | ||
"fyi.opensocial.meta".into(), | ||
"fyi.opensocial.profile".into(), | ||
"self".into(), | ||
fields.as_object().unwrap().clone(), | ||
); | ||
assert_eq!( | ||
plan, | ||
Plan::Write { | ||
space: "fyi.opensocial.meta".into(), | ||
collection: "fyi.opensocial.profile".into(), | ||
rkey: Some("self".into()), | ||
record: Some( | ||
json!({"$type": "fyi.opensocial.profile", "displayName": "Riders United", "avatar": avatar, "joinPolicy": "open", "online": false}) | ||
), | ||
} | ||
); | ||
// None yet: only what is given. | ||
let fields = json!({"displayName": "Riders"}); | ||
let plan = edited( | ||
&Value::Null, | ||
"fyi.opensocial.meta".into(), | ||
"fyi.opensocial.profile".into(), | ||
"self".into(), | ||
fields.as_object().unwrap().clone(), | ||
); | ||
let Plan::Write { record, .. } = plan else { | ||
panic!() | ||
}; | ||
assert_eq!( | ||
record, | ||
json!({"$type": "fyi.opensocial.permissions", "grants": [grant("mod", "e")]}) | ||
Some(json!({"$type": "fyi.opensocial.profile", "displayName": "Riders"})) | ||
); | ||
} | ||
#[tokio::test] | ||
crates/opensocial/src/lib.rs+27−5
| @@ -31,8 +31,8 @@ group | ||
group move <group> --to <address> [--to-did <did>] | ||
move a group, whole, from this host to the one at <address> | ||
profile | ||
profile set <group> --display-name <name> --join-policy <policy> [--description <words>] … | ||
replace the group's profile | ||
profile set <group> [--display-name <name>] [--join-policy <policy>] [--description <words>] … | ||
change the group's profile in what is given; \"\" takes a field away | ||
rule | ||
rule set <group> --title <title> --text <words> [--order <n>] [--rule <key>] | ||
write a rule: the one --rule names, or a new one | ||
| @@ -44,7 +44,7 @@ role | ||
role delete <group> <role> | ||
delete a role nobody holds or is granted | ||
role grant <group> <role> [--scopes <scope,…>] [--assignable <role,…>] [--undo] | ||
set what a role may do, or with --undo drop its grant | ||
add to what a role may do, or with --undo take it away | ||
member | ||
member list <group> [--q <text>] [--limit <n>] [--cursor <cursor>] | ||
who is in the group, and their roles, a page at a time | ||
| @@ -484,6 +484,7 @@ fn typed(name: &str, value: &str, schema: &Value) -> Result<Value> { | ||
let items = value.split(',').map(str::trim).filter(|v| !v.is_empty()); | ||
json!(items.collect::<Vec<_>>()) | ||
} | ||
_ if value.is_empty() => Value::Null, | ||
_ => serde_json::from_str(value).map_err(|_| anyhow!("{name} wants JSON"))?, | ||
}) | ||
} | ||
| @@ -721,9 +722,30 @@ async fn carry_out(me: &Client, host: &Host, group: &str, plan: Plan) -> Result< | ||
json!({"repo": group, "space": inbox, "collection": m("invite"), "rkey": rkey}); | ||
session.call("com.atproto.space.deleteRecord", &body).await | ||
} | ||
Plan::Grant { role, grant } => { | ||
Plan::Edit { | ||
space, | ||
collection, | ||
rkey, | ||
fields, | ||
} => { | ||
// The record as it is, as the space's records are listed. | ||
let uri = format!("at://{group}/space/{space}/self"); | ||
let record = format!("{uri}/{group}/{collection}/{rkey}"); | ||
let asked = [("group", group), ("space", &uri), ("uri", &record)]; | ||
let listed = me.query(host, &m("listSpaceRecords"), &asked).await?; | ||
let kept = listed["records"][0]["value"].clone(); | ||
let write = group_host_mcp::edited(&kept, space, collection, rkey, fields); | ||
Box::pin(carry_out(me, host, group, write)).await | ||
} | ||
Plan::Grant { | ||
role, | ||
scopes, | ||
assignable, | ||
undo, | ||
} => { | ||
let view = me.query(host, &m("getGroup"), &[("group", group)]).await?; | ||
let write = group_host_mcp::regrant(&permissions_of(&view), &role, grant); | ||
let kept = permissions_of(&view); | ||
let write = group_host_mcp::regrant(&kept, &role, &scopes, &assignable, undo); | ||
Box::pin(carry_out(me, host, group, write)).await | ||
} | ||
} | ||
crates/opensocial/tests/commands.rs+51−12
| @@ -14,6 +14,11 @@ use std::collections::HashMap; | ||
use std::sync::Arc; | ||
use tempfile::TempDir; | ||
| ||
/// Two scopes a role may be granted: reading the moderation queue, and | ||
/// inviting. | ||
const MOD_READ: &str = "rpc:fyi.opensocial.listSubjects?aud=*"; | ||
const INVITE: &str = "space:fyi.opensocial.invites?authority=*&collection=fyi.opensocial.invite"; | ||
| ||
/// A host at a free port, on the reference directory, resolving | ||
/// handles at the reference PDS. | ||
struct Running { | ||
| @@ -257,37 +262,62 @@ async fn writes_the_groups_rules_roles_and_profile() { | ||
); | ||
let grants = || kept(&members, "permissions", "self").unwrap()["grants"].clone(); | ||
let before = grants(); | ||
let leaders = || -> Vec<Value> { | ||
let all = grants(); | ||
let all = all.as_array().unwrap().iter(); | ||
all.filter(|g| g["role"] == "leader").cloned().collect() | ||
}; | ||
ok( | ||
&alice, | ||
&["role", "grant", group, "leader", "--assignable", ""], | ||
) | ||
.await; | ||
let leaders: Vec<Value> = grants() | ||
.as_array() | ||
.unwrap() | ||
.iter() | ||
.filter(|g| g["role"] == "leader") | ||
.cloned() | ||
.collect(); | ||
assert_eq!( | ||
leaders, | ||
leaders(), | ||
[json!({"role": "leader", "scopes": [], "assignable": []})] | ||
); | ||
// Each added to what it had; one taken away, the rest kept. | ||
let of_members = || -> Value { | ||
let all = grants(); | ||
let all = all.as_array().unwrap(); | ||
let found = all.iter().find(|g| g["role"] == "member"); | ||
found.cloned().unwrap() | ||
}; | ||
let had = of_members()["scopes"].as_array().unwrap().clone(); | ||
for scope in [MOD_READ, INVITE] { | ||
ok( | ||
&alice, | ||
&["role", "grant", group, "member", "--scopes", scope], | ||
) | ||
.await; | ||
} | ||
let mut want = had.clone(); | ||
for scope in [MOD_READ, INVITE] { | ||
if !want.contains(&json!(scope)) { | ||
want.push(json!(scope)); | ||
} | ||
} | ||
assert_eq!(of_members()["scopes"], json!(want)); | ||
let undo = [ | ||
"role", "grant", group, "member", "--scopes", MOD_READ, "--undo", | ||
]; | ||
ok(&alice, &undo).await; | ||
want.retain(|s| s != MOD_READ); | ||
assert_eq!(of_members()["scopes"], json!(want)); | ||
let said_so = fails(&alice, &["role", "grant", group, "leader", "--undo"]).await; | ||
assert!(said_so.contains("NotAssignable"), "{said_so}"); | ||
assert_ne!(grants(), before); | ||
let said_so = fails(&alice, &["role", "delete", group, "leader"]).await; | ||
assert!(said_so.contains("RoleInUse"), "{said_so}"); | ||
| ||
// The profile, replaced whole. | ||
// The profile, changed in what is given; given empty, taken away. | ||
let before = kept(&meta, "profile", "self").unwrap(); | ||
let profile = [ | ||
"profile", | ||
"set", | ||
group, | ||
"--display-name", | ||
"Riders United", | ||
"--join-policy", | ||
"open", | ||
"--topics", | ||
r#"[{"topic": "cycling"}]"#, | ||
]; | ||
| @@ -295,7 +325,16 @@ async fn writes_the_groups_rules_roles_and_profile() { | ||
let written = kept(&meta, "profile", "self").unwrap(); | ||
assert_eq!(written["displayName"], "Riders United"); | ||
assert_eq!(written["topics"], json!([{"topic": "cycling"}])); | ||
assert_eq!(written.get("description"), None); | ||
assert_eq!(written["joinPolicy"], before["joinPolicy"]); | ||
let profile = ["profile", "set", group, "--description", "Bikes"]; | ||
ok(&alice, &profile).await; | ||
let written = kept(&meta, "profile", "self").unwrap(); | ||
assert_eq!(written["topics"], json!([{"topic": "cycling"}])); | ||
assert_eq!(written["description"], "Bikes"); | ||
ok(&alice, &["profile", "set", group, "--topics", ""]).await; | ||
let written = kept(&meta, "profile", "self").unwrap(); | ||
assert_eq!(written.get("topics"), None); | ||
assert_eq!(written["description"], "Bikes"); | ||
| ||
// The queue; a label on an account, and taken back, in its history. | ||
let queue = said(&ok(&alice, &["mod", "list", group, "--status", "open"]).await); | ||
docs/reference/cli.md+5−3
| @@ -34,7 +34,9 @@ comma-separated (`member,admin`); anything more than that is JSON | ||
(`--access '{"grants": []}'`). A person (`<member>`, `<person>`) may be | ||
a handle, which it resolves. Such a command prints what the host | ||
answered, as JSON, but `group show`, which prints lines. A write | ||
replaces the record whole: a field not given is dropped. | ||
replaces the record whole, a field not given dropped, but `profile set`, | ||
which changes only the fields given (`""` takes one away), and `role | ||
grant`, which adds to a role's grant or with `--undo` takes from it. | ||
| ||
The commands with no tool make or move a group or an account: `group | ||
create`, `group seed`, `group move` and `account import`. | ||
| @@ -52,7 +54,7 @@ create`, `group seed`, `group move` and `account import`. | ||
| ||
| Command | What it does | | ||
| --- | --- | | ||
| `profile set <group> --display-name <name> --join-policy <policy> [--description] [--url] [--online] [--topics <json>] [--languages <json>] [--location <json>]` | replaces the group's profile, as the group | | ||
| `profile set <group> [--display-name <name>] [--join-policy <policy>] [--description] [--url] [--online] [--topics <json>] [--languages <json>] [--location <json>] [--links <json>]` | changes the group's profile in the fields given, as the group, keeping the rest and its pictures; a field given `""` is taken away | | ||
| ||
### rule | ||
| ||
| @@ -67,7 +69,7 @@ create`, `group seed`, `group move` and `account import`. | ||
| --- | --- | | ||
| `role set <group> <role> --display-name <name> [--description] [--default] [--bot]` | writes a role as the group, at its id | | ||
| `role delete <group> <role>` | deletes a role nobody holds or is granted | | ||
| `role grant <group> <role> [--scopes <scope,…>] [--assignable <role,…>] [--undo]` | sets what a role may do, in place of its grant in the permissions record: its scopes, and the roles its holders may assign, each none if not given; with `--undo`, drops its grant | | ||
| `role grant <group> <role> [--scopes <scope,…>] [--assignable <role,…>] [--undo]` | adds the scopes given, and the roles given that its holders may assign, to the role's grant in the permissions record; with `--undo`, takes them away, or with none given drops its grant | | ||
| ||
### member | ||
| ||
docs/reference/mcp.md+6−5
| @@ -52,9 +52,10 @@ allow, or the host refuses, is `isError: true`, its text `<error>: | ||
given, or not as text, is refused before anything is asked: | ||
`<name> is required, as text`. | ||
| ||
A write replaces the record whole: a field not given is dropped. A | ||
picture cannot be uploaded through MCP; `profile_set` keeps one only by | ||
naming a blob the group already holds. | ||
A write replaces the record whole, a field not given dropped, but | ||
`profile_set` and `role_grant`, which change only what they are given. | ||
A picture cannot be uploaded through MCP; `profile_set` keeps the | ||
group's as they are. | ||
| ||
## group | ||
| ||
| @@ -66,7 +67,7 @@ naming a blob the group already holds. | ||
| ||
| Tool | Command | Lexicon | What it does | | ||
| --- | --- | --- | --- | | ||
| `profile_set` | `profile set` | `fyi.opensocial.profile` | replaces the group's profile, at `self` in its meta space, as the group | | ||
| `profile_set` | `profile set` | `fyi.opensocial.profile` | changes the group's profile, at `self` in its meta space, as the group, in the fields given, keeping the rest; a field given empty, an empty list or `null` is taken away | | ||
| ||
## rule | ||
| ||
| @@ -81,7 +82,7 @@ naming a blob the group already holds. | ||
| --- | --- | --- | --- | | ||
| `role_set` | `role set` | `fyi.opensocial.role` | writes the role `role`, its id, in the members space, as the group | | ||
| `role_delete` | `role delete` | `fyi.opensocial.role` | deletes a role nobody holds or is granted | | ||
| `role_grant` | `role grant` | `fyi.opensocial.permissions` | sets the grant of `role` in the permissions record, its `scopes` and the roles its holders may assign (`assignable`), each empty if not given, in place of the one it had; with `undo`, drops it. The rest of the record is as it was, and the write is held to the same rules as any of it | | ||
| `role_grant` | `role grant` | `fyi.opensocial.permissions` | adds the `scopes` given, and the roles given that its holders may assign (`assignable`), to the grant of `role` in the permissions record; with `undo`, takes them away, or with none given drops the grant. The rest of the record is as it was, and the write is held to the same rules as any of it | | ||
| ||
## member | ||