chadtmiller.com/monolith
An atproto PDS
0
0
//! `space:` permissions (`spec/OAUTH-SCOPES.md`, "Spaces"): a token read
//! into its parameters, its defaults filled; a token as a session's scope
//! keeps it, its declared collections and its `self` authority filled at
//! the code grant and each refresh; what one allows; and the scope a
//! refusal names.
use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, percent_decode_str, utf8_percent_encode};
use serde_json::Value as Json;
use std::collections::HashMap;
use std::sync::Arc;
/// The actions, in the order a scope string writes them.
pub(crate) const ACTIONS: [&str; 5] = ["read_self", "read", "create", "update", "delete"];
/// The actions a permission has when it names none.
const DEFAULT_ACTIONS: [&str; 4] = ["read", "create", "update", "delete"];
/// The management operations, in the order a scope string writes them.
pub(crate) const MANAGE: [&str; 3] = ["create", "update", "delete"];
/// What `encodeURIComponent` leaves as it is: letters, digits and `-_.!~*'()`.
const COMPONENT: &AsciiSet = &NON_ALPHANUMERIC
.remove(b'-')
.remove(b'_')
.remove(b'.')
.remove(b'!')
.remove(b'~')
.remove(b'*')
.remove(b'\'')
.remove(b'(')
.remove(b')');
/// What a form-encoded query leaves as it is: letters, digits and `*-._`.
const FORM: &AsciiSet = &NON_ALPHANUMERIC
.remove(b'*')
.remove(b'-')
.remove(b'.')
.remove(b'_');
/// `%3A`, `%2F`, `%2B`, `%2C`, `%40` and `%25` turned back to what they encode.
fn normalized(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut rest = s;
while let Some(i) = rest.find('%') {
out.push_str(&rest[..i]);
let code = rest.get(i..i + 3).unwrap_or(&rest[i..]);
let back = match code.to_ascii_uppercase().as_str() {
"%3A" => Some(':'),
"%2F" => Some('/'),
"%2B" => Some('+'),
"%2C" => Some(','),
"%40" => Some('@'),
"%25" => Some('%'),
_ => None,
};
match back {
Some(c) => {
out.push(c);
rest = &rest[i + code.len()..];
}
None => {
out.push('%');
rest = &rest[i + 1..];
}
}
}
out.push_str(rest);
out
}
/// A value of a form-encoded query, as `URLSearchParams` writes it.
fn form(v: &str) -> String {
utf8_percent_encode(v, FORM).to_string().replace("%20", "+")
}
/// A `space` permission, its defaults filled.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct SpacePermission {
pub space_type: String,
/// A DID, `self` or `*`.
pub authority: String,
/// A record key or `*`.
pub skey: String,
/// None: no collection given, so no write is allowed.
pub collections: Option<Vec<String>>,
pub actions: Vec<String>,
pub manage: Vec<String>,
}
/// A space operation's kind (`spec/OAUTH-SCOPES.md`, "What it allows").
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum SpaceOp<'a> {
/// `read` or `read_self`.
Read { whole: bool },
/// A write of `collection`: `create`, `update` or `delete`.
Write {
action: &'static str,
collection: &'a str,
},
/// Managing the space: `create`, `update` or `delete`.
Manage(&'static str),
}
/// A space operation: the space, by its authority, type and key (each may
/// be `*`, as `listSpaces` asks), and what is done.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct SpaceNeed<'a> {
pub authority: &'a str,
pub space_type: &'a str,
pub skey: &'a str,
pub op: SpaceOp<'a>,
}
impl SpacePermission {
/// The `space` permission a token is, if it is one that parses
/// (`super::scope::permission`).
pub fn of(token: &str) -> Option<SpacePermission> {
if !token.starts_with("space") || !super::scope::permission(token) {
return None;
}
let (head, query) = token.split_once('?').unwrap_or((token, ""));
let mut params: Vec<(String, String)> = Vec::new();
if let Some((_, p)) = head.split_once(':') {
params.push((
"spaceType".into(),
percent_decode_str(p).decode_utf8().ok()?.into_owned(),
));
}
params.extend(
url::form_urlencoded::parse(query.as_bytes())
.map(|(k, v)| (k.into_owned(), v.into_owned())),
);
let one = |k: &str| params.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone());
let all = |k: &str| {
let v: Vec<String> = params
.iter()
.filter(|(n, _)| n == k)
.map(|(_, v)| v.clone())
.collect();
(!v.is_empty()).then_some(v)
};
Some(SpacePermission::new(
one("spaceType")?,
one("authority"),
one("skey"),
all("collection"),
all("action"),
all("manage"),
))
}
/// A permission of these parameters, each as given, its defaults filled
/// where one is not: collections each once and sorted, or `*` alone;
/// actions and management in the order a scope string writes them.
pub fn new(
space_type: String,
authority: Option<String>,
skey: Option<String>,
collection: Option<Vec<String>>,
action: Option<Vec<String>>,
manage: Option<Vec<String>>,
) -> SpacePermission {
SpacePermission {
space_type,
authority: authority.unwrap_or_else(|| "self".into()),
skey: skey.unwrap_or_else(|| "*".into()),
collections: collection.map(|c| collections(&c)),
actions: ordered(
&ACTIONS,
&action.unwrap_or_else(|| DEFAULT_ACTIONS.map(String::from).to_vec()),
),
manage: ordered(&MANAGE, &manage.unwrap_or_default()),
}
}
/// The scope string it is written as (`spec/OAUTH-SCOPES.md`, "The
/// token's scope").
pub fn to_scope(&self) -> String {
let mut q: Vec<String> = Vec::new();
if self.authority != "self" {
q.push(format!("authority={}", form(&self.authority)));
}
if self.skey != "*" {
q.push(format!("skey={}", form(&self.skey)));
}
for c in self.collections.iter().flatten() {
q.push(format!("collection={}", form(c)));
}
let default = self.actions.len() == DEFAULT_ACTIONS.len()
&& DEFAULT_ACTIONS
.iter()
.all(|a| self.actions.iter().any(|x| x == a));
if !default {
q.extend(self.actions.iter().map(|a| format!("action={a}")));
}
q.extend(self.manage.iter().map(|m| format!("manage={m}")));
let head = format!(
"space:{}",
normalized(&utf8_percent_encode(&self.space_type, COMPONENT).to_string())
);
if q.is_empty() {
head
} else {
format!("{head}?{}", normalized(&q.join("&")))
}
}
/// Whether it allows `need`.
pub fn allows(&self, need: &SpaceNeed) -> bool {
let matches = |mine: &str, theirs: &str| mine == "*" || mine == theirs;
if !matches(&self.space_type, need.space_type)
|| self.authority == "self"
|| !matches(&self.authority, need.authority)
|| !matches(&self.skey, need.skey)
{
return false;
}
let has = |a: &str| self.actions.iter().any(|x| x == a);
match need.op {
SpaceOp::Read { whole: true } => has("read"),
SpaceOp::Read { whole: false } => has("read") || has("read_self"),
SpaceOp::Write { action, collection } => {
has(action)
&& self
.collections
.as_ref()
.is_some_and(|c| c.iter().any(|c| c == "*" || c == collection))
}
SpaceOp::Manage(m) => self.manage.iter().any(|x| x == m),
}
}
}
/// Collections as a scope string keeps them: several, each once and
/// sorted, or `*` alone if one is `*`.
fn collections(given: &[String]) -> Vec<String> {
if given.len() <= 1 {
return given.to_vec();
}
if given.iter().any(|c| c == "*") {
return vec!["*".into()];
}
let mut out = given.to_vec();
out.sort();
out.dedup();
out
}
/// Of `given`, those in `order`, in its order, each once.
fn ordered(order: &[&str], given: &[String]) -> Vec<String> {
order
.iter()
.filter(|o| given.iter().any(|g| g == *o))
.map(|o| o.to_string())
.collect()
}
impl SpaceNeed<'_> {
/// The scope a refusal names: the narrowest that would allow it.
pub fn scope(&self) -> String {
let (collections, actions, manage) = match self.op {
SpaceOp::Manage(m) => (None, vec!["read_self".to_string()], vec![m.to_string()]),
SpaceOp::Read { whole } => (
None,
vec![if whole { "read" } else { "read_self" }.to_string()],
vec![],
),
SpaceOp::Write { action, collection } => (
Some(vec![collection.to_string()]),
vec![action.to_string()],
vec![],
),
};
SpacePermission {
space_type: self.space_type.to_string(),
authority: self.authority.to_string(),
skey: self.skey.to_string(),
collections,
actions,
manage,
}
.to_scope()
}
}
/// The space types `space:` tokens name, each once, but `*`.
pub(crate) fn types<'a>(scope: impl IntoIterator<Item = &'a str>) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for p in scope.into_iter().filter_map(SpacePermission::of) {
if p.space_type != "*" && !out.contains(&p.space_type) {
out.push(p.space_type);
}
}
out
}
/// The DIDs `space:` tokens name as their `authority`, each once, in the
/// order first named: whose handles the authorization page verifies
/// (`spec/OAUTH-SCOPES.md`, "On the authorization page").
pub(crate) fn authorities<'a>(scope: impl IntoIterator<Item = &'a str>) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for p in scope.into_iter().filter_map(SpacePermission::of) {
if p.authority.starts_with("did:") && !out.contains(&p.authority) {
out.push(p.authority);
}
}
out
}
/// A token of a session's scope, as its tokens keep it
/// (`spec/OAUTH-SCOPES.md`, "The token's scope"): a `space:` token with no
/// collection gets its declaration's, and one of authority `self` gets
/// `did`; one neither changes, and every other token, is as given.
pub(crate) fn rewritten(
token: &str,
did: &str,
declarations: &HashMap<String, Arc<Json>>,
) -> String {
let Some(mut p) = SpacePermission::of(token) else {
return token.to_string();
};
let mut changed = false;
if p.collections.is_none() && p.space_type != "*" {
let declared: Vec<String> = declarations
.get(&p.space_type)
.and_then(|main| main["collections"].as_array())
.into_iter()
.flatten()
.filter_map(|c| c.as_str().map(str::to_string))
.collect();
if !declared.is_empty() {
p.collections = Some(collections(&declared));
changed = true;
}
}
if p.authority == "self" {
p.authority = did.to_string();
changed = true;
}
if changed {
p.to_scope()
} else {
token.to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn read_and_written() {
let p = SpacePermission::of("space:com.example.forum").unwrap();
assert_eq!(
(p.authority.as_str(), p.skey.as_str(), &p.collections),
("self", "*", &None)
);
assert_eq!(p.actions, ["read", "create", "update", "delete"]);
assert_eq!(p.to_scope(), "space:com.example.forum");
let p = SpacePermission::of(
"space?spaceType=com.example.forum&action=delete&action=read_self&manage=delete&manage=create&collection=b.c.d&collection=a.b.c&collection=a.b.c",
)
.unwrap();
assert_eq!(
p.to_scope(),
"space:com.example.forum?collection=a.b.c&collection=b.c.d&action=read_self&action=delete&manage=create&manage=delete"
);
assert_eq!(
SpacePermission::of("space:*?authority=*&collection=a.b.c&collection=*")
.unwrap()
.to_scope(),
"space:*?authority=*&collection=*"
);
assert!(SpacePermission::of("repo:*").is_none());
assert!(SpacePermission::of("space:com.example.forum?authority=me").is_none());
// The skey's `~` is percent-encoded, a DID's `:` and `%` are not.
let need = SpaceNeed {
authority: "did:web:localhost%3A1234",
space_type: "com.example.forum",
skey: "a~b",
op: SpaceOp::Write {
action: "create",
collection: "com.example.post",
},
};
assert_eq!(
need.scope(),
"space:com.example.forum?authority=did:web:localhost%3A1234&skey=a%7Eb&collection=com.example.post&action=create"
);
}
#[test]
fn rewritten_at_the_grant() {
let decl = HashMap::from([(
"com.example.forum".to_string(),
Arc::new(
json!({ "type": "space", "collections": ["com.example.thread", "com.example.reply"] }),
),
)]);
let did = "did:plc:abc";
let r = |t: &str| rewritten(t, did, &decl);
assert_eq!(
r("space:com.example.forum"),
"space:com.example.forum?authority=did:plc:abc&collection=com.example.reply&collection=com.example.thread"
);
assert_eq!(
r("space:com.example.forum?authority=did:plc:other&skey=*"),
"space:com.example.forum?authority=did:plc:other&collection=com.example.reply&collection=com.example.thread"
);
// Collections given, another authority: as given.
let kept = "space:com.example.forum?authority=*&collection=x.y.z&skey=*";
assert_eq!(r(kept), kept);
assert_eq!(
r("space:*?action=read"),
"space:*?authority=did:plc:abc&action=read"
);
// An undeclared type, or one declaring none: no collections.
assert_eq!(
r("space:com.example.other"),
"space:com.example.other?authority=did:plc:abc"
);
assert_eq!(r("atproto"), "atproto");
assert_eq!(
types([
"space:a.b.c",
"space:*",
"space:a.b.c?action=read",
"repo:*"
]),
["a.b.c"]
);
}
#[test]
fn what_it_allows() {
let p = |t: &str| SpacePermission::of(t).unwrap();
let need = |op| SpaceNeed {
authority: "did:plc:abc",
space_type: "com.example.forum",
skey: "main",
op,
};
let write = |action, collection| need(SpaceOp::Write { action, collection });
let granted =
p("space:com.example.forum?authority=did:plc:abc&collection=com.example.post");
assert!(granted.allows(&write("create", "com.example.post")));
assert!(!granted.allows(&write("create", "com.example.other")));
assert!(granted.allows(&need(SpaceOp::Read { whole: true })));
assert!(!granted.allows(&need(SpaceOp::Manage("create"))));
// `self` unresolved matches nothing; no collection allows no write.
assert!(!p("space:com.example.forum").allows(&need(SpaceOp::Read { whole: false })));
assert!(
!p("space:com.example.forum?authority=did:plc:abc")
.allows(&write("create", "com.example.post"))
);
let read_self = p("space:*?authority=*&action=read_self");
assert!(read_self.allows(&need(SpaceOp::Read { whole: false })));
assert!(!read_self.allows(&need(SpaceOp::Read { whole: true })));
assert!(read_self.allows(&SpaceNeed {
authority: "*",
space_type: "*",
skey: "*",
op: SpaceOp::Read { whole: false }
}));
// A grant of one type is no grant of every type.
assert!(!granted.allows(&SpaceNeed {
space_type: "*",
..need(SpaceOp::Read { whole: false })
}));
let manage = p(
"space:com.example.forum?authority=did:plc:abc&skey=main&manage=create&action=read_self",
);
assert!(manage.allows(&need(SpaceOp::Manage("create"))));
assert!(!manage.allows(&need(SpaceOp::Manage("delete"))));
assert!(
!p("space:com.example.forum?authority=did:plc:abc&skey=other&manage=create")
.allows(&need(SpaceOp::Manage("create")))
);
assert_eq!(
need(SpaceOp::Manage("create")).scope(),
"space:com.example.forum?authority=did:plc:abc&skey=main&action=read_self&manage=create"
);
assert_eq!(
SpaceNeed {
authority: "*",
space_type: "*",
skey: "*",
op: SpaceOp::Read { whole: false }
}
.scope(),
"space:*?authority=*&action=read_self"
);
}
}