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

pds-server: OAuth tokens on the space methods, by their space: scopes

Merged chadtmiller.com asked to merge into main from chadtmiller.com/monolith:oauth/space-scopes
.changeset/oauth-space-scopes.mdnew+7−0
@@ -0,0 +1,7 @@
---
default: minor
---
# OAuth apps can use spaces
The space methods take OAuth access tokens, allowed what their `space:` permissions allow, as the spaces alpha of the reference serves them (`spec/OAUTH-SCOPES.md`, "Spaces"). A client asking for `space:<type>` keeps it in its token: a bare type's collections are those its space type declaration lists, resolved as permission sets are, and `authority=self` becomes the account's DID. A call its scope does not allow is `403 ScopeMissingError`, naming the `space:` scope that would; `transition:generic` allows nothing of a space, and `getDelegationToken` needs `read`. A request naming a space type that does not resolve to a declaration is sent back to its client from the authorization page with `invalid_scope`. Before, the space methods refused every OAuth token as `400 InvalidToken`, and no token kept a `space:` permission.
crates/pds-server/src/oauth/mcp.rs+7−5
@@ -188,7 +188,9 @@ async fn request(svc: &Shared, uri: &Uri, address: &str) -> Response {
if let Err((nsid, why)) = svc.oauth.sets.resolve_all(svc, &kept_scope).await {
let description = match why {
sets::Unresolved::Fails(_) => format!("Permission set {nsid} could not be resolved"),
sets::Unresolved::NotASet => format!("{nsid} is not a permission set"),
sets::Unresolved::NotASet | sets::Unresolved::NotASpace => {
format!("{nsid} is not a permission set")
}
};
return refused("invalid_scope", &description);
}
@@ -318,9 +320,9 @@ pub(super) async fn token(svc: &Service, tx: &mut Tx<'_>, headers: &HeaderMap, b
p.filled("redirect_uri").unwrap_or_default(),
p.filled("code_verifier"),
);
// The sets the code's scope includes, resolved again, with no lock held.
// The sets and declarations the code's scope names, resolved again, with no lock held.
let approved = svc.oauth.approved_scope(code);
let sets = svc.oauth.sets.resolve_all(svc, &approved).await.ok();
let sets = svc.oauth.sets.for_token(svc, &approved).await.ok();
let mut out = tx.change(|st, now| {
unless_low(
low,
@@ -356,9 +358,9 @@ pub(super) async fn token(svc: &Service, tx: &mut Tx<'_>, headers: &HeaderMap, b
);
}
let token = p.filled("refresh_token").unwrap_or_default();
// The session's sets, resolved again, with no lock held.
// The session's sets and declarations, resolved again, with no lock held.
let consented = svc.oauth.session_scope(labels(true).1, token);
let sets = svc.oauth.sets.resolve_all(svc, &consented).await.ok();
let sets = svc.oauth.sets.for_token(svc, &consented).await.ok();
tx.change(|st, now| {
unless_low(
low,
crates/pds-server/src/oauth/page.rs+24−2
@@ -441,8 +441,30 @@ pub(super) async fn authorize(
Err(None) => return bad_page("Unknown or ended request"),
Err(Some((r, back))) => return redirect_to(&r.response_mode, &r.redirect_uri, &back),
};
// Each set the request includes, resolved again (`spec/OAUTH-PERMISSION-SETS.md`).
let mut r = match svc.oauth.sets.resolve_all(&svc, &loaded.request.scope).await {
// 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").
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() {
let mut tx = Tx::new(&svc);
let ended = tx.change(|st, _| match st.requests.get(id) {
Some(r) => {
let back = error_params(&svc, r, "invalid_scope", "Unable to retrieve space declarations");
(vec![json!({ "t": "oauthEndRequest", "id": id })], Some((r.clone(), back)))
}
None => (vec![], None),
});
if !tx.done().await {
return error_page(500, "server_error", "Internal server error");
}
return match ended {
Some((r, back)) => redirect_to(&r.response_mode, &r.redirect_uri, &back),
None => bad_page("Unknown or ended request"),
};
}
let mut r = match sets {
Ok(sets) => authorization_page(&svc, request_uri, &client, &loaded, &sets, &device.id),
Err((nsid, _)) => error_page(400, "invalid_scope", &format!("Permission set {nsid} could not be resolved")),
};
crates/pds-server/src/oauth/scope.rs+56−1
@@ -3,7 +3,7 @@
//! and the `include:` scopes that parse (`super::sets`), as `spec/OAUTH.md`
//! says.
use pds_repo::data::{valid_did, valid_nsid};
use pds_repo::data::{valid_did, valid_nsid, valid_rkey};
use std::collections::HashMap;
/// The scopes the server knows besides permissions.
@@ -133,12 +133,52 @@ fn params(resource: &str) -> Option<&'static [Param]> {
required: true,
allows: |v| ["handle", "*"].contains(&v),
}];
// `spec/OAUTH-SCOPES.md`, "Spaces".
const SPACE: &[Param] = &[
Param {
name: "spaceType",
many: false,
required: true,
allows: nsid_or_any,
},
Param {
name: "authority",
many: false,
required: false,
allows: |v| v == "*" || v == "self" || valid_did(v),
},
Param {
name: "skey",
many: false,
required: false,
allows: |v| v == "*" || valid_rkey(v),
},
Param {
name: "collection",
many: true,
required: false,
allows: nsid_or_any,
},
Param {
name: "action",
many: true,
required: false,
allows: |v| ["read_self", "read", "create", "update", "delete"].contains(&v),
},
Param {
name: "manage",
many: true,
required: false,
allows: |v| ["create", "update", "delete"].contains(&v),
},
];
Some(match resource {
"repo" => REPO,
"rpc" => RPC,
"blob" => BLOB,
"account" => ACCOUNT,
"identity" => IDENTITY,
"space" => SPACE,
_ => return None,
})
}
@@ -223,6 +263,11 @@ mod tests {
"account:repo",
"identity:*",
"identity:handle",
"space:com.example.forum",
"space:*?authority=*&action=read",
"space?spaceType=com.example.forum&manage=create",
"space:com.example.forum?authority=did:plc:abc&skey=main&collection=com.example.post&action=create",
"space:com.example.forum?authority=self&skey=*&collection=*&action=read_self&manage=update&manage=delete",
] {
assert!(permission(ok), "{ok}");
}
@@ -243,6 +288,16 @@ mod tests {
"identity:other",
"transition:other",
"foo:bar",
"space",
"space:forum",
"space:com.example.forum?authority=me",
"space:com.example.forum?action=write",
"space:com.example.forum?manage=read",
"space:com.example.forum?spaceType=com.example.forum",
"space:com.example.forum?authority=*&authority=self",
"space:com.example.forum?skey=a/b",
"space:com.example.forum?collection=com.example.*",
"space:com.example.forum?other=1",
] {
assert!(!permission(bad), "{bad}");
}
crates/pds-server/src/oauth/sets.rs+95−15
@@ -1,5 +1,7 @@
//! Permission sets: `include:` scopes (`spec/OAUTH-PERMISSION-SETS.md`).
//! A set is resolved by its NSID: the authority's DID from DNS (or
//! Permission sets: `include:` scopes (`spec/OAUTH-PERMISSION-SETS.md`);
//! and space type declarations, which `space:` scopes name and which are
//! resolved the same way (`spec/OAUTH-SCOPES.md`, "Spaces"). A document is
//! resolved by its NSID: the authority's DID from DNS (or
//! `PDS_LEXICON_AUTHORITY_DID`), that DID's document, its schema record
//! fetched from its PDS with the record's proof checked, and the document
//! checked; then kept a while, in memory. What a set grants is its
@@ -105,17 +107,21 @@ pub(crate) fn authority(nsid: &str) -> String {
segments.join(".")
}
/// Why a set cannot be used: it does not resolve, or what it resolves to is not a set.
/// Why a document cannot be used: it does not resolve, or what it resolves
/// to is not a set, or not a space type declaration.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Unresolved {
Fails(String),
NotASet,
NotASpace,
}
/// A set resolved: its document's `defs.main`, as published; or not.
/// A document resolved: its `defs.main`, as published, a set's or a
/// declaration's; or why not.
pub(crate) type Resolved = Result<Arc<Json>, Unresolved>;
/// What resolving a document gave: a set's `defs.main`, or a document that is not a set.
/// What resolving a document gave: a set's or a declaration's `defs.main`,
/// or a document that is neither.
type Got = Result<Arc<Json>, ()>;
/// A set kept: what it last resolved to and when, and when resolving it
@@ -219,12 +225,60 @@ impl Sets {
let set = self
.resolve(svc, &i.nsid)
.await
.and_then(|m| {
if m["type"] == "permission-set" {
Ok(m)
} else {
Err(Unresolved::NotASet)
}
})
.map_err(|u| (i.nsid.clone(), u))?;
out.insert(i.nsid, set);
}
Ok(out)
}
/// Each distinct space type `scope`'s `space:` tokens name (but `*`),
/// its declaration resolved; or the first that cannot be used, with why.
pub async fn resolve_spaces(
&self,
svc: &Service,
scope: &[String],
) -> Result<HashMap<String, Arc<Json>>, (String, Unresolved)> {
let mut out = HashMap::new();
for nsid in super::space_scope::types(scope) {
let main = self
.resolve(svc, &nsid)
.await
.and_then(|m| {
if m["type"] == "space" {
Ok(m)
} else {
Err(Unresolved::NotASpace)
}
})
.map_err(|u| match u {
Unresolved::NotASet => (nsid.clone(), Unresolved::NotASpace),
u => (nsid.clone(), u),
})?;
out.insert(nsid, main);
}
Ok(out)
}
/// What a session's scope is expanded with: its sets, then its space
/// types' declarations; or the first that cannot be used, with why.
pub async fn for_token(
&self,
svc: &Service,
scope: &[String],
) -> Result<Expansion, (String, Unresolved)> {
Ok(Expansion {
sets: self.resolve_all(svc, scope).await?,
spaces: self.resolve_spaces(svc, scope).await?,
})
}
/// Resolve the set `nsid` names now (`spec/OAUTH-PERMISSION-SETS.md`,
/// "Resolving a set"), or say why it does not resolve.
async fn fetch(&self, svc: &Service, nsid: &str) -> Result<Got, String> {
@@ -328,8 +382,9 @@ async fn authority_did(dns: &TokioResolver, authority: &str) -> Result<String, S
}
/// A schema record's value checked (`spec/OAUTH-PERMISSION-SETS.md`, "Resolving
/// a set", 5): a set's `defs.main`, a document that is not a set, or why it
/// does not resolve.
/// a set", 5; `spec/OAUTH-SCOPES.md`, "Space type declarations"): a set's or
/// a declaration's `defs.main`, a document that is neither, or why it does
/// not resolve.
fn document(doc: &Json, nsid: &str) -> Result<Got, String> {
let bad = |why: &str| Err(format!("{nsid}'s document: {why}"));
if doc["$type"] != SCHEMA || doc["lexicon"] != 1 || doc["id"] != nsid {
@@ -338,6 +393,18 @@ fn document(doc: &Json, nsid: &str) -> Result<Got, String> {
let Some(main) = doc["defs"].get("main").filter(|m| m.is_object()) else {
return bad("no defs.main");
};
if main["type"] == "space" {
if !main["key"].is_string() {
return bad("a space type declaration with no key");
}
let declared = main["collections"]
.as_array()
.is_some_and(|cs| cs.iter().all(|c| c.as_str().is_some_and(valid_nsid)));
if !declared {
return bad("collections not a list of NSIDs");
}
return Ok(Ok(Arc::new(main.clone())));
}
if main["type"] != "permission-set" {
return Ok(Err(()));
}
@@ -462,20 +529,30 @@ fn permission(
}
}
/// A scope expanded: each `include:` token, in order, replaced by what its
/// set grants, these first; then the other tokens, in order; nothing
/// dropped as a duplicate. Every set `scope` includes must be in `sets`.
pub(crate) fn expand(scope: &[String], sets: &HashMap<String, Arc<Json>>) -> Vec<String> {
/// What a session's scope is expanded with: the sets it includes, and the
/// declarations of the space types it names, each by its NSID.
#[derive(Clone, Debug, Default)]
pub(crate) struct Expansion {
pub sets: HashMap<String, Arc<Json>>,
pub spaces: HashMap<String, Arc<Json>>,
}
/// A scope expanded for the account `did`: 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> {
let mut out = Vec::new();
let mut rest = Vec::new();
for t in scope {
match include(t) {
Some(i) => {
if let Some(main) = sets.get(&i.nsid) {
if let Some(main) = e.sets.get(&i.nsid) {
out.extend(grant(&i.nsid, main, i.aud.as_deref()));
}
}
None => rest.push(t.clone()),
None => rest.push(super::space_scope::rewritten(t, did, &e.spaces)),
}
}
out.extend(rest);
@@ -617,7 +694,10 @@ mod tests {
]
);
// Expanded: each include's grant, in order, then the other tokens; duplicates kept.
let sets = HashMap::from([(SET.to_string(), Arc::new(main))]);
let sets = Expansion {
sets: HashMap::from([(SET.to_string(), Arc::new(main))]),
spaces: HashMap::new(),
};
let scope: Vec<String> = [
"atproto",
"include:com.example.calendar.basePermissions",
@@ -627,7 +707,7 @@ mod tests {
.map(str::to_string)
.to_vec();
assert_eq!(
expand(&scope, &sets),
expand(&scope, &sets, "did:plc:abc"),
[
"rpc:com.example.calendar.b?aud=*",
"repo:com.example.calendar.event",
crates/pds-server/src/oauth/space_scope.rsnew+458−0
458 lines changed: not loaded until asked for.
crates/pds-server/src/oauth.rs+19−13
@@ -36,6 +36,7 @@ mod page;
pub(crate) mod passkeys;
mod scope;
mod sets;
pub(crate) mod space_scope;
#[cfg(test)]
pub(crate) mod tests;
@@ -59,7 +60,7 @@ use std::collections::HashMap;
use std::io::Write;
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::sync::{Mutex, MutexGuard, PoisonError};
/// The kinds of `accounts.log` entry this module keeps.
pub(crate) const ENTRIES: &[&str] = &[
@@ -1825,7 +1826,9 @@ async fn par(
if let Err((nsid, why)) = svc.oauth.sets.resolve_all(svc, &scope::kept(&tokens)).await {
let description = match why {
sets::Unresolved::Fails(_) => format!("Permission set {nsid} could not be resolved"),
sets::Unresolved::NotASet => format!("{nsid} is not a permission set"),
sets::Unresolved::NotASet | sets::Unresolved::NotASpace => {
format!("{nsid} is not a permission set")
}
};
return refuse(400, "invalid_scope", description);
}
@@ -1933,9 +1936,10 @@ async fn token(svc: &Service, tx: &mut Tx<'_>, headers: &HeaderMap, body: &[u8])
p.filled("redirect_uri").unwrap_or_default(),
p.filled("code_verifier"),
);
// The sets the code's scope includes, resolved again, with no lock held.
// The sets and space declarations the code's scope names,
// resolved again, with no lock held.
let approved = svc.oauth.approved_scope(code);
let sets = svc.oauth.sets.resolve_all(svc, &approved).await.ok();
let sets = svc.oauth.sets.for_token(svc, &approved).await.ok();
let mut out = tx.change(|st, now| {
settle(
svc,
@@ -1968,9 +1972,9 @@ async fn token(svc: &Service, tx: &mut Tx<'_>, headers: &HeaderMap, body: &[u8])
}
Some("refresh_token") if client.refresh => {
let token = p.filled("refresh_token").unwrap_or_default();
// The session's sets, resolved again, with no lock held.
// The session's sets and declarations, resolved again, with no lock held.
let consented = svc.oauth.session_scope("refresh", token);
let sets = svc.oauth.sets.resolve_all(svc, &consented).await.ok();
let sets = svc.oauth.sets.for_token(svc, &consented).await.ok();
tx.change(|st, now| {
settle(
svc,
@@ -2013,7 +2017,7 @@ fn exchange(
code: &str,
redirect_uri: &str,
verifier: Option<&str>,
sets: Option<&HashMap<String, Arc<Json>>>,
sets: Option<&sets::Expansion>,
) -> (Vec<Json>, Out) {
let refused = || refuse(400, "invalid_grant", "Invalid code");
// A code the other issuer gave is none of this one's.
@@ -2054,14 +2058,15 @@ fn exchange(
if !up {
return (spend(), refused());
}
// The sets its scope includes, each resolved again (`spec/OAUTH-PERMISSION-SETS.md`).
// The sets and space declarations its scope names, each resolved again
// (`spec/OAUTH-PERMISSION-SETS.md`, `spec/OAUTH-SCOPES.md`).
let Some(sets) = sets else {
return (
vec![],
refuse(
400,
"invalid_request",
"A permission set could not be resolved",
"A permission set or space declaration could not be resolved",
),
);
};
@@ -2080,7 +2085,7 @@ fn exchange(
client_id: client_id.to_string(),
jkt: jkt.to_string(),
scope: a.scope.clone(),
granted: sets::expand(&a.scope, sets),
granted: sets::expand(&a.scope, sets, &a.did),
started: now,
code: code.to_string(),
access: new_id(12),
@@ -2113,7 +2118,7 @@ fn refresh(
jkt: &str,
key: Option<&str>,
token: &str,
sets: Option<&HashMap<String, Arc<Json>>>,
sets: Option<&sets::Expansion>,
) -> (Vec<Json>, Out) {
let refused = || refuse(400, "invalid_grant", "Invalid refresh token");
let Some((sid, jti)) = svc.oauth.token_of(labels(mcp).1, token) else {
@@ -2138,9 +2143,10 @@ fn refresh(
next.refreshed = now;
next.access_exp = (now + ACCESS_LIFE).min(next.end());
next.refresh = new_id(12);
// Expanded again from its sets as they are now; as it was if one no longer resolves.
// Expanded again from its sets and declarations as they are now; as it
// was if one no longer resolves.
if let Some(sets) = sets {
next.granted = sets::expand(&next.scope, sets);
next.granted = sets::expand(&next.scope, sets, &next.did);
}
let entry = json!({ "t": "oauthRefresh", "sid": sid, "access": next.access, "accessExp": next.access_exp, "refresh": next.refresh, "at": now, "granted": next.granted });
(vec![entry], ok(200, token_answer(svc, &sid, &next, now)))
crates/pds-server/src/scopes.rs+99−38
@@ -29,16 +29,16 @@
//! token and proof are looked at once what is checked before them passes
//! (`proxy::forwards`).
//!
//! Spaces: no space method is served with OAuth tokens yet. Each is
//! `Takes::Space` in `METHODS`: a `DPoP` call is not read here, and the
//! method refuses its token as one the server did not give out. Once
//! `oauth::scope` keeps a `space` permission, a space operation is one more
//! `Need`, with the space's authority, type and key and the operation,
//! never granted by `transition:generic`, whose refusal names the `space:`
//! scope that would allow it; its row becomes `Needs(Needs::Nothing)`, and
//! its handler asks `may(call.bearer, &need)`, as a password session is
//! always allowed.
//! Spaces (`spec/OAUTH-SCOPES.md`, "Spaces"): a space method that takes an
//! account's access token is `Takes::Needs(Needs::Space)`, which `look`
//! checks as any method that needs a token; its handler, once its input
//! names the space and the operation, asks `may` with a `Need::Space`, as
//! a password session is always allowed. A method that takes service auth,
//! a delegation token or a space credential alone is `Takes::Space`: a
//! `DPoP` call is not read here, and the method refuses its token as one
//! the server did not give out.
use crate::oauth::space_scope::{SpaceNeed, SpacePermission};
use crate::sessions::Bearer;
use crate::{Call, Service, XrpcError, err, respond};
use axum::http::HeaderMap;
@@ -64,8 +64,8 @@ pub(crate) enum Takes {
Needs(Needs),
/// A refresh token, by the `Bearer` scheme alone.
Refresh,
/// A space method: its own token or service auth, and no OAuth token yet
/// (`spec/OAUTH-SCOPES.md`, "Spaces"); a `DPoP` call is not read here.
/// A space method that takes no account's token, but service auth, a
/// delegation token or a space credential: a `DPoP` call is not read here.
Space,
}
@@ -89,6 +89,8 @@ pub(crate) enum Needs {
Manage(&'static str),
/// `rpc` of the method and the service it goes to (`spec/PROXY.md`).
Rpc,
/// A `space` permission of what its input names, which its handler asks.
Space,
}
/// Every method served, and what it takes of a token.
@@ -236,35 +238,56 @@ const METHODS: &[(&str, Takes)] = &[
"app.bsky.notification.unregisterPush",
Takes::Needs(Needs::Rpc),
),
("com.atproto.space.createSpace", Takes::Space),
("com.atproto.space.getSpace", Takes::Space),
("com.atproto.space.updateSpace", Takes::Space),
("com.atproto.space.deleteSpace", Takes::Space),
("com.atproto.space.removeWriter", Takes::Space),
("com.atproto.space.exportSpaceMeta", Takes::Space),
("com.atproto.space.importSpaceMeta", Takes::Space),
("com.atproto.memberspace.putMembers", Takes::Space),
("com.atproto.memberspace.removeMembers", Takes::Space),
("com.atproto.memberspace.listMembers", Takes::Space),
("com.atproto.space.getDelegationToken", Takes::Space),
("com.atproto.space.createSpace", Takes::Needs(Needs::Space)),
("com.atproto.space.getSpace", Takes::Needs(Needs::Space)),
("com.atproto.space.updateSpace", Takes::Needs(Needs::Space)),
("com.atproto.space.deleteSpace", Takes::Needs(Needs::Space)),
("com.atproto.space.removeWriter", Takes::Needs(Needs::Space)),
(
"com.atproto.space.exportSpaceMeta",
Takes::Needs(Needs::Space),
),
(
"com.atproto.space.importSpaceMeta",
Takes::Needs(Needs::Space),
),
(
"com.atproto.memberspace.putMembers",
Takes::Needs(Needs::Space),
),
(
"com.atproto.memberspace.removeMembers",
Takes::Needs(Needs::Space),
),
(
"com.atproto.memberspace.listMembers",
Takes::Needs(Needs::Space),
),
(
"com.atproto.space.getDelegationToken",
Takes::Needs(Needs::Space),
),
("com.atproto.space.authorizeSpaceSync", Takes::Space),
("com.atproto.space.notifyCredentialsRevoked", Takes::Space),
("com.atproto.space.createRecord", Takes::Space),
("com.atproto.space.putRecord", Takes::Space),
("com.atproto.space.deleteRecord", Takes::Space),
("com.atproto.space.applyWrites", Takes::Space),
("com.atproto.space.clearRecords", Takes::Space),
("com.atproto.space.getRecord", Takes::Space),
("com.atproto.space.listRecords", Takes::Space),
("com.atproto.space.getLatestCommit", Takes::Space),
("com.atproto.space.listRepoOps", Takes::Space),
("com.atproto.space.getRepo", Takes::Space),
("com.atproto.space.getBlob", Takes::Space),
("com.atproto.space.listBlobs", Takes::Space),
("com.atproto.space.importRepo", Takes::Space),
("com.atproto.space.createRecord", Takes::Needs(Needs::Space)),
("com.atproto.space.putRecord", Takes::Needs(Needs::Space)),
("com.atproto.space.deleteRecord", Takes::Needs(Needs::Space)),
("com.atproto.space.applyWrites", Takes::Needs(Needs::Space)),
("com.atproto.space.clearRecords", Takes::Needs(Needs::Space)),
("com.atproto.space.getRecord", Takes::Needs(Needs::Space)),
("com.atproto.space.listRecords", Takes::Needs(Needs::Space)),
(
"com.atproto.space.getLatestCommit",
Takes::Needs(Needs::Space),
),
("com.atproto.space.listRepoOps", Takes::Needs(Needs::Space)),
("com.atproto.space.getRepo", Takes::Needs(Needs::Space)),
("com.atproto.space.getBlob", Takes::Needs(Needs::Space)),
("com.atproto.space.listBlobs", Takes::Needs(Needs::Space)),
("com.atproto.space.importRepo", Takes::Needs(Needs::Space)),
("com.atproto.space.notifyRepoUpdate", Takes::Space),
("com.atproto.space.listWriters", Takes::Space),
("com.atproto.space.listSpaces", Takes::Space),
("com.atproto.space.listSpaces", Takes::Needs(Needs::Space)),
];
/// `requestEmailUpdate`'s and `updateEmail`'s refusal of an OAuth token.
@@ -453,6 +476,36 @@ pub(crate) fn may(bearer: Bearer, need: &Need) -> Result<(), XrpcError> {
}
}
/// Whether a call's session may make the space operation `op` on the space
/// of `authority`, `space_type` and `skey`, each of which may be `*` as
/// `listSpaces` asks (`spec/OAUTH-SCOPES.md`, "Spaces").
pub(crate) fn may_space(
bearer: Bearer,
authority: &str,
space_type: &str,
skey: &str,
op: crate::oauth::space_scope::SpaceOp,
) -> Result<(), XrpcError> {
may(
bearer,
&Need::Space(SpaceNeed {
authority,
space_type,
skey,
op,
}),
)
}
/// `may_space` of a space the call names.
pub(crate) fn may_in(
bearer: Bearer,
space: &pds_space::SpaceRef,
op: crate::oauth::space_scope::SpaceOp,
) -> Result<(), XrpcError> {
may_space(bearer, &space.authority, &space.typ, &space.skey, op)
}
/// Whether a call's session may read its account's email.
pub(crate) fn reads_email(bearer: Bearer) -> bool {
match bearer {
@@ -607,6 +660,8 @@ pub(crate) enum Need<'a> {
/// A call of the method `lxm` to the service `aud` (a DID and a `#` service
/// fragment), as `getServiceAuth` and proxied calls make.
Rpc { lxm: &'a str, aud: &'a str },
/// A space operation (`spec/OAUTH-SCOPES.md`, "Spaces").
Space(SpaceNeed<'a>),
}
/// What a scope's refusal names besides what `encodeURIComponent` leaves as it is.
@@ -644,6 +699,7 @@ impl Need<'_> {
// A space in `aud` is `+`, as the reference writes it; in a
// media type it is `%20` (`spec/OAUTH-SCOPES.md`).
Need::Rpc { lxm, aud } => format!("rpc:{lxm}?aud={}", encode(aud).replace("%20", "+")),
Need::Space(n) => n.scope(),
}
}
}
@@ -670,12 +726,16 @@ enum Permission {
Identity {
attr: String,
},
Space(SpacePermission),
}
impl Permission {
/// A scope token as a permission, if it is one: what `oauth::scope`
/// keeps of a session's scope parses, and anything else allows nothing.
fn of(token: &str) -> Option<Permission> {
if token.starts_with("space") {
return SpacePermission::of(token).map(Permission::Space);
}
let (head, query) = token.split_once('?').unwrap_or((token, ""));
let (resource, positional) = match head.split_once(':') {
Some((r, p)) => (r, Some(p)),
@@ -762,6 +822,7 @@ impl Permission {
aud: service,
},
) => lxm.iter().any(|l| l == "*" || l == method) && (aud == "*" || aud == service),
(Permission::Space(p), Need::Space(n)) => p.allows(&n),
_ => false,
}
}
@@ -830,7 +891,7 @@ impl Scope {
self.chat
}
Need::Rpc { .. } => self.generic,
Need::Identity(_) => false,
Need::Identity(_) | Need::Space(_) => false,
};
transitional || self.permissions.iter().any(|p| p.allows(need))
}
crates/pds-server/src/space_authority.rs+31−15
@@ -8,6 +8,7 @@
//! under its lock, each change one frame of its `repo.log` (`ENTRIES`). A
//! deleted space is remembered as deleted.
use crate::oauth::space_scope::SpaceOp;
use crate::space_authz::{Asking, SpaceState};
use crate::space_repo::Staged;
use crate::{
@@ -731,7 +732,13 @@ enum Session {
Takendown,
}
/// The session a token is of: an OAuth session's is its account's, as a
/// password session's, its scope asked by each method
/// (`spec/OAUTH-SCOPES.md`, "Spaces").
fn session_of(t: &sessions::Token) -> Session {
if t.oauth {
return Session::Password;
}
match t.scope.as_str() {
sessions::ACCESS => Session::Password,
sessions::TAKENDOWN => Session::Takendown,
@@ -774,11 +781,14 @@ fn pay(svc: &Service, call: &Call, a: &Account) -> Result<(), XrpcError> {
crate::limits::guard(svc, call, Some(&a.did), None)
}
/// A space the caller is the authority of, else `NotAuthorized`.
fn owned(a: &Account, space: &str) -> Result<SpaceRef, XrpcError> {
/// A space the call names, the call's scope asked for `op` on it
/// (`spec/OAUTH-SCOPES.md`, "What each method needs"), and the caller its
/// authority, else `NotAuthorized`.
fn owned(call: &Call, a: &Account, space: &str, op: SpaceOp) -> Result<SpaceRef, XrpcError> {
let Some(sr) = SpaceRef::parse(space) else {
return invalid("space must be a valid space-ref");
};
crate::scopes::may_in(call.bearer, &sr, op)?;
if sr.authority != a.did {
return not_authorized();
}
@@ -925,15 +935,18 @@ async fn create_space(svc: &Shared, call: &Call<'_>, m: &Method) -> Result<Resp,
let a = caller(svc, call, Kind::Manage)?;
let b = input(call, m)?;
pay(svc, call, &a)?;
// The key given, or one made for it now, which the scope is asked of.
let skey = match b.get("skey").and_then(Json::as_str) {
Some(k) => k.to_string(),
None => write(&a.store).repo.tids.next_tid(),
};
let typ = text(&b, "spaceType").to_string();
crate::scopes::may_space(call.bearer, &a.did, &typ, &skey, SpaceOp::Manage("create"))?;
let policy = Policy::given(&b["policy"])?;
let uri = change(svc, &a, |st, frame| {
let skey = b
.get("skey")
.and_then(Json::as_str)
.map_or_else(|| st.repo.tids.next_tid(), str::to_string);
let sr = SpaceRef {
authority: a.did.clone(),
typ: text(&b, "spaceType").to_string(),
typ,
skey,
};
let uri = sr.uri();
@@ -965,7 +978,7 @@ async fn get_space(svc: &Shared, call: &Call<'_>, m: &Method) -> Result<Resp, Xr
let a = caller(svc, call, Kind::Read)?;
pay(svc, call, &a)?;
let asked = text(&p, "space");
let uri = owned(&a, asked)?.uri();
let uri = owned(call, &a, asked, SpaceOp::Read { whole: false })?.uri();
let policy = look(&a, |st| {
st.authority
.live(&uri)
@@ -979,7 +992,7 @@ async fn update_space(svc: &Shared, call: &Call<'_>, m: &Method) -> Result<Resp,
let a = caller(svc, call, Kind::Manage)?;
let b = input(call, m)?;
pay(svc, call, &a)?;
let sr = owned(&a, text(&b, "space"))?;
let sr = owned(call, &a, text(&b, "space"), SpaceOp::Manage("update"))?;
let policy = Policy::given(&b["policy"])?;
change(svc, &a, |st, frame| {
let uri = sr.uri();
@@ -1030,7 +1043,7 @@ async fn delete_space(svc: &Shared, call: &Call<'_>, m: &Method) -> Result<Resp,
let a = caller(svc, call, Kind::Manage)?;
let b = input(call, m)?;
pay(svc, call, &a)?;
let sr = owned(&a, text(&b, "space"))?;
let sr = owned(call, &a, text(&b, "space"), SpaceOp::Manage("delete"))?;
change(svc, &a, |st, frame| {
let uri = sr.uri();
match st.authority.state(&uri) {
@@ -1059,7 +1072,7 @@ async fn remove_writer(svc: &Shared, call: &Call<'_>, m: &Method) -> Result<Resp
let a = caller(svc, call, Kind::Manage)?;
let b = input(call, m)?;
pay(svc, call, &a)?;
let sr = owned(&a, text(&b, "space"))?;
let sr = owned(call, &a, text(&b, "space"), SpaceOp::Manage("update"))?;
let did = text(&b, "repo");
change(svc, &a, |st, frame| {
let uri = sr.uri();
@@ -1080,7 +1093,7 @@ async fn put_members(svc: &Shared, call: &Call<'_>, m: &Method) -> Result<Resp,
let a = caller(svc, call, Kind::Manage)?;
let b = input(call, m)?;
pay(svc, call, &a)?;
let sr = owned(&a, text(&b, "space"))?;
let sr = owned(call, &a, text(&b, "space"), SpaceOp::Manage("update"))?;
let given: BTreeMap<String, Access> = b["members"]
.as_array()
.into_iter()
@@ -1130,7 +1143,7 @@ async fn remove_members(svc: &Shared, call: &Call<'_>, m: &Method) -> Result<Res
let a = caller(svc, call, Kind::Manage)?;
let b = input(call, m)?;
pay(svc, call, &a)?;
let sr = owned(&a, text(&b, "space"))?;
let sr = owned(call, &a, text(&b, "space"), SpaceOp::Manage("update"))?;
let dids: std::collections::BTreeSet<&str> = b["dids"]
.as_array()
.into_iter()
@@ -1201,7 +1214,7 @@ async fn list_members(svc: &Shared, call: &Call<'_>, m: &Method) -> Result<Resp,
let p = params(call, m)?;
let a = caller(svc, call, Kind::Read)?;
pay(svc, call, &a)?;
let uri = owned(&a, text(&p, "space"))?.uri();
let uri = owned(call, &a, text(&p, "space"), SpaceOp::Read { whole: false })?.uri();
let limit = p.get("limit").and_then(Json::as_u64).unwrap_or(100) as usize;
// An empty cursor is as none; any other must be a DID, checked last.
let cursor = p
@@ -1240,7 +1253,7 @@ async fn export_space_meta(svc: &Shared, call: &Call<'_>, m: &Method) -> Result<
let p = params(call, m)?;
let a = caller(svc, call, Kind::Export)?;
pay(svc, call, &a)?;
let uri = owned(&a, text(&p, "space"))?.uri();
let uri = owned(call, &a, text(&p, "space"), SpaceOp::Read { whole: false })?.uri();
let bytes = look(&a, |st| {
st.authority
.live(&uri)
@@ -1463,6 +1476,9 @@ async fn import_space_meta(svc: &Shared, call: &Call<'_>) -> Result<Resp, XrpcEr
}
pay(svc, call, &a)?;
let r = read_archive(call.body, Of::Import)?;
for m in ["create", "update"] {
crate::scopes::may_in(call.bearer, &r.space, SpaceOp::Manage(m))?;
}
if r.space.authority != a.did {
return not_authorized();
}
crates/pds-server/src/space_credentials.rs+11−5
@@ -21,6 +21,7 @@ pub(crate) mod jwt;
#[cfg(test)]
pub(crate) mod tests;
use crate::oauth::space_scope::SpaceOp;
use crate::single_use::{Held, SingleUse};
use crate::space_authz::{Lifecycle, Perimeter, SpaceState};
use crate::space_notify::{self, Standing};
@@ -171,7 +172,7 @@ fn get_delegation_token(
let Some(sr) = SpaceRef::parse(space) else {
return invalid("space must be a valid space-ref");
};
let did = delegating_account(s, call)?;
let did = delegating_account(s, call, &sr)?;
let Some(account) = s.account(&did) else {
return invalid_token();
};
@@ -187,10 +188,15 @@ fn get_delegation_token(
}
/// The account a delegation token may be minted for: a full session's, not
/// an app password's. OAuth's `space:` grants join here: an access token
/// whose scope grants `read` of the space is taken as a full session is
/// (`spec/SPACES-CREDENTIALS.md`, "For the other parts").
fn delegating_account(s: &Service, call: &Call) -> Result<String, XrpcError> {
/// an app password's; or an OAuth session's whose scope grants `read` of
/// the space (`spec/SPACES-CREDENTIALS.md`, "getDelegationToken";
/// `spec/OAUTH-SCOPES.md`, "What each method needs").
fn delegating_account(s: &Service, call: &Call, sr: &SpaceRef) -> Result<String, XrpcError> {
if matches!(call.bearer, crate::sessions::Bearer::OAuth(_)) {
let t = crate::sessions::access_token(s, call.bearer)?;
crate::scopes::may_in(call.bearer, sr, SpaceOp::Read { whole: true })?;
return Ok(t.did);
}
crate::sessions::full_access_token(s, call.bearer).map(|t| t.did)
}
crates/pds-server/src/space_repo.rs+128−0
@@ -40,6 +40,7 @@ use crate::cache::Ctx;
use crate::checkpoint::spaces::{
MemRecord, Meta, Old, Ops, SpaceMem, SpaceSnapshot, View, Void, after_prefix, space_key,
};
use crate::oauth::space_scope::SpaceOp;
use crate::repo::{typed, validation_status, with_status};
use crate::space_authority::{Publication, Publisher};
use crate::space_credentials::{presents_credential, verify_space_credential};
@@ -1195,6 +1196,7 @@ async fn write(svc: &Shared, call: &Call<'_>, m: &'static Method) -> Result<Resp
if required(&b, "repo")? != did {
return err(403, "Forbidden", "Cannot write to another account's repo");
}
record_scope(svc, call, &did, &space, &m.name, &b)?;
let asked = asked(&m.name, &b)?;
crate::limits::guard(svc, call, Some(&did), Some(&b))?;
let status = validation_status(&b).unwrap_or(None);
@@ -1206,6 +1208,7 @@ async fn write(svc: &Shared, call: &Call<'_>, m: &'static Method) -> Result<Resp
let mut guard = crate::write(&account.store);
let st = &mut *guard;
st.blobs.time(svc.limits.clock.now(), svc.config.blob_ttl);
writes_scope(st, call, &did, &space, &uri, &asked)?;
let found = space.authority != did || st.authority.live(&uri).is_some();
let (out, commit) = match apply(st, &did, &space, &uri, found, asked, status) {
Ok((answer, Some(c))) => {
@@ -1255,6 +1258,100 @@ async fn write(svc: &Shared, call: &Call<'_>, m: &'static Method) -> Result<Resp
out.map(Resp::Json)
}
/// What `createRecord`, `putRecord` and `deleteRecord` need of an OAuth
/// scope, asked once the collection is checked and before the record
/// (`spec/OAUTH-SCOPES.md`, "What each method needs"): `create` or
/// `delete` of the collection; `putRecord`, `update` if the record is
/// there, else `create`.
fn record_scope(
svc: &Service,
call: &Call,
did: &str,
space: &SpaceRef,
name: &str,
b: &Map<String, Json>,
) -> Result<(), XrpcError> {
if !matches!(call.bearer, crate::sessions::Bearer::OAuth(_))
|| !matches!(name, "createRecord" | "putRecord" | "deleteRecord")
{
return Ok(());
}
let collection = required(b, "collection")?;
refuse_published(collection)?;
let action = match name {
"createRecord" => "create",
"deleteRecord" => "delete",
_ => {
let there = opt(b, "rkey").is_some_and(|rkey| {
svc.account(did).is_some_and(|a| {
read(&a.store)
.space_meta(&space.uri(), &format!("{collection}/{rkey}"))
.is_some()
})
});
if there { "update" } else { "create" }
}
};
crate::scopes::may_in(call.bearer, space, SpaceOp::Write { action, collection })
}
/// What `applyWrites` and `clearRecords` need of an OAuth scope, asked once
/// the input is checked and before the space is looked for
/// (`spec/OAUTH-SCOPES.md`, "What each method needs"): of each write, in
/// order, its action of its collection; of `clearRecords`, `delete` of each
/// collection the caller's repo there holds a record of, but those it
/// keeps, by name.
fn writes_scope(
st: &Store,
call: &Call,
did: &str,
space: &SpaceRef,
uri: &str,
asked: &Asked,
) -> Result<(), XrpcError> {
if !matches!(call.bearer, crate::sessions::Bearer::OAuth(_)) {
return Ok(());
}
let write = |action, collection| {
crate::scopes::may_in(call.bearer, space, SpaceOp::Write { action, collection })
};
match asked {
Asked::ApplyWrites(writes) => writes.iter().try_for_each(|w| {
let action = match w {
Write::Create { .. } | Write::Put { .. } => "create",
Write::Update { .. } => "update",
Write::Delete { .. } => "delete",
};
write(action, w.collection())
}),
Asked::ClearRecords => collections_held(st, uri)
.iter()
.filter(|c| space.authority != did || !PUBLISHED.contains(&c.as_str()))
.try_for_each(|c| write("delete", c)),
_ => Ok(()),
}
}
/// The collections the repo in the space `uri` holds records of, by name,
/// each once: one record looked up for each.
fn collections_held(st: &Store, uri: &str) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
let mut from: Vec<u8> = Vec::new();
loop {
let lo = if out.is_empty() {
Unbounded
} else {
Included(from.as_slice())
};
let Some((path, _, _)) = st.space_records(uri, lo, Unbounded, false).next() else {
return out;
};
let collection = path.split_once('/').map_or(path.as_str(), |(c, _)| c);
from = after_prefix(&format!("{collection}/"));
out.push(collection.to_string());
}
}
/// The blob refs in the records the writes write.
fn refs_of(writes: &[Write]) -> Vec<BlobRef> {
let mut refs = Vec::new();
@@ -1582,6 +1679,11 @@ async fn read_call(
if repo != did {
return err(400, "RepoNotFound", format!("Could not find repo: {repo}"));
}
// `read_self` of the space, once the repo is the caller's own
// (`spec/OAUTH-SCOPES.md`, "What each method needs").
if let Some(sr) = SpaceRef::parse(required(&p, "space")?) {
crate::scopes::may_in(call.bearer, &sr, SpaceOp::Read { whole: false })?;
}
s.account(&did).map_or_else(internal, Ok)?
};
let asked = match profile {
@@ -1903,6 +2005,15 @@ fn list_spaces(
Ok(t) if t.scope == crate::sessions::TAKENDOWN => t.did,
_ => s.auth(call.bearer).did()?,
};
// `read_self` of the spaces it may list (`spec/OAUTH-SCOPES.md`, "What
// each method needs").
crate::scopes::may_space(
call.bearer,
opt(p, "spaceDid").unwrap_or("*"),
opt(p, "spaceType").unwrap_or("*"),
"*",
SpaceOp::Read { whole: false },
)?;
let Some(a) = s.account(&did) else {
return internal();
};
@@ -2180,6 +2291,23 @@ async fn import_repo(svc: &Shared, call: &Call<'_>) -> Result<Resp, XrpcError> {
"The archive is of another account's repo",
);
}
// `create` of each collection its records name, in the order first
// named (`spec/OAUTH-SCOPES.md`, "What each method needs").
let mut named: Vec<&str> = Vec::new();
for (path, _) in &archive.records {
let collection = path.split_once('/').map_or(path.as_str(), |(c, _)| c);
if !named.contains(&collection) {
crate::scopes::may_in(
call.bearer,
&space,
SpaceOp::Write {
action: "create",
collection,
},
)?;
named.push(collection);
}
}
let uri = space.uri();
if space.authority == a.did && read(&a.store).authority.live(&uri).is_none() {
return err(400, "SpaceNotFound", format!("Space not found: {uri}"));
docs/guide/comparing.md+7−0
harness/checks/oauth-scopes.mjs+1−29
harness/spaces/compare.mjs+17−4
harness/spaces/scopes.mjsnew+333−0
harness/gates.mjs+1−1
spec/OAUTH-SCOPES.md+191−42
spec/OAUTH.md+2−1
spec/SPACES-CREDENTIALS.md+3−1
spec/SPACES-EXPORT.md+3−2
spec/SPACES-POLICIES.md+4−3
spec/SPACES-REPO.md+6−4
spec/SPACES.md+5−1
README.md+5−2