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

Apps write as the group with their tokens, within scope and the member's roles

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:host/tokens
crates/group-host/src/lib.rs+52−0
@@ -26,16 +26,19 @@ pub mod lifecycle;
pub mod oauth;
pub mod oauth_clients;
pub mod oauth_dpop;
pub mod oauth_resource;
pub mod oauth_scope;
pub mod oauth_store;
pub mod plc;
pub mod rbac;
pub mod repo;
pub mod scopes;
pub mod secrets;
pub mod space;
pub mod space_api;
pub mod store;
pub mod time;
pub mod token_writes;
pub mod xrpc;
use axum::extract::Path;
@@ -324,6 +327,7 @@ pub fn router(host: Arc<Host>) -> Router {
post(authorization::decline_authorization),
)
.route("/oauth/authorize", get(oauth::authorize))
.merge(token_routes())
.merge(oauth_routes())
.route("/.well-known/did.json", get(api::did_json))
.route("/.well-known/atproto-did", get(api::atproto_did))
@@ -348,6 +352,54 @@ fn oauth_routes() -> Router<Arc<Host>> {
.layer(axum::middleware::from_fn(oauth::cors))
}
/// The methods an app calls with a token, as the group: open to any
/// origin, as the OAuth endpoints are.
fn token_routes() -> Router<Arc<Host>> {
let x = |nsid: &str| format!("/xrpc/{nsid}");
Router::new()
.route(
&x("com.atproto.repo.createRecord"),
post(token_writes::create_record),
)
.route(
&x("com.atproto.repo.putRecord"),
post(token_writes::put_record),
)
.route(
&x("com.atproto.repo.deleteRecord"),
post(token_writes::delete_record),
)
.route(
&x("com.atproto.repo.applyWrites"),
post(token_writes::apply_writes),
)
.route(
&x("com.atproto.repo.uploadBlob"),
post(token_writes::upload_blob),
)
.route(
&x("com.atproto.space.createRecord"),
post(token_writes::space_create_record),
)
.route(
&x("com.atproto.space.putRecord"),
post(token_writes::space_put_record),
)
.route(
&x("com.atproto.space.deleteRecord"),
post(token_writes::space_delete_record),
)
.route(
&x("com.atproto.space.applyWrites"),
post(token_writes::space_apply_writes),
)
.route(
&x("com.atproto.server.getSession"),
get(token_writes::get_session),
)
.layer(axum::middleware::from_fn(oauth::cors))
}
/// That the host is up, and which build it is.
async fn health() -> Json<Value> {
Json(json!({ "version": env!("CARGO_PKG_VERSION") }))
crates/group-host/src/oauth.rs+1−1
@@ -200,7 +200,7 @@ async fn client_and_key(
now: i64,
) -> Result<(crate::oauth_clients::Client, Value, String), OAuthError> {
let client_id = need(form, "client_id")?;
let proof = host.dpop_proof(headers, "POST", path, now)?;
let proof = host.dpop_proof(headers, "POST", path, None, now)?;
let proof =
proof.ok_or_else(|| OAuthError::bad("invalid_dpop_proof", "DPoP proof required"))?;
let client = host.client(client_id, now).await?;
crates/group-host/src/oauth_dpop.rs+6−1
@@ -63,12 +63,14 @@ impl Host {
}
/// The DPoP proof on a request of `method` to `path` here, checked:
/// none if it carries none.
/// none if it carries none. `token` is the access token a request to
/// a resource sends, which the proof must hash.
pub fn dpop_proof(
&self,
headers: &HeaderMap,
method: &str,
path: &str,
token: Option<&str>,
now: i64,
) -> Result<Option<Proof>, OAuthError> {
let mut sent = headers.get_all("dpop").iter();
@@ -106,6 +108,9 @@ impl Host {
"the authorization server requires a nonce in the DPoP proof",
));
}
if token.is_some_and(|t| claims["ath"] != jose::sha256(t)) {
return Err(invalid("the DPoP proof's ath is not this token's"));
}
let jkt = jose::thumbprint(&key);
let until = (iat + PROOF_MAX_AGE + CLOCK_SKEW) * 1000;
let fresh = self.store.spend(&format!("dpop:{jkt}"), jti, until, now);
crates/group-host/src/oauth_resource.rsnew+114−0
@@ -0,0 +1,114 @@
//! The resource server's half of OAuth: a request to one of the group's
//! PDS methods made with a token this host issued, checked. The token is
//! sent as `Authorization: DPoP <token>`, with a proof of the request that
//! hashes it, signed by the key the token is bound to. A refusal is 401
//! with a `WWW-Authenticate` challenge and the nonce for the next proof,
//! as RFC 9449 has a resource server answer.
//!
//! As the prototype's `pds/oauth/resource.ts`.
use crate::Host;
use crate::oauth::OAuthError;
use crate::oauth_store::Grant;
use crate::scopes::Permissions;
use crate::time::now_millis;
use crate::xrpc::XrpcError;
use atproto::jose;
use axum::Json;
use axum::http::{HeaderMap, StatusCode, header};
use axum::response::{IntoResponse, Response};
use serde_json::json;
/// A request made with a token: the grant it is of, and what it may do.
pub struct Acting {
pub grant: Grant,
pub permissions: Permissions,
}
/// Why a request was not answered: its token refused, or the method's own
/// failure.
#[derive(Debug)]
pub enum Refusal {
Token {
error: &'static str,
description: String,
nonce: String,
},
Xrpc(XrpcError),
}
impl From<XrpcError> for Refusal {
fn from(e: XrpcError) -> Refusal {
Refusal::Xrpc(e)
}
}
impl IntoResponse for Refusal {
fn into_response(self) -> Response {
let (error, description, nonce) = match self {
Refusal::Xrpc(e) => return e.into_response(),
Refusal::Token {
error,
description,
nonce,
} => (error, description, nonce),
};
let challenge = format!(
r#"DPoP error="{error}", error_description="{}""#,
description.replace('"', "'")
);
let headers = [
(header::WWW_AUTHENTICATE, challenge),
(header::HeaderName::from_static("dpop-nonce"), nonce),
(
header::ACCESS_CONTROL_EXPOSE_HEADERS,
"dpop-nonce, www-authenticate".into(),
),
];
let body = json!({"error": error, "message": description});
(StatusCode::UNAUTHORIZED, headers, Json(body)).into_response()
}
}
impl Host {
fn refuse(&self, error: &'static str, description: impl Into<String>) -> Refusal {
Refusal::Token {
error,
description: description.into(),
nonce: self.dpop_nonce(now_millis()),
}
}
/// The grant the token on a request of `method` to `path` is of, once
/// the token is current and the request proved by its key.
pub fn acting(&self, headers: &HeaderMap, method: &str, path: &str) -> Result<Acting, Refusal> {
let authorization = headers
.get(header::AUTHORIZATION)
.and_then(|v| v.to_str().ok());
let Some((scheme, token)) = authorization.and_then(|a| a.split_once(' ')) else {
return Err(XrpcError::new(
StatusCode::UNAUTHORIZED,
"AuthMissing",
"a token is required",
)
.into());
};
if !scheme.eq_ignore_ascii_case("DPoP") {
return Err(self.refuse("invalid_token", "this host's tokens are DPoP-bound"));
}
let now = now_millis();
let found = self.store.grant_by_access(&jose::sha256(token), now);
let grant = found.map_err(XrpcError::internal)?;
let grant =
grant.ok_or_else(|| self.refuse("invalid_token", "an unknown or lapsed token"))?;
let proof = self.dpop_proof(headers, method, path, Some(token), now);
let proof = proof.map_err(|e: OAuthError| self.refuse(e.error, e.description))?;
let proof =
proof.ok_or_else(|| self.refuse("invalid_dpop_proof", "DPoP proof required"))?;
if proof.jkt != grant.dpop_jkt {
return Err(self.refuse("invalid_token", "the DPoP key is not the token's"));
}
let permissions = Permissions::new(&grant.scope, &grant.group);
Ok(Acting { grant, permissions })
}
}
crates/group-host/src/oauth_scope.rs+5−1
@@ -105,7 +105,11 @@ pub fn writes_for(access: &Value, roles: &[String]) -> BTreeMap<String, BTreeSet
}
/// Whether those writes include `action` on `collection`.
fn may_write(writes: &BTreeMap<String, BTreeSet<String>>, collection: &str, action: &str) -> bool {
pub(crate) fn may_write(
writes: &BTreeMap<String, BTreeSet<String>>,
collection: &str,
action: &str,
) -> bool {
["*", collection]
.iter()
.any(|c| writes.get(*c).is_some_and(|w| w.contains(action)))
crates/group-host/src/oauth_store.rs+10−0
@@ -193,6 +193,16 @@ impl Store {
Ok(found.optional()?)
}
/// The grant whose access token hashes to `hash`, while that lasts.
pub fn grant_by_access(&self, hash: &str, now: i64) -> Result<Option<Grant>> {
let conn = self.conn();
let sql = format!(
"SELECT {GRANT_COLUMNS} FROM oauth_token WHERE access_hash = ?1 AND access_expires > ?2"
);
let found = conn.query_row(&sql, params![hash, now], grant);
Ok(found.optional()?)
}
/// Gives the grant whose refresh token hashes to `old` new tokens: the
/// old ones stop working. `false` if it was refreshed or revoked first.
pub fn rotate(&self, old: &str, tokens: &Tokens, now: i64) -> Result<bool> {
crates/group-host/src/repo.rs+6−0
@@ -453,6 +453,12 @@ fn walk<'a>(
}
}
/// The CID a record's JSON is kept under, once it is a record of
/// `collection`.
pub(crate) fn record_cid(collection: &str, value: &serde_json::Value) -> Result<Cid, XrpcError> {
Ok(record(collection, value)?.0)
}
/// A record's JSON as kept: its CID and DRISL. It must be a record by the
/// data model, of its collection's `$type`.
fn record(collection: &str, value: &serde_json::Value) -> Result<(Cid, Vec<u8>), XrpcError> {
crates/group-host/src/scopes.rsnew+140−0
@@ -0,0 +1,140 @@
//! What a token's scope lets it do, asked at each use: write a kind of
//! record in the group's repo, upload a blob of a type, or read or write
//! in a space. A token's scope is concrete (`oauth_scope.rs` made it so),
//! and read as atproto's permission spec reads one, as pds.js does: a
//! space scope's authority is `self` (the token's group) unless named,
//! and a scope naming no action grants every one but `read_self`, which
//! `read` holds.
use atproto::space::SpaceRef;
/// The writes a repo scope may name.
const REPO_ACTIONS: [&str; 3] = ["create", "update", "delete"];
/// What a space scope grants when it names no action.
const SPACE_DEFAULT: [&str; 4] = ["read", "create", "update", "delete"];
const SPACE_ACTIONS: [&str; 5] = ["read_self", "read", "create", "update", "delete"];
/// The values of `name` in a scope's query.
fn query<'a>(scope: &'a str, name: &str) -> Vec<&'a str> {
let q = scope.split_once('?').map_or("", |(_, q)| q);
q.split('&')
.filter_map(|kv| kv.split_once('='))
.filter(|(k, _)| *k == name)
.map(|(_, v)| v)
.collect()
}
/// The resource a scope names after its prefix and colon, if any:
/// `repo:app.bsky.feed.post?…` names `app.bsky.feed.post`.
fn named<'a>(scope: &'a str, prefix: &str) -> Option<&'a str> {
let rest = scope.strip_prefix(prefix)?;
let resource = rest.split('?').next().unwrap_or_default();
match resource.strip_prefix(':') {
Some(r) => Some(r),
None => resource.is_empty().then_some(""),
}
}
/// The actions a scope names, of `known`, or `default` when it names none.
fn actions<'a>(scope: &'a str, known: &[&str], default: &[&'a str]) -> Vec<&'a str> {
let asked = query(scope, "action");
if asked.is_empty() {
return default.to_vec();
}
asked.into_iter().filter(|a| known.contains(a)).collect()
}
/// Whether `pattern` (`*/*`, `image/*`, `image/png`) takes `mime`.
fn mime_matches(pattern: &str, mime: &str) -> bool {
let (p, m) = (pattern.to_lowercase(), mime.to_lowercase());
if p == "*/*" {
return true;
}
match p.strip_suffix("/*") {
Some(kind) => m.split('/').next() == Some(kind),
None => p == m,
}
}
/// A token's scope, for the group it acts as.
#[derive(Debug, Clone)]
pub struct Permissions {
scopes: Vec<String>,
group: String,
}
impl Permissions {
pub fn new(scope: &str, group: &str) -> Permissions {
let scopes = scope.split(' ').filter(|s| !s.is_empty()).map(String::from);
Permissions {
scopes: scopes.collect(),
group: group.into(),
}
}
/// May it `action` (`create`, `update`, `delete`) a `collection`
/// record in the group's repo?
pub fn repo(&self, collection: &str, action: &str) -> bool {
self.scopes.iter().any(|s| {
let Some(resource) = named(s, "repo") else {
return false;
};
let resource = match resource {
"" => query(s, "collection"),
r => vec![r],
};
let covers = resource.iter().any(|c| *c == "*" || *c == collection);
covers && actions(s, &REPO_ACTIONS, &REPO_ACTIONS).contains(&action)
})
}
/// May it upload a blob of type `mime`?
pub fn blob(&self, mime: &str) -> bool {
self.scopes.iter().any(|s| {
let Some(resource) = named(s, "blob") else {
return false;
};
let accept = match resource {
"" => query(s, "accept"),
r => r.split(',').collect(),
};
accept.iter().any(|p| mime_matches(p, mime))
})
}
/// May it `action` (`read`, `read_self`, `create`, `update`,
/// `delete`) in `space`, on a `collection` record for a write?
pub fn space(&self, space: &SpaceRef, collection: Option<&str>, action: &str) -> bool {
self.scopes.iter().any(|s| {
let Some(kind) = named(s, "space") else {
return false;
};
let kind = if kind.is_empty() {
query(s, "type").first().copied()
} else {
Some(kind)
};
let one = |name: &str, default: &'static str| {
query(s, name).first().copied().unwrap_or(default)
};
let authority = match one("authority", "self") {
"self" => self.group.as_str(),
a => a,
};
let at = kind.is_some_and(|k| k == "*" || k == space.kind)
&& (authority == "*" || authority == space.authority)
&& ["*", space.skey.as_str()].contains(&one("skey", "*"));
let granted = actions(s, &SPACE_ACTIONS, &SPACE_DEFAULT);
let may =
granted.contains(&action) || (action == "read_self" && granted.contains(&"read"));
if !at || !may {
return false;
}
if action == "read" || action == "read_self" {
return true;
}
let collections = query(s, "collection");
collection.is_some_and(|c| collections.iter().any(|x| *x == "*" || *x == c))
})
}
}
crates/group-host/src/token_writes.rsnew+605−0
605 lines changed: not loaded until asked for.
crates/group-host/tests/common/oauth.rs+50−0
@@ -213,6 +213,56 @@ impl App {
}
}
impl App {
/// A proof of a request to a resource, hashing `token`.
pub fn resource_proof(&self, h: &Running, method: &str, nsid: &str, token: &str) -> String {
self.proof_with(h, method, &format!("/xrpc/{nsid}"), |c| {
c["ath"] = json!(jose::sha256(token));
})
}
/// Calls `nsid` with `token` and a fresh proof, `body` as JSON (a POST)
/// or none (a GET), once more with the server's nonce if it asks.
pub async fn call(&self, h: &Running, nsid: &str, token: &str, body: Option<&Json>) -> Said {
let said = self.call_once(h, nsid, token, body).await;
let stale = said
.headers
.get("www-authenticate")
.is_some_and(|v| v.to_str().unwrap().contains("use_dpop_nonce"));
if !stale {
return said;
}
self.call_once(h, nsid, token, body).await
}
async fn call_once(&self, h: &Running, nsid: &str, token: &str, body: Option<&Json>) -> Said {
let url = format!("{}/xrpc/{nsid}", h.url);
let (method, req) = match body {
Some(b) => ("POST", h.http.post(url).json(b)),
None => ("GET", h.http.get(url)),
};
let req = req
.header("authorization", format!("DPoP {token}"))
.header("dpop", self.resource_proof(h, method, nsid, token));
self.said(req).await
}
/// What the server said to `req`, its nonce kept.
pub async fn said(&self, req: reqwest::RequestBuilder) -> Said {
let res = req.send().await.unwrap();
let (status, headers) = (res.status().as_u16(), res.headers().clone());
if let Some(nonce) = headers.get("dpop-nonce") {
*self.nonce.lock().unwrap() = Some(nonce.to_str().unwrap().into());
}
let body = res.json().await.unwrap_or(Json::Null);
Said {
status,
body,
headers,
}
}
}
/// `member` approves `request_uri` for `group`.
pub async fn approve(
h: &Running,
crates/group-host/tests/tokens.rsnew+744−0
744 lines changed: not loaded until asked for.
docs/design/README.md+4−3
@@ -97,9 +97,10 @@ says otherwise.
6. **Signing in.** Service auth for callers; the OAuth server an app signs
in to as a group (PAR, DPoP, consent, refresh), with its JWKs and JWTs
in `atproto::jose` (`oauth*.rs`, `authorization.rs`; done, see
[signing in](signing-in.md)); then what its tokens do: writes as the
group within their scope, group tokens, app passwords and connected
apps; then provisioning: `auth.ts`, `pds/auth.ts`, `pds/oauth/*`,
[signing in](signing-in.md)); writes as the group with its tokens,
within their scope and the member's roles (`oauth_resource.rs`,
`scopes.rs`, `token_writes.rs`; done); then group tokens, app
passwords and connected apps; then provisioning: `auth.ts`, `pds/auth.ts`, `pds/oauth/*`,
`methods/{authorization,groupAuth,appPasswords,connectedApps,provision}.ts`.
The console signs its people in at their own PDS here, as a
confidential client, and keeps the session on the server, as knotless
docs/design/signing-in.md+44−5