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

Scopes are read in every form atproto writes them

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:host/scope-forms
crates/group-host/src/oauth_scope.rs+7−4
@@ -11,6 +11,7 @@
use crate::Host;
use crate::group::members_space;
use crate::rbac::{Access, NS, actions_for, grants, listed, repo_collections_for};
use crate::scopes::{decoded, is_blob, repo_collections};
use crate::xrpc::XrpcError;
use atproto::space::SpaceRef;
use serde_json::Value;
@@ -39,6 +40,7 @@ pub struct SpaceScope {
impl SpaceScope {
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();
@@ -217,8 +219,9 @@ impl Host {
true
} else if *s == configure() {
configures
} else if let Some(c) = s.strip_prefix("repo:") {
everything || repo.contains(c.split('?').next().unwrap_or_default())
} 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();
everything && method != "*" && !method.starts_with(&format!("{NS}."))
@@ -236,13 +239,13 @@ impl Host {
}
let writes = |s: &String| {
*s == configure()
|| s.starts_with("repo:")
|| repo_collections(s).is_some()
|| SpaceScope::parse(s).is_some_and(|w| !w.read_only)
};
let any_write = kept.iter().chain(&made).any(writes);
let mut out: Vec<String> = requested
.iter()
.filter(|s| kept.contains(s) || (any_write && s.starts_with("blob:")))
.filter(|s| kept.contains(s) || (any_write && is_blob(s)))
.cloned()
.collect();
for m in made {
crates/group-host/src/scopes.rs+36−1
@@ -14,6 +14,41 @@ const REPO_ACTIONS: [&str; 3] = ["create", "update", "delete"];
const SPACE_DEFAULT: [&str; 4] = ["read", "create", "update", "delete"];
const SPACE_ACTIONS: [&str; 5] = ["read_self", "read", "create", "update", "delete"];
/// `scope` with its percent-escapes read, as the permission spec reads a
/// scope's values (`authority=did%3Aplc%3Aabc` names `did:plc:abc`), but
/// for an escape of what shapes a scope (`%`, `&`, `=`, `?`), which stays
/// as written so that it cannot split a value.
pub fn decoded(scope: &str) -> String {
let bytes = scope.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
let hex = scope.get(i + 1..i + 3).filter(|_| bytes[i] == b'%');
let byte = hex.and_then(|h| u8::from_str_radix(h, 16).ok());
match byte.filter(|b| !b"%&=?".contains(b)) {
Some(b) => (out.push(b), i += 3),
None => (out.push(bytes[i]), i += 1),
};
}
String::from_utf8_lossy(&out).into_owned()
}
/// The collections a repo scope names, `repo:C` or `repo?collection=C…`,
/// if it is one.
pub fn repo_collections(scope: &str) -> Option<Vec<String>> {
let scope = decoded(scope);
let named = match named(&scope, "repo")? {
"" => query(&scope, "collection"),
r => vec![r],
};
Some(named.into_iter().map(String::from).collect())
}
/// Whether `scope` is a blob scope, `blob:…` or `blob?accept=…`.
pub fn is_blob(scope: &str) -> bool {
named(scope, "blob").is_some()
}
/// 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);
@@ -65,7 +100,7 @@ pub struct Permissions {
impl Permissions {
pub fn new(scope: &str, group: &str) -> Permissions {
let scopes = scope.split(' ').filter(|s| !s.is_empty()).map(String::from);
let scopes = scope.split(' ').filter(|s| !s.is_empty()).map(decoded);
Permissions {
scopes: scopes.collect(),
group: group.into(),
crates/group-host/tests/oauth_scope.rs+34−0
@@ -140,6 +140,40 @@ async fn keeps_for_each_role_what_its_grants_hold() {
assert_eq!(member, asked(&["atproto"]));
}
#[tokio::test]
async fn reads_every_form_a_scope_may_take() {
let h = start(&[], false).await;
let (did, _, alice) = group(&h).await;
// Collections named by query, files by type, and values escaped, as
// an app's URLSearchParams writes them.
let encoded = format!("space:{CALENDAR}?authority={}", did.replace(':', "%3A"));
let all = asked(&[
"atproto",
"repo?collection=app.bsky.feed.post&collection=app.bsky.feed.like",
"repo?collection=app.bsky.feed.post",
"blob?accept=image/*",
&encoded,
]);
let admin = h
.host
.narrow(&did, &roles(&["admin"]), &alice.did, &all)
.unwrap();
assert_eq!(admin, all);
// Kept only when every collection it names is one the roles write.
let poster = h
.host
.narrow(&did, &roles(&["poster"]), &alice.did, &all)
.unwrap();
assert_eq!(
poster,
asked(&[
"atproto",
"repo?collection=app.bsky.feed.post",
"blob?accept=image/*"
])
);
}
#[tokio::test]
async fn keeps_a_space_scope_a_spaces_access_record_grants() {
let h = start(&[], false).await;
crates/group-host/tests/tokens.rs+13−0
@@ -745,6 +745,19 @@ fn reads_a_scope_as_atproto_has_it() {
assert!(p.blob("video/mp4") && p.blob("IMAGE/png") && p.blob("text/plain"));
assert!(!p.blob("text/html") && !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.
let ours = SpaceRef::parse("at://did:plc:riders/space/com.example.calendar/rides").unwrap();
let p = Permissions::new(
"space:com.example.calendar?authority=did%3Aplc%3Ariders&collection=a.b%2Ec",
group,
);
assert!(p.space(&ours, Some("a.b.c"), "create"));
let p = Permissions::new(
"repo?collection=a.b.c%26action%3Ddelete&action=create%zz%4",
group,
);
assert!(!p.repo("a.b.c", "delete") && !p.repo("a.b.c", "create"));
let space = |uri: &str| SpaceRef::parse(uri).unwrap();
let ours = space("at://did:plc:riders/space/com.example.calendar/rides");