chadtmiller.com/group-host
atmosphere group host
0
0
Scopes are read by atproto's scope module, as the reference reads them
.changeset/scopes-by-atproto.mdnew+13−0
| @@ -0,0 +1,13 @@ | ||
--- | ||
default: patch | ||
--- | ||
| ||
# Scopes read as atproto's reference reads them | ||
| ||
The host reads OAuth scopes, roles' permissions and space policies' permissions with atproto 0.4.4's `scope` module, as atproto's permission spec and `@atproto/oauth-scopes` read them. A scope its grammar doesn't take is no scope: one naming an action there is none of (`repo:C?action=upsert`, where the unknown action was left out before), a parameter its resource doesn't take, a value it takes once named twice, a collection that isn't an NSID, or an `rpc:` audience with no `#service`. Approval withholds such a scope, and `createSpace` and `updateSpace` refuse a policy permission that is one (`InvalidRequest`). | ||
| ||
A blob scope names one type or pattern: `blob:image/*,video/*` is no scope, where it was read as both. An upload's type is compared with the scope as written, not ignoring case, so `IMAGE/png` no longer passes `blob:image/*`. A token now keeps each blob scope it is given as one scope per type, lowercase (`blob?accept=Image/PNG` becomes `blob:image/png`). | ||
| ||
An `rpc:` scope for one of the host's own methods names it at `<host DID>#atgrp` or `*`; the host's DID alone, which it took before, is no audience. `space?spaceType=T` is now kept at approval as `space:T` is. | ||
| ||
Tokens already issued keep what they were granted: upgrading rewrites each grant's scope once so that it reads the same. A blob list becomes a scope per type, lowercase; unknown actions and parameters, and repeated values after the first, are dropped; and the host's DID alone as an audience of its own methods becomes `<host DID>#atgrp`. A scope that granted nothing before still does. Roles and space policies already written are records and are not rewritten: a permission in one that the grammar doesn't take now grants nothing. Those the console and `atgrp` write all read the same. | ||
crates/group-host/src/group_tokens.rs+4−1
| @@ -111,7 +111,10 @@ impl Host { | ||
/// The scopes the writes a role holds in `space` become: each collection | ||
/// with its actions, in the space and in the group's repo, and the files | ||
/// those records hold. | ||
fn scopes_for(space: &SpaceRef, writes: &BTreeMap<String, BTreeSet<String>>) -> Vec<String> { | ||
pub(crate) fn scopes_for( | ||
space: &SpaceRef, | ||
writes: &BTreeMap<String, BTreeSet<String>>, | ||
) -> Vec<String> { | ||
let mut out = vec!["atproto".to_string()]; | ||
let at = format!( | ||
"space:{}?authority={}&skey={}", | ||
crates/group-host/src/oauth_scope.rs+60−57
| @@ -17,8 +17,9 @@ use crate::group::{members_space, meta_space}; | ||
use crate::lexicons::lexicons; | ||
use crate::permission_sets::{Sets, included}; | ||
use crate::rbac::{self, LABEL, NS, actions_for, label_writes, meta_writes, repo_collections_for}; | ||
use crate::scopes::{decoded, is_blob, repo_collections}; | ||
use crate::scopes::blob_scopes; | ||
use crate::xrpc::XrpcError; | ||
use atproto::scope::{Rpc, Scope, SpaceAction}; | ||
use serde_json::Value; | ||
use std::collections::{BTreeMap, BTreeSet}; | ||
| ||
| @@ -76,38 +77,32 @@ pub struct SpaceScope { | ||
} | ||
| ||
impl SpaceScope { | ||
/// `scope`, if it is a space scope, as atproto reads one. | ||
pub fn parse(scope: &str) -> Option<SpaceScope> { | ||
let scope = decoded(scope); | ||
let rest = scope.strip_prefix("space:")?; | ||
let (kind, query) = rest.split_once('?').unwrap_or((rest, "")); | ||
let mut values: BTreeMap<&str, Vec<&str>> = BTreeMap::new(); | ||
for (k, v) in query.split('&').filter_map(|kv| kv.split_once('=')) { | ||
values.entry(k).or_default().push(v); | ||
} | ||
let all = |k: &str| values.get(k).cloned().unwrap_or_default(); | ||
let one = |k: &str| all(k).first().map_or("*", |v| v).to_string(); | ||
let actions = all("action"); | ||
let named: Vec<String> = WRITES | ||
.iter() | ||
.filter(|w| actions.contains(w)) | ||
.map(|w| w.to_string()) | ||
.collect(); | ||
let Scope::Space(s) = Scope::parse(scope) else { | ||
return None; | ||
}; | ||
let asked = |w: &&str| s.actions.iter().any(|a| a.as_str() == *w); | ||
let named: Vec<String> = WRITES.into_iter().filter(asked).map(String::from).collect(); | ||
let writes = if named.is_empty() { | ||
WRITES.map(String::from).to_vec() | ||
} else { | ||
named | ||
}; | ||
let manage: Vec<String> = all("manage").iter().map(|m| m.to_string()).collect(); | ||
let read_only = manage.is_empty() | ||
&& !actions.is_empty() | ||
&& actions.iter().all(|a| *a == "read" || *a == "read_self"); | ||
let manage: Vec<String> = s | ||
.manage | ||
.iter() | ||
.flatten() | ||
.map(|m| m.as_str().into()) | ||
.collect(); | ||
let reads = |a: &SpaceAction| matches!(a, SpaceAction::Read | SpaceAction::ReadSelf); | ||
Some(SpaceScope { | ||
kind: kind.into(), | ||
authority: one("authority"), | ||
skey: one("skey"), | ||
collections: all("collection").iter().map(|c| c.to_string()).collect(), | ||
read_only: manage.is_empty() && s.actions.iter().all(reads), | ||
kind: s.space_type, | ||
authority: s.authority, | ||
skey: s.skey, | ||
collections: s.collections.unwrap_or_default(), | ||
writes, | ||
read_only, | ||
manage, | ||
}) | ||
} | ||
| @@ -118,6 +113,14 @@ impl SpaceScope { | ||
} | ||
} | ||
| ||
/// The collections `scope` names, if it is a repo scope. | ||
fn repo_collections(scope: &str) -> Option<Vec<String>> { | ||
match Scope::parse(scope) { | ||
Scope::Repo(r) => Some(r.collections), | ||
_ => None, | ||
} | ||
} | ||
| ||
/// Whether a holder of `actions`, with `rooms`, may have the scope `want`, | ||
/// which manages spaces: each thing it asks to do to spaces of its type | ||
/// they may do to any of the group's spaces, or, for one of a type named, | ||
| @@ -245,23 +248,17 @@ impl Host { | ||
Ok(rooms.iter().any(|r| !r.writable.is_empty())) | ||
} | ||
| ||
/// Whether `scope`, `rpc:method?aud=…` for one of this host's own | ||
/// methods, may be given to a holder of `held`: a method a group | ||
/// session calls ([`ASKS`], but the `internal` ones), for this host | ||
/// or any audience, and the roles hold the action it asks. | ||
fn own_method(&self, scope: &str, method: &str, held: &BTreeSet<&'static str>) -> bool { | ||
/// Whether `rpc`'s method `method`, one of this host's own, may be | ||
/// given to a holder of `held`: a method a group session calls | ||
/// ([`ASKS`], but the `internal` ones), for this host or any | ||
/// audience, and the roles hold the action it asks. | ||
fn own_method(&self, rpc: &Rpc, method: &str, held: &BTreeSet<&'static str>) -> bool { | ||
let internal = format!("{NS}.internal."); | ||
let asks = ASKS | ||
.iter() | ||
.find(|(m, _)| *m == method && !m.starts_with(&internal)); | ||
let decoded = decoded(scope); | ||
let query = decoded.split_once('?').map_or("", |(_, q)| q); | ||
let mut auds = query.split('&').filter_map(|kv| kv.strip_prefix("aud=")); | ||
let ours = |aud: &str| aud == "*" || crate::group_api::for_host(self, aud); | ||
let first = auds.next(); | ||
asks.is_some_and(|(_, action)| held.contains(action)) | ||
&& first.is_some_and(ours) | ||
&& auds.all(ours) | ||
let ours = rpc.aud == "*" || crate::group_api::for_host(self, &rpc.aud); | ||
asks.is_some_and(|(_, action)| held.contains(action)) && ours | ||
} | ||
| ||
/// The scopes of `requested` a holder of `roles` in `group` may give | ||
| @@ -310,6 +307,7 @@ impl Host { | ||
// What each scope asked for gives, in the order asked. | ||
let mut each: Vec<Vec<String>> = Vec::new(); | ||
for s in requested { | ||
let scope = Scope::parse(s); | ||
let space = SpaceScope::parse(s).filter(|w| w.for_group(group)); | ||
let keep = if s == "atproto" { | ||
true | ||
| @@ -330,16 +328,14 @@ impl Host { | ||
continue; | ||
} else if s == "transition:generic" || s == "transition:chat.bsky" { | ||
everything | ||
} else if let Some(named) = repo_collections(s) { | ||
let each = !named.is_empty() && named.iter().all(|c| repo.contains(c)); | ||
everything || each | ||
} else if let Some(m) = s.strip_prefix("rpc:") { | ||
let method = m.split('?').next().unwrap_or_default(); | ||
if method.starts_with(&format!("{NS}.")) { | ||
self.own_method(s, method, &held) | ||
} else { | ||
everything && method != "*" | ||
} | ||
} else if let Scope::Repo(r) = &scope { | ||
everything || r.collections.iter().all(|c| repo.contains(c)) | ||
} else if let Scope::Rpc(r) = &scope { | ||
let ours = format!("{NS}."); | ||
r.lxms.iter().all(|m| match m.starts_with(&ours) { | ||
true => self.own_method(r, m, &held), | ||
false => everything && m != "*", | ||
}) | ||
} else if let Some(want) = space.as_ref().filter(|w| !w.manage.is_empty()) { | ||
manages(want, &held, &rooms) | ||
} else if let Some(want) = inbox_scope(s) { | ||
| @@ -369,7 +365,7 @@ impl Host { | ||
let any_write = each.iter().flatten().any(writes); | ||
let mut out: Vec<String> = Vec::new(); | ||
for (s, mut gives) in requested.iter().zip(each) { | ||
if any_write && is_blob(s) { | ||
if any_write && matches!(Scope::parse(s), Scope::Blob(_)) { | ||
gives.push(s.clone()); | ||
} | ||
for g in gives { | ||
| @@ -391,10 +387,10 @@ impl Host { | ||
fn parts(set: &Value, actions: &BTreeSet<&'static str>, rooms: &[Room]) -> Vec<String> { | ||
let mut out = Vec::new(); | ||
for scope in scopes_of(set) { | ||
if let Some(rpc) = scope.strip_prefix("rpc:") { | ||
let method = rpc.split('?').next().unwrap_or_default(); | ||
let asks = ASKS.iter().find(|(m, _)| *m == method); | ||
if asks.is_some_and(|(_, a)| actions.contains(a)) { | ||
if let Scope::Rpc(rpc) = Scope::parse(&scope) { | ||
let asks = |l: &String| ASKS.iter().find(|(m, _)| m == l); | ||
let held = |l: &String| asks(l).is_some_and(|(_, a)| actions.contains(a)); | ||
if rpc.lxms.iter().all(held) { | ||
out.push(scope); | ||
} | ||
continue; | ||
| @@ -534,8 +530,9 @@ fn any_kind(group: &str, want: &SpaceScope, rooms: &[Room]) -> Vec<String> { | ||
| ||
/// A granted scope as the token carries it: a permission set, ours or | ||
/// another app's (as `sets` holds it), as the scopes it lists, | ||
/// `authority=self` as the group, and a space scope naming no collection | ||
/// as naming every one. | ||
/// `authority=self` as the group, a space scope naming no collection as | ||
/// naming every one, and a blob scope as a scope of each type it takes, | ||
/// written as atproto writes one ([`blob_scopes`]). | ||
pub fn concrete(granted: &[String], group: &str, sets: &Sets) -> String { | ||
let mut out: Vec<String> = Vec::new(); | ||
for s in granted { | ||
| @@ -554,8 +551,14 @@ pub fn concrete(granted: &[String], group: &str, sets: &Sets) -> String { | ||
"?collection=*" | ||
}); | ||
} | ||
if !out.contains(&s) { | ||
out.push(s); | ||
let each = match Scope::parse(&s) { | ||
Scope::Blob(b) => blob_scopes(&b), | ||
_ => vec![s], | ||
}; | ||
for s in each { | ||
if !out.contains(&s) { | ||
out.push(s); | ||
} | ||
} | ||
} | ||
} | ||
crates/group-host/src/permission_sets.rs+6−7
| @@ -19,9 +19,9 @@ | ||
| ||
use crate::Host; | ||
use crate::rbac::NS; | ||
use crate::scopes::{decoded, named, query}; | ||
use atproto::did; | ||
use atproto::syntax::{is_did, is_nsid}; | ||
use atproto::scope::Scope; | ||
use atproto::syntax::is_did; | ||
use reqwest::Url; | ||
use serde_json::{Value, json}; | ||
use std::collections::{BTreeMap, HashMap}; | ||
| @@ -49,11 +49,10 @@ pub struct Read(Mutex<HashMap<String, (i64, Option<Value>)>>); | ||
/// The NSID an `include:` scope names, and its audience, if it is one of | ||
/// another app's sets. | ||
pub fn include(scope: &str) -> Option<(String, Option<String>)> { | ||
let scope = decoded(scope); | ||
let nsid = named(&scope, "include")?; | ||
let aud = query(&scope, "aud").first().map(|a| a.to_string()); | ||
let ours = nsid.starts_with(&format!("{NS}.")); | ||
(is_nsid(nsid) && !ours).then(|| (nsid.to_string(), aud)) | ||
match Scope::parse(scope) { | ||
Scope::Include(i) if !i.nsid.starts_with(&format!("{NS}.")) => Some((i.nsid, i.aud)), | ||
_ => None, | ||
} | ||
} | ||
| ||
/// Whether `nsid` is within the namespace of the set `set`: its NSID up | ||
crates/group-host/src/rbac.rs+61−66
| @@ -12,7 +12,8 @@ | ||
| ||
use crate::group::{members_space, meta_space}; | ||
use crate::oauth_scope::{concrete, scopes_of, set_of}; | ||
use crate::scopes::{Permissions, decoded}; | ||
use crate::scopes::Permissions; | ||
use atproto::scope::{Scope, Space, SpaceAction, Write}; | ||
use atproto::space::SpaceRef; | ||
use serde_json::Value; | ||
use std::collections::{BTreeMap, BTreeSet}; | ||
| @@ -156,7 +157,8 @@ impl Policy { | ||
let mut out: BTreeMap<String, BTreeSet<String>> = BTreeMap::new(); | ||
for scope in self.permissions(roles) { | ||
let held = self.held(std::slice::from_ref(&scope)); | ||
for collection in query_of(&decoded(&scope), "collection") { | ||
let named = space_of(&scope).and_then(|s| s.collections); | ||
for collection in named.into_iter().flatten() { | ||
for action in WRITES { | ||
if held.space(&self.space, Some(&collection), action) { | ||
out.entry(collection.clone()) | ||
| @@ -179,9 +181,12 @@ fn strings(value: &Value) -> Vec<String> { | ||
items.filter_map(|s| s.as_str().map(String::from)).collect() | ||
} | ||
| ||
/// The values of `name` in a scope's query, owned. | ||
fn query_of(scope: &str, name: &str) -> Vec<String> { | ||
query(scope, name).into_iter().map(String::from).collect() | ||
/// The space scope `scope` is, if it is one. | ||
fn space_of(scope: &str) -> Option<Space> { | ||
match Scope::parse(scope) { | ||
Scope::Space(s) => Some(s), | ||
_ => None, | ||
} | ||
} | ||
| ||
/// The actions a host method's `rpc:` permission grants, by method. | ||
| @@ -225,47 +230,58 @@ pub fn scope_of(action: &str) -> Option<String> { | ||
}) | ||
} | ||
| ||
/// The values of `name` in a scope's query. | ||
fn query<'a>(scope: &'a str, name: &str) -> Vec<&'a str> { | ||
let q = scope.split_once('?').map_or("", |(_, q)| q); | ||
q.split('&') | ||
.filter_map(|kv| kv.split_once('=')) | ||
.filter(|(k, _)| *k == name) | ||
.map(|(_, v)| v) | ||
.collect() | ||
} | ||
| ||
/// What a space scope lets its holder do of writing memberships: `admit` | ||
/// for making one, `role.assign` for changing one, `eject` for deleting | ||
/// one, in the members space or in every space. | ||
fn membership_actions(scope: &str, out: &mut BTreeSet<&'static str>) { | ||
let Some(rest) = scope.strip_prefix("space:") else { | ||
return; | ||
}; | ||
let kind = rest.split('?').next().unwrap_or_default(); | ||
let members = kind == "*" || kind == format!("{NS}.members"); | ||
if !members || !query(scope, "manage").is_empty() { | ||
return; | ||
} | ||
let collections = query(scope, "collection"); | ||
fn membership_actions(scope: &Space, out: &mut BTreeSet<&'static str>) { | ||
let members = scope.space_type == "*" || scope.space_type == format!("{NS}.members"); | ||
let membership = format!("{NS}.membership"); | ||
let any = collections.is_empty() || collections.contains(&"*"); | ||
if !any && !collections.contains(&membership.as_str()) { | ||
let named = |c: &Vec<String>| c.iter().any(|c| *c == "*" || *c == membership); | ||
if !members || scope.manage.is_some() || !scope.collections.as_ref().is_none_or(named) { | ||
return; | ||
} | ||
let named = query(scope, "action"); | ||
let writes = [ | ||
("create", "admit"), | ||
("update", "role.assign"), | ||
("delete", "eject"), | ||
(SpaceAction::Create, "admit"), | ||
(SpaceAction::Update, "role.assign"), | ||
(SpaceAction::Delete, "eject"), | ||
]; | ||
for (write, action) in writes { | ||
if named.is_empty() || named.contains(&write) { | ||
if scope.actions.contains(&write) { | ||
out.insert(action); | ||
} | ||
} | ||
} | ||
| ||
/// What a space scope lets its holder do: write memberships, invites in | ||
/// people's inboxes, labels in every space, and make, change and end | ||
/// spaces of every type. | ||
fn space_actions(scope: &Space, out: &mut BTreeSet<&'static str>) { | ||
membership_actions(scope, out); | ||
let collections = scope.collections.as_deref().unwrap_or_default(); | ||
if scope.space_type == format!("{NS}.inbox") { | ||
// Invites written in people's inboxes. | ||
if collections.contains(&format!("{NS}.invite")) { | ||
out.insert("invite"); | ||
} | ||
} else if scope.space_type == "*" { | ||
let manage = scope.manage.as_deref().unwrap_or_default(); | ||
let ops = [ | ||
(Write::Create, "space.create"), | ||
(Write::Update, "space.configure"), | ||
(Write::Delete, "space.delete"), | ||
]; | ||
for (op, action) in ops { | ||
if manage.contains(&op) { | ||
out.insert(action); | ||
} | ||
} | ||
let every = |c: &String| c == "*" || c == LABEL; | ||
if scope.manage.is_none() && (collections.is_empty() || collections.iter().any(every)) { | ||
out.insert("label"); | ||
} | ||
} | ||
} | ||
| ||
/// What these permissions let their holder do: each of the group's | ||
/// permission sets as the permissions its lexicon lists, and | ||
/// `authManageAdmin` `group.configure` beside. A permission that is none | ||
| @@ -273,44 +289,20 @@ fn membership_actions(scope: &str, out: &mut BTreeSet<&'static str>) { | ||
pub fn actions_of(scopes: &[String]) -> BTreeSet<&'static str> { | ||
let mut out = BTreeSet::new(); | ||
for scope in scopes { | ||
membership_actions(scope, &mut out); | ||
if let Some(set) = set_of(scope) { | ||
out.extend(actions_of(&scopes_of(set))); | ||
if *scope == format!("include:{NS}.{ADMIN_SET}") { | ||
out.insert("group.configure"); | ||
} | ||
} else if let Some(rpc) = scope.strip_prefix("rpc:") { | ||
let method = rpc.split('?').next().unwrap_or_default(); | ||
let action = BY_METHOD | ||
.iter() | ||
.find(|(m, _)| method == format!("{NS}.{m}")); | ||
if let Some((_, action)) = action { | ||
out.insert(*action); | ||
} | ||
} else if scope.starts_with(&format!("space:{NS}.inbox?")) { | ||
// Invites written in people's inboxes. | ||
if query(scope, "collection").contains(&format!("{NS}.invite").as_str()) { | ||
out.insert("invite"); | ||
} | ||
} else if scope.starts_with("space:*") { | ||
let manage = query(scope, "manage"); | ||
if manage.contains(&"create") { | ||
out.insert("space.create"); | ||
} | ||
if manage.contains(&"update") { | ||
out.insert("space.configure"); | ||
} | ||
if manage.contains(&"delete") { | ||
out.insert("space.delete"); | ||
} | ||
if !manage.is_empty() { | ||
continue; | ||
} | ||
let collections = query(scope, "collection"); | ||
let every = collections.is_empty() || collections.contains(&"*"); | ||
if every || collections.contains(&LABEL) { | ||
out.insert("label"); | ||
continue; | ||
} | ||
match Scope::parse(scope) { | ||
Scope::Rpc(rpc) => { | ||
let ours = |m: &&(&str, &str)| rpc.lxms.contains(&format!("{NS}.{}", m.0)); | ||
out.extend(BY_METHOD.iter().filter(ours).map(|(_, a)| *a)); | ||
} | ||
Scope::Space(space) => space_actions(&space, &mut out), | ||
_ => {} | ||
} | ||
} | ||
out | ||
| @@ -375,12 +367,15 @@ pub fn actions_for(grants: &[Grant], roles: &[String]) -> BTreeSet<&'static str> | ||
| ||
/// The public-repo collections a holder of `roles` may write as the group. | ||
pub fn repo_collections_for(grants: &[Grant], roles: &[String]) -> BTreeSet<String> { | ||
let collections = |s: &String| match Scope::parse(s) { | ||
Scope::Repo(r) => r.collections, | ||
_ => Vec::new(), | ||
}; | ||
grants | ||
.iter() | ||
.filter(|g| roles.contains(&g.role)) | ||
.flat_map(|g| g.permissions.iter()) | ||
.filter_map(|s| s.strip_prefix("repo:")) | ||
.map(|c| c.split('?').next().unwrap_or_default().to_string()) | ||
.flat_map(collections) | ||
.collect() | ||
} | ||
| ||
crates/group-host/src/scopes.rs+260−252
512 lines changed: not loaded until asked for.
crates/group-host/src/store.rs+17−0
| @@ -5,6 +5,7 @@ | ||
| ||
use anyhow::{Context, Result}; | ||
use atproto::{Cid, Curve, Keypair}; | ||
use rusqlite::functions::FunctionFlags; | ||
use rusqlite::{Connection, OptionalExtension, params}; | ||
use std::collections::BTreeMap; | ||
use std::path::Path; | ||
| @@ -576,6 +577,14 @@ pub const MIGRATIONS: &[&str] = &[ | ||
did TEXT PRIMARY KEY, | ||
session TEXT NOT NULL | ||
); | ||
", | ||
// Scopes are read as atproto's reference reads them: each token's, | ||
// and each approved request's, written so that it grants what it did | ||
// (`scopes::upgraded`, which `Store::open` gives SQL as | ||
// `upgraded_scope`). | ||
" | ||
UPDATE oauth_token SET scope = upgraded_scope(scope); | ||
UPDATE oauth_request SET scope = upgraded_scope(scope) WHERE scope IS NOT NULL; | ||
", | ||
]; | ||
| ||
| @@ -1076,6 +1085,12 @@ fn record(row: &rusqlite::Row) -> rusqlite::Result<Record> { | ||
}) | ||
} | ||
| ||
/// A scope as [`crate::scopes::upgraded`] writes it, for the migration | ||
/// that rewrites those kept. | ||
fn upgraded_scope(ctx: &mut rusqlite::functions::Context) -> rusqlite::Result<String> { | ||
Ok(crate::scopes::upgraded(&ctx.get::<String>(0)?)) | ||
} | ||
| ||
impl Store { | ||
/// The database at `path`, made or brought up to date. `:memory:` for | ||
/// one that lasts as long as the process. | ||
| @@ -1084,6 +1099,8 @@ impl Store { | ||
let mut conn = Connection::open(path).context(opening)?; | ||
conn.pragma_update(None, "journal_mode", "wal")?; | ||
conn.pragma_update(None, "foreign_keys", true)?; | ||
let pure = FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC; | ||
conn.create_scalar_function("upgraded_scope", 1, pure, upgraded_scope)?; | ||
let version: i64 = conn.pragma_query_value(None, "user_version", |r| r.get(0))?; | ||
let tx = conn.transaction()?; | ||
for (i, migration) in (0..).zip(MIGRATIONS).skip(version as usize) { | ||
crates/group-host/tests/members.rs+18−7
| @@ -408,8 +408,8 @@ fn reads_a_scope_as_covered_by_those_held() { | ||
"repo:*", | ||
"space:com.example.calendar?skey=rides&collection=com.example.event", | ||
"space:*?manage=create", | ||
"rpc:com.example.thing?aud=did:web:example.com", | ||
"rpc:*?aud=*", | ||
"rpc:com.example.thing?aud=did:web:example.com%23svc", | ||
"rpc:*?aud=did:web:example.com%23svc", | ||
"blob:image/*", | ||
] | ||
.map(String::from) | ||
| @@ -423,9 +423,10 @@ fn reads_a_scope_as_covered_by_those_held() { | ||
"space:com.example.calendar?skey=rides&action=read", | ||
"space?spaceType=com.example.calendar&skey=rides&collection=com.example.event", | ||
"space:com.example.thing?manage=create", | ||
"rpc:com.example.other?aud=did:web:example.com", | ||
"rpc:com.example.other?aud=did:web:example.com%23svc", | ||
"rpc?lxm=com.example.thing&lxm=com.example.other&aud=did:web:example.com%23svc", | ||
"blob:image/png", | ||
"blob?accept=image/jpeg", | ||
"blob?accept=image/jpeg&accept=image/*", | ||
] { | ||
assert!(some(yes), "{yes}"); | ||
} | ||
| @@ -437,23 +438,33 @@ fn reads_a_scope_as_covered_by_those_held() { | ||
"space?skey=rides", | ||
"space:*?manage=delete", | ||
"blob:video/*", | ||
"blob:Image/png", | ||
"blob?action=x", | ||
"rpc:com.example.thing?aud=did:web:other.example%23svc", | ||
"rpc:*?aud=*", | ||
"transition:generic", | ||
] { | ||
assert!(!some(no), "{no}"); | ||
} | ||
let narrow = ["rpc:com.example.thing?aud=did:web:example.com".to_string()]; | ||
let narrow = ["rpc:com.example.thing?aud=did:web:example.com%23svc".to_string()]; | ||
assert!(covers( | ||
&narrow, | ||
"rpc:com.example.thing?aud=did:web:example.com", | ||
"rpc:com.example.thing?aud=did:web:example.com%23svc", | ||
group | ||
)); | ||
assert!(!covers(&narrow, "rpc:com.example.thing?aud=*", group)); | ||
assert!(!covers( | ||
&narrow, | ||
"rpc:com.example.other?aud=did:web:example.com", | ||
"rpc:com.example.other?aud=did:web:example.com%23svc", | ||
group | ||
)); | ||
// An app password's scope writes any record and takes any file. | ||
let generic = ["transition:generic".to_string()]; | ||
assert!(covers(&generic, "repo:a.b.c", group)); | ||
assert!(covers(&generic, "blob:*/*", group)); | ||
assert!(!covers(&generic, "space:*?collection=*", group)); | ||
let any = ["blob:*/*".to_string()]; | ||
assert!(covers(&any, "blob?accept=video/*&accept=text/plain", group)); | ||
} | ||
| ||
#[tokio::test] | ||
crates/group-host/tests/oauth_scope.rs+20−10
| @@ -728,16 +728,21 @@ fn makes_a_permission_set_concrete() { | ||
| ||
#[test] | ||
fn reads_a_space_scope() { | ||
let s = SpaceScope::parse("space:com.example.calendar?skey=rides&collection=a&collection=b&action=create&manage=create").unwrap(); | ||
let s = SpaceScope::parse("space:com.example.calendar?skey=rides&collection=a.b.c&collection=d.e.f&action=create&manage=create").unwrap(); | ||
assert_eq!(s.kind, "com.example.calendar"); | ||
assert_eq!((s.authority.as_str(), s.skey.as_str()), ("*", "rides")); | ||
assert_eq!(s.collections, ["a", "b"]); | ||
assert_eq!((s.authority.as_str(), s.skey.as_str()), ("self", "rides")); | ||
assert_eq!(s.collections, ["a.b.c", "d.e.f"]); | ||
assert_eq!(s.writes, ["create"]); | ||
assert_eq!(s.manage, ["create"]); | ||
assert!(!s.read_only); | ||
let s = SpaceScope::parse("space:*").unwrap(); | ||
assert_eq!(s.writes, ["create", "update", "delete"]); | ||
assert!(!s.read_only); | ||
assert_eq!(SpaceScope::parse("repo:x"), None); | ||
let s = SpaceScope::parse("space:*?action=read&action=read_self").unwrap(); | ||
assert!(s.read_only); | ||
assert_eq!(SpaceScope::parse("repo:x.y.z"), None); | ||
// A scope atproto's grammar does not take is none. | ||
assert_eq!(SpaceScope::parse("space:*?action=frob"), None); | ||
} | ||
| ||
#[test] | ||
| @@ -745,15 +750,20 @@ fn unions_a_roles_writes() { | ||
let space = SpaceRef::parse("at:space/did:plc:g/com.example.calendar/rides").unwrap(); | ||
let at = "space:com.example.calendar"; | ||
let policy = json!({"grants": [ | ||
{"role": "a", "permissions": [format!("{at}?collection=x&action=create"), format!("{at}?collection=y")]}, | ||
{"role": "b", "permissions": [format!("{at}?collection=x&action=delete&action=other")]}, | ||
{"role": "c", "permissions": [format!("{at}?collection=z")]}, | ||
{"role": "a", "permissions": [format!("{at}?collection=a.b.x&action=create"), format!("{at}?collection=a.b.y")]}, | ||
{"role": "b", "permissions": [format!("{at}?collection=a.b.x&action=delete"), format!("{at}?collection=a.b.w&action=delete&action=other")]}, | ||
{"role": "c", "permissions": [format!("{at}?collection=a.b.z"), "repo:a.b.q".to_string()]}, | ||
]}); | ||
let writes = Policy::of(&policy, &space).writes(&roles(&["a", "b"])); | ||
let x: Vec<&str> = writes["x"].iter().map(String::as_str).collect(); | ||
let x: Vec<&str> = writes["a.b.x"].iter().map(String::as_str).collect(); | ||
assert_eq!(x, ["create", "delete"]); | ||
assert_eq!(writes["y"].len(), 3); | ||
assert!(!writes.contains_key("z")); | ||
assert_eq!(writes["a.b.y"].len(), 3); | ||
assert!(!writes.contains_key("a.b.z")); | ||
// A permission naming an action there is none of grants nothing. | ||
assert!(!writes.contains_key("a.b.w")); | ||
// Nor does one that is no space scope. | ||
let c = Policy::of(&policy, &space).writes(&roles(&["c"])); | ||
assert_eq!(c.keys().collect::<Vec<_>>(), ["a.b.z"]); | ||
assert!( | ||
Policy::of(&json!({}), &space) | ||
.writes(&roles(&["a"])) | ||
crates/group-host/tests/rbac.rs+9−9
| @@ -47,7 +47,7 @@ fn reads_writes_and_manages_by_the_policy() { | ||
"space:xyz.app.forum?manage=update", | ||
"space:xyz.app.calendar?skey=laps&manage=update", | ||
"space:xyz.app.calendar?authority=did:plc:other&manage=update", | ||
"repo:xyz.event", | ||
"repo:xyz.app.event", | ||
] { | ||
let p = policy(json!({"grants": [{"role": "member", "permissions": [elsewhere]}]})); | ||
assert!(!p.manages(&roles(&["member"]), "update"), "{elsewhere}"); | ||
| @@ -65,8 +65,8 @@ fn reads_writes_and_manages_by_the_policy() { | ||
// What a role writes as the group: each collection a permission names, | ||
// as its actions say, every write when it names none. | ||
let writers = policy(json!({"grants": [ | ||
{"role": "admin", "permissions": ["space:xyz.app.calendar?collection=xyz.event&collection=xyz.rsvp", "space:xyz.app.forum?collection=xyz.post"]}, | ||
{"role": "member", "read": true, "permissions": ["space:xyz.app.calendar?collection=xyz.rsvp&action=create"]}, | ||
{"role": "admin", "permissions": ["space:xyz.app.calendar?collection=xyz.app.event&collection=xyz.app.rsvp", "space:xyz.app.forum?collection=xyz.app.post"]}, | ||
{"role": "member", "read": true, "permissions": ["space:xyz.app.calendar?collection=xyz.app.rsvp&action=create"]}, | ||
]})); | ||
let writes = writers.writes(&roles(&["admin", "member"])); | ||
let as_lists: Vec<(&str, Vec<&str>)> = writes | ||
| @@ -76,12 +76,12 @@ fn reads_writes_and_manages_by_the_policy() { | ||
assert_eq!( | ||
as_lists, | ||
[ | ||
("xyz.event", vec!["create", "delete", "update"]), | ||
("xyz.rsvp", vec!["create", "delete", "update"]), | ||
("xyz.app.event", vec!["create", "delete", "update"]), | ||
("xyz.app.rsvp", vec!["create", "delete", "update"]), | ||
] | ||
); | ||
let member = writers.writes(&roles(&["member"])); | ||
assert_eq!(member["xyz.rsvp"].len(), 1); | ||
assert_eq!(member["xyz.app.rsvp"].len(), 1); | ||
assert_eq!(writers.permissions(&roles(&["member"])).len(), 1); | ||
assert_eq!( | ||
listed(&json!({"x": [{"role": 1}, {"role": "a"}]}), "x", "role"), | ||
| @@ -183,7 +183,7 @@ fn answers_each_action_by_its_scope() { | ||
manage.into_iter().collect::<Vec<_>>(), | ||
["space.create", "space.delete"] | ||
); | ||
let other = actions_of(&["space:*?collection=xyz.task".into()]); | ||
let other = actions_of(&["space:*?collection=xyz.app.task".into()]); | ||
assert!(other.is_empty()); | ||
} | ||
| ||
| @@ -203,7 +203,7 @@ fn roles_compose_by_union() { | ||
"mod", | ||
&["label"], | ||
&[], | ||
&["xyz.post?action=create"], | ||
&["xyz.app.post?action=create"], | ||
)), | ||
), | ||
("odd".into(), json!({"displayName": "Odd"})), | ||
| @@ -221,7 +221,7 @@ fn roles_compose_by_union() { | ||
repo_collections_for(&granted, &both) | ||
.into_iter() | ||
.collect::<Vec<_>>(), | ||
["*", "xyz.post"] | ||
["*", "xyz.app.post"] | ||
); | ||
assert!(actions_for(&granted, &[]).is_empty()); | ||
assert!(grants(&[]).is_empty()); | ||
crates/group-host/tests/tokens.rs+83−8
| @@ -858,19 +858,22 @@ fn reads_a_scope_as_atproto_has_it() { | ||
use group_host::scopes::Permissions; | ||
let group = "did:plc:riders"; | ||
let p = Permissions::new( | ||
"atproto repo?collection=a.b.c&collection=d.e.f&action=create repo:g.h.i?action=delete&action=other repository:x.y.z blob?accept=video/mp4 blob:image/*,text/plain", | ||
"atproto repo?collection=a.b.c&collection=d.e.f&action=create repo:g.h.i?action=delete repo:j.k.l?action=delete&action=other repository:x.y.z blob?accept=video/mp4 blob:image/* blob:text/plain,text/html", | ||
group, | ||
); | ||
assert!(p.repo("a.b.c", "create") && p.repo("d.e.f", "create")); | ||
assert!(!p.repo("a.b.c", "update")); | ||
assert!(!p.repo("a.b.c", "update") && !p.repo("a.b.c", "upsert")); | ||
assert!(p.repo("g.h.i", "delete") && !p.repo("g.h.i", "create")); | ||
// A scope naming an action there is none of is no scope. | ||
assert!(!p.repo("j.k.l", "delete")); | ||
assert!(!p.repo("x.y.z", "create")); | ||
assert!(Permissions::new("repo:*", group).repo("any.thing.here", "update")); | ||
assert!(p.blob("video/mp4") && p.blob("IMAGE/png") && p.blob("text/plain")); | ||
assert!(!p.blob("text/html") && !p.blob("video/webm")); | ||
// A blob scope takes one type or pattern, compared as written. | ||
assert!(p.blob("video/mp4") && p.blob("image/png")); | ||
assert!(!p.blob("IMAGE/png") && !p.blob("text/plain") && !p.blob("video/webm")); | ||
assert!(Permissions::new("blob:*/*", group).blob("application/zip")); | ||
// Escaped values read as they are meant; an escape of what shapes a | ||
// scope, or none at all, stays as written. | ||
// Escaped values read as they are meant, each value on its own, so | ||
// an escaped `&` or `=` stays in its value. | ||
let ours = SpaceRef::parse("at:space/did:plc:riders/com.example.calendar/rides").unwrap(); | ||
let p = Permissions::new( | ||
"space:com.example.calendar?authority=did%3Aplc%3Ariders&collection=a.b%2Ec", | ||
| @@ -1055,8 +1058,10 @@ async fn calls_the_hosts_own_methods_with_an_rpc_scope() { | ||
.await; | ||
assert_eq!(said.error(), (400, "SubjectNotFound")); | ||
| ||
// Or for this host by name, or through one of its permission sets. | ||
let ours = &h.host.config.service_did; | ||
// Or for this host's service by name, its value escaped as an app's | ||
// URLSearchParams writes it, or through one of its permission sets. | ||
let ours = format!("{}#atgrp", h.host.config.service_did); | ||
let ours = ours.replace('%', "%25").replace('#', "%23"); | ||
let named = format!("atproto rpc:{NS}.mod.querySubjects?aud={ours}"); | ||
for scope in [named.as_str(), "atproto include:org.atgrp.authModerate"] { | ||
let app = App::loopback(scope); | ||
| @@ -1248,3 +1253,73 @@ async fn what_a_grant_bought_ends_once_its_member_reads_no_more() { | ||
.await; | ||
assert_eq!(said.status, 200, "{}", said.body); | ||
} | ||
| ||
#[test] | ||
fn a_token_from_before_keeps_what_its_scope_granted() { | ||
use group_host::store::{MIGRATIONS, Store}; | ||
let dir = tempfile::tempdir().unwrap(); | ||
let path = dir.path().join("host.sqlite"); | ||
drop(Store::open(&path).unwrap()); | ||
// Back to before scopes were read as atproto reads them, with a token | ||
// whose scope this host took then as an app asked for it. | ||
let conn = rusqlite::Connection::open(&path).unwrap(); | ||
let account = "INSERT INTO account (did, handle, signing_key, kem_key, created_at) VALUES ('did:plc:g', 'g.test', x'', x'', 0)"; | ||
conn.execute(account, []).unwrap(); | ||
let before = [ | ||
"atproto", | ||
"repo:app.bsky.feed.post?action=create&action=upsert", | ||
"repo:app.bsky.feed.like?collection=app.bsky.feed.repost", | ||
"repo:a.b.c?action=bogus", | ||
"repository:x.y.z", | ||
"blob:image/*,VIDEO/MP4", | ||
"blob:IMAGE/*", | ||
"blob?accept=Image/PNG", | ||
"blob?accept=image/svg+xml", | ||
"blob:*", | ||
"space:com.example.calendar?authority=did:plc:g&skey=*&collection=com.example.event&action=read&action=create&action=frob&foo=bar", | ||
"space:com.example.calendar?spaceType=com.example.other&skey=a&skey=b&manage=create&manage=frob", | ||
"space:com.example.calendar?foo=1", | ||
"rpc:com.example.get?aud=did:web:x.example%23svc&aud=did:web:y.example%23svc", | ||
"rpc:com.example.get?aud=did:web:nofragment", | ||
"rpc:org.atgrp.mod.querySubjects?aud=did:web:groups.example", | ||
] | ||
.join(" "); | ||
let token = "INSERT INTO oauth_token (id, grp, member, client_id, client_auth, scope, dpop_jkt, access_hash, access_expires, refresh_hash, expires_at, created_at) VALUES ('t', 'did:plc:g', 'did:plc:m', 'https://app.example/client.json', '{}', ?1, 'jkt', 'a', 0, 'r', 0, 0)"; | ||
conn.execute(token, [&before]).unwrap(); | ||
let upgrade = MIGRATIONS | ||
.iter() | ||
.position(|m| m.contains("upgraded_scope")) | ||
.unwrap(); | ||
common::rewind(&conn, upgrade); | ||
drop(conn); | ||
drop(Store::open(&path).unwrap()); | ||
let conn = rusqlite::Connection::open(&path).unwrap(); | ||
let scope: String = conn | ||
.query_row("SELECT scope FROM oauth_token", [], |r| r.get(0)) | ||
.unwrap(); | ||
let after = [ | ||
"atproto", | ||
"repo:app.bsky.feed.post?action=create", | ||
"repo:app.bsky.feed.like", | ||
"repo:a.b.c?action=bogus", | ||
"repository:x.y.z", | ||
"blob:image/*", | ||
"blob:video/mp4", | ||
"blob:image/png", | ||
"blob:image/svg+xml", | ||
"space:com.example.calendar?authority=did:plc:g&skey=*&collection=com.example.event&action=read&action=create", | ||
"space:com.example.calendar?skey=a&manage=create", | ||
"space:com.example.calendar", | ||
"rpc:com.example.get?aud=did:web:x.example%23svc", | ||
"rpc:com.example.get?aud=did:web:nofragment", | ||
"rpc:org.atgrp.mod.querySubjects?aud=did:web:groups.example%23atgrp", | ||
]; | ||
assert_eq!(scope.split(' ').collect::<Vec<_>>(), after); | ||
// And grants, read as atproto reads it, what it did. | ||
let p = group_host::scopes::Permissions::new(&scope, "did:plc:g"); | ||
assert!(p.repo("app.bsky.feed.post", "create") && !p.repo("app.bsky.feed.post", "delete")); | ||
assert!(p.blob("video/mp4") && p.blob("image/png") && p.blob("image/svg+xml")); | ||
assert!(p.rpc("com.example.get", "did:web:x.example#svc")); | ||
let here = |aud: &str| aud == "did:web:groups.example#atgrp"; | ||
assert!(p.calls("org.atgrp.mod.querySubjects", here)); | ||
} | ||