chadtmiller.com/monolith
An atproto PDS
0
0
Permission sets grant space permissions, as the spaces alpha does
.changeset/set-space-permissions.mdnew+7−0
| @@ -0,0 +1,7 @@ | ||
--- | ||
default: minor | ||
--- | ||
| ||
# Permission sets grant space permissions | ||
| ||
A permission set may now grant `space` permissions, as the spaces proposal and the reference's spaces alpha allow. Each one's `spaceType` must be under the set's own namespace, and never `*`; its collections may be anywhere. An `include:` of such a set gives the token's scope those `space:` permissions. They are written and rewritten as a `space:` scope asked for directly would be: a bare type gets the collections its declaration lists, and `self` becomes the account's DID. The authorization page and the code grant resolve those space types' declarations too. Before this, a set's `space` permissions were dropped, so an app that asked for its space access through a set got a token the space methods refused. | ||
crates/pds-server/src/oauth/page.rs+6−3
| @@ -443,11 +443,14 @@ pub(super) async fn authorize( | ||
}; | ||
// Each set the request includes, resolved again | ||
// (`spec/OAUTH-PERMISSION-SETS.md`); then each space type it names, | ||
// one that cannot be used ending the request, which is sent back | ||
// to its client (`spec/OAUTH-SCOPES.md`, "Space type declarations"). | ||
// its sets' too, one that cannot be used ending the request, which | ||
// is sent back to its client (`spec/OAUTH-SCOPES.md`, "Space type | ||
// declarations"). | ||
let scope = &loaded.request.scope; | ||
let sets = svc.oauth.sets.resolve_all(&svc, scope).await; | ||
if sets.is_ok() && svc.oauth.sets.resolve_spaces(&svc, scope).await.is_err() { | ||
if let Ok(s) = &sets | ||
&& svc.oauth.sets.resolve_spaces(&svc, scope, s).await.is_err() | ||
{ | ||
let mut tx = Tx::new(&svc); | ||
let ended = tx.change(|st, _| match st.requests.get(id) { | ||
Some(r) => { | ||
crates/pds-server/src/oauth/scope.rs+6−6
| @@ -46,11 +46,11 @@ pub(crate) fn kept(tokens: &[&str]) -> Vec<String> { | ||
| ||
/// A parameter a resource takes: its name, whether it takes more than one | ||
/// value, whether it is required, and the values it allows. | ||
struct Param { | ||
name: &'static str, | ||
many: bool, | ||
required: bool, | ||
allows: fn(&str) -> bool, | ||
pub(crate) struct Param { | ||
pub name: &'static str, | ||
pub many: bool, | ||
pub required: bool, | ||
pub allows: fn(&str) -> bool, | ||
} | ||
| ||
fn nsid_or_any(v: &str) -> bool { | ||
| @@ -78,7 +78,7 @@ fn mime(v: &str) -> bool { | ||
} | ||
| ||
/// The parameters each resource takes, the positional one first. | ||
fn params(resource: &str) -> Option<&'static [Param]> { | ||
pub(crate) fn params(resource: &str) -> Option<&'static [Param]> { | ||
const REPO: &[Param] = &[ | ||
Param { | ||
name: "collection", | ||
crates/pds-server/src/oauth/sets.rs+197−15
| @@ -7,11 +7,13 @@ | ||
//! checked; then kept a while, in memory. What a set grants is its | ||
//! permissions that are valid, written as scope strings. | ||
| ||
use super::space_scope::SpacePermission; | ||
use crate::Service; | ||
use crate::space_credentials::jwt::Key; | ||
use hickory_resolver::TokioResolver; | ||
use pds_repo::data::{valid_did, valid_nsid}; | ||
use serde_json::{Map, Value as Json}; | ||
use std::borrow::Cow; | ||
use std::collections::HashMap; | ||
use std::net::SocketAddr; | ||
use std::sync::atomic::{AtomicU64, Ordering}; | ||
| @@ -238,15 +240,17 @@ impl Sets { | ||
Ok(out) | ||
} | ||
| ||
/// Each distinct space type `scope`'s `space:` tokens name (but `*`), | ||
/// its declaration resolved; or the first that cannot be used, with why. | ||
/// Each distinct space type `scope` names (`space_types`), with the | ||
/// sets it includes `sets`, its declaration resolved; or the first that | ||
/// cannot be used, with why. | ||
pub async fn resolve_spaces( | ||
&self, | ||
svc: &Service, | ||
scope: &[String], | ||
sets: &HashMap<String, Arc<Json>>, | ||
) -> Result<HashMap<String, Arc<Json>>, (String, Unresolved)> { | ||
let mut out = HashMap::new(); | ||
for nsid in super::space_scope::types(scope) { | ||
for nsid in space_types(scope, sets) { | ||
let main = self | ||
.resolve(svc, &nsid) | ||
.await | ||
| @@ -273,10 +277,9 @@ impl Sets { | ||
svc: &Service, | ||
scope: &[String], | ||
) -> Result<Expansion, (String, Unresolved)> { | ||
Ok(Expansion { | ||
sets: self.resolve_all(svc, scope).await?, | ||
spaces: self.resolve_spaces(svc, scope).await?, | ||
}) | ||
let sets = self.resolve_all(svc, scope).await?; | ||
let spaces = self.resolve_spaces(svc, scope, &sets).await?; | ||
Ok(Expansion { sets, spaces }) | ||
} | ||
| ||
/// Resolve the set `nsid` names now (`spec/OAUTH-PERMISSION-SETS.md`, | ||
| @@ -525,6 +528,44 @@ fn permission( | ||
s.extend(percent_encoding::utf8_percent_encode(audience, AUDIENCE)); | ||
Some(s) | ||
} | ||
// A `space:` token's parameters (`spec/OAUTH-SCOPES.md`, "Spaces", | ||
// "Which parse"): each a string, or an array of one or more where | ||
// it takes many, with values the table allows; the type within the | ||
// set's namespace, its collections under any. Written as a `space:` | ||
// token is written again, its defaults left out. | ||
"space" => { | ||
let params = super::scope::params("space")?; | ||
let mut given: HashMap<&str, Vec<String>> = HashMap::new(); | ||
for (k, v) in p { | ||
if k == "type" || k == "resource" { | ||
continue; | ||
} | ||
let param = params.iter().find(|t| t.name == k.as_str())?; | ||
let values: Vec<String> = match v { | ||
Json::String(s) if !param.many => vec![s.clone()], | ||
Json::Array(a) if param.many && !a.is_empty() => a | ||
.iter() | ||
.map(|x| x.as_str().map(str::to_string)) | ||
.collect::<Option<_>>()?, | ||
_ => return None, | ||
}; | ||
if !values.iter().all(|v| (param.allows)(v)) { | ||
return None; | ||
} | ||
given.insert(param.name, values); | ||
} | ||
let mut take = |k: &str| given.remove(k); | ||
let space_type = take("spaceType")?.pop().filter(|t| inside(t))?; | ||
let permission = SpacePermission::new( | ||
space_type, | ||
take("authority").and_then(|mut v| v.pop()), | ||
take("skey").and_then(|mut v| v.pop()), | ||
take("collection"), | ||
take("action"), | ||
take("manage"), | ||
); | ||
Some(permission.to_scope()) | ||
} | ||
_ => None, | ||
} | ||
} | ||
| @@ -537,28 +578,46 @@ pub(crate) struct Expansion { | ||
pub spaces: HashMap<String, Arc<Json>>, | ||
} | ||
| ||
/// A scope expanded for the account `did`: each `include:` token, in order, | ||
/// A scope as the sets `sets` grant it: each `include:` token, in order, | ||
/// replaced by what its set grants, these first; then the other tokens, in | ||
/// order, a `space:` token rewritten (`super::space_scope::rewritten`); | ||
/// nothing dropped as a duplicate. Every set `scope` includes must be in | ||
/// `e.sets`. | ||
pub(crate) fn expand(scope: &[String], e: &Expansion, did: &str) -> Vec<String> { | ||
/// order; nothing dropped as a duplicate. Every set `scope` includes must | ||
/// be in `sets`. | ||
fn granted<'a>(scope: &'a [String], sets: &HashMap<String, Arc<Json>>) -> Vec<Cow<'a, str>> { | ||
let mut out = Vec::new(); | ||
let mut rest = Vec::new(); | ||
for t in scope { | ||
match include(t) { | ||
Some(i) => { | ||
if let Some(main) = e.sets.get(&i.nsid) { | ||
out.extend(grant(&i.nsid, main, i.aud.as_deref())); | ||
if let Some(main) = sets.get(&i.nsid) { | ||
out.extend( | ||
grant(&i.nsid, main, i.aud.as_deref()) | ||
.into_iter() | ||
.map(Cow::Owned), | ||
); | ||
} | ||
} | ||
None => rest.push(super::space_scope::rewritten(t, did, &e.spaces)), | ||
None => rest.push(Cow::Borrowed(t.as_str())), | ||
} | ||
} | ||
out.extend(rest); | ||
out | ||
} | ||
| ||
/// The space types a scope names, each once, but `*`: those of its `space:` | ||
/// tokens and of the `space` permissions its sets `sets` grant. | ||
pub(crate) fn space_types(scope: &[String], sets: &HashMap<String, Arc<Json>>) -> Vec<String> { | ||
super::space_scope::types(granted(scope, sets).iter().map(|t| t.as_ref())) | ||
} | ||
| ||
/// A scope expanded for the account `did` (`granted`), each `space:` string | ||
/// then rewritten (`super::space_scope::rewritten`). | ||
pub(crate) fn expand(scope: &[String], e: &Expansion, did: &str) -> Vec<String> { | ||
granted(scope, &e.sets) | ||
.iter() | ||
.map(|t| super::space_scope::rewritten(t, did, &e.spaces)) | ||
.collect() | ||
} | ||
| ||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
| @@ -719,6 +778,129 @@ mod tests { | ||
); | ||
} | ||
| ||
/// The `space` rows of `spec/OAUTH-PERMISSION-SETS.md`, "As scope | ||
/// strings", and each reason a `space` permission is dropped, alone; then | ||
/// its types resolved and its strings rewritten in the expansion. | ||
#[test] | ||
fn space_grants() { | ||
const SET: &str = "com.example.calendar.basePermissions"; | ||
let one = |p: Json| { | ||
grant( | ||
SET, | ||
&json!({ "type": "permission-set", "permissions": [p] }), | ||
None, | ||
) | ||
}; | ||
let st = "com.example.calendar.space"; | ||
let space = |fields: Json| { | ||
let mut p = json!({ "type": "permission", "resource": "space", "spaceType": st }); | ||
p.as_object_mut() | ||
.unwrap() | ||
.extend(fields.as_object().unwrap().clone()); | ||
p | ||
}; | ||
for (p, want) in [ | ||
(space(json!({})), "space:com.example.calendar.space"), | ||
( | ||
space( | ||
json!({ "authority": "self", "action": ["delete", "read", "create", "update"] }), | ||
), | ||
"space:com.example.calendar.space", | ||
), | ||
( | ||
space( | ||
json!({ "authority": "did:plc:abc", "skey": "main", "collection": ["org.other.note", "*"], "action": ["create", "read"] }), | ||
), | ||
"space:com.example.calendar.space?authority=did:plc:abc&skey=main&collection=*&action=read&action=create", | ||
), | ||
( | ||
space( | ||
json!({ "collection": ["com.example.calendar.event"], "manage": ["delete", "create"] }), | ||
), | ||
"space:com.example.calendar.space?collection=com.example.calendar.event&manage=create&manage=delete", | ||
), | ||
( | ||
space( | ||
json!({ "authority": "*", "skey": "*", "collection": ["org.b.c", "org.a.c", "org.b.c"], "action": ["read_self", "read_self"] }), | ||
), | ||
"space:com.example.calendar.space?authority=*&collection=org.a.c&collection=org.b.c&action=read_self", | ||
), | ||
( | ||
space( | ||
json!({ "collection": ["*"], "action": ["read", "create", "update", "delete", "read_self"] }), | ||
), | ||
"space:com.example.calendar.space?collection=*&action=read_self&action=read&action=create&action=update&action=delete", | ||
), | ||
( | ||
json!({ "type": "permission", "resource": "space", "spaceType": "com.example.calendar.sub.space", "manage": ["update"] }), | ||
"space:com.example.calendar.sub.space?manage=update", | ||
), | ||
] { | ||
assert_eq!(one(p.clone()), [want], "{p}"); | ||
} | ||
for p in [ | ||
json!({ "type": "permission", "resource": "space" }), | ||
json!({ "type": "permission", "resource": "space", "spaceType": "*" }), | ||
json!({ "type": "permission", "resource": "space", "spaceType": "com.example.other.space" }), | ||
json!({ "type": "permission", "resource": "space", "spaceType": "com.example.calendar" }), | ||
json!({ "type": "permission", "resource": "space", "spaceType": "com.Example.calendar.space" }), | ||
json!({ "type": "permission", "resource": "space", "spaceType": ["com.example.calendar.space"] }), | ||
space(json!({ "other": 1 })), | ||
space(json!({ "aud": "*" })), | ||
space(json!({ "authority": "me" })), | ||
space(json!({ "authority": ["self"] })), | ||
space(json!({ "skey": "a/b" })), | ||
space(json!({ "skey": 1 })), | ||
space(json!({ "collection": "com.example.calendar.event" })), | ||
space(json!({ "collection": [] })), | ||
space(json!({ "collection": ["notansid"] })), | ||
space(json!({ "collection": [1] })), | ||
space(json!({ "action": ["write"] })), | ||
space(json!({ "action": [] })), | ||
space(json!({ "action": "read" })), | ||
space(json!({ "manage": ["read"] })), | ||
space(json!({ "manage": [] })), | ||
] { | ||
assert_eq!(one(p.clone()), Vec::<String>::new(), "{p}"); | ||
} | ||
// A set's types beside the scope's own, each once, but `*`; then | ||
// each `space:` string of the expansion rewritten. | ||
let main = json!({ "permissions": [ | ||
{ "type": "permission", "resource": "space", "spaceType": st }, | ||
{ "type": "permission", "resource": "space", "spaceType": st, "authority": "*", "action": ["read"] }, | ||
] }); | ||
let sets = HashMap::from([(SET.to_string(), Arc::new(main))]); | ||
let scope: Vec<String> = [ | ||
"space:com.example.forum", | ||
"include:com.example.calendar.basePermissions", | ||
"space:*?authority=*&action=read", | ||
] | ||
.map(str::to_string) | ||
.to_vec(); | ||
assert_eq!( | ||
space_types(&scope, &sets), | ||
["com.example.calendar.space", "com.example.forum"] | ||
); | ||
let e = Expansion { | ||
sets, | ||
spaces: HashMap::from([( | ||
st.to_string(), | ||
Arc::new( | ||
json!({ "type": "space", "key": "any", "collections": ["com.example.calendar.event"] }), | ||
), | ||
)]), | ||
}; | ||
assert_eq!( | ||
expand(&scope, &e, "did:plc:abc"), | ||
[ | ||
"space:com.example.calendar.space?authority=did:plc:abc&collection=com.example.calendar.event", | ||
"space:com.example.calendar.space?authority=*&collection=com.example.calendar.event&action=read", | ||
"space:com.example.forum?authority=did:plc:abc", | ||
"space:*?authority=*&action=read", | ||
] | ||
); | ||
} | ||
| ||
#[test] | ||
fn documents() { | ||
const N: &str = "com.example.calendar.basePermissions"; | ||
crates/pds-server/src/oauth/space_scope.rs+37−16
| @@ -136,17 +136,38 @@ impl SpacePermission { | ||
.collect(); | ||
(!v.is_empty()).then_some(v) | ||
}; | ||
Some(SpacePermission { | ||
space_type: one("spaceType")?, | ||
authority: one("authority").unwrap_or_else(|| "self".into()), | ||
skey: one("skey").unwrap_or_else(|| "*".into()), | ||
collections: all("collection").map(|c| collections(&c)), | ||
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, | ||
&all("action").unwrap_or_else(|| DEFAULT_ACTIONS.map(String::from).to_vec()), | ||
&action.unwrap_or_else(|| DEFAULT_ACTIONS.map(String::from).to_vec()), | ||
), | ||
manage: ordered(&MANAGE, &all("manage").unwrap_or_default()), | ||
}) | ||
manage: ordered(&MANAGE, &manage.unwrap_or_default()), | ||
} | ||
} | ||
| ||
/// The scope string it is written as (`spec/OAUTH-SCOPES.md`, "The | ||
| @@ -259,10 +280,10 @@ impl SpaceNeed<'_> { | ||
} | ||
} | ||
| ||
/// The space types a scope's `space:` tokens name, each once, but `*`. | ||
pub(crate) fn types(scope: &[String]) -> Vec<String> { | ||
/// 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.iter().filter_map(|t| SpacePermission::of(t)) { | ||
for p in scope.into_iter().filter_map(SpacePermission::of) { | ||
if p.space_type != "*" && !out.contains(&p.space_type) { | ||
out.push(p.space_type); | ||
} | ||
| @@ -385,11 +406,11 @@ mod tests { | ||
); | ||
assert_eq!(r("atproto"), "atproto"); | ||
assert_eq!( | ||
types(&[ | ||
"space:a.b.c".into(), | ||
"space:*".into(), | ||
"space:a.b.c?action=read".into(), | ||
"repo:*".into() | ||
types([ | ||
"space:a.b.c", | ||
"space:*", | ||
"space:a.b.c?action=read", | ||
"repo:*" | ||
]), | ||
["a.b.c"] | ||
); | ||
docs/guide/comparing.md+4−2
| @@ -231,10 +231,12 @@ node compare.mjs --seed 1 -- ../../target/release/pds serve | ||
| ||
Besides the alpha's PDS and a second one for the spaces' peers, it starts | ||
a third as the run's lexicon authority. That one publishes the space type | ||
declarations that OAuth `space:` scopes name. The server is started with | ||
declarations that OAuth `space:` scopes name, and permission sets that | ||
grant `space` permissions. The server is started with | ||
`PDS_LEXICON_AUTHORITY_DID` set to that account's DID, and the alpha | ||
resolves from it too ([OAUTH-SCOPES.md](../../spec/OAUTH-SCOPES.md), "How | ||
it is checked"). | ||
it is checked"; [OAUTH-PERMISSION-SETS.md](../../spec/OAUTH-PERMISSION-SETS.md), | ||
"How it is checked"). | ||
| ||
## Performance | ||
| ||
harness/checks/pages.mjs+1−1
| @@ -232,7 +232,7 @@ function grantDetails(grant) { | ||
return { | ||
details: { | ||
summary: 'Details', | ||
sentence: tables.length ? 'The application requests the permissions necessary to perform the following actions on your behalf:' : 'Asks for nothing this server grants.', | ||
sentence: grant.length ? 'The application requests the permissions necessary to perform the following actions on your behalf:' : 'Asks for nothing this server grants.', | ||
tables, | ||
}, | ||
codes, | ||
harness/lib/sets.mjs+33−0
| @@ -173,7 +173,37 @@ export async function hostSets(plcUrl) { | ||
| ||
const NSID = /^[a-zA-Z](?:[a-zA-Z0-9-]{0,62})?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,62})?)+\.[a-zA-Z][a-zA-Z0-9]{0,62}$/ | ||
const ACTIONS = ['create', 'update', 'delete'] | ||
const SPACE_ACTIONS = ['read_self', 'read', 'create', 'update', 'delete'] | ||
const scalarArray = (v) => Array.isArray(v) && v.length > 0 && v.every((x) => typeof x === 'string') | ||
const DID = /^did:[a-z]+:[a-zA-Z0-9._:%-]*[a-zA-Z0-9._-]$/ | ||
const RKEY = (k) => /^[a-zA-Z0-9_~.:-]{1,512}$/.test(k) && k !== '.' && k !== '..' | ||
| ||
/// A `space` permission of a set as a scope string, as spec/OAUTH-SCOPES.md | ||
/// writes a `space:` token again ("Spaces", "The token's scope"), or null | ||
/// when it is dropped (spec/OAUTH-PERMISSION-SETS.md, "What a set grants"). | ||
function spaceOf(p, inside) { | ||
const keys = Object.keys(p).filter((k) => k !== 'type' && k !== 'resource') | ||
if (keys.some((k) => !['spaceType', 'authority', 'skey', 'collection', 'action', 'manage'].includes(k))) return null | ||
if (typeof p.spaceType !== 'string' || !inside(p.spaceType)) return null | ||
const authority = p.authority ?? 'self' | ||
if (typeof authority !== 'string' || !(authority === '*' || authority === 'self' || DID.test(authority))) return null | ||
const skey = p.skey ?? '*' | ||
if (typeof skey !== 'string' || !(skey === '*' || RKEY(skey))) return null | ||
const many = (name, ok) => !(name in p) || (scalarArray(p[name]) && p[name].every(ok)) | ||
if (!many('collection', (c) => c === '*' || NSID.test(c))) return null | ||
if (!many('action', (a) => SPACE_ACTIONS.includes(a))) return null | ||
if (!many('manage', (m) => ACTIONS.includes(m))) return null | ||
const q = new URLSearchParams() | ||
if (authority !== 'self') q.append('authority', authority) | ||
if (skey !== '*') q.append('skey', skey) | ||
if (p.collection) for (const c of p.collection.includes('*') ? ['*'] : [...new Set(p.collection)].sort()) q.append('collection', c) | ||
const actions = 'action' in p ? SPACE_ACTIONS.filter((a) => p.action.includes(a)) : SPACE_ACTIONS.slice(1) | ||
if (actions.join() !== SPACE_ACTIONS.slice(1).join()) for (const a of actions) q.append('action', a) | ||
if (p.manage) for (const m of ACTIONS.filter((m) => p.manage.includes(m))) q.append('manage', m) | ||
const back = (s) => s.replace(/%3A/g, ':').replace(/%2F/g, '/').replace(/%2B/g, '+').replace(/%2C/g, ',').replace(/%40/g, '@').replace(/%25/g, '%') | ||
const query = back(q.toString()) | ||
return `space:${back(encodeURIComponent(p.spaceType))}${query ? `?${query}` : ''}` | ||
} | ||
| ||
/// `include:`'s parts, `{nsid, aud}`, or null if it is not one. | ||
export function includeOf(token) { | ||
| @@ -215,6 +245,9 @@ export function grantOf(nsid, main, aud) { | ||
else continue | ||
const ls = [...new Set(p.lxm)].sort() | ||
out.push(`rpc${ls.length === 1 ? `:${ls[0]}?` : `?${ls.map((l) => `lxm=${l}`).join('&')}&`}aud=${encode(to)}`) | ||
} else if (p.resource === 'space') { | ||
const s = spaceOf(p, inside) | ||
if (s) out.push(s) | ||
} | ||
} | ||
return out | ||
harness/spaces/scopes.mjs+75−11
| @@ -1,12 +1,14 @@ | ||
// OAuth `space:` permissions (spec/OAUTH-SCOPES.md, "Spaces"), against the | ||
// pinned alpha, which keeps them. The run's lexicon authority, a PDS of its | ||
// own on the alpha's directory, publishes space type declarations, and both | ||
// sides resolve each space type from it (PDS_LEXICON_AUTHORITY_DID, the | ||
// alpha's `lexicon.didAuthority`). Loopback clients asking for `atproto` and | ||
// `space:` scopes sign in on both sides: PAR, the authorization page, sign-in | ||
// OAuth `space:` permissions (spec/OAUTH-SCOPES.md, "Spaces"), and those a | ||
// permission set grants (spec/OAUTH-PERMISSION-SETS.md, "What a set | ||
// grants"), against the pinned alpha, which keeps them. The run's lexicon | ||
// authority, a PDS of its own on the alpha's directory, publishes space type | ||
// declarations and permission sets, and both sides resolve each from it | ||
// (PDS_LEXICON_AUTHORITY_DID, the alpha's `lexicon.didAuthority`). Loopback | ||
// clients asking for `atproto` and `space:` scopes, or `include:` scopes of | ||
// those sets, sign in on both sides: PAR, the authorization page, sign-in | ||
// and consent through the page's API, the redirect and the code grant, each | ||
// side's answers compared. With each session's access token, a good proof and | ||
// a nonce, the space methods are called on the account's own spaces and | ||
// side's answers compared. With each session's access token, a good proof | ||
// and a nonce, the space methods are called on the account's own spaces and | ||
// another's, and each answer compared: its status, its error, and a | ||
// ScopeMissingError's message, each account's DID named alike. | ||
| ||
| @@ -45,13 +47,64 @@ const DECLARATIONS = { | ||
[NOT_SPACE]: { type: 'record', key: 'tid', record: { type: 'object', properties: {} } }, | ||
} | ||
| ||
/// Permission sets granting `space` permissions, each under `com.example.` | ||
/// as the space types are (spec/OAUTH-PERMISSION-SETS.md, "What a set | ||
/// grants"): kept as a bare type, managing every authority, with a key and | ||
/// actions, with collections of another namespace and `*`, of a type with | ||
/// no collections declared and of one with no document, beside `repo`; | ||
/// and dropped, each for one reason. | ||
const SP = (o) => ({ type: 'permission', resource: 'space', ...o }) | ||
const SET_BARE = 'com.example.wsBare' | ||
const SET_MANAGE = 'com.example.wsManage' | ||
const SET_KEYED = 'com.example.wsKeyed' | ||
const SET_FOREIGN = 'com.example.wsForeign' | ||
const SET_EMPTY = 'com.example.wsEmpty' | ||
const SET_MISSING = 'com.example.wsMissing' | ||
const SET_MIXED = 'com.example.wsMixed' | ||
const SET_DROPPED = 'com.example.wsDropped' | ||
const PERMISSION_SETS = { | ||
[SET_BARE]: { title: 'Workspaces', permissions: [SP({ spaceType: W })] }, | ||
[SET_MANAGE]: { permissions: [SP({ spaceType: W, authority: '*', manage: ['update', 'create', 'delete'] })] }, | ||
[SET_KEYED]: { permissions: [SP({ spaceType: W, authority: 'self', skey: 'main', collection: [TILE], action: ['create', 'read_self'], manage: ['create'] })] }, | ||
[SET_FOREIGN]: { | ||
permissions: [ | ||
SP({ spaceType: W, collection: ['org.other.thing', NOTE, NOTE], action: ['create'] }), | ||
SP({ spaceType: W, collection: [TILE, '*'], action: ['update', 'read', 'delete'], manage: ['delete'] }), | ||
], | ||
}, | ||
[SET_EMPTY]: { permissions: [SP({ spaceType: EMPTY, manage: ['create'] })] }, | ||
[SET_MISSING]: { permissions: [SP({ spaceType: MISSING }), SP({ spaceType: W })] }, | ||
[SET_MIXED]: { | ||
permissions: [ | ||
{ type: 'permission', resource: 'repo', collection: [NOTE] }, | ||
SP({ spaceType: TILED, action: ['read', 'create'] }), | ||
{ type: 'permission', resource: 'rpc', lxm: ['com.example.ping'], inheritAud: true }, | ||
], | ||
}, | ||
[SET_DROPPED]: { | ||
permissions: [ | ||
SP({ spaceType: W, action: ['read'] }), | ||
SP({ spaceType: '*', manage: ['create'] }), | ||
SP({ spaceType: 'org.other.space', manage: ['create'] }), | ||
SP({ spaceType: W, authority: 'me', manage: ['create'] }), | ||
SP({ spaceType: W, manage: ['create'], inheritAud: true }), | ||
SP({ spaceType: W, manage: 'create' }), | ||
SP({ spaceType: [W], manage: ['create'] }), | ||
SP({ spaceType: W, collection: [], manage: ['create'] }), | ||
SP({ spaceType: W, action: ['write'] }), | ||
SP({ manage: ['create'] }), | ||
], | ||
}, | ||
} | ||
| ||
/// The run's lexicon authority: a PDS on the alpha's directory with one | ||
/// account publishing the declarations. Answers `{pds, did}`. | ||
/// account publishing the declarations and the sets. Answers `{pds, did}`. | ||
export async function hostDeclarations(plcUrl) { | ||
const pds = await TestPds.create({ didPlcUrl: plcUrl, hostname: 'localhost', inviteRequired: false }) | ||
const handle = `lex${randomBytes(4).toString('hex')}.test` | ||
const made = await fetch(`${pds.url}/xrpc/com.atproto.server.createAccount`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ handle, email: `${handle}@example.com`, password: 'lexicons' }) }).then((r) => r.json()) | ||
for (const [id, main] of Object.entries(DECLARATIONS)) { | ||
const sets = Object.entries(PERMISSION_SETS).map(([id, main]) => [id, { type: 'permission-set', ...main }]) | ||
for (const [id, main] of [...Object.entries(DECLARATIONS), ...sets]) { | ||
const r = await fetch(`${pds.url}/xrpc/com.atproto.repo.createRecord`, { method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${made.accessJwt}` }, body: JSON.stringify({ repo: made.did, collection: SCHEMA, rkey: id, validate: false, record: { $type: SCHEMA, lexicon: 1, id, defs: { main } } }) }) | ||
if (!r.ok) throw new Error(`the lexicon authority could not publish ${id}: ${r.status} ${await r.text()}`) | ||
} | ||
| @@ -224,6 +277,16 @@ export async function checkSpaceScopes(h) { | ||
['a declaration with no collections field', () => `atproto space:${NO_COLLECTIONS}`], | ||
['a document that is no declaration', () => `atproto space:${NOT_SPACE}`], | ||
['a type with no document', () => `atproto space:${MISSING} space:${W}`], | ||
// Sets granting `space` permissions (spec/OAUTH-PERMISSION-SETS.md, | ||
// "What a set grants", "The token's scope"). | ||
['a set of a bare type', () => `atproto include:${SET_BARE}`], | ||
['a set managing every authority', () => `atproto include:${SET_MANAGE}`], | ||
['a set with a key and actions, beside a space: token', () => `atproto include:${SET_KEYED} space:${TILED}?action=read_self`], | ||
['a set with collections of another namespace and every collection', () => `atproto include:${SET_FOREIGN}`], | ||
['a set of a type declaring no collections', () => `atproto include:${SET_EMPTY}`], | ||
['a set of a type with no document', () => `atproto include:${SET_MISSING}`], | ||
['a set whose space permissions are dropped but one', () => `atproto include:${SET_DROPPED}`], | ||
['sets with an aud, twice, beside repo', () => `atproto include:${SET_MIXED}?aud=did:web:api.example.com%23svc include:${SET_BARE} repo:${NOTE} include:${SET_BARE}`], | ||
] | ||
| ||
// The account's spaces, made with its password session on each side: a | ||
| @@ -253,7 +316,8 @@ export async function checkSpaceScopes(h) { | ||
return v | ||
}) | ||
const request = { client: named(ref, scopeOf(ref)) } | ||
if (!isDeepStrictEqual(views[0], views[1])) await differ(`space scopes: a sign-in asking for ${what} (spec/OAUTH-SCOPES.md, "Spaces", "Space type declarations", "The token's scope")`, request, views[0], views[1]) | ||
const cites = /include:/.test(scopeOf(ref)) ? '; spec/OAUTH-PERMISSION-SETS.md, "What a set grants", "The token\'s scope"' : '' | ||
if (!isDeepStrictEqual(views[0], views[1])) await differ(`space scopes: a sign-in asking for ${what} (spec/OAUTH-SCOPES.md, "Spaces", "Space type declarations", "The token's scope"${cites})`, request, views[0], views[1]) | ||
count(`space scopes: sign-in, ${what}`) | ||
if (!signed.reference.session) continue | ||
const sessions = { reference: signed.reference.session, server: signed.server.session } | ||
spec/OAUTH-PERMISSION-SETS.md+53−17
| @@ -1,8 +1,8 @@ | ||
# OAuth: permission sets | ||
| ||
A permission set is a Lexicon schema an app's author publishes, naming a | ||
bundle of `repo` and `rpc` permissions under the set's own namespace, with | ||
a title and description for the people asked to grant it | ||
bundle of `repo`, `rpc` and `space` permissions under the set's own | ||
namespace, with a title and description for the people asked to grant it | ||
(`atproto/permission.md`, "Permission Sets"; `atproto/lexicon.md`, | ||
"Permission Set"). A client asks for one with an `include:` scope: | ||
`include:com.example.authFull`, or with an audience for the set's `rpc` | ||
| @@ -24,6 +24,7 @@ what the consent view shows of a set is in | ||
| `atproto/permission.md` | permissions, the `include` resource, permission sets, their namespace authority, resolution and caching | CC-BY, `atproto/LICENSE.txt` | | ||
| `atproto/lexicon.md` | the `permission-set` and `permission` types; Lexicon publication and resolution | CC-BY, `atproto/LICENSE.txt` | | ||
| `atproto/nsid.md` | an NSID's authority and name | CC-BY, `atproto/LICENSE.txt` | | ||
| `spaces/proposal.md` | `space` permissions in a set ("Permission sets") | `spaces/README.md` | | ||
| ||
The rules those leave open are the reference's, probed, and where the | ||
reference departs from them it says so below ("Where the reference departs | ||
| @@ -101,13 +102,17 @@ A set grants its permissions that are valid, each as the granular | ||
permission of `OAUTH-SCOPES.md` ("What a scope allows"). A permission is | ||
dropped, alone, and the rest kept, when: | ||
| ||
- its `resource` is not `repo` or `rpc` (`blob`, `account` and `identity` | ||
permissions are not for sets, and others are unknown); | ||
- its `resource` is not `repo`, `rpc` or `space` (`blob`, `account` and | ||
`identity` permissions are not for sets, and others are unknown); | ||
- it has a field its resource does not take: for `repo`, `collection` | ||
(required, an array of one or more NSIDs) and `action` (an array of | ||
`create`, `update`, `delete`); for `rpc`, `lxm` (required, an array of | ||
one or more NSIDs), `aud` and `inheritAud`; | ||
- a field's value is not as above, or a collection or method is `*`; | ||
one or more NSIDs), `aud` and `inheritAud`; for `space`, the parameters | ||
of `OAUTH-SCOPES.md` ("Spaces", "Which parse"): `spaceType` (required), | ||
`authority` and `skey`, each a string, and `collection`, `action` and | ||
`manage`, each an array of one or more strings; | ||
- a field's value is not as above, or as that table allows for a `space` | ||
permission; or a `repo` collection or an `rpc` method is `*`; | ||
- an `rpc` permission's `aud` is anything but `*`; | ||
- `inheritAud` is anything but `true`; or it is `true` and the permission | ||
has an `aud` too, or the `include:` has no `aud`. With `inheritAud: | ||
| @@ -116,13 +121,17 @@ dropped, alone, and the rest kept, when: | ||
- an `rpc` permission has neither an `aud` nor `inheritAud` with an | ||
`include:` `aud` (an `rpc` permission needs one audience); | ||
- `lxm` is `*` and `aud` is `*`; | ||
- any of its collections or methods is outside the set's namespace | ||
(`atproto/permission.md`, "Namespace Authority"): each must begin with | ||
the set's NSID up to and including its last `.`, and be longer than | ||
that, compared character by character, case and all. The set | ||
`com.example.calendar.basePermissions` grants `com.example.calendar.event` | ||
and `com.example.calendar.sub.thing`, not `com.example.other.x` nor | ||
`com.example.calendar` itself. | ||
- any of a `repo` permission's collections or an `rpc` permission's | ||
methods, or a `space` permission's `spaceType`, is outside the set's | ||
namespace (`atproto/permission.md`, "Namespace Authority"): each must | ||
begin with the set's NSID up to and including its last `.`, and be | ||
longer than that, compared character by character, case and all. The | ||
set `com.example.calendar.basePermissions` grants | ||
`com.example.calendar.event` and `com.example.calendar.sub.thing`, not | ||
`com.example.other.x` nor `com.example.calendar` itself. A `spaceType` | ||
of `*` is outside every namespace. A `space` permission's collections | ||
are not asked: they may be `*`, or under any namespace | ||
(`spaces/proposal.md`, "Permission sets"). | ||
| ||
A set whose permissions are all dropped resolves, and grants nothing. | ||
| ||
| @@ -139,6 +148,10 @@ order of its permissions, one for each kept: | ||
several as `rpc?lxm=…&lxm=…`. Then `aud=<audience>`, the audience | ||
percent-encoded but for letters, digits, `-_.!~*'()`, `:` and `/`: so | ||
`#` is written `%23`, and `*`, `:` and `/` are as they are. | ||
- **`space`**: as `OAUTH-SCOPES.md` writes a `space:` token again | ||
("Spaces", "The token's scope"), from the permission's fields, their | ||
defaults left out: `authority` `self` and `skey` `*` are not written, | ||
nor the four default actions. | ||
| ||
| Permission (`com.example.calendar.basePermissions`) | Scope string | | ||
| --- | --- | | ||
| @@ -148,6 +161,10 @@ order of its permissions, one for each kept: | ||
| `repo`, `collection: [com.example.calendar.event]`, `action: [create, update, delete]` | `repo:com.example.calendar.event` | | ||
| `rpc`, `lxm: [com.example.calendar.getEvents]`, `aud: "*"` | `rpc:com.example.calendar.getEvents?aud=*` | | ||
| `rpc`, `lxm: [com.example.calendar.getEvents, com.example.calendar.addEvent]`, `inheritAud: true`, with `include:…?aud=did:web:api.example.com%23cal` | `rpc?lxm=com.example.calendar.addEvent&lxm=com.example.calendar.getEvents&aud=did:web:api.example.com%23cal` | | ||
| `space`, `spaceType: com.example.calendar.space` | `space:com.example.calendar.space` | | ||
| `space`, `spaceType: com.example.calendar.space`, `authority: self`, `action: [delete, read, create, update]` | `space:com.example.calendar.space` | | ||
| `space`, `spaceType: com.example.calendar.space`, `authority: did:plc:abc`, `skey: main`, `collection: [org.other.note, *]`, `action: [create, read]` | `space:com.example.calendar.space?authority=did:plc:abc&skey=main&collection=*&action=read&action=create` | | ||
| `space`, `spaceType: com.example.calendar.space`, `collection: [com.example.calendar.event]`, `manage: [delete, create]` | `space:com.example.calendar.space?collection=com.example.calendar.event&manage=create&manage=delete` | | ||
| ||
## At PAR | ||
| ||
| @@ -178,9 +195,11 @@ one that does not resolve is `400 invalid_request`, as the reference | ||
answers. The session's scope is then expanded: each `include:` token, in | ||
the scope's order, is replaced by the scope strings of its grant, and | ||
these come first, followed by the scope's other tokens in their order, | ||
with nothing removed as a duplicate. That is the token answer's `scope`, | ||
and what the session's tokens allow (`OAUTH-SCOPES.md`): an `include:` | ||
token itself allows nothing. | ||
with nothing removed as a duplicate. Each `space:` string of the | ||
expansion is then rewritten as any `space:` token is (`OAUTH-SCOPES.md`, | ||
"Spaces", "The token's scope"). That is the token answer's `scope`, and | ||
what the session's tokens allow (`OAUTH-SCOPES.md`): an `include:` token | ||
itself allows nothing. | ||
| ||
At each refresh the session's scope is expanded again from its kept | ||
`include:` tokens, so a set changed since reaches the session, as | ||
| @@ -203,6 +222,7 @@ them, but holds the server to this page: | ||
| keeps a set that resolved once for ever | `atproto/permission.md`: an expiry of about 90 days | 90 days | | ||
| reads a set hosted on its own accounts from its store, with no proof | `atproto/lexicon.md`: resolution is authenticated | resolves it as any other, with its proof | | ||
| fails a whole set when one permission has a field whose value is an object | `atproto/permission.md`: such a permission is ignored | the same, as the reference: the harness compares the PAR's answer | | ||
| drops a set's `space` permissions, as it serves no spaces | `spaces/proposal.md`, "Permission sets": a set may grant them | grants them, as the pinned spaces alpha does (`SPACES.md`), against which the spaces run checks them (below) | | ||
| ||
And these, which the specs leave open and the server does as the | ||
reference does: | ||
| @@ -241,7 +261,23 @@ Compared with the reference: PAR's answers for clients declaring each | ||
keeping or dropping each `include:`, and the token answers' `scope`; a | ||
refresh's `scope`; and the calls of `OAUTH-SCOPES.md`'s steps made with | ||
such a session, allowed or refused as the reference allows or refuses | ||
them. The pages run (`OAUTH-PAGES.md`) draws clients with sets too. | ||
them. The pages run (`OAUTH-PAGES.md`) draws clients with sets too. No | ||
set of this run grants a `space` permission, as the reference drops them. | ||
| ||
A set's `space` permissions are checked in the spaces run | ||
(`harness/spaces/scopes.mjs`, `SPACES.md`), against the pinned spaces | ||
alpha: the run's lexicon authority publishes, beside its space type | ||
declarations, sets granting `space` permissions: a bare type, managing | ||
every authority, a key and actions, collections of another namespace and | ||
`*`, a type with no collections declared, and a type with no document; | ||
and permissions dropped, each for one reason above: `spaceType` `*`, a | ||
type of another namespace, a value the table does not allow, a field | ||
`space` does not take, a string for an array, an array for a string, and | ||
an empty array. Clients ask for them alone, with `aud`, beside `space:` | ||
and `repo:` tokens of their own, and twice. Compared: PAR's answer, the | ||
page's, the sign-in's and the token answer's `scope`, and each space | ||
method's answer to the session, as for a `space:` token | ||
(`OAUTH-SCOPES.md`, "How it is checked"). | ||
| ||
Held to this page, the server alone: a `PDS_LEXICON_AUTHORITY_DID` that is | ||
not a DID. | ||